firebase 10.3.0 → 10.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/dist/esm/index.esm.js +1 -1
- package/app/dist/index.cjs.js +1 -1
- package/app/dist/index.mjs +1 -1
- package/compat/app/dist/esm/index.esm.js +1 -1
- package/compat/app/dist/index.cjs.js +1 -1
- package/compat/app/dist/index.mjs +1 -1
- package/compat/dist/esm/index.esm.js +2 -2
- package/compat/dist/index.node.cjs +2 -2
- package/compat/dist/index.rn.cjs.js +2 -2
- package/firebase-analytics.js +1 -1
- package/firebase-app-check.js +1 -1
- package/firebase-app-compat.js +2 -2
- package/firebase-app.js +5 -5
- package/firebase-auth-cordova.js +1 -1
- package/firebase-auth.js +1 -1
- package/firebase-compat.js +4 -4
- package/firebase-compat.js.map +1 -1
- package/firebase-database.js +1 -1
- package/firebase-firestore-compat.js +1 -1
- package/firebase-firestore-compat.js.map +1 -1
- package/firebase-firestore-lite.js +1 -1
- package/firebase-firestore-lite.js.map +1 -1
- package/firebase-firestore.js +1 -1
- package/firebase-firestore.js.map +1 -1
- package/firebase-functions.js +1 -1
- package/firebase-installations.js +1 -1
- package/firebase-messaging-sw.js +1 -1
- package/firebase-messaging.js +1 -1
- package/firebase-performance-standalone-compat.es2017.js +5 -5
- package/firebase-performance-standalone-compat.js +1 -1
- package/firebase-performance.js +1 -1
- package/firebase-remote-config.js +1 -1
- package/firebase-storage.js +1 -1
- package/package.json +5 -5
package/firebase-compat.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()}(this,function(){"use strict";const t={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},f=function(e,t){if(!e)throw u(t)},u=function(e){return new Error("Firebase Database ("+t.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},n=function(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n},r={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(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let u=0;u<n.length;u+=3){var s=n[u],a=u+1<n.length,o=a?n[u+1]:0,c=u+2<n.length,l=c?n[u+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,a||(e=64)),i.push(r[s>>2],r[(3&s)<<4|o>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(i=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&i)):239<a&&a<365?(s=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let c=0;c<e.length;){var i=n[e.charAt(c++)],s=c<e.length?n[e.charAt(c)]:0;++c;var a=c<e.length?n[e.charAt(c)]:64;++c;var o=c<e.length?n[e.charAt(c)]:64;if(++c,null==i||null==s||null==a||null==o)throw new l;r.push(i<<2|s>>4),64!==a&&(r.push(s<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class l extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}function i(e){var t=n(e);return r.encodeByteArray(t,!0)}const s=function(e){return i(e).replace(/\./g,"")},a=function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function c(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:const n=t;return new Date(n.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=c(e[r],t[r]));return e}function o(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}const e=()=>o().__FIREBASE_DEFAULTS__,h=()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}},d=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&a(e[1]);return t&&JSON.parse(t)}},p=()=>{try{return e()||h()||d()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},g=()=>{var e;return null===(e=p())||void 0===e?void 0:e.config};var m,v,_;class y{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function w(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[s(JSON.stringify({alg:"none",type:"JWT"})),s(JSON.stringify(i)),""].join(".")}function b(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function I(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(b())}function T(){var e=null===(e=p())||void 0===e?void 0:e.forceEnvironment;if("node"===e)return!0;if("browser"===e)return!1;try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function E(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function C(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function S(){const e=b();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function k(){return!0===t.NODE_ADMIN}function A(){try{return"object"==typeof indexedDB}catch(e){return!1}}function N(){return new Promise((t,n)=>{try{let e=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),e||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=()=>{e=!1},i.onerror=()=>{var e;n((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){n(e)}})}function R(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class P extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,P.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,D.prototype.create)}}class D{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(x,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new P(i,s,n)}}const x=/\{\$([^}]+)}/g;function O(e){return JSON.parse(e)}function M(e){return JSON.stringify(e)}function L(e){let t={},n={},r={},i="";try{var s=e.split(".");t=O(a(s[0])||""),n=O(a(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function F(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function U(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function V(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function q(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function j(e,t){if(e===t)return 1;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return;var i=e[a],s=t[a];if(B(i)&&B(s)){if(!j(i,s))return}else if(i!==s)return}for(const o of r)if(!n.includes(o))return;return 1}function B(e){return null!==e&&"object"==typeof e}function z(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function $(e){const r={},t=e.replace(/^\?/,"").split("&");return t.forEach(e=>{var t,n;e&&([t,n]=e.split("="),r[decodeURIComponent(t)]=decodeURIComponent(n))}),r}function K(e){var t=e.indexOf("?");if(!t)return"";var n=e.indexOf("#",t);return e.substring(t,0<n?n:void 0)}class W{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;const i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],a=this.chain_[2],o=this.chain_[3],c=this.chain_[4],l,u;for(let p=0;p<80;p++){u=p<40?p<20?(l=o^s&(a^o),1518500249):(l=s^a^o,1859775393):p<60?(l=s&a|o&(s|a),2400959708):(l=s^a^o,3395469782);var h=(t<<5|t>>>27)+l+c+u+i[p]&4294967295;c=o,o=a,a=4294967295&(s<<30|s>>>2),s=t,t=h}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+o&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;const s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){const t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function G(e,t){const n=new H(e,t);return n.subscribe.bind(n)}class H{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(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=Q),void 0===r.error&&(r.error=Q),void 0===r.complete&&(r.complete=Q);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}}),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function Q(){}function Y(e,t,n,r){let i;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i){var s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".";throw new Error(s)}}function J(e,t){return`${e} failed: ${t} argument `}function X(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(J(e,t)+"must be a valid function.")}function Z(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(J(e,t)+"must be a valid context object.")}function ee(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0,n="x"===e?t:3&t|8;return n.toString(16)})}const te=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t},ne=1e3,re=2,ie=144e5,se=.5;function ae(e,t=ne,n=re){var r=t*Math.pow(n,e),i=Math.round(se*r*(Math.random()-.5)*2);return Math.min(ie,r+i)}function oe(e){return e&&e._delegate?e._delegate:e}class ce{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}}const le="[DEFAULT]";class ue{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){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const r=new y;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{var n=this.getOrInitializeService({instanceIdentifier:t});n&&r.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),n=null!==(n=null==e?void 0:e.optional)&&void 0!==n&&n;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:le})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=le){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=le){return this.instances.has(e)}getOptions(e=le){return this.instancesOptions.get(e)||{}}initialize(e={}){var{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`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);const r=null!==(i=this.onInitCallbacks.get(n))&&void 0!==i?i:new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===le?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=le){return!this.component||this.component.multipleInstances?e:le}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class he{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){const t=this.getProvider(e.name);t.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);var t=new ue(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const de=[];(v=m=m||{})[v.DEBUG=0]="DEBUG",v[v.VERBOSE=1]="VERBOSE",v[v.INFO=2]="INFO",v[v.WARN=3]="WARN",v[v.ERROR=4]="ERROR",v[v.SILENT=5]="SILENT";const pe={debug:m.DEBUG,verbose:m.VERBOSE,info:m.INFO,warn:m.WARN,error:m.ERROR,silent:m.SILENT},fe=m.INFO,ge={[m.DEBUG]:"log",[m.VERBOSE]:"log",[m.INFO]:"info",[m.WARN]:"warn",[m.ERROR]:"error"},me=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=ge[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class ve{constructor(e){this.name=e,this._logLevel=fe,this._logHandler=me,this._userLogHandler=null,de.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in m))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?pe[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,m.DEBUG,...e),this._logHandler(this,m.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,m.VERBOSE,...e),this._logHandler(this,m.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,m.INFO,...e),this._logHandler(this,m.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,m.WARN,...e),this._logHandler(this,m.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,m.ERROR,...e),this._logHandler(this,m.ERROR,...e)}}const _e=(t,e)=>e.some(e=>t instanceof e);let ye,we;const be=new WeakMap,Ie=new WeakMap,Te=new WeakMap,Ee=new WeakMap,Ce=new WeakMap;let Se={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Ie.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Te.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Ne(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function ke(r){return r!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(we=we||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(r)?function(...e){return r.apply(Re(this),e),Ne(be.get(this))}:function(...e){return Ne(r.apply(Re(this),e))}:function(e,...t){var n=r.call(Re(this),e,...t);return Te.set(n,e.sort?e.sort():[e]),Ne(n)}}function Ae(e){return"function"==typeof e?ke(e):(e instanceof IDBTransaction&&(s=e,Ie.has(s)||(t=new Promise((e,t)=>{const n=()=>{s.removeEventListener("complete",r),s.removeEventListener("error",i),s.removeEventListener("abort",i)},r=()=>{e(),n()},i=()=>{t(s.error||new DOMException("AbortError","AbortError")),n()};s.addEventListener("complete",r),s.addEventListener("error",i),s.addEventListener("abort",i)}),Ie.set(s,t))),_e(e,ye=ye||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,Se):e);var s,t}function Ne(e){if(e instanceof IDBRequest)return function(s){const e=new Promise((e,t)=>{const n=()=>{s.removeEventListener("success",r),s.removeEventListener("error",i)},r=()=>{e(Ne(s.result)),n()},i=()=>{t(s.error),n()};s.addEventListener("success",r),s.addEventListener("error",i)});return e.then(e=>{e instanceof IDBCursor&&be.set(e,s)}).catch(()=>{}),Ce.set(e,s),e}(e);if(Ee.has(e))return Ee.get(e);var t=Ae(e);return t!==e&&(Ee.set(e,t),Ce.set(t,e)),t}const Re=e=>Ce.get(e);function Pe(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const a=indexedDB.open(e,t),o=Ne(a);return r&&a.addEventListener("upgradeneeded",e=>{r(Ne(a.result),e.oldVersion,e.newVersion,Ne(a.transaction),e)}),n&&a.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),o.then(e=>{s&&e.addEventListener("close",()=>s()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),o}function De(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",e=>t(e.oldVersion,e)),Ne(n).then(()=>{})}const xe=["get","getKey","getAll","getAllKeys","count"],Oe=["put","add","delete","clear"],Me=new Map;function Le(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(Me.get(t))return Me.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,a=Oe.includes(i);if(i in(s?IDBIndex:IDBObjectStore).prototype&&(a||xe.includes(i))){var n=async function(e,...t){var n=this.transaction(e,a?"readwrite":"readonly");let r=n.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),a&&n.done]))[0]};return Me.set(t,n),n}}}Se={..._=Se,get:(e,t,n)=>Le(e,t)||_.get(e,t,n),has:(e,t)=>!!Le(e,t)||_.has(e,t)};class Fe{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map(e=>{if("VERSION"!==(null==(t=e.getComponent())?void 0:t.type))return null;var t,t=e.getImmediate();return`${t.library}/${t.version}`}).filter(e=>e).join(" ")}}const Ue="@firebase/app",Ve=new ve("@firebase/app");var qe;const je="[DEFAULT]",Be={"@firebase/app":"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/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","fire-js":"fire-js",firebase:"fire-js-all"},ze=new Map,$e=new Map;function Ke(t,n){try{t.container.addComponent(n)}catch(e){Ve.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function We(e,t){e.container.addOrOverwriteComponent(t)}function Ge(e){var t=e.name;if($e.has(t))return Ve.debug(`There were multiple attempts to register component ${t}.`),!1;$e.set(t,e);for(const n of ze.values())Ke(n,e);return!0}function He(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}const Qe=new D("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","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}."});class Ye{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 ce("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 Qe.create("app-deleted",{appName:this._name})}}const Je="10.3.0";function Xe(e,t={}){let n=e;if("object"!=typeof t){const i=t;t={name:i}}var r=Object.assign({name:je,automaticDataCollectionEnabled:!1},t);const i=r.name;if("string"!=typeof i||!i)throw Qe.create("bad-app-name",{appName:String(i)});if(n=n||g(),!n)throw Qe.create("no-options");var s=ze.get(i);if(s){if(j(n,s.options)&&j(r,s.config))return s;throw Qe.create("duplicate-app",{appName:i})}const a=new he(i);for(const o of $e.values())a.addComponent(o);r=new Ye(n,r,a);return ze.set(i,r),r}function Ze(e=je){var t=ze.get(e);if(!t&&e===je&&g())return Xe();if(!t)throw Qe.create("no-app",{appName:e});return t}async function et(e){var t=e.name;ze.has(t)&&(ze.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function tt(e,t,n){let r=null!==(s=Be[e])&&void 0!==s?s:e;n&&(r+=`-${n}`);var i=r.match(/\s|\//),s=t.match(/\s|\//);if(i||s){const a=[`Unable to register library "${r}" with version "${t}":`];return i&&a.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&s&&a.push("and"),s&&a.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void Ve.warn(a.join(" "))}Ge(new ce(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function nt(e,t){if(null!==e&&"function"!=typeof e)throw Qe.create("invalid-log-argument");!function(s,e){for(const t of de){let i=null;e&&e.level&&(i=pe[e.level]),t.userLogHandler=null===s?null:(e,t,...n)=>{var r=n.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(" ");t>=(null!==i&&void 0!==i?i:e.logLevel)&&s({level:m[t].toLowerCase(),message:r,args:n,type:e.name})}}}(e,t)}function rt(e){var t;t=e,de.forEach(e=>{e.setLogLevel(t)})}const it="firebase-heartbeat-database",st=1,at="firebase-heartbeat-store";let ot=null;function ct(){return ot=ot||Pe(it,st,{upgrade:(e,t)=>{0===t&&e.createObjectStore(at)}}).catch(e=>{throw Qe.create("idb-open",{originalErrorMessage:e.message})}),ot}async function lt(e,t){try{const r=await ct(),i=r.transaction(at,"readwrite"),s=i.objectStore(at);await s.put(t,ut(e)),await i.done}catch(e){var n;e instanceof P?Ve.warn(e.message):(n=Qe.create("idb-set",{originalErrorMessage:null==e?void 0:e.message}),Ve.warn(n.message))}}function ut(e){return`${e.name}!${e.options.appId}`}class ht{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new pt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate();var t=e.getPlatformInfoString();const n=dt();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some(e=>e.date===n))return this._heartbeatsCache.heartbeats.push({date:n,agent:t}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{var t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";var e=dt(),{heartbeatsToSend:t,unsentEntries:n}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const s=n.find(e=>e.agent===i.agent);if(s){if(s.dates.push(i.date),ft(n)>t){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),ft(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),t=s(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,0<n.length?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),t}}function dt(){const e=new Date;return e.toISOString().substring(0,10)}class pt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!A()&&N().then(()=>!0).catch(()=>!1)}async read(){return await this._canUseIndexedDBPromise&&await async function(e){try{const n=await ct();return await n.transaction(at).objectStore(at).get(ut(e))}catch(e){var t;e instanceof P?Ve.warn(e.message):(t=Qe.create("idb-get",{originalErrorMessage:null==e?void 0:e.message}),Ve.warn(t.message))}}(this.app)||{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return lt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return lt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function ft(e){return s(JSON.stringify({version:2,heartbeats:e})).length}qe="",Ge(new ce("platform-logger",e=>new Fe(e),"PRIVATE")),Ge(new ce("heartbeat",e=>new ht(e),"PRIVATE")),tt(Ue,"0.9.17",qe),tt(Ue,"0.9.17","esm2017"),tt("fire-js","");var gt=Object.freeze({__proto__:null,SDK_VERSION:Je,_DEFAULT_ENTRY_NAME:je,_addComponent:Ke,_addOrOverwriteComponent:We,_apps:ze,_clearComponents:function(){$e.clear()},_components:$e,_getProvider:He,_registerComponent:Ge,_removeServiceInstance:function(e,t,n=je){He(e,t).clearInstance(n)},deleteApp:et,getApp:Ze,getApps:function(){return Array.from(ze.values())},initializeApp:Xe,onLog:nt,registerVersion:tt,setLogLevel:rt,FirebaseError:P});class mt{constructor(e,t){this._delegate=e,this.firebase=t,Ke(e,new ce("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),et(this._delegate)))}_getService(e,t=je){var n;this._delegate.checkDestroyed();const r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==(null===(n=r.getComponent())||void 0===n?void 0:n.instantiationMode)||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=je){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){Ke(this._delegate,e)}_addOrOverwriteComponent(e){We(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const vt=new D("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function _t(i){const s={},a={__esModule:!0,initializeApp:function(e,t={}){var n=Xe(e,t);if(F(s,n.name))return s[n.name];var r=new i(n,a);return s[n.name]=r},app:o,registerVersion:tt,setLogLevel:rt,onLog:nt,apps:null,SDK_VERSION:Je,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;Ge(n)&&"PUBLIC"===n.type&&(e=(e=o())=>{if("function"!=typeof e[t])throw vt.create("invalid-app-argument",{appName:r});return e[t]()},void 0!==n.serviceProps&&c(e,n.serviceProps),a[t]=e,i.prototype[t]=function(...e){const t=this._getService.bind(this,r);return t.apply(this,n.multipleInstances?e:[])})}return"PUBLIC"===n.type?a[t]:null},removeApp:function(e){delete s[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var n=t;return n},modularAPIs:gt}};function o(e){if(e=e||je,!F(s,e))throw vt.create("no-app",{appName:e});return s[e]}return a.default=a,Object.defineProperty(a,"apps",{get:function(){return Object.keys(s).map(e=>s[e])}}),o.App=i,a}var yt=function e(){const t=_t(mt);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){c(t,e)},createSubscribe:G,ErrorFactory:D,deepExtend:c}),t}();const wt=new ve("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){wt.warn(`
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()}(this,function(){"use strict";const t={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},f=function(e,t){if(!e)throw u(t)},u=function(e){return new Error("Firebase Database ("+t.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},n=function(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n},r={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(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let u=0;u<n.length;u+=3){var s=n[u],a=u+1<n.length,o=a?n[u+1]:0,c=u+2<n.length,l=c?n[u+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,a||(e=64)),i.push(r[s>>2],r[(3&s)<<4|o>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(n(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,a=e[n++];a<128?t[r++]=String.fromCharCode(a):191<a&&a<224?(i=e[n++],t[r++]=String.fromCharCode((31&a)<<6|63&i)):239<a&&a<365?(s=((7&a)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&a)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let c=0;c<e.length;){var i=n[e.charAt(c++)],s=c<e.length?n[e.charAt(c)]:0;++c;var a=c<e.length?n[e.charAt(c)]:64;++c;var o=c<e.length?n[e.charAt(c)]:64;if(++c,null==i||null==s||null==a||null==o)throw new l;r.push(i<<2|s>>4),64!==a&&(r.push(s<<4&240|a>>2),64!==o&&r.push(a<<6&192|o))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class l extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}function i(e){var t=n(e);return r.encodeByteArray(t,!0)}const s=function(e){return i(e).replace(/\./g,"")},a=function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function c(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:const n=t;return new Date(n.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=c(e[r],t[r]));return e}function o(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}const e=()=>o().__FIREBASE_DEFAULTS__,h=()=>{if("undefined"!=typeof process&&void 0!==process.env){var e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0}},d=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&a(e[1]);return t&&JSON.parse(t)}},p=()=>{try{return e()||h()||d()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},g=()=>{var e;return null===(e=p())||void 0===e?void 0:e.config};var m,v,_;class y{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function w(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[s(JSON.stringify({alg:"none",type:"JWT"})),s(JSON.stringify(i)),""].join(".")}function b(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function I(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(b())}function T(){var e=null===(e=p())||void 0===e?void 0:e.forceEnvironment;if("node"===e)return!0;if("browser"===e)return!1;try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function E(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function C(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function k(){const e=b();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function S(){return!0===t.NODE_ADMIN}function A(){try{return"object"==typeof indexedDB}catch(e){return!1}}function N(){return new Promise((t,n)=>{try{let e=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),e||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=()=>{e=!1},i.onerror=()=>{var e;n((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){n(e)}})}function R(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class P extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,P.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,D.prototype.create)}}class D{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(x,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new P(i,s,n)}}const x=/\{\$([^}]+)}/g;function O(e){return JSON.parse(e)}function M(e){return JSON.stringify(e)}function L(e){let t={},n={},r={},i="";try{var s=e.split(".");t=O(a(s[0])||""),n=O(a(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function F(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function U(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function V(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function q(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function B(e,t){if(e===t)return 1;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return;var i=e[a],s=t[a];if(j(i)&&j(s)){if(!B(i,s))return}else if(i!==s)return}for(const o of r)if(!n.includes(o))return;return 1}function j(e){return null!==e&&"object"==typeof e}function z(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function $(e){const r={},t=e.replace(/^\?/,"").split("&");return t.forEach(e=>{var t,n;e&&([t,n]=e.split("="),r[decodeURIComponent(t)]=decodeURIComponent(n))}),r}function K(e){var t=e.indexOf("?");if(!t)return"";var n=e.indexOf("#",t);return e.substring(t,0<n?n:void 0)}class G{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;const i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],a=this.chain_[2],o=this.chain_[3],c=this.chain_[4],l,u;for(let p=0;p<80;p++){u=p<40?p<20?(l=o^s&(a^o),1518500249):(l=s^a^o,1859775393):p<60?(l=s&a|o&(s|a),2400959708):(l=s^a^o,3395469782);var h=(t<<5|t>>>27)+l+c+u+i[p]&4294967295;c=o,o=a,a=4294967295&(s<<30|s>>>2),s=t,t=h}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+o&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;const s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){const t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function W(e,t){const n=new H(e,t);return n.subscribe.bind(n)}class H{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(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=Q),void 0===r.error&&(r.error=Q),void 0===r.complete&&(r.complete=Q);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}}),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function Q(){}function Y(e,t,n,r){let i;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i){var s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".";throw new Error(s)}}function J(e,t){return`${e} failed: ${t} argument `}function X(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(J(e,t)+"must be a valid function.")}function Z(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(J(e,t)+"must be a valid context object.")}function ee(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0,n="x"===e?t:3&t|8;return n.toString(16)})}const te=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t},ne=1e3,re=2,ie=144e5,se=.5;function ae(e,t=ne,n=re){var r=t*Math.pow(n,e),i=Math.round(se*r*(Math.random()-.5)*2);return Math.min(ie,r+i)}function oe(e){return e&&e._delegate?e._delegate:e}class ce{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}}const le="[DEFAULT]";class ue{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){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const r=new y;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{var n=this.getOrInitializeService({instanceIdentifier:t});n&&r.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),n=null!==(n=null==e?void 0:e.optional)&&void 0!==n&&n;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:le})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=le){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=le){return this.instances.has(e)}getOptions(e=le){return this.instancesOptions.get(e)||{}}initialize(e={}){var{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`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);const r=null!==(i=this.onInitCallbacks.get(n))&&void 0!==i?i:new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===le?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=le){return!this.component||this.component.multipleInstances?e:le}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class he{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){const t=this.getProvider(e.name);t.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);var t=new ue(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const de=[];(v=m=m||{})[v.DEBUG=0]="DEBUG",v[v.VERBOSE=1]="VERBOSE",v[v.INFO=2]="INFO",v[v.WARN=3]="WARN",v[v.ERROR=4]="ERROR",v[v.SILENT=5]="SILENT";const pe={debug:m.DEBUG,verbose:m.VERBOSE,info:m.INFO,warn:m.WARN,error:m.ERROR,silent:m.SILENT},fe=m.INFO,ge={[m.DEBUG]:"log",[m.VERBOSE]:"log",[m.INFO]:"info",[m.WARN]:"warn",[m.ERROR]:"error"},me=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=ge[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class ve{constructor(e){this.name=e,this._logLevel=fe,this._logHandler=me,this._userLogHandler=null,de.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in m))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?pe[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,m.DEBUG,...e),this._logHandler(this,m.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,m.VERBOSE,...e),this._logHandler(this,m.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,m.INFO,...e),this._logHandler(this,m.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,m.WARN,...e),this._logHandler(this,m.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,m.ERROR,...e),this._logHandler(this,m.ERROR,...e)}}const _e=(t,e)=>e.some(e=>t instanceof e);let ye,we;const be=new WeakMap,Ie=new WeakMap,Te=new WeakMap,Ee=new WeakMap,Ce=new WeakMap;let ke={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Ie.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Te.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Ne(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e}};function Se(r){return r!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(we=we||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(r)?function(...e){return r.apply(Re(this),e),Ne(be.get(this))}:function(...e){return Ne(r.apply(Re(this),e))}:function(e,...t){var n=r.call(Re(this),e,...t);return Te.set(n,e.sort?e.sort():[e]),Ne(n)}}function Ae(e){return"function"==typeof e?Se(e):(e instanceof IDBTransaction&&(s=e,Ie.has(s)||(t=new Promise((e,t)=>{const n=()=>{s.removeEventListener("complete",r),s.removeEventListener("error",i),s.removeEventListener("abort",i)},r=()=>{e(),n()},i=()=>{t(s.error||new DOMException("AbortError","AbortError")),n()};s.addEventListener("complete",r),s.addEventListener("error",i),s.addEventListener("abort",i)}),Ie.set(s,t))),_e(e,ye=ye||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,ke):e);var s,t}function Ne(e){if(e instanceof IDBRequest)return function(s){const e=new Promise((e,t)=>{const n=()=>{s.removeEventListener("success",r),s.removeEventListener("error",i)},r=()=>{e(Ne(s.result)),n()},i=()=>{t(s.error),n()};s.addEventListener("success",r),s.addEventListener("error",i)});return e.then(e=>{e instanceof IDBCursor&&be.set(e,s)}).catch(()=>{}),Ce.set(e,s),e}(e);if(Ee.has(e))return Ee.get(e);var t=Ae(e);return t!==e&&(Ee.set(e,t),Ce.set(t,e)),t}const Re=e=>Ce.get(e);function Pe(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const a=indexedDB.open(e,t),o=Ne(a);return r&&a.addEventListener("upgradeneeded",e=>{r(Ne(a.result),e.oldVersion,e.newVersion,Ne(a.transaction),e)}),n&&a.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),o.then(e=>{s&&e.addEventListener("close",()=>s()),i&&e.addEventListener("versionchange",e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),o}function De(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",e=>t(e.oldVersion,e)),Ne(n).then(()=>{})}const xe=["get","getKey","getAll","getAllKeys","count"],Oe=["put","add","delete","clear"],Me=new Map;function Le(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(Me.get(t))return Me.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,a=Oe.includes(i);if(i in(s?IDBIndex:IDBObjectStore).prototype&&(a||xe.includes(i))){var n=async function(e,...t){var n=this.transaction(e,a?"readwrite":"readonly");let r=n.store;return s&&(r=r.index(t.shift())),(await Promise.all([r[i](...t),a&&n.done]))[0]};return Me.set(t,n),n}}}ke={..._=ke,get:(e,t,n)=>Le(e,t)||_.get(e,t,n),has:(e,t)=>!!Le(e,t)||_.has(e,t)};class Fe{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map(e=>{if("VERSION"!==(null==(t=e.getComponent())?void 0:t.type))return null;var t,t=e.getImmediate();return`${t.library}/${t.version}`}).filter(e=>e).join(" ")}}const Ue="@firebase/app",Ve=new ve("@firebase/app");var qe;const Be="[DEFAULT]",je={"@firebase/app":"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/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","fire-js":"fire-js",firebase:"fire-js-all"},ze=new Map,$e=new Map;function Ke(t,n){try{t.container.addComponent(n)}catch(e){Ve.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function Ge(e,t){e.container.addOrOverwriteComponent(t)}function We(e){var t=e.name;if($e.has(t))return Ve.debug(`There were multiple attempts to register component ${t}.`),!1;$e.set(t,e);for(const n of ze.values())Ke(n,e);return!0}function He(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}const Qe=new D("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","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}."});class Ye{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 ce("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 Qe.create("app-deleted",{appName:this._name})}}const Je="10.3.1";function Xe(e,t={}){let n=e;if("object"!=typeof t){const i=t;t={name:i}}var r=Object.assign({name:Be,automaticDataCollectionEnabled:!1},t);const i=r.name;if("string"!=typeof i||!i)throw Qe.create("bad-app-name",{appName:String(i)});if(n=n||g(),!n)throw Qe.create("no-options");var s=ze.get(i);if(s){if(B(n,s.options)&&B(r,s.config))return s;throw Qe.create("duplicate-app",{appName:i})}const a=new he(i);for(const o of $e.values())a.addComponent(o);r=new Ye(n,r,a);return ze.set(i,r),r}function Ze(e=Be){var t=ze.get(e);if(!t&&e===Be&&g())return Xe();if(!t)throw Qe.create("no-app",{appName:e});return t}async function et(e){var t=e.name;ze.has(t)&&(ze.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function tt(e,t,n){let r=null!==(s=je[e])&&void 0!==s?s:e;n&&(r+=`-${n}`);var i=r.match(/\s|\//),s=t.match(/\s|\//);if(i||s){const a=[`Unable to register library "${r}" with version "${t}":`];return i&&a.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&s&&a.push("and"),s&&a.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void Ve.warn(a.join(" "))}We(new ce(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function nt(e,t){if(null!==e&&"function"!=typeof e)throw Qe.create("invalid-log-argument");!function(s,e){for(const t of de){let i=null;e&&e.level&&(i=pe[e.level]),t.userLogHandler=null===s?null:(e,t,...n)=>{var r=n.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(" ");t>=(null!==i&&void 0!==i?i:e.logLevel)&&s({level:m[t].toLowerCase(),message:r,args:n,type:e.name})}}}(e,t)}function rt(e){var t;t=e,de.forEach(e=>{e.setLogLevel(t)})}const it="firebase-heartbeat-database",st=1,at="firebase-heartbeat-store";let ot=null;function ct(){return ot=ot||Pe(it,st,{upgrade:(e,t)=>{0===t&&e.createObjectStore(at)}}).catch(e=>{throw Qe.create("idb-open",{originalErrorMessage:e.message})}),ot}async function lt(e,t){try{const r=await ct(),i=r.transaction(at,"readwrite"),s=i.objectStore(at);await s.put(t,ut(e)),await i.done}catch(e){var n;e instanceof P?Ve.warn(e.message):(n=Qe.create("idb-set",{originalErrorMessage:null==e?void 0:e.message}),Ve.warn(n.message))}}function ut(e){return`${e.name}!${e.options.appId}`}class ht{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new pt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){const e=this.container.getProvider("platform-logger").getImmediate();var t=e.getPlatformInfoString();const n=dt();if(null===this._heartbeatsCache&&(this._heartbeatsCache=await this._heartbeatsCachePromise),this._heartbeatsCache.lastSentHeartbeatDate!==n&&!this._heartbeatsCache.heartbeats.some(e=>e.date===n))return this._heartbeatsCache.heartbeats.push({date:n,agent:t}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{var t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null===this._heartbeatsCache||0===this._heartbeatsCache.heartbeats.length)return"";var e=dt(),{heartbeatsToSend:t,unsentEntries:n}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const s=n.find(e=>e.agent===i.agent);if(s){if(s.dates.push(i.date),ft(n)>t){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),ft(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),t=s(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,0<n.length?(this._heartbeatsCache.heartbeats=n,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),t}}function dt(){const e=new Date;return e.toISOString().substring(0,10)}class pt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!A()&&N().then(()=>!0).catch(()=>!1)}async read(){return await this._canUseIndexedDBPromise&&await async function(e){try{const n=await ct();return await n.transaction(at).objectStore(at).get(ut(e))}catch(e){var t;e instanceof P?Ve.warn(e.message):(t=Qe.create("idb-get",{originalErrorMessage:null==e?void 0:e.message}),Ve.warn(t.message))}}(this.app)||{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return lt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return lt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function ft(e){return s(JSON.stringify({version:2,heartbeats:e})).length}qe="",We(new ce("platform-logger",e=>new Fe(e),"PRIVATE")),We(new ce("heartbeat",e=>new ht(e),"PRIVATE")),tt(Ue,"0.9.18",qe),tt(Ue,"0.9.18","esm2017"),tt("fire-js","");var gt=Object.freeze({__proto__:null,SDK_VERSION:Je,_DEFAULT_ENTRY_NAME:Be,_addComponent:Ke,_addOrOverwriteComponent:Ge,_apps:ze,_clearComponents:function(){$e.clear()},_components:$e,_getProvider:He,_registerComponent:We,_removeServiceInstance:function(e,t,n=Be){He(e,t).clearInstance(n)},deleteApp:et,getApp:Ze,getApps:function(){return Array.from(ze.values())},initializeApp:Xe,onLog:nt,registerVersion:tt,setLogLevel:rt,FirebaseError:P});class mt{constructor(e,t){this._delegate=e,this.firebase=t,Ke(e,new ce("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),et(this._delegate)))}_getService(e,t=Be){var n;this._delegate.checkDestroyed();const r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==(null===(n=r.getComponent())||void 0===n?void 0:n.instantiationMode)||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=Be){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){Ke(this._delegate,e)}_addOrOverwriteComponent(e){Ge(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const vt=new D("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function _t(i){const s={},a={__esModule:!0,initializeApp:function(e,t={}){var n=Xe(e,t);if(F(s,n.name))return s[n.name];var r=new i(n,a);return s[n.name]=r},app:o,registerVersion:tt,setLogLevel:rt,onLog:nt,apps:null,SDK_VERSION:Je,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;We(n)&&"PUBLIC"===n.type&&(e=(e=o())=>{if("function"!=typeof e[t])throw vt.create("invalid-app-argument",{appName:r});return e[t]()},void 0!==n.serviceProps&&c(e,n.serviceProps),a[t]=e,i.prototype[t]=function(...e){const t=this._getService.bind(this,r);return t.apply(this,n.multipleInstances?e:[])})}return"PUBLIC"===n.type?a[t]:null},removeApp:function(e){delete s[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var n=t;return n},modularAPIs:gt}};function o(e){if(e=e||Be,!F(s,e))throw vt.create("no-app",{appName:e});return s[e]}return a.default=a,Object.defineProperty(a,"apps",{get:function(){return Object.keys(s).map(e=>s[e])}}),o.App=i,a}var yt=function e(){const t=_t(mt);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){c(t,e)},createSubscribe:W,ErrorFactory:D,deepExtend:c}),t}();const wt=new ve("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){wt.warn(`
|
|
2
2
|
Warning: Firebase is already defined in the global scope. Please make sure
|
|
3
3
|
Firebase library is only loaded once.
|
|
4
|
-
`);const
|
|
4
|
+
`);const X1=self.firebase.SDK_VERSION;X1&&0<=X1.indexOf("LITE")&&wt.warn(`
|
|
5
5
|
Warning: You are trying to load Firebase while using Firebase Performance standalone script.
|
|
6
6
|
You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.
|
|
7
|
-
`)}const bt=yt;tt("@firebase/app-compat","0.2.17",void 0);bt.registerVersion("firebase","10.3.0","app-compat");var It="@firebase/installations",Tt="0.6.4";const Et=1e4,Ct="w:0.6.4",St="FIS_v2",kt="https://firebaseinstallations.googleapis.com/v1",At=36e5;const Nt=new D("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Rt(e){return e instanceof P&&e.code.includes("request-failed")}function Pt({projectId:e}){return`${kt}/projects/${e}/installations`}function Dt(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function xt(e,t){var n=(await t.json()).error;return Nt.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function Ot({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function Mt(e,{refreshToken:t}){const n=Ot(e);return n.append("Authorization",(t=t,`${St} ${t}`)),n}async function Lt(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function Ft(t){return new Promise(e=>{setTimeout(e,t)})}const Ut=/^[cdef][\w-]{21}$/,Vt="";function qt(){try{const t=new Uint8Array(17),n=self.crypto||self.msCrypto;n.getRandomValues(t),t[0]=112+t[0]%16;var e=function(e){const t=function(e){const t=btoa(String.fromCharCode(...e));return t.replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(t);return Ut.test(e)?e:Vt}catch(e){return Vt}}function jt(e){return`${e.appName}!${e.appId}`}const Bt=new Map;function zt(e,t){var n=jt(e);$t(n,t),function(e,t){const n=function(){!Kt&&"BroadcastChannel"in self&&(Kt=new BroadcastChannel("[Firebase] FID Change"),Kt.onmessage=e=>{$t(e.data.key,e.data.fid)});return Kt}();n&&n.postMessage({key:e,fid:t});0===Bt.size&&Kt&&(Kt.close(),Kt=null)}(n,t)}function $t(e,t){var n=Bt.get(e);if(n)for(const r of n)r(t)}let Kt=null;const Wt="firebase-installations-store";let Gt=null;function Ht(){return Gt=Gt||Pe("firebase-installations-database",1,{upgrade:(e,t)=>{0===t&&e.createObjectStore(Wt)}}),Gt}async function Qt(e,t){var n=jt(e);const r=await Ht(),i=r.transaction(Wt,"readwrite"),s=i.objectStore(Wt);var a=await s.get(n);return await s.put(t,n),await i.done,a&&a.fid===t.fid||zt(e,t.fid),t}async function Yt(e){var t=jt(e);const n=await Ht(),r=n.transaction(Wt,"readwrite");await r.objectStore(Wt).delete(t),await r.done}async function Jt(e,t){var n=jt(e);const r=await Ht(),i=r.transaction(Wt,"readwrite"),s=i.objectStore(Wt);var a=await s.get(n),o=t(a);return void 0===o?await s.delete(n):await s.put(o,n),await i.done,!o||a&&a.fid===o.fid||zt(e,o.fid),o}async function Xt(n){let r;var e=await Jt(n.appConfig,e=>{var t=en(e||{fid:qt(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await Zt(e.appConfig);for(;1===t.registrationStatus;)await Ft(100),t=await Zt(e.appConfig);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await Xt(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(Nt.create("app-offline"));return{installationEntry:t,registrationPromise:n}}var r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(t,n){try{var e=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=Pt(e),i=Ot(e),s=t.getImmediate({optional:!0});!s||(a=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",a);var a={fid:n,authVersion:St,appId:e.appId,sdkVersion:Ct};const o={method:"POST",headers:i,body:JSON.stringify(a)},c=await Lt(()=>fetch(r,o));if(c.ok){a=await c.json();return{fid:a.fid||n,registrationStatus:2,refreshToken:a.refreshToken,authToken:Dt(a.authToken)}}throw await xt("Create Installation",c)}(t,n);return Qt(t.appConfig,e)}catch(e){throw Rt(e)&&409===e.customData.serverCode?await Yt(t.appConfig):await Qt(t.appConfig,{fid:n.fid,registrationStatus:0}),e}}(e,r);return{installationEntry:r,registrationPromise:n}}}(n,t);return r=t.registrationPromise,t.installationEntry});return e.fid===Vt?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function Zt(e){return Jt(e,e=>{if(!e)throw Nt.create("installation-not-found");return en(e)})}function en(e){return 1===(t=e).registrationStatus&&t.registrationTime+Et<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function tn({appConfig:e,heartbeatServiceProvider:t},n){const r=([i,s]=[e,n["fid"]],`${Pt(i)}/${s}/authTokens:generate`);var i,s;const a=Mt(e,n),o=t.getImmediate({optional:!0});!o||(c=await o.getHeartbeatsHeader())&&a.append("x-firebase-client",c);var c={installation:{sdkVersion:Ct,appId:e.appId}};const l={method:"POST",headers:a,body:JSON.stringify(c)},u=await Lt(()=>fetch(r,l));if(u.ok)return Dt(await u.json());throw await xt("Generate Auth Token",u)}async function nn(r,i=!1){let s;var e=await Jt(r.appConfig,e=>{if(!sn(e))throw Nt.create("not-registered");var t,n=e.authToken;if(i||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+At}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await rn(e.appConfig);for(;1===n.authToken.requestStatus;)await Ft(100),n=await rn(e.appConfig);var r=n.authToken;return 0===r.requestStatus?nn(e,t):r}(r,i),e;if(!navigator.onLine)throw Nt.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},t),{authToken:n}));return s=async function(t,n){try{var r=await tn(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await Qt(t.appConfig,e),r}catch(e){throw!Rt(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await Qt(t.appConfig,r)):await Yt(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function rn(e){return Jt(e,e=>{if(!sn(e))throw Nt.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+Et<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function sn(e){return void 0!==e&&2===e.registrationStatus}async function an(e,t=!1){var n,r=e;return await((n=(await Xt(r)).registrationPromise)&&await n),(await nn(r,t)).token}function on(e){return Nt.create("missing-app-config-values",{valueName:e})}const cn="installations",ln=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw on("App Configuration");if(!e.name)throw on("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw on(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),heartbeatServiceProvider:He(t,"heartbeat"),_delete:()=>Promise.resolve()}},un=e=>{const t=He(e.getProvider("app").getImmediate(),cn).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await Xt(t);return(r||nn(t)).catch(console.error),n.fid}(t),getToken:e=>an(t,e)}};Ge(new ce(cn,ln,"PUBLIC")),Ge(new ce("installations-internal",un,"PRIVATE")),tt(It,Tt),tt(It,Tt,"esm2017");const hn="analytics",dn="firebase_id",pn="origin",fn="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",gn="https://www.googletagmanager.com/gtag/js",mn=new ve("@firebase/analytics"),vn=new D("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function _n(e){if(e.startsWith(gn))return e;var t=vn.create("invalid-gtag-resource",{gtagURL:e});return mn.warn(t.message),""}function yn(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function wn(e,t){const n=function(e,t){let n;return window.trustedTypes&&(n=window.trustedTypes.createPolicy(e,t)),n}("firebase-js-sdk-policy",{createScriptURL:_n}),r=document.createElement("script");var i=`${gn}?l=${e}&id=${t}`;r.src=n?null===n||void 0===n?void 0:n.createScriptURL(i):i,r.async=!0,document.head.appendChild(r)}function bn(h,d,p,f){return async function(e,...t){try{var n,r,i,s,a,o,c,l,u;"event"===e?([n,r]=t,await async function(e,n,r,i,s){try{let t=[];if(s&&s.send_to){let e=s.send_to;Array.isArray(e)||(e=[e]);const c=await yn(r);for(const l of e){var a=c.find(e=>e.measurementId===l),o=a&&n[a.appId];if(!o){t=[];break}t.push(o)}}0===t.length&&(t=Object.values(n)),await Promise.all(t),e("event",i,s||{})}catch(e){mn.error(e)}}(h,d,p,n,r)):"config"===e?([i,s]=t,await async function(e,t,n,r,i,s){var a=r[i];try{if(a)await t[a];else{const c=await yn(n);var o=c.find(e=>e.measurementId===i);o&&await t[o.appId]}}catch(e){mn.error(e)}e("config",i,s)}(h,d,p,f,i,s)):"consent"===e?([a]=t,h("consent","update",a)):"get"===e?([o,c,l]=t,h("get",o,c,l)):"set"===e?([u]=t,h("set",u)):h(e,...t)}catch(e){mn.error(e)}}}const In=30;const Tn=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};async function En(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=fn.replace("{app-id}",n);const i=await fetch(n,r);if(200===i.status||304===i.status)return i.json();{let e="";try{var s=await i.json();null!==(t=s.error)&&void 0!==t&&t.message&&(e=s.error.message)}catch(e){}throw vn.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function Cn(e,t=Tn,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw vn.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw vn.create("no-api-key")}var a=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const o=new An;return setTimeout(async()=>{o.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=Tn){var a;const{appId:o,measurementId:c}=n;try{await Sn(i,e)}catch(e){if(c)return mn.warn("Timed out fetching this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${c}`+` provided in the "measurementId" field in the local Firebase config. [${null==e?void 0:e.message}]`),{appId:o,measurementId:c};throw e}try{const l=await En(n);return s.deleteThrottleMetadata(o),l}catch(e){const u=e;if(!kn(u)){if(s.deleteThrottleMetadata(o),c)return mn.warn("Failed to fetch this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${c}`+` provided in the "measurementId" field in the local Firebase config. [${null===u||void 0===u?void 0:u.message}]`),{appId:o,measurementId:c};throw e}const h=503===Number(null===(a=null===u||void 0===u?void 0:u.customData)||void 0===a?void 0:a.httpStatus)?ae(r,s.intervalMillis,In):ae(r,s.intervalMillis),d={throttleEndTimeMillis:Date.now()+h,backoffCount:r+1};return s.setThrottleMetadata(o,d),mn.debug(`Calling attemptFetch again in ${h} millis`),t(n,d,i,s)}}({appId:r,apiKey:i,measurementId:s},a,o,t)}function Sn(i,s){return new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(vn.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function kn(e){if(!(e instanceof P&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class An{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function Nn(t,e,n,r,i,s,a){const o=Cn(t);o.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&mn.warn(`The measurement ID in the local Firebase config (${t.options.measurementId})`+` does not match the measurement ID fetched from the server (${e.measurementId}).`+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")}).catch(e=>mn.error(e)),e.push(o);var c=async function(){if(!A())return mn.warn(vn.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await N()}catch(e){return mn.warn(vn.create("indexeddb-unavailable",{errorInfo:null==e?void 0:e.toString()}).message),!1}return!0}().then(e=>{if(e)return r.getId()}),[l,u]=await Promise.all([o,c]);!function(e){var t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(gn)&&n.src.includes(e))return n}(s)&&wn(s,l.measurementId),i("js",new Date);const h=null!==(c=null==a?void 0:a.config)&&void 0!==c?c:{};return h[pn]="firebase",h.update=!0,null!=u&&(h[dn]=u),i("config",l.measurementId,h),l.measurementId}class Rn{constructor(e){this.app=e}_delete(){return delete Pn[this.app.options.appId],Promise.resolve()}}let Pn={},Dn=[];const xn={};let On="dataLayer",Mn="gtag",Ln,Fn,Un=!1;function Vn(e){if(Un)throw vn.create("already-initialized");e.dataLayerName&&(On=e.dataLayerName),e.gtagName&&(Mn=e.gtagName)}function qn(e,t,n){!function(){const e=[];var t;E()&&e.push("This is a browser extension environment."),R()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=vn.create("invalid-analytics-context",{errorInfo:t}),mn.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw vn.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw vn.create("no-api-key");mn.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest'+` measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId}`+' provided in the "measurementId" field in the local Firebase config.')}if(null!=Pn[s])throw vn.create("already-exists",{id:s});return Un||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(On),{wrappedGtag:r,gtagCore:i}=function(e,t,n,r,i){let s=function(){window[r].push(arguments)};return window[i]&&"function"==typeof window[i]&&(s=window[i]),window[i]=bn(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(Pn,Dn,xn,On,Mn),Fn=r,Ln=i,Un=!0),Pn[s]=Nn(e,Dn,xn,t,Ln,On,n),new Rn(e)}async function jn(){if(E())return!1;if(!R())return!1;if(!A())return!1;try{return await N()}catch(e){return!1}}function Bn(e,t,n){e=oe(e),async function(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(Fn,Pn[e.app.options.appId],t,n).catch(e=>mn.error(e))}function zn(e,t,n){e=oe(e),async function(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(Fn,Pn[e.app.options.appId],t,n).catch(e=>mn.error(e))}function $n(e,t,n){e=oe(e),async function(e,t,n,r){if(r&&r.global){const i={};for(const s of Object.keys(n))i[`user_properties.${s}`]=n[s];return e("set",i),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(Fn,Pn[e.app.options.appId],t,n).catch(e=>mn.error(e))}function Kn(e,t){e=oe(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(Pn[e.app.options.appId],t).catch(e=>mn.error(e))}function Wn(e,t,n,r){e=oe(e),async function(e,t,n,r,i){var s;i&&i.global?e("event",n,r):(s=await t,e("event",n,Object.assign(Object.assign({},r),{send_to:s})))}(Fn,Pn[e.app.options.appId],t,n,r).catch(e=>mn.error(e))}const Gn="@firebase/analytics";Ge(new ce(hn,(e,{options:t})=>{return qn(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),Ge(new ce("analytics-internal",function(e){try{const r=e.getProvider(hn).getImmediate();return{logEvent:(e,t,n)=>Wn(r,e,t,n)}}catch(e){throw vn.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),tt(Gn,"0.10.0"),tt(Gn,"0.10.0","esm2017");var Hn,Qn;class Yn{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){Wn(this._delegate,e,t,n)}setCurrentScreen(e,t){Bn(this._delegate,e,t)}setUserId(e,t){zn(this._delegate,e,t)}setUserProperties(e,t){$n(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){Kn(this._delegate,e)}}(Kk=Hn=Hn||{}).ADD_SHIPPING_INFO="add_shipping_info",Kk.ADD_PAYMENT_INFO="add_payment_info",Kk.ADD_TO_CART="add_to_cart",Kk.ADD_TO_WISHLIST="add_to_wishlist",Kk.BEGIN_CHECKOUT="begin_checkout",Kk.CHECKOUT_PROGRESS="checkout_progress",Kk.EXCEPTION="exception",Kk.GENERATE_LEAD="generate_lead",Kk.LOGIN="login",Kk.PAGE_VIEW="page_view",Kk.PURCHASE="purchase",Kk.REFUND="refund",Kk.REMOVE_FROM_CART="remove_from_cart",Kk.SCREEN_VIEW="screen_view",Kk.SEARCH="search",Kk.SELECT_CONTENT="select_content",Kk.SELECT_ITEM="select_item",Kk.SELECT_PROMOTION="select_promotion",Kk.SET_CHECKOUT_OPTION="set_checkout_option",Kk.SHARE="share",Kk.SIGN_UP="sign_up",Kk.TIMING_COMPLETE="timing_complete",Kk.VIEW_CART="view_cart",Kk.VIEW_ITEM="view_item",Kk.VIEW_ITEM_LIST="view_item_list",Kk.VIEW_PROMOTION="view_promotion",Kk.VIEW_SEARCH_RESULTS="view_search_results";const Jn=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new Yn(t,n)};Qn={Analytics:Yn,settings:Vn,isSupported:jn,EventName:Hn},bt.INTERNAL.registerComponent(new ce("analytics-compat",Jn,"PUBLIC").setServiceProps(Qn).setMultipleInstances(!0)),bt.registerVersion("@firebase/analytics-compat","0.2.6");const Xn=new Map,Zn={activated:!1,tokenObservers:[]},er={initialized:!1,enabled:!1};function tr(e){return Xn.get(e)||Object.assign({},Zn)}const nr="https://content-firebaseappcheck.googleapis.com/v1",rr="exchangeDebugToken",ir={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class sr{constructor(e,t,n,r,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=n,this.lowerBound=r,this.upperBound=i,this.pending=null,i<(this.nextErrorWaitInterval=r))throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new y,t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new y,await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(e){this.retryPolicy(e)?this.process(!1).catch(()=>{}):this.stop()}var t}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();var t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}const ar=new D("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","recaptcha-error":"ReCAPTCHA error.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function or(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function cr(e){if(!tr(e).activated)throw ar.create("use-before-activation",{appName:e.name})}function lr(e){var t=Math.round(e/1e3),n=Math.floor(t/86400),r=Math.floor((t-3600*n*24)/3600),i=Math.floor((t-3600*n*24-3600*r)/60),t=t-3600*n*24-3600*r-60*i;let s="";return n&&(s+=ur(n)+"d:"),r&&(s+=ur(r)+"h:"),s+=ur(i)+"m:"+ur(t)+"s",s}function ur(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function hr({url:e,body:t},n){const r={"Content-Type":"application/json"},i=n.getImmediate({optional:!0});!i||(c=await i.getHeartbeatsHeader())&&(r["X-Firebase-Client"]=c);var s={method:"POST",body:JSON.stringify(t),headers:r};let a;try{a=await fetch(e,s)}catch(e){throw ar.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==a.status)throw ar.create("fetch-status-error",{httpStatus:a.status});let o;try{o=await a.json()}catch(e){throw ar.create("fetch-parse-error",{originalErrorMessage:null==e?void 0:e.message})}var c=o.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw ar.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration "+`format: ${o.ttl}`});s=1e3*Number(c[1]),c=Date.now();return{token:o.token,expireTimeMillis:c+s,issuedAtTimeMillis:c}}function dr(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${nr}/projects/${n}/apps/${r}:${rr}?key=${i}`,body:{debug_token:t}}}const pr="firebase-app-check-database",fr=1,gr="firebase-app-check-store",mr="debug-token";let vr=null;function _r(){return vr||(vr=new Promise((t,n)=>{try{const e=indexedDB.open(pr,fr);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(ar.create("storage-open",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(gr,{keyPath:"compositeKey"})}}catch(e){n(ar.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}),vr)}async function yr(e,t){const n=await _r(),r=n.transaction(gr,"readwrite"),i=r.objectStore(gr),s=i.put({compositeKey:e,value:t});return new Promise((t,n)=>{s.onsuccess=e=>{t()},r.onerror=e=>{var t;n(ar.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function wr(e){const t=await _r(),i=t.transaction(gr,"readonly"),n=i.objectStore(gr),s=n.get(e);return new Promise((n,r)=>{s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)},i.onerror=e=>{var t;r(ar.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function br(e){return`${e.options.appId}-${e.name}`}const Ir=new ve("@firebase/app-check");async function Tr(t){if(A()){let e=void 0;try{e=await wr(br(t))}catch(e){Ir.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function Er(e,t){return A()?yr(br(e),t).catch(e=>{Ir.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function Cr(){let e=void 0;try{e=await wr(mr)}catch(e){}if(e)return e;var t,n=ee();return t=n,yr(mr,t).catch(e=>Ir.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),n}function Sr(){return er.enabled}async function kr(){var e=er;if(e.enabled&&e.token)return e.token.promise;throw Error(`
|
|
7
|
+
`)}const bt=yt;tt("@firebase/app-compat","0.2.18",void 0);bt.registerVersion("firebase","10.3.1","app-compat");var It="@firebase/installations",Tt="0.6.4";const Et=1e4,Ct="w:0.6.4",kt="FIS_v2",St="https://firebaseinstallations.googleapis.com/v1",At=36e5;const Nt=new D("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Rt(e){return e instanceof P&&e.code.includes("request-failed")}function Pt({projectId:e}){return`${St}/projects/${e}/installations`}function Dt(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function xt(e,t){var n=(await t.json()).error;return Nt.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function Ot({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function Mt(e,{refreshToken:t}){const n=Ot(e);return n.append("Authorization",(t=t,`${kt} ${t}`)),n}async function Lt(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function Ft(t){return new Promise(e=>{setTimeout(e,t)})}const Ut=/^[cdef][\w-]{21}$/,Vt="";function qt(){try{const t=new Uint8Array(17),n=self.crypto||self.msCrypto;n.getRandomValues(t),t[0]=112+t[0]%16;var e=function(e){const t=function(e){const t=btoa(String.fromCharCode(...e));return t.replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(t);return Ut.test(e)?e:Vt}catch(e){return Vt}}function Bt(e){return`${e.appName}!${e.appId}`}const jt=new Map;function zt(e,t){var n=Bt(e);$t(n,t),function(e,t){const n=function(){!Kt&&"BroadcastChannel"in self&&(Kt=new BroadcastChannel("[Firebase] FID Change"),Kt.onmessage=e=>{$t(e.data.key,e.data.fid)});return Kt}();n&&n.postMessage({key:e,fid:t});0===jt.size&&Kt&&(Kt.close(),Kt=null)}(n,t)}function $t(e,t){var n=jt.get(e);if(n)for(const r of n)r(t)}let Kt=null;const Gt="firebase-installations-store";let Wt=null;function Ht(){return Wt=Wt||Pe("firebase-installations-database",1,{upgrade:(e,t)=>{0===t&&e.createObjectStore(Gt)}}),Wt}async function Qt(e,t){var n=Bt(e);const r=await Ht(),i=r.transaction(Gt,"readwrite"),s=i.objectStore(Gt);var a=await s.get(n);return await s.put(t,n),await i.done,a&&a.fid===t.fid||zt(e,t.fid),t}async function Yt(e){var t=Bt(e);const n=await Ht(),r=n.transaction(Gt,"readwrite");await r.objectStore(Gt).delete(t),await r.done}async function Jt(e,t){var n=Bt(e);const r=await Ht(),i=r.transaction(Gt,"readwrite"),s=i.objectStore(Gt);var a=await s.get(n),o=t(a);return void 0===o?await s.delete(n):await s.put(o,n),await i.done,!o||a&&a.fid===o.fid||zt(e,o.fid),o}async function Xt(n){let r;var e=await Jt(n.appConfig,e=>{var t=en(e||{fid:qt(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await Zt(e.appConfig);for(;1===t.registrationStatus;)await Ft(100),t=await Zt(e.appConfig);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await Xt(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(Nt.create("app-offline"));return{installationEntry:t,registrationPromise:n}}var r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(t,n){try{var e=await async function({appConfig:e,heartbeatServiceProvider:t},{fid:n}){const r=Pt(e),i=Ot(e),s=t.getImmediate({optional:!0});!s||(a=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",a);var a={fid:n,authVersion:kt,appId:e.appId,sdkVersion:Ct};const o={method:"POST",headers:i,body:JSON.stringify(a)},c=await Lt(()=>fetch(r,o));if(c.ok){a=await c.json();return{fid:a.fid||n,registrationStatus:2,refreshToken:a.refreshToken,authToken:Dt(a.authToken)}}throw await xt("Create Installation",c)}(t,n);return Qt(t.appConfig,e)}catch(e){throw Rt(e)&&409===e.customData.serverCode?await Yt(t.appConfig):await Qt(t.appConfig,{fid:n.fid,registrationStatus:0}),e}}(e,r);return{installationEntry:r,registrationPromise:n}}}(n,t);return r=t.registrationPromise,t.installationEntry});return e.fid===Vt?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function Zt(e){return Jt(e,e=>{if(!e)throw Nt.create("installation-not-found");return en(e)})}function en(e){return 1===(t=e).registrationStatus&&t.registrationTime+Et<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function tn({appConfig:e,heartbeatServiceProvider:t},n){const r=([i,s]=[e,n["fid"]],`${Pt(i)}/${s}/authTokens:generate`);var i,s;const a=Mt(e,n),o=t.getImmediate({optional:!0});!o||(c=await o.getHeartbeatsHeader())&&a.append("x-firebase-client",c);var c={installation:{sdkVersion:Ct,appId:e.appId}};const l={method:"POST",headers:a,body:JSON.stringify(c)},u=await Lt(()=>fetch(r,l));if(u.ok)return Dt(await u.json());throw await xt("Generate Auth Token",u)}async function nn(r,i=!1){let s;var e=await Jt(r.appConfig,e=>{if(!sn(e))throw Nt.create("not-registered");var t,n=e.authToken;if(i||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+At}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await rn(e.appConfig);for(;1===n.authToken.requestStatus;)await Ft(100),n=await rn(e.appConfig);var r=n.authToken;return 0===r.requestStatus?nn(e,t):r}(r,i),e;if(!navigator.onLine)throw Nt.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},t),{authToken:n}));return s=async function(t,n){try{var r=await tn(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await Qt(t.appConfig,e),r}catch(e){throw!Rt(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await Qt(t.appConfig,r)):await Yt(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function rn(e){return Jt(e,e=>{if(!sn(e))throw Nt.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+Et<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function sn(e){return void 0!==e&&2===e.registrationStatus}async function an(e,t=!1){var n,r=e;return await((n=(await Xt(r)).registrationPromise)&&await n),(await nn(r,t)).token}function on(e){return Nt.create("missing-app-config-values",{valueName:e})}const cn="installations",ln=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw on("App Configuration");if(!e.name)throw on("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw on(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),heartbeatServiceProvider:He(t,"heartbeat"),_delete:()=>Promise.resolve()}},un=e=>{const t=He(e.getProvider("app").getImmediate(),cn).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await Xt(t);return(r||nn(t)).catch(console.error),n.fid}(t),getToken:e=>an(t,e)}};We(new ce(cn,ln,"PUBLIC")),We(new ce("installations-internal",un,"PRIVATE")),tt(It,Tt),tt(It,Tt,"esm2017");const hn="analytics",dn="firebase_id",pn="origin",fn="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",gn="https://www.googletagmanager.com/gtag/js",mn=new ve("@firebase/analytics"),vn=new D("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id} already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.',"no-client-id":'The "client_id" field is empty.',"invalid-gtag-resource":"Trusted Types detected an invalid gtag resource: {$gtagURL}."});function _n(e){if(e.startsWith(gn))return e;var t=vn.create("invalid-gtag-resource",{gtagURL:e});return mn.warn(t.message),""}function yn(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function wn(e,t){const n=function(e,t){let n;return window.trustedTypes&&(n=window.trustedTypes.createPolicy(e,t)),n}("firebase-js-sdk-policy",{createScriptURL:_n}),r=document.createElement("script");var i=`${gn}?l=${e}&id=${t}`;r.src=n?null===n||void 0===n?void 0:n.createScriptURL(i):i,r.async=!0,document.head.appendChild(r)}function bn(h,d,p,f){return async function(e,...t){try{var n,r,i,s,a,o,c,l,u;"event"===e?([n,r]=t,await async function(e,n,r,i,s){try{let t=[];if(s&&s.send_to){let e=s.send_to;Array.isArray(e)||(e=[e]);const c=await yn(r);for(const l of e){var a=c.find(e=>e.measurementId===l),o=a&&n[a.appId];if(!o){t=[];break}t.push(o)}}0===t.length&&(t=Object.values(n)),await Promise.all(t),e("event",i,s||{})}catch(e){mn.error(e)}}(h,d,p,n,r)):"config"===e?([i,s]=t,await async function(e,t,n,r,i,s){var a=r[i];try{if(a)await t[a];else{const c=await yn(n);var o=c.find(e=>e.measurementId===i);o&&await t[o.appId]}}catch(e){mn.error(e)}e("config",i,s)}(h,d,p,f,i,s)):"consent"===e?([a]=t,h("consent","update",a)):"get"===e?([o,c,l]=t,h("get",o,c,l)):"set"===e?([u]=t,h("set",u)):h(e,...t)}catch(e){mn.error(e)}}}const In=30;const Tn=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};async function En(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=fn.replace("{app-id}",n);const i=await fetch(n,r);if(200===i.status||304===i.status)return i.json();{let e="";try{var s=await i.json();null!==(t=s.error)&&void 0!==t&&t.message&&(e=s.error.message)}catch(e){}throw vn.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function Cn(e,t=Tn,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw vn.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw vn.create("no-api-key")}var a=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const o=new An;return setTimeout(async()=>{o.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=Tn){var a;const{appId:o,measurementId:c}=n;try{await kn(i,e)}catch(e){if(c)return mn.warn("Timed out fetching this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${c}`+` provided in the "measurementId" field in the local Firebase config. [${null==e?void 0:e.message}]`),{appId:o,measurementId:c};throw e}try{const l=await En(n);return s.deleteThrottleMetadata(o),l}catch(e){const u=e;if(!Sn(u)){if(s.deleteThrottleMetadata(o),c)return mn.warn("Failed to fetch this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${c}`+` provided in the "measurementId" field in the local Firebase config. [${null===u||void 0===u?void 0:u.message}]`),{appId:o,measurementId:c};throw e}const h=503===Number(null===(a=null===u||void 0===u?void 0:u.customData)||void 0===a?void 0:a.httpStatus)?ae(r,s.intervalMillis,In):ae(r,s.intervalMillis),d={throttleEndTimeMillis:Date.now()+h,backoffCount:r+1};return s.setThrottleMetadata(o,d),mn.debug(`Calling attemptFetch again in ${h} millis`),t(n,d,i,s)}}({appId:r,apiKey:i,measurementId:s},a,o,t)}function kn(i,s){return new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(vn.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function Sn(e){if(!(e instanceof P&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class An{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function Nn(t,e,n,r,i,s,a){const o=Cn(t);o.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&mn.warn(`The measurement ID in the local Firebase config (${t.options.measurementId})`+` does not match the measurement ID fetched from the server (${e.measurementId}).`+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")}).catch(e=>mn.error(e)),e.push(o);var c=async function(){if(!A())return mn.warn(vn.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await N()}catch(e){return mn.warn(vn.create("indexeddb-unavailable",{errorInfo:null==e?void 0:e.toString()}).message),!1}return!0}().then(e=>{if(e)return r.getId()}),[l,u]=await Promise.all([o,c]);!function(e){var t=window.document.getElementsByTagName("script");for(const n of Object.values(t))if(n.src&&n.src.includes(gn)&&n.src.includes(e))return n}(s)&&wn(s,l.measurementId),i("js",new Date);const h=null!==(c=null==a?void 0:a.config)&&void 0!==c?c:{};return h[pn]="firebase",h.update=!0,null!=u&&(h[dn]=u),i("config",l.measurementId,h),l.measurementId}class Rn{constructor(e){this.app=e}_delete(){return delete Pn[this.app.options.appId],Promise.resolve()}}let Pn={},Dn=[];const xn={};let On="dataLayer",Mn="gtag",Ln,Fn,Un=!1;function Vn(e){if(Un)throw vn.create("already-initialized");e.dataLayerName&&(On=e.dataLayerName),e.gtagName&&(Mn=e.gtagName)}function qn(e,t,n){!function(){const e=[];var t;E()&&e.push("This is a browser extension environment."),R()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=vn.create("invalid-analytics-context",{errorInfo:t}),mn.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw vn.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw vn.create("no-api-key");mn.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest'+` measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId}`+' provided in the "measurementId" field in the local Firebase config.')}if(null!=Pn[s])throw vn.create("already-exists",{id:s});return Un||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(On),{wrappedGtag:r,gtagCore:i}=function(e,t,n,r,i){let s=function(){window[r].push(arguments)};return window[i]&&"function"==typeof window[i]&&(s=window[i]),window[i]=bn(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(Pn,Dn,xn,On,Mn),Fn=r,Ln=i,Un=!0),Pn[s]=Nn(e,Dn,xn,t,Ln,On,n),new Rn(e)}async function Bn(){if(E())return!1;if(!R())return!1;if(!A())return!1;try{return await N()}catch(e){return!1}}function jn(e,t,n){e=oe(e),async function(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(Fn,Pn[e.app.options.appId],t,n).catch(e=>mn.error(e))}function zn(e,t,n){e=oe(e),async function(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(Fn,Pn[e.app.options.appId],t,n).catch(e=>mn.error(e))}function $n(e,t,n){e=oe(e),async function(e,t,n,r){if(r&&r.global){const i={};for(const s of Object.keys(n))i[`user_properties.${s}`]=n[s];return e("set",i),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(Fn,Pn[e.app.options.appId],t,n).catch(e=>mn.error(e))}function Kn(e,t){e=oe(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(Pn[e.app.options.appId],t).catch(e=>mn.error(e))}function Gn(e,t,n,r){e=oe(e),async function(e,t,n,r,i){var s;i&&i.global?e("event",n,r):(s=await t,e("event",n,Object.assign(Object.assign({},r),{send_to:s})))}(Fn,Pn[e.app.options.appId],t,n,r).catch(e=>mn.error(e))}const Wn="@firebase/analytics";We(new ce(hn,(e,{options:t})=>{return qn(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),We(new ce("analytics-internal",function(e){try{const r=e.getProvider(hn).getImmediate();return{logEvent:(e,t,n)=>Gn(r,e,t,n)}}catch(e){throw vn.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),tt(Wn,"0.10.0"),tt(Wn,"0.10.0","esm2017");var Hn,Qn;class Yn{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){Gn(this._delegate,e,t,n)}setCurrentScreen(e,t){jn(this._delegate,e,t)}setUserId(e,t){zn(this._delegate,e,t)}setUserProperties(e,t){$n(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){Kn(this._delegate,e)}}(GS=Hn=Hn||{}).ADD_SHIPPING_INFO="add_shipping_info",GS.ADD_PAYMENT_INFO="add_payment_info",GS.ADD_TO_CART="add_to_cart",GS.ADD_TO_WISHLIST="add_to_wishlist",GS.BEGIN_CHECKOUT="begin_checkout",GS.CHECKOUT_PROGRESS="checkout_progress",GS.EXCEPTION="exception",GS.GENERATE_LEAD="generate_lead",GS.LOGIN="login",GS.PAGE_VIEW="page_view",GS.PURCHASE="purchase",GS.REFUND="refund",GS.REMOVE_FROM_CART="remove_from_cart",GS.SCREEN_VIEW="screen_view",GS.SEARCH="search",GS.SELECT_CONTENT="select_content",GS.SELECT_ITEM="select_item",GS.SELECT_PROMOTION="select_promotion",GS.SET_CHECKOUT_OPTION="set_checkout_option",GS.SHARE="share",GS.SIGN_UP="sign_up",GS.TIMING_COMPLETE="timing_complete",GS.VIEW_CART="view_cart",GS.VIEW_ITEM="view_item",GS.VIEW_ITEM_LIST="view_item_list",GS.VIEW_PROMOTION="view_promotion",GS.VIEW_SEARCH_RESULTS="view_search_results";const Jn=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new Yn(t,n)};Qn={Analytics:Yn,settings:Vn,isSupported:Bn,EventName:Hn},bt.INTERNAL.registerComponent(new ce("analytics-compat",Jn,"PUBLIC").setServiceProps(Qn).setMultipleInstances(!0)),bt.registerVersion("@firebase/analytics-compat","0.2.6");const Xn=new Map,Zn={activated:!1,tokenObservers:[]},er={initialized:!1,enabled:!1};function tr(e){return Xn.get(e)||Object.assign({},Zn)}const nr="https://content-firebaseappcheck.googleapis.com/v1",rr="exchangeDebugToken",ir={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class sr{constructor(e,t,n,r,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=n,this.lowerBound=r,this.upperBound=i,this.pending=null,i<(this.nextErrorWaitInterval=r))throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new y,t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new y,await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(e){this.retryPolicy(e)?this.process(!1).catch(()=>{}):this.stop()}var t}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();var t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}const ar=new D("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","recaptcha-error":"ReCAPTCHA error.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function or(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function cr(e){if(!tr(e).activated)throw ar.create("use-before-activation",{appName:e.name})}function lr(e){var t=Math.round(e/1e3),n=Math.floor(t/86400),r=Math.floor((t-3600*n*24)/3600),i=Math.floor((t-3600*n*24-3600*r)/60),t=t-3600*n*24-3600*r-60*i;let s="";return n&&(s+=ur(n)+"d:"),r&&(s+=ur(r)+"h:"),s+=ur(i)+"m:"+ur(t)+"s",s}function ur(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function hr({url:e,body:t},n){const r={"Content-Type":"application/json"},i=n.getImmediate({optional:!0});!i||(c=await i.getHeartbeatsHeader())&&(r["X-Firebase-Client"]=c);var s={method:"POST",body:JSON.stringify(t),headers:r};let a;try{a=await fetch(e,s)}catch(e){throw ar.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==a.status)throw ar.create("fetch-status-error",{httpStatus:a.status});let o;try{o=await a.json()}catch(e){throw ar.create("fetch-parse-error",{originalErrorMessage:null==e?void 0:e.message})}var c=o.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw ar.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration "+`format: ${o.ttl}`});s=1e3*Number(c[1]),c=Date.now();return{token:o.token,expireTimeMillis:c+s,issuedAtTimeMillis:c}}function dr(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${nr}/projects/${n}/apps/${r}:${rr}?key=${i}`,body:{debug_token:t}}}const pr="firebase-app-check-database",fr=1,gr="firebase-app-check-store",mr="debug-token";let vr=null;function _r(){return vr||(vr=new Promise((t,n)=>{try{const e=indexedDB.open(pr,fr);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(ar.create("storage-open",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(gr,{keyPath:"compositeKey"})}}catch(e){n(ar.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}),vr)}async function yr(e,t){const n=await _r(),r=n.transaction(gr,"readwrite"),i=r.objectStore(gr),s=i.put({compositeKey:e,value:t});return new Promise((t,n)=>{s.onsuccess=e=>{t()},r.onerror=e=>{var t;n(ar.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function wr(e){const t=await _r(),i=t.transaction(gr,"readonly"),n=i.objectStore(gr),s=n.get(e);return new Promise((n,r)=>{s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)},i.onerror=e=>{var t;r(ar.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function br(e){return`${e.options.appId}-${e.name}`}const Ir=new ve("@firebase/app-check");async function Tr(t){if(A()){let e=void 0;try{e=await wr(br(t))}catch(e){Ir.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function Er(e,t){return A()?yr(br(e),t).catch(e=>{Ir.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function Cr(){let e=void 0;try{e=await wr(mr)}catch(e){}if(e)return e;var t,n=ee();return t=n,yr(mr,t).catch(e=>Ir.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),n}function kr(){return er.enabled}async function Sr(){var e=er;if(e.enabled&&e.token)return e.token.promise;throw Error(`
|
|
8
8
|
Can't get debug token in production mode.
|
|
9
|
-
`)}const Ar={error:"UNKNOWN_ERROR"};async function Nr(e,t=!1){var n=e.app;cr(n);const r=tr(n);let i=r.token,s=void 0;if(i&&!Or(i)&&(r.token=void 0,i=void 0),i||(o=await r.cachedTokenPromise)&&(Or(o)?i=o:await Er(n,void 0)),!t&&i&&Or(i))return{token:i.token};let a=!1;if(Sr()){r.exchangeTokenPromise||(r.exchangeTokenPromise=hr(dr(n,await kr()),e.heartbeatServiceProvider).finally(()=>{r.exchangeTokenPromise=void 0}),a=!0);var o=await r.exchangeTokenPromise;return await Er(n,o),{token:(r.token=o).token}}try{r.exchangeTokenPromise||(r.exchangeTokenPromise=r.provider.getToken().finally(()=>{r.exchangeTokenPromise=void 0}),a=!0),i=await tr(n).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?Ir.warn(e.message):Ir.error(e),s=e}let c;return i?s?c=Or(i)?{token:i.token,internalError:s}:Mr(s):(c={token:i.token},r.token=i,await Er(n,i)):c=Mr(s),a&&xr(n,c),c}function Rr(e,t,n,r){var i=e["app"];const s=tr(i);i={next:n,error:r,type:t};if(s.tokenObservers=[...s.tokenObservers,i],s.token&&Or(s.token)){const a=s.token;Promise.resolve().then(()=>{n({token:a.token}),Dr(e)}).catch(()=>{})}s.cachedTokenPromise.then(()=>Dr(e))}function Pr(e,t){const n=tr(e);var r=n.tokenObservers.filter(e=>e.next!==t);0===r.length&&n.tokenRefresher&&n.tokenRefresher.isRunning()&&n.tokenRefresher.stop(),n.tokenObservers=r}function Dr(e){var t=e["app"];const n=tr(t);let r=n.tokenRefresher;r||(r=function(n){const r=n["app"];return new sr(async()=>{var e=tr(r);let t;if(t=e.token?await Nr(n,!0):await Nr(n),t.error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e=tr(r);if(e.token){var t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5,e=e.token.expireTimeMillis-3e5,t=Math.min(t,e);return Math.max(0,t-Date.now())}return 0},ir.RETRIAL_MIN_WAIT,ir.RETRIAL_MAX_WAIT)}(e),n.tokenRefresher=r),!r.isRunning()&&n.isTokenAutoRefreshEnabled&&r.start()}function xr(e,t){for(const n of tr(e).tokenObservers)try{"EXTERNAL"===n.type&&null!=t.error?n.error(t.error):n.next(t)}catch(e){}}function Or(e){return 0<e.expireTimeMillis-Date.now()}function Mr(e){return{token:(t=Ar,r.encodeString(JSON.stringify(t),!1)),error:e};var t}class Lr{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e=tr(this.app)["tokenObservers"];for(const t of e)Pr(this.app,t.next);return Promise.resolve()}}function Fr(t){return{getToken:e=>Nr(t,e),getLimitedUseToken:()=>async function(e){var t=e.app;cr(t);const n=tr(t)["provider"];if(Sr()){var r=(await hr(dr(t,await kr()),e.heartbeatServiceProvider))["token"];return{token:r}}return{token:r=(await n.getToken())["token"]}}(t),addTokenListener:e=>Rr(t,"INTERNAL",e),removeTokenListener:e=>Pr(t.app,e)}}const Ur="https://www.google.com/recaptcha/api.js",Vr="https://www.google.com/recaptcha/enterprise.js";function qr(t,n){const r=new y,e=tr(t);e.reCAPTCHAState={initialized:r};const i=zr(t);var s=or(!1);return s?Br(t,n,s,i,r):function(e){const t=document.createElement("script");t.src=Ur,t.onload=e,document.head.appendChild(t)}(()=>{var e=or(!1);if(!e)throw new Error("no recaptcha");Br(t,n,e,i,r)}),r.promise}function jr(t,n){const r=new y,e=tr(t);e.reCAPTCHAState={initialized:r};const i=zr(t);var s=or(!0);return s?Br(t,n,s,i,r):function(e){const t=document.createElement("script");t.src=Vr,t.onload=e,document.head.appendChild(t)}(()=>{var e=or(!0);if(!e)throw new Error("no recaptcha");Br(t,n,e,i,r)}),r.promise}function Br(e,t,n,r,i){n.ready(()=>{!function(e,t,n,r){const i=n.render(r,{sitekey:t,size:"invisible",callback:()=>{tr(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{tr(e).reCAPTCHAState.succeeded=!1}}),s=tr(e);s.reCAPTCHAState=Object.assign(Object.assign({},s.reCAPTCHAState),{widgetId:i})}(e,t,n,r),i.resolve(n)})}function zr(e){var t=`fire_app_check_${e.name}`;const n=document.createElement("div");return n.id=t,n.style.display="none",document.body.appendChild(n),t}async function $r(r){cr(r);const i=await tr(r).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const n=tr(r).reCAPTCHAState;i.ready(()=>{e(i.execute(n.widgetId,{action:"fire_app_check"}))})})}class Kr{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;Qr(this._throttleData);var t=await $r(this._app).catch(e=>{throw ar.create("recaptcha-error")});if(null===(e=tr(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw ar.create("recaptcha-error");let n;try{n=await hr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${nr}/projects/${n}/apps/${r}:exchangeRecaptchaV3Token?key=${i}`,body:{recaptcha_v3_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=Hr(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),ar.create("throttled",{time:lr(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,n}initialize(e){this._app=e,this._heartbeatServiceProvider=He(e,"heartbeat"),qr(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Kr&&this._siteKey===e._siteKey}}class Wr{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;Qr(this._throttleData);var t=await $r(this._app).catch(e=>{throw ar.create("recaptcha-error")});if(null===(e=tr(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw ar.create("recaptcha-error");let n;try{n=await hr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${nr}/projects/${n}/apps/${r}:exchangeRecaptchaEnterpriseToken?key=${i}`,body:{recaptcha_enterprise_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=Hr(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),ar.create("throttled",{time:lr(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,n}initialize(e){this._app=e,this._heartbeatServiceProvider=He(e,"heartbeat"),jr(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Wr&&this._siteKey===e._siteKey}}class Gr{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=function(e){const t=L(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null}(e.token),t=null!==t&&t<Date.now()&&0<t?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:t})}initialize(e){this._app=e}isEqual(e){return e instanceof Gr&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function Hr(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var n=t?t.backoffCount:0,r=ae(n,1e3,2);return{backoffCount:n+1,allowRequestsAfter:Date.now()+r,httpStatus:e}}function Qr(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw ar.create("throttled",{time:lr(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function Yr(e=Ze(),t){const n=He(e=oe(e),"app-check");if(er.initialized||function(){var e=o();const t=er;if(t.initialized=!0,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN||!0===e.FIREBASE_APPCHECK_DEBUG_TOKEN){t.enabled=!0;const n=new y;t.token=n,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?n.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):n.resolve(Cr())}}(),Sr()&&kr().then(e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)),n.isInitialized()){var r=n.getImmediate();const i=n.getOptions();if(i.isTokenAutoRefreshEnabled===t.isTokenAutoRefreshEnabled&&i.provider.isEqual(t.provider))return r;throw ar.create("already-initialized",{appName:e.name})}r=n.initialize({options:t});return function(t,e,n){const r=function(e,t){return Xn.set(e,t),Xn.get(e)}(t,Object.assign({},Zn));r.activated=!0,r.provider=e,r.cachedTokenPromise=Tr(t).then(e=>(e&&Or(e)&&(r.token=e,xr(t,{token:e.token})),e)),r.isTokenAutoRefreshEnabled=void 0===n?t.automaticDataCollectionEnabled:n,r.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),tr(e).isTokenAutoRefreshEnabled&&Rr(r,"INTERNAL",()=>{}),r}const Jr="app-check-internal";Ge(new ce("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat");return t=n,e=r,new Lr(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(Jr).initialize()})),Ge(new ce(Jr,e=>{return Fr(e.getProvider("app-check").getImmediate())},"PUBLIC").setInstantiationMode("EXPLICIT")),tt("@firebase/app-check","0.8.0");const Xr=new D("appCheck","AppCheck",{"use-before-activation":"App Check is being used before activate() is called for FirebaseApp {$appName}. Call activate() before instantiating other Firebase services."});class Zr{constructor(e){this.app=e}activate(e,t){let n;n="string"==typeof e?new Kr(e):e instanceof Wr||e instanceof Kr||e instanceof Gr?e:new Gr({getToken:e.getToken}),this._delegate=Yr(this.app,{provider:n,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw Xr.create("use-before-activation",{appName:this.app.name});!function(e,t){const n=tr(e.app);n.tokenRefresher&&(!0===t?n.tokenRefresher.start():n.tokenRefresher.stop()),n.isTokenAutoRefreshEnabled=t}(this._delegate,e)}getToken(e){if(!this._delegate)throw Xr.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await Nr(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw Xr.create("use-before-activation",{appName:this.app.name});return function(e,t,n){let r=()=>{},i=()=>{};return r=null!=t.next?t.next.bind(t):t,null!=t.error?i=t.error.bind(t):n&&(i=n),Rr(e,"EXTERNAL",r,i),()=>Pr(e.app,r)}(this._delegate,e,t)}}const ei=e=>{var t=e.getProvider("app-compat").getImmediate();return new Zr(t)};function ti(e,t){var n={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}bt.INTERNAL.registerComponent(new ce("appCheck-compat",ei,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:Wr,ReCaptchaV3Provider:Kr,CustomProvider:Gr})),bt.registerVersion("@firebase/app-check-compat","0.3.7");const ni={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},ri={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function ii(e){return void 0!==e&&void 0!==e.getResponse}function si(e){return void 0!==e&&void 0!==e.enterprise}class ai{constructor(e){if(this.siteKey="",this.emailPasswordEnabled=!1,void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.emailPasswordEnabled=e.recaptchaEnforcementState.some(e=>"EMAIL_PASSWORD_PROVIDER"===e.provider&&"OFF"!==e.enforcementState)}}function oi(){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."}}function ci(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend.","unsupported-password-policy-schema-version":"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.","password-does-not-meet-requirements":"The password does not meet the requirements."}}const li=oi,ui=new D("auth","Firebase",oi()),hi=new ve("@firebase/auth");function di(e,...t){hi.logLevel<=m.ERROR&&hi.error(`Auth (${Je}): ${e}`,...t)}function pi(e,...t){throw vi(e,...t)}function fi(e,...t){return vi(e,...t)}function gi(e,t,n){var r=Object.assign(Object.assign({},li()),{[t]:n});const i=new D("auth","Firebase",r);return i.create(t,{appName:e.name})}function mi(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&pi(e,"argument-error"),gi(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function vi(e,...t){if("string"==typeof e)return ui.create(e,...t);{var n=t[0];const r=[...t.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(n,...r)}}function _i(e,t,...n){if(!e)throw vi(t,...n)}function yi(e){var t="INTERNAL ASSERTION FAILED: "+e;throw di(t),new Error(t)}function wi(e,t){e||yi(t)}function bi(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Ii(){return"http:"===Ti()||"https:"===Ti()}function Ti(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Ei{constructor(e,t){wi((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=I()||C()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(Ii()||E()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function Ci(e,t){wi(e.emulator,"Emulator should always be set here");var n=e.emulator["url"];return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class Si{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:void yi("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static headers(){return this.headersImpl||("undefined"!=typeof self&&"Headers"in self?self.Headers:void yi("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static response(){return this.responseImpl||("undefined"!=typeof self&&"Response"in self?self.Response:void yi("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}const ki={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",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},Ai=new Ei(3e4,6e4);function Ni(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function Ri(i,s,a,o,e={}){return Pi(i,e,async()=>{let e={},t={};o&&("GET"===s?t=o:e={body:JSON.stringify(o)});var n=z(Object.assign({key:i.config.apiKey},t)).slice(1);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/json",i.languageCode&&(r["X-Firebase-Locale"]=i.languageCode),Si.fetch()(xi(i,i.config.apiHost,a,n),Object.assign({method:s,headers:r,referrerPolicy:"no-referrer"},e))})}async function Pi(t,e,n){t._canInitEmulator=!1;var r=Object.assign(Object.assign({},ki),e);try{const a=new Oi(t),o=await Promise.race([n(),a.promise]);a.clearNetworkTimeout();var i=await o.json();if("needConfirmation"in i)throw Mi(t,"account-exists-with-different-credential",i);if(o.ok&&!("errorMessage"in i))return i;{const c=o.ok?i.errorMessage:i.error.message,[l,u]=c.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===l)throw Mi(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===l)throw Mi(t,"email-already-in-use",i);if("USER_DISABLED"===l)throw Mi(t,"user-disabled",i);var s=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw gi(t,s,u);pi(t,s)}}catch(e){if(e instanceof P)throw e;pi(t,"network-request-failed",{message:String(e)})}}async function Di(e,t,n,r,i={}){var s=await Ri(e,t,n,r,i);return"mfaPendingCredential"in s&&pi(e,"multi-factor-auth-required",{_serverResponse:s}),s}function xi(e,t,n,r){var i=`${t}${n}?${r}`;return e.config.emulator?Ci(e.config,i):`${e.config.apiScheme}://${i}`}class Oi{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(fi(this.auth,"network-request-failed")),Ai.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function Mi(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=fi(e,t,r);return i.customData._tokenResponse=n,i}function Li(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Fi(e){return 1e3*Number(e)}function Ui(e){var[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return di("JWT malformed, contained fewer than 3 sections"),null;try{var i=a(n);return i?JSON.parse(i):(di("Failed to decode base64 JWT payload"),null)}catch(e){return di("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}async function Vi(t,n,e=!1){if(e)return n;try{return n}catch(e){throw e instanceof P&&(n=[e["code"]][0],"auth/user-disabled"===n||"auth/user-token-expired"===n)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class qi{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){if(e){var t=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t}this.errorBackoff=3e4;t=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,t)}schedule(e=!1){var t;this.isRunning&&(t=this.getInterval(e),this.timerId=setTimeout(async()=>{await this.iteration()},t))}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===(null==e?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class ji{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Li(this.lastLoginAt),this.creationTime=Li(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Bi(e){var t=e.auth,n=await e.getIdToken(),r=await Vi(e,async function(e,t){return Ri(e,"POST","/v1/accounts:lookup",t)}(t,{idToken:n}));_i(null==r?void 0:r.users.length,t,"internal-error");var i=r.users[0];e._notifyReloadListener(i);var s,a,t=null!==(n=i.providerUserInfo)&&void 0!==n&&n.length?i.providerUserInfo.map(e=>{var t=e["providerId"],n=ti(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}}):[],r=(s=e.providerData,a=t,[...s.filter(t=>!a.some(e=>e.providerId===t.providerId)),...a]),n=e.isAnonymous,t=!(e.email&&i.passwordHash||null!==r&&r.length),t=!!n&&t,t={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 ji(i.createdAt,i.lastLoginAt),isAnonymous:t};Object.assign(e,t)}class zi{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){_i(e.idToken,"internal-error"),_i(void 0!==e.idToken,"internal-error"),_i(void 0!==e.refreshToken,"internal-error");var t,n,n="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):(t=e.idToken,_i(n=Ui(t),"internal-error"),_i(void 0!==n.exp,"internal-error"),_i(void 0!==n.iat,"internal-error"),Number(n.exp)-Number(n.iat));this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}async getToken(e,t=!1){return _i(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){var i,s,{accessToken:n,refreshToken:r,expiresIn:a}=(s=t,await{accessToken:(a=await Pi(i=e,{},async()=>{var e=z({grant_type:"refresh_token",refresh_token:s}).slice(1),{tokenApiHost:t,apiKey:n}=i.config,n=xi(i,t,"/v1/token",`key=${n}`);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",Si.fetch()(n,{method:"POST",headers:r,body:e})})).access_token,expiresIn:a.expires_in,refreshToken:a.refresh_token});this.updateTokensAndExpiration(n,r,Number(a))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){var{refreshToken:n,accessToken:r,expirationTime:i}=t;const s=new zi;return n&&(_i("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(_i("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(_i("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new zi,this.toJSON())}_performRefresh(){return yi("not implemented")}}function $i(e,t){_i("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Ki{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=ti(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new qi(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new ji(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await Vi(this,this.stsTokenManager.getToken(this.auth,e));return _i(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return async function(e,t=!1){const n=oe(e);var r=await n.getIdToken(t),i=Ui(r);_i(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");var s="object"==typeof i.firebase?i.firebase:void 0,a=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:Li(Fi(i.auth_time)),issuedAtTime:Li(Fi(i.iat)),expirationTime:Li(Fi(i.exp)),signInProvider:a||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=oe(e);await Bi(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(_i(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){const t=new Ki(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){_i(!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 Bi(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e=await this.getIdToken();return await Vi(this,async function(e,t){return Ri(e,"POST","/v1/accounts:delete",t)}(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,isAnonymous: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=null!==(a=t.displayName)&&void 0!==a?a:void 0,r=null!==(g=t.email)&&void 0!==g?g:void 0,i=null!==(o=t.phoneNumber)&&void 0!==o?o:void 0,s=null!==(l=t.photoURL)&&void 0!==l?l:void 0,a=null!==(c=t.tenantId)&&void 0!==c?c:void 0,o=null!==(g=t._redirectEventId)&&void 0!==g?g:void 0,c=null!==(l=t.createdAt)&&void 0!==l?l:void 0,l=null!==(g=t.lastLoginAt)&&void 0!==g?g:void 0;const{uid:u,emailVerified:h,isAnonymous:d,providerData:p,stsTokenManager:f}=t;_i(u&&f,e,"internal-error");var g=zi.fromJSON(this.name,f);_i("string"==typeof u,e,"internal-error"),$i(n,e.name),$i(r,e.name),_i("boolean"==typeof h,e,"internal-error"),_i("boolean"==typeof d,e,"internal-error"),$i(i,e.name),$i(s,e.name),$i(a,e.name),$i(o,e.name),$i(c,e.name),$i(l,e.name);const m=new Ki({uid:u,auth:e,email:r,emailVerified:h,displayName:n,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:a,stsTokenManager:g,createdAt:c,lastLoginAt:l});return p&&Array.isArray(p)&&(m.providerData=p.map(e=>Object.assign({},e))),o&&(m._redirectEventId=o),m}static async _fromIdTokenResponse(e,t,n=!1){const r=new zi;r.updateFromServerResponse(t);var i=new Ki({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await Bi(i),i}}const Wi=new Map;function Gi(e){wi(e instanceof Function,"Expected a class definition");let t=Wi.get(e);return t?wi(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Wi.set(e,t)),t}class Hi{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){var t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Hi.type="NONE";const Qi=Hi;function Yi(e,t,n){return`firebase:${e}:${t}:${n}`}class Ji{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;var{config:r,name:i}=this.auth;this.fullUserKey=Yi(this.userKey,r.apiKey,i),this.fullPersistenceKey=Yi("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){var e=await this.persistence._get(this.fullUserKey);return e?Ki._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){var t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length)return new Ji(Gi(Qi),e,n);const r=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let i=r[0]||Gi(Qi);const s=Yi(n,e.config.apiKey,e.name);let a=null;for(const u of t)try{var o=await u._get(s);if(o){var c=Ki._fromJSON(e,o);u!==i&&(a=c),i=u;break}}catch(e){}var l=r.filter(e=>e._shouldAllowMigration);return i._shouldAllowMigration&&l.length&&(i=l[0],a&&await i._set(s,a.toJSON()),await Promise.all(t.map(async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new Ji(i,e,n)}}function Xi(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(ns(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(Zi(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(is(t))return"Blackberry";if(ss(t))return"Webos";if(es(t))return"Safari";if((t.includes("chrome/")||ts(t))&&!t.includes("edge/"))return"Chrome";if(rs(t))return"Android";var n=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);return 2===(null==n?void 0:n.length)?n[1]:"Other"}function Zi(e=b()){return/firefox\//i.test(e)}function es(e=b()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function ts(e=b()){return/crios\//i.test(e)}function ns(e=b()){return/iemobile/i.test(e)}function rs(e=b()){return/android/i.test(e)}function is(e=b()){return/blackberry/i.test(e)}function ss(e=b()){return/webos/i.test(e)}function as(e=b()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function os(e=b()){return as(e)||rs(e)||ss(e)||is(e)||/windows phone/i.test(e)||ns(e)}function cs(e,t=[]){let n;switch(e){case"Browser":n=Xi(b());break;case"Worker":n=`${Xi(b())}-${e}`;break;default:n=e}var r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${Je}/${r}`}class ls{constructor(e){this.auth=e,this.queue=[]}pushCallback(r,e){var t=n=>new Promise((e,t)=>{try{e(r(n))}catch(e){t(e)}});t.onAbort=e,this.queue.push(t);const n=this.queue.length-1;return()=>{this.queue[n]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser!==e){const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){t.reverse();for(const r of t)try{r()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==e?void 0:e.message})}}}}class us{constructor(e){var t,n=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(t=n.minPasswordLength)&&void 0!==t?t:6,n.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=n.maxPasswordLength),void 0!==n.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=n.containsLowercaseCharacter),void 0!==n.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=n.containsUppercaseCharacter),void 0!==n.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=n.containsNumericCharacter),void 0!==n.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=n.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!==(n=null===(n=e.allowedNonAlphanumericCharacters)||void 0===n?void 0:n.join(""))&&void 0!==n?n:"",this.forceUpgradeOnSignin=null!==(n=e.forceUpgradeOnSignin)&&void 0!==n&&n,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,n,r;const i={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,i),this.validatePasswordCharacterOptions(e,i),i.isValid&&(i.isValid=null===(t=i.meetsMinPasswordLength)||void 0===t||t),i.isValid&&(i.isValid=null===(t=i.meetsMaxPasswordLength)||void 0===t||t),i.isValid&&(i.isValid=null===(n=i.containsLowercaseLetter)||void 0===n||n),i.isValid&&(i.isValid=null===(n=i.containsUppercaseLetter)||void 0===n||n),i.isValid&&(i.isValid=null===(r=i.containsNumericCharacter)||void 0===r||r),i.isValid&&(i.isValid=null===(r=i.containsNonAlphanumericCharacter)||void 0===r||r),i}validatePasswordLengthOptions(e,t){var n=this.customStrengthOptions.minPasswordLength,r=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),r&&(t.meetsMaxPasswordLength=e.length<=r)}validatePasswordCharacterOptions(e,t){var n;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let r=0;r<e.length;r++)n=e.charAt(r),this.updatePasswordCharacterOptionsStatuses(t,"a"<=n&&n<="z","A"<=n&&n<="Z","0"<=n&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,r,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=r)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class hs{constructor(e,t,n,r){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=r,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new ps(this),this.idTokenSubscription=new ps(this),this.beforeStateQueue=new ls(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=ui,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=r.sdkClientVersion}_initializeWithPersistence(t,n){return n&&(this._popupRedirectResolver=Gi(n)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await Ji.create(this,t),!this._deleted)){if(null!==(e=this._popupRedirectResolver)&&void 0!==e&&e._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(n),this.lastNotifiedUid=(null===(e=this.currentUser)||void 0===e?void 0:e.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(!this._deleted){var e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e)return this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0)}}async initializeCurrentUser(e){var t,n,r,i=await this.assertedPersistence.getCurrentUser();let s=i,a=!1;if(e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=null===(r=this.redirectUser)||void 0===r?void 0:r._redirectEventId,n=null===s||void 0===s?void 0:s._redirectEventId,r=await this.tryRedirectSignIn(e),t&&t!==n||null==r||!r.user||(s=r.user,a=!0)),!s)return this.directlySetCurrentUser(null);if(s._redirectEventId)return _i(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===s._redirectEventId?this.directlySetCurrentUser(s):this.reloadAndSetCurrentUserOrClear(s);if(a)try{await this.beforeStateQueue.runMiddleware(s)}catch(e){s=i,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return s?this.reloadAndSetCurrentUserOrClear(s):this.directlySetCurrentUser(null)}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 Bi(e)}catch(e){if("auth/network-request-failed"!==(null==e?void 0:e.code))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;var e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?oe(e):null;return t&&_i(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&&_i(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 await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0)}setPersistence(e){return this.queue(async()=>{await this.assertedPersistence.setPersistence(Gi(e))})}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const 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(){var e,t=await Ri(e=this,"GET","/v2/passwordPolicy",Ni(e,{})),t=new us(t);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new D("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{const n=this.onAuthStateChanged(()=>{n(),e()},t)}})}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(_i(t=e&&Gi(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await Ji.create(this,[Gi(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){var t;return this._isInitialized&&await this.queue(async()=>{}),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(t=this.redirectUser)||void 0===t?void 0:t._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;this._isInitialized&&(this.idTokenSubscription.next(this.currentUser),e=null!==(e=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==e?e:null,this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser)))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t);let s=!1;const a=this._isInitialized?Promise.resolve():this._initializationPromise;if(_i(a,this,"internal-error"),a.then(()=>{s||i(this.currentUser)}),"function"==typeof t){const o=e.addObserver(t,n,r);return()=>{s=!0,o()}}{const c=e.addObserver(t);return()=>{s=!0,c()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),(this.currentUser=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 _i(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=cs(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);var t=await(null===(t=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===t?void 0:t.getHeartbeatsHeader());t&&(e["X-Firebase-Client"]=t);t=await this._getAppCheckToken();return t&&(e["X-Firebase-AppCheck"]=t),e}async _getAppCheckToken(){var e,t,n=await(null===(n=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===n?void 0:n.getToken());return null!=n&&n.error&&(e=`Error while retrieving App Check token: ${n.error}`,t=[],hi.logLevel<=m.WARN&&hi.warn(`Auth (${Je}): ${e}`,...t)),null==n?void 0:n.token}}function ds(e){return oe(e)}class ps{constructor(e){this.auth=e,this.observer=null,this.addObserver=G(e=>this.observer=e)}get next(){return _i(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function fs(i){return new Promise((e,n)=>{const t=document.createElement("script");var r;t.setAttribute("src",i),t.onload=e,t.onerror=e=>{const t=fi("internal-error");t.customData=e,n(t)},t.type="text/javascript",t.charset="UTF-8",(null!==(r=null===(r=document.getElementsByTagName("head"))||void 0===r?void 0:r[0])&&void 0!==r?r:document).appendChild(t)})}function gs(e){return`__${e}${Math.floor(1e6*Math.random())}`}class ms{constructor(e){this.type="recaptcha-enterprise",this.auth=ds(e)}async verify(i="verify",r=!1){async function e(i){if(!r){if(null==i.tenantId&&null!=i._agentRecaptchaConfig)return i._agentRecaptchaConfig.siteKey;if(null!=i.tenantId&&void 0!==i._tenantRecaptchaConfigs[i.tenantId])return i._tenantRecaptchaConfigs[i.tenantId].siteKey}return new Promise(async(n,r)=>{!async function(e,t){return Ri(e,"GET","/v2/recaptchaConfig",Ni(e,t))}(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(e=>{if(void 0!==e.recaptchaKey){var t=new ai(e);return null==i.tenantId?i._agentRecaptchaConfig=t:i._tenantRecaptchaConfigs[i.tenantId]=t,n(t.siteKey)}r(new Error("recaptcha Enterprise site key undefined"))}).catch(e=>{r(e)})})}function s(e,t,n){const r=window.grecaptcha;si(r)?r.enterprise.ready(()=>{r.enterprise.execute(e,{action:i}).then(e=>{t(e)}).catch(()=>{t("NO_RECAPTCHA")})}):n(Error("No reCAPTCHA enterprise script loaded."))}return new Promise((t,n)=>{e(this.auth).then(e=>{!r&&si(window.grecaptcha)?s(e,t,n):"undefined"!=typeof window?fs("https://www.google.com/recaptcha/enterprise.js?render="+e).then(()=>{s(e,t,n)}).catch(e=>{n(e)}):n(new Error("RecaptchaVerifier is only supported in browser"))}).catch(e=>{n(e)})})}}async function vs(e,t,n,r=!1){const i=new ms(e);let s;try{s=await i.verify(n)}catch(e){s=await i.verify(n,!0)}var a=Object.assign({},t);return r?Object.assign(a,{captchaResp:s}):Object.assign(a,{captchaResponse:s}),Object.assign(a,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(a,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),a}function _s(e,t,n){const r=ds(e);_i(r._canInitEmulator,r,"emulator-config-failed"),_i(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");var i=!(null==n||!n.disableWarnings);const s=ys(t);var{host:a,port:o}=function(e){const t=ys(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);{if(i){var s=i[1];return{host:s,port:ws(r.substr(s.length+1))}}var[a,s]=r.split(":");return{host:a,port:ws(s)}}}(t);r.config.emulator={url:`${s}//${a}${null===o?"":`:${o}`}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const 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)}"undefined"!=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.");"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}function ys(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function ws(e){if(!e)return null;var t=Number(e);return isNaN(t)?null:t}class bs{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return yi("not implemented")}_getIdTokenResponse(e){return yi("not implemented")}_linkToIdToken(e,t){return yi("not implemented")}_getReauthenticationResolver(e){return yi("not implemented")}}async function Is(e,t){return Ri(e,"POST","/v1/accounts:resetPassword",Ni(e,t))}async function Ts(e,t){return Ri(e,"POST","/v1/accounts:update",t)}async function Es(e,t){return Di(e,"POST","/v1/accounts:signInWithPassword",Ni(e,t))}async function Cs(e,t){return Ri(e,"POST","/v1/accounts:sendOobCode",Ni(e,t))}async function Ss(e,t){return Cs(e,t)}async function ks(e,t){return Cs(e,t)}class As extends bs{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new As(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new As(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e;if(null!=t&&t.email&&null!=t&&t.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(n){switch(this.signInMethod){case"password":const r={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};if(null!==(e=n._getRecaptchaConfig())&&void 0!==e&&e.emailPasswordEnabled){var e=await vs(n,r,"signInWithPassword");return Es(n,e)}return Es(n,r).catch(async e=>{if("auth/missing-recaptcha-token"!==e.code)return Promise.reject(e);console.log("Sign-in with email address and password is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.");var t=await vs(n,r,"signInWithPassword");return Es(n,t)});case"emailLink":return async function(e,t){return Di(e,"POST","/v1/accounts:signInWithEmailLink",Ni(e,t))}(n,{email:this._email,oobCode:this._password});default:pi(n,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Ts(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Di(e,"POST","/v1/accounts:signInWithEmailLink",Ni(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:pi(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Ns(e,t){return Di(e,"POST","/v1/accounts:signInWithIdp",Ni(e,t))}class Rs extends bs{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new Rs(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):pi("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){var t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:r}=t,t=ti(t,["providerId","signInMethod"]);if(!n||!r)return null;const i=new Rs(n,r);return i.idToken=t.idToken||void 0,i.accessToken=t.accessToken||void 0,i.secret=t.secret,i.nonce=t.nonce,i.pendingToken=t.pendingToken||null,i}_getIdTokenResponse(e){return Ns(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Ns(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Ns(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const 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=z(t)}return e}}const Ps={USER_NOT_FOUND:"user-not-found"};class Ds extends bs{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Ds({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Ds({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return Di(e,"POST","/v1/accounts:signInWithPhoneNumber",Ni(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await Di(e,"POST","/v1/accounts:signInWithPhoneNumber",Ni(e,t));if(n.temporaryProof)throw Mi(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return Di(e,"POST","/v1/accounts:signInWithPhoneNumber",Ni(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Ps)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const 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){var{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e="string"==typeof e?JSON.parse(e):e;return n||t||r||i?new Ds({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class xs{constructor(e){var t=$(K(e)),n=null!==(r=t.apiKey)&&void 0!==r?r:null,r=null!==(i=t.oobCode)&&void 0!==i?i:null,i=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(i=t.mode)&&void 0!==i?i:null);_i(n&&r&&i,"argument-error"),this.apiKey=n,this.operation=i,this.code=r,this.continueUrl=null!==(r=t.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(r=t.languageCode)&&void 0!==r?r:null,this.tenantId=null!==(t=t.tenantId)&&void 0!==t?t:null}static parseLink(e){var t,n,r,t=(t=$(K(e=e)).link,n=t?$(K(t)).deep_link_id:null,((r=$(K(e)).deep_link_id)?$(K(r)).link:null)||r||n||t||e);try{return new xs(t)}catch(e){return null}}}class Os{constructor(){this.providerId=Os.PROVIDER_ID}static credential(e,t){return As._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var n=xs.parseLink(t);return _i(n,"argument-error"),As._fromEmailAndCode(e,n.code,n.tenantId)}}Os.PROVIDER_ID="password",Os.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Os.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Ms{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 Ls extends Ms{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Fs extends Ls{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return _i("providerId"in t&&"signInMethod"in t,"argument-error"),Rs._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return _i(e.idToken||e.accessToken,"argument-error"),Rs._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return Fs.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return Fs.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:a}=e;if(!(n||r||t||i))return null;if(!a)return null;try{return new Fs(a)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class Us extends Ls{constructor(){super("facebook.com")}static credential(e){return Rs._fromParams({providerId:Us.PROVIDER_ID,signInMethod:Us.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Us.credentialFromTaggedObject(e)}static credentialFromError(e){return Us.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Us.credential(e.oauthAccessToken)}catch(e){return null}}}Us.FACEBOOK_SIGN_IN_METHOD="facebook.com",Us.PROVIDER_ID="facebook.com";class Vs extends Ls{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Rs._fromParams({providerId:Vs.PROVIDER_ID,signInMethod:Vs.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Vs.credentialFromTaggedObject(e)}static credentialFromError(e){return Vs.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return Vs.credential(t,n)}catch(e){return null}}}Vs.GOOGLE_SIGN_IN_METHOD="google.com",Vs.PROVIDER_ID="google.com";class qs extends Ls{constructor(){super("github.com")}static credential(e){return Rs._fromParams({providerId:qs.PROVIDER_ID,signInMethod:qs.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return qs.credentialFromTaggedObject(e)}static credentialFromError(e){return qs.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return qs.credential(e.oauthAccessToken)}catch(e){return null}}}qs.GITHUB_SIGN_IN_METHOD="github.com",qs.PROVIDER_ID="github.com";class js extends bs{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return Ns(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Ns(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Ns(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:n,pendingToken:r}="string"==typeof e?JSON.parse(e):e;return t&&n&&r&&t===n?new js(t,r):null}static _create(e,t){return new js(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Bs extends Ms{constructor(e){_i(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Bs.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Bs.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=js.fromJSON(e);return _i(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return js._create(n,t)}catch(e){return null}}}class zs extends Ls{constructor(){super("twitter.com")}static credential(e,t){return Rs._fromParams({providerId:zs.PROVIDER_ID,signInMethod:zs.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return zs.credentialFromTaggedObject(e)}static credentialFromError(e){return zs.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return zs.credential(t,n)}catch(e){return null}}}async function $s(e,t){return Di(e,"POST","/v1/accounts:signUp",Ni(e,t))}zs.TWITTER_SIGN_IN_METHOD="twitter.com",zs.PROVIDER_ID="twitter.com";class Ks{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){var i=await Ki._fromIdTokenResponse(e,n,r),s=Ws(n);return new Ks({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);var r=Ws(n);return new Ks({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function Ws(e){return e.providerId||("phoneNumber"in e?"phone":null)}class Gs extends P{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,Gs.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new Gs(e,t,n,r)}}function Hs(t,n,e,r){const i="reauthenticate"===n?e._getReauthenticationResolver(t):e._getIdTokenResponse(t);return i.catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw Gs._fromErrorAndOperation(t,e,n,r);throw e})}function Qs(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Ys(e,t){const n=oe(e);await Xs(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await Ri(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=Qs(r||[]);return n.providerData=n.providerData.filter(e=>i.has(e.providerId)),i.has("phone")||(n.phoneNumber=null),await n.auth._persistUserIfCurrent(n),n}async function Js(e,t,n=!1){var r=await Vi(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Ks._forOperation(e,"link",r)}async function Xs(e,t,n){await Bi(t);const r=Qs(t.providerData);var i=!1===e?"provider-already-linked":"no-such-provider";_i(r.has(n)===e,t.auth,i)}async function Zs(e,t,n=!1){var r=e["auth"],i="reauthenticate";try{var s=await Vi(e,Hs(r,i,t,e),n);_i(s.idToken,r,"internal-error");var a=Ui(s.idToken);_i(a,r,"internal-error");var o=a["sub"];return _i(e.uid===o,r,"user-mismatch"),Ks._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&pi(r,"user-mismatch"),e}}async function ea(e,t,n=!1){var r=await Hs(e,"signIn",t),r=await Ks._fromIdTokenResponse(e,"signIn",r);return n||await e._updateCurrentUser(r.user),r}async function ta(e,t){return ea(ds(e),t)}async function na(e,t){var n=oe(e);return await Xs(!1,n,t.providerId),Js(n,t)}async function ra(e,t){return Zs(oe(e),t)}async function ia(e,t){const n=ds(e);var r=await Di(n,"POST","/v1/accounts:signInWithCustomToken",Ni(n,{token:t,returnSecureToken:!0})),r=await Ks._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(r.user),r}class sa{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?aa._fromServerResponse(e,t):"totpInfo"in t?oa._fromServerResponse(e,t):pi(e,"internal-error")}}class aa extends sa{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new aa(t)}}class oa extends sa{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new oa(t)}}function ca(e,t,n){var r;_i(0<(null===(r=n.url)||void 0===r?void 0:r.length),e,"invalid-continue-uri"),_i(void 0===n.dynamicLinkDomain||0<n.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(_i(0<n.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(_i(0<n.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function la(e){const t=ds(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function ua(e,t){await Ri(e=oe(e),"POST","/v1/accounts:update",Ni(e,{oobCode:t}))}async function ha(e,t){var n=oe(e),r=await Is(n,{oobCode:t}),i=r.requestType;switch(_i(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":_i(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":_i(r.mfaInfo,n,"internal-error");default:_i(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=sa._fromServerResponse(ds(n),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:s},operation:i}}async function da(e,t){var n=Ii()?bi():"http://localhost",n=(await Ri(e=oe(e),"POST","/v1/accounts:createAuthUri",Ni(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function pa(e,t){var n=oe(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&ca(n.auth,r,t);var r=(await Cs(n.auth,r))["email"];r!==e.email&&await e.reload()}async function fa(e,t,n){var r=oe(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&ca(r.auth,i,n);var i=(await Cs(r.auth,i))["email"];i!==e.email&&await e.reload()}async function ga(e,{displayName:t,photoURL:n}){if(void 0!==t||void 0!==n){const i=oe(e);var r=await i.getIdToken(),r=await Vi(i,async function(e,t){return Ri(e,"POST","/v1/accounts:update",t)}(i.auth,{idToken:r,displayName:t,photoUrl:n,returnSecureToken:!0}));i.displayName=r.displayName||null,i.photoURL=r.photoUrl||null;const s=i.providerData.find(({providerId:e})=>"password"===e);s&&(s.displayName=i.displayName,s.photoURL=i.photoURL),await i._updateTokensIfNecessary(r)}}async function ma(e,t,n){var r=e["auth"];const i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),n&&(i.password=n);r=await Vi(e,Ts(r,i));await e._updateTokensIfNecessary(r,!0)}class va{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class _a extends va{constructor(e,t,n,r){super(e,t,n),this.username=r}}class ya extends va{constructor(e,t){super(e,"facebook.com",t)}}class wa extends _a{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class ba extends va{constructor(e,t){super(e,"google.com",t)}}class Ia extends _a{constructor(e,t,n){super(e,"twitter.com",t,n)}}function Ta(e){var{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:function(e){if(!e)return null;var t=e["providerId"],n=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},r=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&null!=e&&e.idToken){var i=null===(i=null===(i=Ui(e.idToken))||void 0===i?void 0:i.firebase)||void 0===i?void 0:i.sign_in_provider;if(i){i="anonymous"!==i&&"custom"!==i?i:null;return new va(r,i)}}if(!t)return null;switch(t){case"facebook.com":return new ya(r,n);case"github.com":return new wa(r,n);case"google.com":return new ba(r,n);case"twitter.com":return new Ia(r,n,e.screenName||null);case"custom":case"anonymous":return new va(r,null);default:return new va(r,t,n)}}(n)}class Ea{constructor(e,t,n){this.type=e,this.credential=t,this.user=n}static _fromIdtoken(e,t){return new Ea("enroll",e,t)}static _fromMfaPendingCredential(e){return new Ea("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t;if(null!=e&&e.multiFactorSession){if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.pendingCredential)return Ea._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.idToken)return Ea._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Ca{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,i){const s=ds(e),a=i.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>sa._fromServerResponse(s,e));_i(a.mfaPendingCredential,s,"internal-error");const o=Ea._fromMfaPendingCredential(a.mfaPendingCredential);return new Ca(o,t,async e=>{var t=await e._process(s,o);delete a.mfaInfo,delete a.mfaPendingCredential;var n=Object.assign(Object.assign({},a),{idToken:t.idToken,refreshToken:t.refreshToken});switch(i.operationType){case"signIn":var r=await Ks._fromIdTokenResponse(s,i.operationType,n);return await s._updateCurrentUser(r.user),r;case"reauthenticate":return _i(i.user,s,"internal-error"),Ks._forOperation(i.user,i.operationType,n);default:pi(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}class Sa{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>sa._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new Sa(e)}async getSession(){return Ea._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const n=e;var r=await this.getSession(),r=await Vi(this.user,n._process(this.user.auth,r,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid;var n,r,i=await this.user.getIdToken();try{var s=await Vi(this.user,(n=this.user.auth,r={idToken:i,mfaEnrollmentId:t},Ri(n,"POST","/v2/accounts/mfaEnrollment:withdraw",Ni(n,r))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(s),await this.user.reload()}catch(e){throw e}}}const ka=new WeakMap;const Aa="__sak";class Na{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Aa,"1"),this.storage.removeItem(Aa),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){var 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 Ra extends Na{constructor(){var e;super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=(es(e=b())||as(e))&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=os(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const r of Object.keys(this.listeners)){var t=this.storage.getItem(r),n=this.localCache[r];t!==n&&e(r,n,t)}}onStorageEvent(e,t=!1){if(e.key){const r=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(r);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(r,e.newValue):this.storage.removeItem(r);else if(this.localCache[r]===e.newValue&&!t)return}var n=()=>{var e=this.storage.getItem(r);!t&&this.localCache[r]===e||this.notifyListeners(r,e)};const i=this.storage.getItem(r);S()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}else this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)})}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t&&JSON.parse(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){var t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}Ra.type="LOCAL";const Pa=Ra;class Da extends Na{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}Da.type="SESSION";const xa=Da;class Oa{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){var e=this.receivers.find(e=>e.isListeningto(t));if(e)return e;e=new Oa(t);return this.receivers.push(e),e}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data;var s=this.handlersMap[r];null!=s&&s.size&&(t.ports[0].postMessage({status:"ack",eventId:n,eventType:r}),s=Array.from(s).map(async e=>e(t.origin,i)),s=await Promise.all(s.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})),t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:s}))}_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 Ma(e="",t=10){let n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}Oa.receivers=[];class La{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,a=50){const o="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!o)throw new Error("connection_unavailable");let c,l;return new Promise((n,r)=>{const i=Ma("",20);o.port1.start();const s=setTimeout(()=>{r(new Error("unsupported_event"))},a);l={messageChannel:o,onMessage(e){var t=e;if(t.data.eventId===i)switch(t.data.status){case"ack":clearTimeout(s),c=setTimeout(()=>{r(new Error("timeout"))},3e3);break;case"done":clearTimeout(c),n(t.data.response);break;default:clearTimeout(s),clearTimeout(c),r(new Error("invalid_response"))}}},this.handlers.add(l),o.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:e,eventId:i,data:t},[o.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}}function Fa(){return window}function Ua(){return void 0!==Fa().WorkerGlobalScope&&"function"==typeof Fa().importScripts}const Va="firebaseLocalStorageDb",qa="firebaseLocalStorage",ja="fbase_key";class Ba{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 za(e,t){return e.transaction([qa],t?"readwrite":"readonly").objectStore(qa)}function $a(){const r=indexedDB.open(Va,1);return new Promise((n,t)=>{r.addEventListener("error",()=>{t(r.error)}),r.addEventListener("upgradeneeded",()=>{const e=r.result;try{e.createObjectStore(qa,{keyPath:ja})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains(qa)?n(e):(e.close(),t=indexedDB.deleteDatabase(Va),await new Ba(t).toPromise(),n(await $a()))})})}async function Ka(e,t,n){var r=za(e,!0).put({fbase_key:t,value:n});return new Ba(r).toPromise()}function Wa(e,t){var n=za(e,!0).delete(t);return new Ba(n).toPromise()}class Ga{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 $a(),this.db)}async _withRetries(e){let t=0;for(;;)try{return e(await this._openDb())}catch(e){if(3<t++)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Ua()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Oa._getInstance(Ua()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>{const n=await this._poll();return{keyProcessed:n.includes(t.key)}}),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t,n;this.activeServiceWorker=await async function(){if(null===navigator||void 0===navigator||!navigator.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),this.activeServiceWorker&&(this.sender=new La(this.activeServiceWorker),(n=await this.sender._send("ping",{},800))&&null!==(e=n[0])&&void 0!==e&&e.fulfilled&&null!==(t=n[0])&&void 0!==t&&t.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0))}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?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;var e=await $a();return await Ka(e,Aa,"1"),await Wa(e,Aa),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,n){return this._withPendingWrite(async()=>(await this._withRetries(e=>Ka(e,t,n)),this.localCache[t]=n,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>async function(e,t){var n=za(e,!1).get(t);return void 0===(n=await new Ba(n).toPromise())?null:n.value}(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>Wa(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e,t,n=await this._withRetries(e=>{var t=za(e,!1).getAll();return new Ba(t).toPromise()});if(!n)return[];if(0!==this.pendingWrites)return[];const r=[],i=new Set;for({fbase_key:e,value:t}of n)i.add(e),JSON.stringify(this.localCache[e])!==JSON.stringify(t)&&(this.notifyListeners(e,t),r.push(e));for(const s of Object.keys(this.localCache))this.localCache[s]&&!i.has(s)&&(this.notifyListeners(s,null),r.push(s));return r}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(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()}}Ga.type="LOCAL";const Ha=Ga;class Qa{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var n=this.counter;return this._widgets.set(n,new Ya(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t,n=e||1e12;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;return(null===(t=this._widgets.get(e||1e12))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;return null===(t=this._widgets.get(e||1e12))||void 0===t||t.execute(),""}}class Ya{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var r="string"==typeof e?document.getElementById(e):e;_i(r,"argument-error",{appName:t}),this.container=r,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=function(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()},6e4)},500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}const Ja=gs("rcb"),Xa=new Ei(3e4,6e4);class Za{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!(null===(e=Fa().grecaptcha)||void 0===e||!e.render)}load(s,a=""){var e;return _i((e=a).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),s,"argument-error"),this.shouldResolveImmediately(a)&&ii(Fa().grecaptcha)?Promise.resolve(Fa().grecaptcha):new Promise((t,n)=>{const i=Fa().setTimeout(()=>{n(fi(s,"network-request-failed"))},Xa.get());Fa()[Ja]=()=>{Fa().clearTimeout(i),delete Fa()[Ja];const e=Fa().grecaptcha;if(e&&ii(e)){const r=e.render;e.render=(e,t)=>{var n=r(e,t);return this.counter++,n},this.hostLanguage=a,t(e)}else n(fi(s,"internal-error"))},fs(`https://www.google.com/recaptcha/api.js??${z({onload:Ja,render:"explicit",hl:a})}`).catch(()=>{clearTimeout(i),n(fi(s,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!(null===(t=Fa().grecaptcha)||void 0===t||!t.render)&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class eo{async load(e){return new Qa(e)}clearedOneInstance(){}}const to="recaptcha",no={theme:"light",type:"image"};class ro{constructor(e,t,n=Object.assign({},no)){this.parameters=n,this.type=to,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=ds(e),this.isInvisible="invisible"===this.parameters.size,_i("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var r="string"==typeof t?document.getElementById(t):t;_i(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?eo:Za),this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),r=this.getAssertedRecaptcha();var t=r.getResponse(e);return t||new Promise(t=>{const n=e=>{e&&(this.tokenChangeListeners.delete(n),t(e))};this.tokenChangeListeners.add(n),this.isInvisible&&r.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e}),this.renderPromise)}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){_i(!this.parameters.sitekey,this.auth,"argument-error"),_i(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),_i("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(n){return t=>{if(this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof n)n(t);else if("string"==typeof n){const e=Fa()[n];"function"==typeof e&&e(t)}}}assertNotDestroyed(){_i(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;var t;this.isInvisible||(t=document.createElement("div"),e.appendChild(t),e=t),this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){_i(Ii()&&!Ua(),this.auth,"internal-error"),await function(){let t=null;return new Promise(e=>{"complete"!==document.readyState?(t=()=>e(),window.addEventListener("load",t)):e()}).catch(e=>{throw t&&window.removeEventListener("load",t),e})}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);var e=await((await Ri(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");_i(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return _i(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class io{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Ds._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function so(t,n,r){var i,s,a,o,c,l,u=await r.verify();try{_i("string"==typeof u,t,"argument-error"),_i(r.type===to,t,"argument-error");let e;if(e="string"==typeof n?{phoneNumber:n}:n,"session"in e){var h=e.session;if("phoneNumber"in e)return _i("enroll"===h.type,t,"internal-error"),(c=t,l={idToken:h.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,recaptchaToken:u}},await Ri(c,"POST","/v2/accounts/mfaEnrollment:start",Ni(c,l))).phoneSessionInfo.sessionInfo;_i("signin"===h.type,t,"internal-error");var d=(null===(i=e.multiFactorHint)||void 0===i?void 0:i.uid)||e.multiFactorUid;return _i(d,t,"missing-multi-factor-info"),(o={mfaPendingCredential:h.credential,mfaEnrollmentId:d,phoneSignInInfo:{recaptchaToken:u}},await Ri(t,"POST","/v2/accounts/mfaSignIn:start",Ni(t,o))).phoneResponseInfo.sessionInfo}var p=(s=t,a={phoneNumber:e.phoneNumber,recaptchaToken:u},await Ri(s,"POST","/v1/accounts:sendVerificationCode",Ni(s,a)))["sessionInfo"];return p}finally{r._reset()}}class ao{constructor(e){this.providerId=ao.PROVIDER_ID,this.auth=ds(e)}verifyPhoneNumber(e,t){return so(this.auth,e,oe(t))}static credential(e,t){return Ds._fromVerification(e,t)}static credentialFromResult(e){var t=e;return ao.credentialFromTaggedObject(t)}static credentialFromError(e){return ao.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{phoneNumber:t,temporaryProof:n}=e;return t&&n?Ds._fromTokenResponse(t,n):null}}function oo(e,t){return t?Gi(t):(_i(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}ao.PROVIDER_ID="phone",ao.PHONE_SIGN_IN_METHOD="phone";class co extends bs{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Ns(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Ns(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Ns(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function lo(e){return ea(e.auth,new co(e),e.bypassAuthState)}function uo(e){var{auth:t,user:n}=e;return _i(n,t,"internal-error"),Zs(n,new co(e),e.bypassAuthState)}async function ho(e){var{auth:t,user:n}=e;return _i(n,t,"internal-error"),Js(n,new co(e),e.bypassAuthState)}class po{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){var{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:a}=e;if(s)this.reject(s);else{r={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(r))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return lo;case"linkViaPopup":case"linkViaRedirect":return ho;case"reauthViaPopup":case"reauthViaRedirect":return uo;default:pi(this.auth,"internal-error")}}resolve(e){wi(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){wi(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const fo=new Ei(2e3,1e4);class go extends po{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,go.currentPopupAction&&go.currentPopupAction.cancel(),go.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return _i(e,this.auth,"internal-error"),e}async onExecution(){wi(1===this.filter.length,"Popup operations only handle one event");var e=Ma();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(fi(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(fi(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,go.currentPopupAction=null}pollUserCancellation(){const t=()=>{var e;null!==(e=null===(e=this.authWindow)||void 0===e?void 0:e.window)&&void 0!==e&&e.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(fi(this.auth,"popup-closed-by-user"))},8e3):this.pollId=window.setTimeout(t,fo.get())};t()}}go.currentPopupAction=null;const mo="pendingRedirect",vo=new Map;class _o extends po{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let t=vo.get(this.auth._key());if(!t){try{const e=await async function(e,t){const n=Io(t),r=bo(e);if(!await r._isAvailable())return!1;var i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}vo.set(this.auth._key(),t)}return this.bypassAuthState||vo.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function yo(e,t){return bo(e)._set(Io(t),"true")}function wo(e,t){vo.set(e._key(),t)}function bo(e){return Gi(e._redirectPersistence)}function Io(e){return Yi(mo,e.config.apiKey,e.name)}function To(e,t,n){return async function(e,t,n){var r=ds(e);mi(e,t,Ms),await r._initializationPromise;const i=oo(r,n);return await yo(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function Eo(e,t,n){return async function(e,t,n){var r=oe(e);mi(r.auth,t,Ms),await r.auth._initializationPromise;const i=oo(r.auth,n);await yo(i,r.auth);var s=await ko(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function Co(e,t,n){return async function(e,t,n){var r=oe(e);mi(r.auth,t,Ms),await r.auth._initializationPromise;const i=oo(r.auth,n);await Xs(!1,r,t.providerId),await yo(i,r.auth);var s=await ko(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function So(e,t,n=!1){const r=ds(e);var i=oo(r,t);const s=new _o(r,i,n),a=await s.execute();return a&&!n&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,t)),a}async function ko(e){var t=Ma(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class Ao{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(t){if(this.hasEventBeenHandled(t))return!1;let n=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(n=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return Ro(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!Ro(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(fi(this.auth,n))):t.onAuthEvent(e)}isEventForConsumer(e,t){var n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(No(e))}saveEventToCache(e){this.cachedEventUids.add(No(e)),this.lastProcessedEventTime=Date.now()}}function No(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function Ro({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function Po(e,t={}){return Ri(e,"GET","/v1/projects",t)}const Do=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,xo=/^https?/;async function Oo(e){if(!e.config.emulator){var t=(await Po(e))["authorizedDomains"];for(const n of t)try{if(function(e){const t=bi(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){var i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!xo.test(n))return!1;if(Do.test(e))return r===e;const s=e.replace(/\./g,"\\."),a=new RegExp("^(.+\\."+s+"|"+s+")$","i");return a.test(r)}(n))return}catch(e){}pi(e,"unauthorized-domain")}}const Mo=new Ei(3e4,6e4);function Lo(){const t=Fa().___jsl;if(null!==t&&void 0!==t&&t.H)for(const n of Object.keys(t.H))if(t.H[n].r=t.H[n].r||[],t.H[n].L=t.H[n].L||[],t.H[n].r=[...t.H[n].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}let Fo=null;function Uo(e){var i;return Fo=Fo||(i=e,new Promise((e,t)=>{function n(){Lo(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Lo(),t(fi(i,"network-request-failed"))},timeout:Mo.get()})}if(null!==(r=null===(r=Fa().gapi)||void 0===r?void 0:r.iframes)&&void 0!==r&&r.Iframe)e(gapi.iframes.getContext());else{if(null===(r=Fa().gapi)||void 0===r||!r.load){var r=gs("iframefcb");return Fa()[r]=()=>{gapi.load?n():t(fi(i,"network-request-failed"))},fs(`https://apis.google.com/js/api.js?onload=${r}`).catch(e=>t(e))}n()}}).catch(e=>{throw Fo=null,e})),Fo}const Vo=new Ei(5e3,15e3),qo="__/auth/iframe",jo="emulator/auth/iframe",Bo={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},zo=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function $o(a){const e=await Uo(a);var t=Fa().gapi;return _i(t,a,"internal-error"),e.open({where:document.body,url:function(e){var t=e.config;_i(t.authDomain,e,"auth-domain-config-required");var n=t.emulator?Ci(t,jo):`https://${e.config.authDomain}/${qo}`;const r={apiKey:t.apiKey,appName:e.name,v:Je};(t=zo.get(e.config.apiHost))&&(r.eid=t);const i=e._getFrameworks();return i.length&&(r.fw=i.join(",")),`${n}?${z(r).slice(1)}`}(a),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Bo,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=fi(a,"network-request-failed"),r=Fa().setTimeout(()=>{t(n)},Vo.get());function i(){Fa().clearTimeout(r),e(s)}s.ping(i).then(i,()=>{t(n)})}))}const Ko={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Wo{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Go(e,t,n,r=500,i=600){var s=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let o="";const c=Object.assign(Object.assign({},Ko),{width:r.toString(),height:i.toString(),top:s,left:a});s=b().toLowerCase();n&&(o=ts(s)?"_blank":n),Zi(s)&&(t=t||"http://localhost",c.scrollbars="yes");var l,a=Object.entries(c).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if([n=b()]=[s],as(n)&&null!==(l=window.navigator)&&void 0!==l&&l.standalone&&"_self"!==o)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",o),new Wo(null);const u=window.open(t||"",o,a);_i(u,e,"popup-blocked");try{u.focus()}catch(e){}return new Wo(u)}const Ho="__/auth/handler",Qo="emulator/auth/handler",Yo=encodeURIComponent("fac");async function Jo(e,t,n,r,i,s){_i(e.config.authDomain,e,"auth-domain-config-required"),_i(e.config.apiKey,e,"invalid-api-key");const a={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:Je,eventId:i};if(t instanceof Ms){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",V(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,c]of Object.entries(s||{}))a[o]=c}if(t instanceof Ls){const h=t.getScopes().filter(e=>""!==e);0<h.length&&(a.scopes=h.join(","))}e.tenantId&&(a.tid=e.tenantId);const l=a;for(const d of Object.keys(l))void 0===l[d]&&delete l[d];var u=await e._getAppCheckToken(),u=u?`#${Yo}=${encodeURIComponent(u)}`:"";return`${e=[e["config"]][0],e.emulator?Ci(e,Qo):`https://${e.authDomain}/${Ho}`}?${z(l).slice(1)}${u}`}const Xo="webStorageSupport";const Zo=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=xa,this._completeRedirectFn=So,this._overrideRedirectResult=wo}async _openPopup(e,t,n,r){var i;return wi(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),Go(e,await Jo(e,t,n,bi(),r),Ma())}async _openRedirect(e,t,n,r){await this._originValidation(e);var i=await Jo(e,t,n,bi(),r);return Fa().location.href=i,new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:r,promise:n}=this.eventManagers[t];return r?Promise.resolve(r):(wi(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch(()=>{delete this.eventManagers[t]}),n}async initAndGetManager(t){const e=await $o(t),n=new Ao(t);return e.register("authEvent",e=>{return _i(null==e?void 0:e.authEvent,t,"invalid-auth-event"),{status:n.onEvent(e.authEvent)?"ACK":"ERROR"}},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:n},this.iframes[t._key()]=e,n}_isIframeWebStorageSupported(n,r){const e=this.iframes[n._key()];e.send(Xo,{type:Xo},e=>{var t=null===(t=null==e?void 0:e[0])||void 0===t?void 0:t[Xo];void 0!==t&&r(!!t),pi(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Oo(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return os()||es()||as()}};class ec extends class{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return yi("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new ec(e)}_finalizeEnroll(e,t,n){return e=e,n={idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()},Ri(e,"POST","/v2/accounts/mfaEnrollment:finalize",Ni(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},Ri(e,"POST","/v2/accounts/mfaSignIn:finalize",Ni(e,t))}}class tc{constructor(){}static assertion(e){return ec._fromCredential(e)}}tc.FACTOR_ID="phone";var nc="@firebase/auth";class rc{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?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(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t((null==e?void 0:e.stsTokenManager.accessToken)||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){_i(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}var ic,sc,ac;function oc(){return window}ic="authIdTokenMaxAge",null===(sc=p())||void 0===sc||sc[`_${ic}`],ac="Browser",Ge(new ce("auth",(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal");const{apiKey:s,authDomain:a}=n.options;_i(s&&!s.includes(":"),"invalid-api-key",{appName:n.name});var o={apiKey:s,authDomain:a,clientPlatform:ac,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:cs(ac)},o=new hs(n,r,i,o);return function(e,t){const n=(null==t?void 0:t.persistence)||[];var r=(Array.isArray(n)?n:[n]).map(Gi);null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(o,t),o},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{const r=e.getProvider("auth-internal");r.initialize()})),Ge(new ce("auth-internal",e=>{var t=ds(e.getProvider("auth").getImmediate());return e=t,new rc(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),tt(nc,"1.3.0",function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(ac)),tt(nc,"1.3.0","esm2017");async function cc(e,t,n){var r=oc()["BuildInfo"];wi(t.sessionId,"AuthEvent did not contain a session ID");var i=await async function(e){const t=function(e){if(wi(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}(e),n=await crypto.subtle.digest("SHA-256",t),r=Array.from(new Uint8Array(n));return r.map(e=>e.toString(16).padStart(2,"0")).join("")}(t.sessionId);const s={};return as()?s.ibi=r.packageName:rs()?s.apn=r.packageName:pi(e,"operation-not-supported-in-this-environment"),r.displayName&&(s.appDisplayName=r.displayName),s.sessionId=i,Jo(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,s)}function lc(r){const i=oc()["cordova"];return new Promise(n=>{i.plugins.browsertab.isAvailable(e=>{let t=null;e?i.plugins.browsertab.openUrl(r):t=i.InAppBrowser.open(r,(e=b(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),n(t)})})}const uc=20;class hc extends Ao{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function dc(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:function(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<uc;r++){var n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}(),postBody:null,tenantId:e.tenantId,error:fi(e,"no-auth-event")}}async function pc(e){var t=await gc()._get(mc(e));return t&&await gc()._remove(mc(e)),t}function fc(e,t){var n,r,i;const s=(n=vc(t=t),a=n.link?decodeURIComponent(n.link):void 0,r=vc(a).link,i=n.deep_link_id?decodeURIComponent(n.deep_link_id):void 0,(n=vc(i).link)||i||r||a||t);if(s.includes("/__/auth/callback")){var a=vc(s),a=a.firebaseError?function(e){try{return JSON.parse(e)}catch(e){return null}}(decodeURIComponent(a.firebaseError)):null,a=null===(a=null===(a=null==a?void 0:a.code)||void 0===a?void 0:a.split("auth/"))||void 0===a?void 0:a[1],a=a?fi(a):null;return a?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:a,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:s,postBody:null}}return null}function gc(){return Gi(Pa)}function mc(e){return Yi("authEvent",e.config.apiKey,e.name)}function vc(e){if(null==e||!e.includes("?"))return{};const[,...t]=e.split("?");return $(t.join("?"))}const _c=class{constructor(){this._redirectPersistence=xa,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=So,this._overrideRedirectResult=wo}async _initialize(e){var t=e._key();let n=this.eventManagers.get(t);return n||(n=new hc(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){pi(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){var i,s;i=e,o=oc(),_i("function"==typeof(null===(s=null==o?void 0:o.universalLinks)||void 0===s?void 0:s.subscribe),i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),_i(void 0!==(null===(s=null==o?void 0:o.BuildInfo)||void 0===s?void 0:s.packageName),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),_i("function"==typeof(null===(s=null===(s=null===(s=null==o?void 0:o.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.openUrl),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),_i("function"==typeof(null===(s=null===(s=null===(s=null==o?void 0:o.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.isAvailable),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),_i("function"==typeof(null===(o=null===(o=null==o?void 0:o.cordova)||void 0===o?void 0:o.InAppBrowser)||void 0===o?void 0:o.open),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});const a=await this._initialize(e);await a.initialized(),a.resetRedirect(),vo.clear(),await this._originValidation(e);var o=dc(e,n,r);n=e,r=o,await gc()._set(mc(n),r);o=await lc(await cc(e,o,t));return async function(a,o,c){const l=oc()["cordova"];let u=()=>{};try{await new Promise((n,e)=>{let t=null;function r(){var e;n();const t=null===(e=l.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==c?void 0:c.close)&&c.close()}function i(){t=t||window.setTimeout(()=>{e(fi(a,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&i()}o.addPassiveListener(r),document.addEventListener("resume",i,!1),rs()&&document.addEventListener("visibilitychange",s,!1),u=()=>{o.removePassiveListener(r),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),t&&window.clearTimeout(t)}})}finally{u()}}(e,a,o)}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){var t=oc()["BuildInfo"];const n={};as()?n.iosBundleId=t.packageName:rs()?n.androidPackageName=t.packageName:pi(e,"operation-not-supported-in-this-environment"),await Po(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=oc(),s=setTimeout(async()=>{await pc(r),i.onEvent(yc())},500),a=async e=>{clearTimeout(s);var t=await pc(r);let n=null;t&&null!=e&&e.url&&(n=fc(t,e.url)),i.onEvent(n||yc())};void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a);const o=t,c=`${n.packageName.toLowerCase()}://`;oc().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}};function yc(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:fi("no-auth-event")}}var wc;function bc(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function Ic(e=b()){return!("file:"!==bc()&&"ionic:"!==bc()&&"capacitor:"!==bc()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function Tc(e=b()){return S()&&11===(null===document||void 0===document?void 0:document.documentMode)||([e=b()]=[e],/Edge\/\d+/.test(e))}function Ec(){try{const t=self.localStorage;var e=Ma();if(t)return t.setItem(e,"1"),t.removeItem(e),!Tc()||A()}catch(e){return Cc()&&A()}return!1}function Cc(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function Sc(){return("http:"===bc()||"https:"===bc()||E()||Ic())&&!(C()||T())&&Ec()&&!Cc()}function kc(){return Ic()&&"undefined"!=typeof document}const Ac={LOCAL:"local",NONE:"none",SESSION:"session"},Nc=_i,Rc="persistence";async function Pc(e){await e._initializationPromise;const t=Dc();var n=Yi(Rc,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function Dc(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}const xc=_i;class Oc{constructor(){this.browserResolver=Gi(Zo),this.cordovaResolver=Gi(_c),this.underlyingResolver=null,this._redirectPersistence=xa,this._completeRedirectFn=So,this._overrideRedirectResult=wo}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,n,r)}async _openRedirect(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,n,r)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return kc()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return xc(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!kc()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function Mc(e){return e.unwrap()}function Lc(e,t){var n,r,i,s=null===(r=t.customData)||void 0===r?void 0:r._tokenResponse;if("auth/multi-factor-auth-required"===(null==t?void 0:t.code)){const o=t;o.resolver=new qc(e,(n=t,i=oe(e),_i((a=n).customData.operationType,i,"argument-error"),_i(null===(r=a.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,i,"argument-error"),Ca._fromError(i,a)))}else if(s){var a=Fc(t);const c=t;a&&(c.credential=a,c.tenantId=s.tenantId||void 0,c.email=s.email||void 0,c.phoneNumber=s.phoneNumber||void 0)}}function Fc(e){var t=(e instanceof P?e.customData:e)["_tokenResponse"];if(!t)return null;if(!(e instanceof P)&&"temporaryProof"in t&&"phoneNumber"in t)return ao.credentialFromResult(e);const n=t.providerId;if(!n||n===ni.PASSWORD)return null;let r;switch(n){case ni.GOOGLE:r=Vs;break;case ni.FACEBOOK:r=Us;break;case ni.GITHUB:r=qs;break;case ni.TWITTER:r=zs;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:c}=t;return s||a||i||o?o?n.startsWith("saml.")?js._create(n,o):Rs._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:i,accessToken:s}):new Fs(n).credential({idToken:i,accessToken:s,rawNonce:c}):null}return e instanceof P?r.credentialFromError(e):r.credentialFromResult(e)}function Uc(t,e){return e.catch(e=>{throw e instanceof P&&Lc(t,e),e}).then(e=>{var t=e.operationType,n=e.user;return{operationType:t,credential:Fc(e),additionalUserInfo:Ta(e),user:jc.getOrCreate(n)}})}async function Vc(t,e){const n=await e;return{verificationId:n.verificationId,confirm:e=>Uc(t,n.confirm(e))}}class qc{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return Uc(Mc(this.auth),this.resolver.resolveSignIn(e))}}class jc{constructor(e){var t;this._delegate=e,this.multiFactor=(t=oe(e),ka.has(t)||ka.set(t,Sa._fromUser(t)),ka.get(t))}static getOrCreate(e){return jc.USER_MAP.has(e)||jc.USER_MAP.set(e,new jc(e)),jc.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return Uc(this.auth,na(this._delegate,e))}async linkWithPhoneNumber(e,t){return Vc(this.auth,async function(e,t,n){const r=oe(e);await Xs(!1,r,"phone");var i=await so(r.auth,t,oe(n));return new io(i,e=>na(r,e))}(this._delegate,e,t))}async linkWithPopup(e){return Uc(this.auth,async function(e,t,n){var r=oe(e);mi(r.auth,t,Ms);var i=oo(r.auth,n);const s=new go(r.auth,"linkViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,Oc))}async linkWithRedirect(e){return await Pc(ds(this.auth)),Co(this._delegate,e,Oc)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Uc(this.auth,ra(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Vc(this.auth,async function(e,t,n){const r=oe(e);var i=await so(r.auth,t,oe(n));return new io(i,e=>ra(r,e))}(this._delegate,e,t))}reauthenticateWithPopup(e){return Uc(this.auth,async function(e,t,n){var r=oe(e);mi(r.auth,t,Ms);var i=oo(r.auth,n);const s=new go(r.auth,"reauthViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,Oc))}async reauthenticateWithRedirect(e){return await Pc(ds(this.auth)),Eo(this._delegate,e,Oc)}sendEmailVerification(e){return pa(this._delegate,e)}async unlink(e){return await Ys(this._delegate,e),this}updateEmail(e){return ma(oe(this._delegate),e,null)}updatePassword(e){return ma(oe(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){await Js(oe(e),t)}(this._delegate,e)}updateProfile(e){return ga(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return fa(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}jc.USER_MAP=new WeakMap;const Bc=_i;class zc{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();var n=e.options["apiKey"];Bc(n,"invalid-api-key",{appName:e.name}),Bc(n,"invalid-api-key",{appName:e.name});var r="undefined"!=typeof window?Oc:void 0;this._delegate=t.initialize({options:{persistence:function(e,t){const n=function(e,t){const n=Dc();if(!n)return[];var r=Yi(Rc,e,t);switch(n.getItem(r)){case Ac.NONE:return[Qi];case Ac.LOCAL:return[Ha,xa];case Ac.SESSION:return[xa];default:return[]}}(e,t);"undefined"==typeof self||n.includes(Ha)||n.push(Ha);if("undefined"!=typeof window)for(const r of[Pa,xa])n.includes(r)||n.push(r);n.includes(Qi)||n.push(Qi);return n}(n,e.name),popupRedirectResolver:r}}),this._delegate._updateErrorMap(ci),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?jc.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){_s(this._delegate,e,t)}applyActionCode(e){return ua(this._delegate,e)}checkActionCode(e){return ha(this._delegate,e)}confirmPasswordReset(e,t){return async function(t,e,n){await Is(oe(t),{oobCode:e,newPassword:n}).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&la(t),e})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Uc(this._delegate,async function(t,e,n){var r;const i=ds(t),s={returnSecureToken:!0,email:e,password:n,clientType:"CLIENT_TYPE_WEB"};let a;a=null!==(r=i._getRecaptchaConfig())&&void 0!==r&&r.emailPasswordEnabled?(o=await vs(i,s,"signUpPassword"),$s(i,o)):$s(i,s).catch(async e=>{if("auth/missing-recaptcha-token"!==e.code)throw e;console.log("Sign-up is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-up flow.");var t=await vs(i,s,"signUpPassword");return $s(i,t)});var o=await a.catch(e=>{throw"auth/password-does-not-meet-requirements"===e.code&&la(t),e}),o=await Ks._fromIdTokenResponse(i,"signIn",o);return await i._updateCurrentUser(o.user),o}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return da(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=xs.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){Bc(Sc(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=Oc,await ds(e)._initializationPromise,await So(e,t,!1));return n?Uc(this._delegate,Promise.resolve(n)):{credential:null,user:null}}addFrameworkForLogging(e){ds(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,n){var{next:r,error:i,complete:s}=$c(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=$c(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return async function(e,t,n){var r;const i=ds(e),s={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};function a(e,t){_i(t.handleCodeInApp,i,"argument-error"),t&&ca(i,e,t)}null!==(r=i._getRecaptchaConfig())&&void 0!==r&&r.emailPasswordEnabled?(a(r=await vs(i,s,"getOobCode",!0),n),await ks(i,r)):(a(s,n),await ks(i,s).catch(async e=>{if("auth/missing-recaptcha-token"!==e.code)return Promise.reject(e);console.log("Email link sign-in is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.");var t=await vs(i,s,"getOobCode",!0);a(t,n),await ks(i,t)}))}(this._delegate,e,t)}sendPasswordResetEmail(e,t){return async function(e,t,n){var r;const i=ds(e),s={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};null!==(r=i._getRecaptchaConfig())&&void 0!==r&&r.emailPasswordEnabled?(r=await vs(i,s,"getOobCode",!0),n&&ca(i,r,n),await Ss(i,r)):(n&&ca(i,s,n),await Ss(i,s).catch(async e=>{if("auth/missing-recaptcha-token"!==e.code)return Promise.reject(e);console.log("Password resets are protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the password reset flow.");var t=await vs(i,s,"getOobCode",!0);n&&ca(i,t,n),await Ss(i,t)}))}(this._delegate,e,t||void 0)}async setPersistence(e){var t,n;t=this._delegate,n=e,Nc(Object.values(Ac).includes(n),t,"invalid-persistence-type"),C()?Nc(n!==Ac.SESSION,t,"unsupported-persistence-type"):T()?Nc(n===Ac.NONE,t,"unsupported-persistence-type"):Cc()?Nc(n===Ac.NONE||n===Ac.LOCAL&&A(),t,"unsupported-persistence-type"):Nc(n===Ac.NONE||Ec(),t,"unsupported-persistence-type");let r;switch(e){case Ac.SESSION:r=xa;break;case Ac.LOCAL:var i=await Gi(Ha)._isAvailable();r=i?Ha:Pa;break;case Ac.NONE:r=Qi;break;default:return pi("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(r)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Uc(this._delegate,async function(e){const t=ds(e);if(await t._initializationPromise,null!==(n=t.currentUser)&&void 0!==n&&n.isAnonymous)return new Ks({user:t.currentUser,providerId:null,operationType:"signIn"});var n=await $s(t,{returnSecureToken:!0}),n=await Ks._fromIdTokenResponse(t,"signIn",n,!0);return await t._updateCurrentUser(n.user),n}(this._delegate))}signInWithCredential(e){return Uc(this._delegate,ta(this._delegate,e))}signInWithCustomToken(e){return Uc(this._delegate,ia(this._delegate,e))}signInWithEmailAndPassword(e,t){return Uc(this._delegate,(n=this._delegate,e=e,t=t,ta(oe(n),Os.credential(e,t)).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&la(n),e})));var n}signInWithEmailLink(e,t){return Uc(this._delegate,async function(e,t,n){var r=oe(e),i=Os.credentialWithLink(t,n||bi());return _i(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),ta(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Vc(this._delegate,async function(e,t,n){const r=ds(e);var i=await so(r,t,oe(n));return new io(i,e=>ta(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return Bc(Sc(),this._delegate,"operation-not-supported-in-this-environment"),Uc(this._delegate,async function(e,t,n){var r=ds(e);mi(e,t,Ms);var i=oo(r,n);const s=new go(r,"signInViaPopup",t,i);return s.executeNotNull()}(this._delegate,e,Oc))}async signInWithRedirect(e){return Bc(Sc(),this._delegate,"operation-not-supported-in-this-environment"),await Pc(this._delegate),To(this._delegate,e,Oc)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await ha(oe(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function $c(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&jc.getOrCreate(e)),error:t,complete:n}}zc.Persistence=Ac;class Kc{constructor(){this.providerId="phone",this._delegate=new ao(Mc(bt.auth()))}static credential(e,t){return ao.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Kc.PHONE_SIGN_IN_METHOD=ao.PHONE_SIGN_IN_METHOD,Kc.PROVIDER_ID=ao.PROVIDER_ID;const Wc=_i;class Gc{constructor(e,t,n=bt.app()){var r;Wc(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new ro(n.auth(),e,t),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(wc=bt).INTERNAL.registerComponent(new ce("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new zc(t,n)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:ri.EMAIL_SIGNIN,PASSWORD_RESET:ri.PASSWORD_RESET,RECOVER_EMAIL:ri.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:ri.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:ri.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:ri.VERIFY_EMAIL}},EmailAuthProvider:Os,FacebookAuthProvider:Us,GithubAuthProvider:qs,GoogleAuthProvider:Vs,OAuthProvider:Fs,SAMLAuthProvider:Bs,PhoneAuthProvider:Kc,PhoneMultiFactorGenerator:tc,RecaptchaVerifier:Gc,TwitterAuthProvider:zs,Auth:zc,AuthCredential:bs,Error:P}).setInstantiationMode("LAZY").setMultipleInstances(!1)),wc.registerVersion("@firebase/auth-compat","0.4.6");const Hc="@firebase/database";let Qc="";function Yc(e){Qc=e}class Jc{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),M(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:O(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Xc{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return F(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}var Zc,el,tl,nl,rl,il,sl=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new Jc(t)}}catch(e){}return new Xc};function al(e){var t=function(t){const n=[];let r=0;for(let a=0;a<t.length;a++){let e=t.charCodeAt(a);var i,s;55296<=e&&e<=56319&&(i=e-55296,a++,f(a<t.length,"Surrogate pair missing trail surrogate."),s=t.charCodeAt(a)-56320,e=65536+(i<<10)+s),e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(e<65536?n[r++]=e>>12|224:(n[r++]=e>>18|240,n[r++]=e>>12&63|128),n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}(e);const n=new W;return n.update(t),t=n.digest(),r.encodeByteArray(t)}const ol=sl("localStorage"),cl=sl("sessionStorage"),ll=new ve("@firebase/database"),ul=function(){let e=1;return function(){return e++}}(),hl=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=hl.apply(null,n):t+="object"==typeof n?M(n):n,t+=" "}return t};let dl=null,pl=!0;function fl(t){return function(...e){bl(t,...e)}}function gl(...e){var t="FIREBASE INTERNAL ERROR: "+hl(...e);ll.error(t)}function ml(e,t){return e===t?0:e<t?-1:1}function vl(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+M(t))}function _l(e){if("object"!=typeof e||null===e)return M(e);const t=[];for(const r in e)t.push(r);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=M(t[i]),n+=":",n+=_l(e[t[i]]);return n+="}",n}function yl(e,t){var n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}const wl=function(e,t){f(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(ll.logLevel=m.VERBOSE,dl=ll.log.bind(ll),t&&cl.set("logging_enabled",!0)):"function"==typeof e?dl=e:(dl=null,cl.remove("logging_enabled"))},bl=function(...e){var t;!0===pl&&(pl=!1,null===dl&&!0===cl.get("logging_enabled")&&wl(!0)),dl&&(t=hl.apply(null,e),dl(t))},Il=function(...e){var t=`FIREBASE FATAL ERROR: ${hl(...e)}`;throw ll.error(t),new Error(t)},Tl=function(...e){var t="FIREBASE WARNING: "+hl(...e);ll.warn(t)},El=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Tl("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Cl=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},Sl="[MIN_NAME]",kl="[MAX_NAME]",Al=function(e,t){if(e===t)return 0;if(e===Sl||t===kl)return-1;if(t===Sl||e===kl)return 1;var n=Pl(e),r=Pl(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1};function Nl(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Rl(e){f(!Cl(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));const a=[];for(s=52;s;--s)a.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)a.push(n%2?1:0),n=Math.floor(n/2);a.push(t?1:0),a.reverse();const o=a.join("");let c="";for(s=0;s<64;s+=8){let e=parseInt(o.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),c+=e}return c.toLowerCase()}function Pl(e){if(xl.test(e)){var t=Number(e);if(t>=Ol&&t<=Ml)return t}return null}function Dl(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n}const xl=new RegExp("^-?(0*)\\d{1,10}$"),Ol=-2147483648,Ml=2147483647,Ll=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw Tl("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Fl{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(n){return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){var e;null!==(e=this.appCheckProvider)&&void 0!==e&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){Tl(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Ul{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(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(bl("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}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/.',Tl(e)}}class Vl{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Vl.OWNER="owner";const ql=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,jl="websocket",Bl="long_polling";class zl{constructor(e,t,n,r,i=!1,s="",a=!1,o=!1){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=o,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ol.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()&&ol.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function $l(e,t,n){f("string"==typeof t,"typeof type must == string"),f("object"==typeof n,"typeof params must == object");let r;if(t===jl)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Bl)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);const i=[];return Nl(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class Kl{constructor(){this.counters_={}}incrementCounter(e,t=1){F(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return c(void 0,this.counters_)}}const Wl={},Gl={};function Hl(e){var t=e.toString();return Wl[t]||(Wl[t]=new Kl),Wl[t]}class Ql{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];){const n=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let e=0;e<n.length;++e)n[e]&&Ll(()=>{this.onMessage_(n[e])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class Yl{constructor(e,t,n,r,i,s,a){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=fl(e),this.stats_=Hl(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),$l(t,Bl,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Ql(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),function(t){if("complete"===document.readyState)t();else{let e=!1;const n=function(){document.body?e||(e=!0,t()):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))}}(()=>{if(!this.isClosed_){this.scriptTagHolder=new Jl((...e)=>{var[t,n,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const t={start:"t"};t.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(t.cb=this.scriptTagHolder.uniqueCallbackIdentifier),t.v="5",this.transportSessionId&&(t.s=this.transportSessionId),this.lastSessionId&&(t.ls=this.lastSessionId),this.applicationId&&(t.p=this.applicationId),this.appCheckToken&&(t.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&ql.test(location.hostname)&&(t.r="f");var e=this.urlFn(t);this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{})}})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Yl.forceAllow_=!0}static forceDisallow(){Yl.forceDisallow_=!0}static isAvailable(){return!!Yl.forceAllow_||!(Yl.forceDisallow_||"undefined"==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){var t=M(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var t=i(t),n=yl(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const 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){var t=M(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class Jl{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=ul(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=Jl.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){bl("frame writing exception"),e.stack&&bl(e.stack),bl(e)}}}static createIFrame_(){const t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||bl("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}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)));const 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<(0<this.pendingSegs.length?2:1)){this.currentSerial++;const i={};i.id=this.myID,i.pw=this.myPW,i.ser=this.currentSerial;var n=this.urlFn(i);let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{bl("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}catch(e){}},Math.floor(1))}}let Xl=null;"undefined"!=typeof MozWebSocket?Xl=MozWebSocket:"undefined"!=typeof WebSocket&&(Xl=WebSocket);class Zl{constructor(e,t,n,r,i,s,a){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=fl(this.connId),this.stats_=Hl(t),this.connURL=Zl.connectionURL_(t,s,a,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){const s={v:"5"};return"undefined"!=typeof location&&location.hostname&&ql.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s.ac=r),i&&(s.p=i),$l(e,jl,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ol.set("previous_websocket_failure",!0);try{k(),this.mySock=new Xl(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},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.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){Zl.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return"undefined"==typeof navigator||!navigator.userAgent||(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4&&(e=!0),!e&&null!==Xl&&!Zl.forceDisallow_}static previouslyFailed(){return ol.isInMemoryStorage||!0===ol.get("previous_websocket_failure")}markConnectionHealthy(){ol.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=O(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(f(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=M(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var n=yl(t,16384);1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}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)}}}Zl.responsesRequiredToBeHealthy=2,Zl.healthyTimeout=3e4;class eu{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[Yl,Zl]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){var t=Zl&&Zl.isAvailable();let n=t&&!Zl.previouslyFailed();if(e.webSocketOnly&&(t||Tl("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[Zl];else{const r=this.transports_=[];for(const i of eu.ALL_TRANSPORTS)i&&i.isAvailable()&&r.push(i);eu.globalTransportInitialized_=!0}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}eu.globalTransportInitialized_=!1;class tu{constructor(e,t,n,r,i,s,a,o,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=a,this.onDisconnect_=o,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=fl("c:"+this.id+":"),this.transportManager_=new eu(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),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));var r=e.healthyTimeout||0;0<r&&(this.healthyTimeout_=Dl(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?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(r)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):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){var t;"t"in e&&("a"===(t=e.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){var t=vl("t",e),n=vl("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}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:"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){var t=vl("t",e),n=vl("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){var t=vl("t",e);if("d"in e){var n=e.d;if("h"===t){const r=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(r.h=this.repoInfo_.host),this.onHandshake_(r)}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?gl("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):gl("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&Tl("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var 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;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),Dl(()=>{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):Dl(()=>{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_(){var 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()&&(ol.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 nu{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class ru{constructor(e){this.allowedEvents_=e,this.listeners_={},f(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){const r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){f(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class iu extends ru{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||I()||(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 iu}getInitialEvent(e){return f("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class su{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function au(){return new su("")}function ou(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function cu(e){return e.pieces_.length-e.pieceNum_}function lu(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new su(e.pieces_,t)}function uu(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function hu(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function du(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new su(t,0)}function pu(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof su)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new su(n,0)}function fu(e){return e.pieceNum_>=e.pieces_.length}function gu(e,t){var n=ou(e),r=ou(t);if(null===n)return t;if(n===r)return gu(lu(e),lu(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function mu(e,t){var n=hu(e,0),r=hu(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Al(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function vu(e,t){if(cu(e)!==cu(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function _u(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(cu(e)>cu(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class yu{constructor(e,t){this.errorPrefix_=t,this.parts_=hu(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=te(this.parts_[n]);wu(this)}}function wu(e){if(768<e.byteLength_)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(32<e.parts_.length)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+bu(e))}function bu(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class Iu extends ru{constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}static getInstance(){return new Iu}getInitialEvent(e){return f("visible"===e,"Unknown event type: "+e),[this.visible_]}}class Tu extends nu{constructor(e,t,n,r,i,s,a,o){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=a,this.authOverride_=o,this.id=Tu.nextPersistentConnectionId_++,this.log_=fl("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,o&&!k())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Iu.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&iu.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(M(i)),f(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const n=new y;var t={p:e._path.toString(),q:e._queryObject};this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?n.resolve(t):n.reject(t)}}),this.outstandingGetCount_++;t=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(t),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),f(!this.listens.get(s).has(i),"listen() called twice for same path/queryId.");var a={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(s).set(i,a),this.connected_&&this.sendListen_(a)}sendGet_(t){const n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(r){const i=r.query,s=i._path.toString(),a=i._queryIdentifier;this.log_("Listen on "+s+" for "+a);const e={p:s};r.tag&&(e.q=i._queryObject,e.t=r.tag),e.h=r.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s;Tu.warnOnListenWarnings_(t,i),(this.listens.get(s)&&this.listens.get(s).get(a))===r&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(s,a),r.onComplete&&r.onComplete(n,t))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&F(e,"w")){const i=U(e,"w");var n,r;Array.isArray(i)&&~i.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),Tl("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+`${r} 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){var t;(e&&40===e.length||(e=e,"object"==typeof(t=L(e).claims)&&!0===t.admin))&&(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_){const r=this.authToken_;var e=function(e){const t=L(e),n=t.claims;return!!n&&"object"==typeof n&&n.hasOwnProperty("iat")}(r)?"auth":"gauth";const t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}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,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const s={p:t,d:n};void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++;var a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+t)}sendPut_(t){const n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;const r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+M(e));var t=e.r;const 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;"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):gl("Unrecognized action received from server: "+M(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){f(!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_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=(new Date).getTime()-this.lastConnectionAttemptTime_,e=Math.max(0,this.reconnectDelay_-e),e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),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;var e=this.onDataMessage_.bind(this),r=this.onReady_.bind(this);const u=this.onRealtimeDisconnect_.bind(this);var i=this.id+":"+Tu.nextConnectionId_++,s=this.lastSessionId;let t=!1,n=null;var a=function(){n?n.close():(t=!0,u())};this.realtime_={close:a,sendRequest:function(e){f(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}};var o=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{var[c,l]=await Promise.all([this.authTokenProvider_.getToken(o),this.appCheckTokenProvider_.getToken(o)]);t?bl("getToken() completed but was canceled"):(bl("getToken() completed. Creating connection."),this.authToken_=c&&c.accessToken,this.appCheckToken_=l&&l.token,n=new tu(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,r,u,e=>{Tl(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&Tl(e),a())}}}interrupt(e){bl("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){bl("Resuming connection for reason: "+e),delete this.interruptReasons_[e],V(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const 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=>_l(e)).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n=new su(e).toString();let r;if(this.listens.has(n)){const i=this.listens.get(n);r=i.get(t),i.delete(t),0===i.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){bl("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){bl("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const t of this.listens.values())for(const n of t.values())this.sendListen_(n);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){const e={};e["sdk.js."+Qc.replace(/\./g,"-")]=1,I()?e["framework.cordova"]=1:C()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=iu.getInstance().currentlyOnline();return V(this.interruptReasons_)&&e}}Tu.nextPersistentConnectionId_=0,Tu.nextConnectionId_=0;class Eu{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new Eu(e,t)}}class Cu{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new Eu(Sl,e),r=new Eu(Sl,t);return 0!==this.compare(n,r)}minPost(){return Eu.MIN}}let Su;class ku extends Cu{static get __EMPTY_NODE(){return Su}static set __EMPTY_NODE(e){Su=e}compare(e,t){return Al(e.name,t.name)}isDefinedOn(e){throw u("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return Eu.MIN}maxPost(){return new Eu(kl,Su)}makePost(e,t){return f("string"==typeof e,"KeyIndex indexValue must always be a string."),new Eu(e,Su)}toString(){return".key"}}const Au=new ku;class Nu{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){if(0===this.nodeStack_.length)return null;var e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class Ru{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:Ru.RED,this.left=null!=r?r:Du.EMPTY_NODE,this.right=null!=i?i:Du.EMPTY_NODE}copy(e,t,n,r,i){return new Ru(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}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 r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return Du.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),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)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 Du.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){var e=this.copy(null,null,Ru.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,Ru.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var 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_(){var e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}Ru.RED=!0,Ru.BLACK=!1;class Pu{copy(e,t,n,r,i){return this}insert(e,t,n){return new Ru(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}}class Du{constructor(e,t=Du.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Du(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,Ru.BLACK,null,null))}remove(e){return new Du(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Ru.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new Nu(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Nu(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Nu(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Nu(this.root_,null,this.comparator_,!0,e)}}function xu(e,t){return Al(e.name,t.name)}function Ou(e,t){return Al(e,t)}Du.EMPTY_NODE=new Pu;let Mu;function Lu(e){return"number"==typeof e?"number:"+Rl(e):"string:"+e}function Fu(e){var t;e.isLeafNode()?(t=e.val(),f("string"==typeof t||"number"==typeof t||"object"==typeof t&&F(t,".sv"),"Priority must be a string or number.")):f(e===Mu||e.isEmpty(),"priority of unexpected type."),f(e===Mu||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let Uu;class Vu{constructor(e,t=Vu.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,f(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Fu(this.priorityNode_)}static set __childrenNodeConstructor(e){Uu=e}static get __childrenNodeConstructor(){return Uu}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Vu(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Vu.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return fu(e)?this:".priority"===ou(e)?this.priorityNode_:Vu.__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:Vu.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=ou(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(f(".priority"!==n||1===cu(e),".priority must be the last token in a path"),this.updateImmediateChild(n,Vu.__childrenNodeConstructor.EMPTY_NODE.updateChild(lu(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:"+Lu(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"==t?Rl(this.value_):this.value_,this.lazyHash_=al(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Vu.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Vu.__childrenNodeConstructor?-1:(f(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=Vu.VALUE_TYPE_ORDER.indexOf(t),i=Vu.VALUE_TYPE_ORDER.indexOf(n);return f(0<=r,"Unknown leaf type: "+t),f(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&(this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_))}}Vu.VALUE_TYPE_ORDER=["object","boolean","number","string"];let qu,ju;const Bu=new class extends Cu{compare(e,t){const n=e.node.getPriority();var r=t.node.getPriority(),r=n.compareTo(r);return 0===r?Al(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return Eu.MIN}maxPost(){return new Eu(kl,new Vu("[PRIORITY-POST]",ju))}makePost(e,t){var n=qu(e);return new Eu(t,new Vu("[PRIORITY-POST]",n))}toString(){return".priority"}},zu=Math.log(2);class $u{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/zu,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=e+1&r}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function Ku(c,e,l,t){c.sort(e);const u=function(e,t){var n=t-e;let r,i;if(0==n)return null;if(1==n)return r=c[e],i=l?l(r):r,new Ru(i,r.node,Ru.BLACK,null,null);var s=parseInt(n/2,10)+e,a=u(e,s),n=u(s+1,t);return r=c[s],i=l?l(r):r,new Ru(i,r.node,Ru.BLACK,a,n)};var n=function(e){let s=null,a=null,o=c.length;function t(e,t){var n=o-e,r=o;o-=e;var i=u(1+n,r),r=c[n],n=l?l(r):r;!function(e){if(s){s.left=e;s=e}else{a=e;s=e}}(new Ru(n,r.node,t,null,i))}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,Ru.BLACK):(t(r,Ru.BLACK),t(r,Ru.RED))}return a}(new $u(c.length));return new Du(t||e,n)}let Wu;const Gu={};class Hu{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return f((Gu,Bu),"ChildrenNode.ts has not been loaded"),Wu=Wu||new Hu({".priority":Gu},{".priority":Bu}),Wu}get(e){var t=U(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof Du?t:null}hasIndex(e){return F(this.indexSet_,e.toString())}addIndex(e,t){f(e!==Au,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(Eu.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let a;a=r?Ku(n,e.getCompare()):Gu;var o=e.toString();const c=Object.assign({},this.indexSet_);c[o]=e;const l=Object.assign({},this.indexes_);return l[o]=a,new Hu(l,c)}addToIndexes(a,o){var e=q(this.indexes_,(t,e)=>{const n=U(this.indexSet_,e);if(f(n,"Missing index implementation for "+e),t===Gu){if(n.isDefinedOn(a.node)){const i=[],s=o.getIterator(Eu.Wrap);let e=s.getNext();for(;e;)e.name!==a.name&&i.push(e),e=s.getNext();return i.push(a),Ku(i,n.getCompare())}return Gu}{var r=o.get(a.name);let e=t;return r&&(e=e.remove(new Eu(a.name,r))),e.insert(a,a.node)}});return new Hu(e,this.indexSet_)}removeFromIndexes(n,r){var e=q(this.indexes_,e=>{if(e===Gu)return e;var t=r.get(n.name);return t?e.remove(new Eu(n.name,t)):e});return new Hu(e,this.indexSet_)}}let Qu;class Yu{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Fu(this.priorityNode_),this.children_.isEmpty()&&f(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return Qu=Qu||new Yu(new Du(Ou),null,Hu.Default)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Qu}updatePriority(e){return this.children_.isEmpty()?this:new Yu(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?Qu:t}getChild(e){var t=ou(e);return null===t?this:this.getImmediateChild(t).getChild(lu(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(f(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new Eu(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?Qu:this.priorityNode_;return new Yu(e,i,t)}}updateChild(e,t){var n=ou(e);if(null===n)return t;f(".priority"!==ou(e)||1===cu(e),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(lu(e),t);return this.updateImmediateChild(n,r)}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;const r={};let i=0,s=0,a=!0;if(this.forEachChild(Bu,(e,t)=>{r[e]=t.val(n),i++,a&&Yu.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):a=!1}),!n&&a&&s<2*i){const e=[];for(const t in r)e[t]=r[t];return e}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+Lu(this.getPriority().val())+":"),this.forEachChild(Bu,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":al(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new Eu(e,t));return i?i.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.minKey();return n&&n.name}return this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new Eu(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.maxKey();return n&&n.name}return this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new Eu(t,this.children_.get(t)):null}forEachChild(e,t){const 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(t,n){const e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{const r=this.children_.getIteratorFrom(t.name,Eu.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{const r=this.children_.getReverseIteratorFrom(t.name,Eu.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===Xu?-1:0}withIndex(e){if(e===Au||this.indexMap_.hasIndex(e))return this;var t=this.indexMap_.addIndex(e,this.children_);return new Yu(this.children_,this.priorityNode_,t)}isIndexed(e){return e===Au||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{const r=this.getIterator(Bu),i=n.getIterator(Bu);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}return!1}}resolveIndex_(e){return e===Au?null:this.indexMap_.get(e.toString())}}Yu.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Ju extends Yu{constructor(){super(new Du(Ou),Yu.EMPTY_NODE,Hu.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return Yu.EMPTY_NODE}isEmpty(){return!1}}const Xu=new Ju;Object.defineProperties(Eu,{MIN:{value:new Eu(Sl,Yu.EMPTY_NODE)},MAX:{value:new Eu(kl,Xu)}}),ku.__EMPTY_NODE=Yu.EMPTY_NODE,Vu.__childrenNodeConstructor=Yu,Zc=Xu,Mu=Zc,el=Xu,ju=el;const Zu=!0;function eh(i,e=null){if(null===i)return Yu.EMPTY_NODE;if("object"==typeof i&&".priority"in i&&(e=i[".priority"]),f(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(i="object"==typeof i&&".value"in i&&null!==i[".value"]?i[".value"]:i)||".sv"in i){var t=i;return new Vu(t,eh(e))}if(i instanceof Array||!Zu){let r=Yu.EMPTY_NODE;return Nl(i,(e,t)=>{if(F(i,e)&&"."!==e.substring(0,1)){const n=eh(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(eh(e))}{const s=[];let r=!1;if(Nl(i,(e,t)=>{if("."!==e.substring(0,1)){const n=eh(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new Eu(e,n)))}}),0===s.length)return Yu.EMPTY_NODE;var n=Ku(s,xu,e=>e.name,Ou);if(r){t=Ku(s,Bu.getCompare());return new Yu(n,eh(e),new Hu({".priority":t},{".priority":Bu}))}return new Yu(n,eh(e),Hu.Default)}}qu=eh;class th extends Cu{constructor(e){super(),this.indexPath_=e,f(!fu(e)&&".priority"!==ou(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){const n=this.extractChild(e.node);var r=this.extractChild(t.node),r=n.compareTo(r);return 0===r?Al(e.name,t.name):r}makePost(e,t){var n=eh(e),n=Yu.EMPTY_NODE.updateChild(this.indexPath_,n);return new Eu(t,n)}maxPost(){var e=Yu.EMPTY_NODE.updateChild(this.indexPath_,Xu);return new Eu(kl,e)}toString(){return hu(this.indexPath_,0).join("/")}}const nh=new class extends Cu{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?Al(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return Eu.MIN}maxPost(){return Eu.MAX}makePost(e,t){var n=eh(e);return new Eu(t,n)}toString(){return".value"}};function rh(e){return{type:"value",snapshotNode:e}}function ih(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function sh(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function ah(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class oh{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){f(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(r).equals(n.getChild(r))&&a.isEmpty()===n.isEmpty()?e:(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(sh(t,a)):f(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(ih(t,n)):s.trackChildChange(ah(t,n,a))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(Bu,(e,t)=>{n.hasChild(e)||i.trackChildChange(sh(e,t))}),n.isLeafNode()||n.forEachChild(Bu,(e,t)=>{if(r.hasChild(e)){const n=r.getImmediateChild(e);n.equals(t)||i.trackChildChange(ah(e,t,n))}else i.trackChildChange(ih(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?Yu.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class ch{constructor(e){this.indexedFilter_=new oh(e.getIndex()),this.index_=e.getIndex(),this.startPost_=ch.getStartPost_(e),this.endPost_=ch.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){var t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,s){return this.matches(new Eu(t,n))||(n=Yu.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?Yu.EMPTY_NODE:t).withIndex(this.index_);r=r.updatePriority(Yu.EMPTY_NODE);const i=this;return t.forEachChild(Bu,(e,t)=>{i.matches(new Eu(e,t))||(r=r.updateImmediateChild(e,Yu.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){var t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){var t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class lh{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=>{var t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{var t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new ch(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new Eu(t,n))||(n=Yu.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,n,t){let r;if(n.isLeafNode()||n.isEmpty())r=Yu.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<n.numChildren()&&n.isIndexed(this.index_)){r=Yu.EMPTY_NODE.withIndex(this.index_);let e;e=this.reverse_?n.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):n.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let t=0;for(;e.hasNext()&&t<this.limit_;){var i=e.getNext();if(this.withinDirectionalStart(i)){if(!this.withinDirectionalEnd(i))break;r=r.updateImmediateChild(i.name,i.node),t++}}}else{r=n.withIndex(this.index_),r=r.updatePriority(Yu.EMPTY_NODE);let e;e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_);let t=0;for(;e.hasNext();){var s=e.getNext();t<this.limit_&&this.withinDirectionalStart(s)&&this.withinDirectionalEnd(s)?t++:r=r.updateImmediateChild(s.name,Yu.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){const d=this.index_.getCompare();s=(e,t)=>d(t,e)}else s=this.index_.getCompare();const a=e;f(a.numChildren()===this.limit_,"");var o=new Eu(t,n),c=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),l=this.rangedFilter_.matches(o);if(a.hasChild(t)){var u=a.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,c,this.reverse_);for(;null!=e&&(e.name===t||a.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var h=null==e?1:s(e,o);if(l&&!n.isEmpty()&&0<=h)return null!=i&&i.trackChildChange(ah(t,n,u)),a.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(sh(t,u));const p=a.updateImmediateChild(t,Yu.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(ih(e.name,e.node)),p.updateImmediateChild(e.name,e.node)):p}}return!n.isEmpty()&&l&&0<=s(c,o)?(null!=i&&(i.trackChildChange(sh(c.name,c.node)),i.trackChildChange(ih(t,n))),a.updateImmediateChild(t,n).updateImmediateChild(c.name,Yu.EMPTY_NODE)):e}}class uh{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_=Bu}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return f(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return f(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Sl}hasEnd(){return this.endSet_}getIndexEndValue(){return f(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return f(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:kl}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return f(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_===Bu}copy(){const e=new uh;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 hh(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function dh(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function ph(e,t){const n=e.copy();return n.index_=t,n}function fh(e){const t={};if(e.isDefault())return t;let n;var r;return n=e.index_===Bu?"$priority":e.index_===nh?"$value":e.index_===Au?"$key":(f(e.index_ instanceof th,"Unrecognized index type!"),e.index_.toString()),t.orderBy=M(n),e.startSet_&&(r=e.startAfterSet_?"startAfter":"startAt",t[r]=M(e.indexStartValue_),e.startNameSet_&&(t[r]+=","+M(e.indexStartName_))),e.endSet_&&(r=e.endBeforeSet_?"endBefore":"endAt",t[r]=M(e.indexEndValue_),e.endNameSet_&&(t[r]+=","+M(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function gh(t){const n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_),n.sin=!t.startAfterSet_),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_),n.ein=!t.endBeforeSet_),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==Bu&&(n.i=t.index_.toString()),n}class mh extends nu{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=fl("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(f(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,r,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const a=mh.getListenId_(e,r),o={};this.listens_[a]=o;var n=fh(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),U(this.listens_,a)===o){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=mh.getListenId_(e,t);delete this.listens_[n]}get(e){var t=fh(e._queryParams);const r=e._path.toString(),i=new y;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},a){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);const n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+z(s);this.log_("Sending REST request for "+n);const r=new XMLHttpRequest;r.onreadystatechange=()=>{if(a&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=O(r.responseText)}catch(e){Tl("Failed to parse JSON response for "+n+": "+r.responseText)}a(null,e)}else 401!==r.status&&404!==r.status&&Tl("Got unsuccessful REST response for "+n+" Status: "+r.status),a(r.status);a=null}},r.open("GET",n,!0),r.send()})}}class vh{constructor(){this.rootNode_=Yu.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function _h(){return{value:null,children:new Map}}function yh(e,t,n){var r;fu(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=ou(t),e.children.has(r)||e.children.set(r,_h()),yh(e.children.get(r),t=lu(t),n))}function wh(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{wh(t,new su(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class bh{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();const n=Object.assign({},e);return this.last_&&Nl(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class Ih{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new bh(e);var n=1e4+2e4*Math.random();Dl(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();const n={};let r=!1;Nl(e,(e,t)=>{0<t&&F(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),Dl(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function Th(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Eh(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function Ch(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(Kk=tl=tl||{})[Kk.OVERWRITE=0]="OVERWRITE",Kk[Kk.MERGE=1]="MERGE",Kk[Kk.ACK_USER_WRITE=2]="ACK_USER_WRITE",Kk[Kk.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class Sh{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=tl.ACK_USER_WRITE,this.source=Th()}operationForChild(e){if(fu(this.path)){if(null!=this.affectedTree.value)return f(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var t=this.affectedTree.subtree(new su(e));return new Sh(au(),t,this.revert)}return f(ou(this.path)===e,"operationForChild called for unrelated child."),new Sh(lu(this.path),this.affectedTree,this.revert)}}class kh{constructor(e,t){this.source=e,this.path=t,this.type=tl.LISTEN_COMPLETE}operationForChild(e){return fu(this.path)?new kh(this.source,au()):new kh(this.source,lu(this.path))}}class Ah{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=tl.OVERWRITE}operationForChild(e){return fu(this.path)?new Ah(this.source,au(),this.snap.getImmediateChild(e)):new Ah(this.source,lu(this.path),this.snap)}}class Nh{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=tl.MERGE}operationForChild(e){if(fu(this.path)){const t=this.children.subtree(new su(e));return t.isEmpty()?null:t.value?new Ah(this.source,au(),t.value):new Nh(this.source,au(),t)}return f(ou(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Nh(this.source,lu(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Rh{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(fu(e))return this.isFullyInitialized()&&!this.filtered_;var t=ou(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Ph{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function Dh(n,e,t,r){var i=[];const s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),xh(n,i,"child_removed",e,r,t),xh(n,i,"child_added",e,r,t),xh(n,i,"child_moved",s,r,t),xh(n,i,"child_changed",e,r,t),xh(n,i,"value",e,r,t),i}function xh(s,a,t,e,o,c){const n=e.filter(e=>e.type===t);n.sort((e,t)=>function(e,t,n){if(null==t.childName||null==n.childName)throw u("Should only compare child_ events.");var r=new Eu(t.childName,t.snapshotNode),i=new Eu(n.childName,n.snapshotNode);return e.index_.compare(r,i)}(s,e,t)),n.forEach(t=>{const n=(e=s,i=c,"value"===(r=t).type||"child_removed"===r.type||(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_)),r);var e,r,i;o.forEach(e=>{e.respondsTo(t.type)&&a.push(e.createEvent(n,s.query_))})})}function Oh(e,t){return{eventCache:e,serverCache:t}}function Mh(e,t,n,r){return Oh(new Rh(t,n,r),e.serverCache)}function Lh(e,t,n,r){return Oh(e.eventCache,new Rh(t,n,r))}function Fh(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function Uh(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Vh;class qh{constructor(e,t=(Vh=Vh||new Du(ml),Vh)){this.value=e,this.children=t}static fromObject(e){let n=new qh(null);return Nl(e,(e,t)=>{n=n.set(new su(e),t)}),n}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:au(),value:this.value};if(fu(e))return null;{var n=ou(e);const i=this.children.get(n);if(null===i)return null;var r=i.findRootMostMatchingPathAndValue(lu(e),t);return null==r?null:{path:pu(new su(n),r.path),value:r.value}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(fu(e))return this;{var t=ou(e);const n=this.children.get(t);return null!==n?n.subtree(lu(e)):new qh(null)}}set(e,t){if(fu(e))return new qh(t,this.children);{var n=ou(e);const i=this.children.get(n)||new qh(null);var r=i.set(lu(e),t),r=this.children.insert(n,r);return new qh(this.value,r)}}remove(t){if(fu(t))return this.children.isEmpty()?new qh(null):new qh(null,this.children);{var n=ou(t);const r=this.children.get(n);if(r){const i=r.remove(lu(t));let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&e.isEmpty()?new qh(null):new qh(this.value,e)}return this}}get(e){if(fu(e))return this.value;{var t=ou(e);const n=this.children.get(t);return n?n.get(lu(e)):null}}setTree(t,n){if(fu(t))return n;{var r=ou(t);const i=this.children.get(r)||new qh(null),s=i.setTree(lu(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new qh(this.value,e)}}fold(e){return this.fold_(au(),e)}fold_(n,r){const i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(pu(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,au(),t)}findOnPath_(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(fu(e))return null;{r=ou(e);const i=this.children.get(r);return i?i.findOnPath_(lu(e),pu(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,au(),t)}foreachOnPath_(e,t,n){if(fu(e))return this;{this.value&&n(t,this.value);var r=ou(e);const i=this.children.get(r);return i?i.foreachOnPath_(lu(e),pu(t,r),n):new qh(null)}}foreach(e){this.foreach_(au(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(pu(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class jh{constructor(e){this.writeTree_=e}static empty(){return new jh(new qh(null))}}function Bh(t,n,r){if(fu(n))return new jh(new qh(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=gu(s,n);return e=e.updateChild(i,r),new jh(t.writeTree_.set(s,e))}s=new qh(r),s=t.writeTree_.setTree(n,s);return new jh(s)}function zh(e,n,t){let r=e;return Nl(t,(e,t)=>{r=Bh(r,pu(n,e),t)}),r}function $h(e,t){if(fu(t))return jh.empty();var n=e.writeTree_.setTree(t,new qh(null));return new jh(n)}function Kh(e,t){return null!=Wh(e,t)}function Wh(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(gu(n.path,t)):null}function Gh(e){const n=[],t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(Bu,(e,t)=>{n.push(new Eu(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new Eu(e,t.value))}),n}function Hh(e,t){if(fu(t))return e;var n=Wh(e,t);return null!=n?new jh(new qh(n)):new jh(e.writeTree_.subtree(t))}function Qh(e){return e.writeTree_.isEmpty()}function Yh(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(f(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(pu(i,e),t,s)}),s=!s.getChild(i).isEmpty()&&null!==n?s.updateChild(pu(i,".priority"),n):s}}}(au(),e.writeTree_,t)}function Jh(e,t){return ld(t,e)}function Xh(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);f(0<=r,"removeWrite called with nonexistent writeId.");const i=t.allWrites[r];t.allWrites.splice(r,1);let s=i.visible,a=!1,o=t.allWrites.length-1;for(;s&&0<=o;){var c=t.allWrites[o];c.visible&&(o>=r&&function(e,t){{if(e.snap)return _u(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&_u(pu(e.path,n),t))return!0;return!1}}(c,i.path)?s=!1:_u(i.path,c.path)&&(a=!0)),o--}return!!s&&(a?((e=t).visibleWrites=ed(e.allWrites,Zh,au()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=$h(t.visibleWrites,i.path):Nl(i.children,e=>{t.visibleWrites=$h(t.visibleWrites,pu(i.path,e))}),!0)}function Zh(e){return e.visible}function ed(e,t,n){let r=jh.empty();for(let s=0;s<e.length;++s){const a=e[s];if(t(a)){var i=a.path;let e;if(a.snap)_u(n,i)?(e=gu(n,i),r=Bh(r,e,a.snap)):_u(i,n)&&(e=gu(i,n),r=Bh(r,au(),a.snap.getChild(e)));else{if(!a.children)throw u("WriteRecord should have .snap or .children");if(_u(n,i))e=gu(n,i),r=zh(r,e,a.children);else if(_u(i,n))if(e=gu(i,n),fu(e))r=zh(r,au(),a.children);else{const o=U(a.children,ou(e));o&&(i=o.getChild(lu(e)),r=Bh(r,au(),i))}}}}return r}function td(e,t,n,r,i){if(r||i){var s=Hh(e.visibleWrites,t);if(!i&&Qh(s))return n;if(i||null!=n||Kh(s,au()))return Yh(ed(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(_u(e.path,t)||_u(t,e.path))},t),n||Yu.EMPTY_NODE);return null}s=Wh(e.visibleWrites,t);if(null!=s)return s;s=Hh(e.visibleWrites,t);return Qh(s)?n:null!=n||Kh(s,au())?Yh(s,n||Yu.EMPTY_NODE):null}function nd(e,t,n,r){return td(e.writeTree,e.treePath,t,n,r)}function rd(e,t){return function(e,t,n){let r=Yu.EMPTY_NODE;const i=Wh(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(Bu,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const s=Hh(e.visibleWrites,t);return n.forEachChild(Bu,(e,t)=>{var n=Yh(Hh(s,new su(e)),t);r=r.updateImmediateChild(e,n)}),Gh(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return Gh(Hh(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function id(e,t,n,r){return function(e,t,n,r,i){f(r||i,"Either existingEventSnap or existingServerSnap must exist");var s=pu(t,n);return Kh(e.visibleWrites,s)?null:Qh(s=Hh(e.visibleWrites,s))?i.getChild(n):Yh(s,i.getChild(n))}(e.writeTree,e.treePath,t,n,r)}function sd(e,t){return n=e.writeTree,t=pu(e.treePath,t),Wh(n.visibleWrites,t);var n}function ad(e,t,n,r,i,s){return function(e,t,n,r,i,s,a){let o;var c=Hh(e.visibleWrites,t),l=Wh(c,au());if(null!=l)o=l;else{if(null==n)return[];o=Yh(c,n)}if(o=o.withIndex(a),o.isEmpty()||o.isLeafNode())return[];{const u=[],h=a.getCompare(),d=s?o.getReverseIteratorFrom(r,a):o.getIteratorFrom(r,a);let e=d.getNext();for(;e&&u.length<i;)0!==h(e,r)&&u.push(e),e=d.getNext();return u}}(e.writeTree,e.treePath,t,n,r,i,s)}function od(e,t,n){return r=e.writeTree,e=e.treePath,n=n,i=pu(e,t=t),null!=(s=Wh(r.visibleWrites,i))?s:n.isCompleteForChild(t)?Yh(Hh(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function cd(e,t){return ld(pu(e.treePath,t),e.writeTree)}function ld(e,t){return{treePath:e,writeTree:t}}class ud{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName;f("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),f(".priority"!==n,"Only non-priority child changes can be tracked.");var r=this.changeMap.get(n);if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,ah(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,sh(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,ih(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw u("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,ah(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const hd=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class dd{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.optCompleteServerCache_?new Rh(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return od(this.writes_,e,n)}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:Uh(this.viewCache_),r=ad(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function pd(e,t,n,r,i){const s=new ud;let a,o;if(n.type===tl.OVERWRITE){var c=n;a=c.source.fromUser?md(e,t,c.path,c.snap,r,i,s):(f(c.source.fromServer,"Unknown source."),o=c.source.tagged||t.serverCache.isFiltered()&&!fu(c.path),gd(e,t,c.path,c.snap,r,i,o,s))}else if(n.type===tl.MERGE){c=n;a=c.source.fromUser?function(r,i,s,e,a,o,c){let l=i;return e.foreach((e,t)=>{var n=pu(s,e);vd(i,ou(n))&&(l=md(r,l,n,t,a,o,c))}),e.foreach((e,t)=>{var n=pu(s,e);vd(i,ou(n))||(l=md(r,l,n,t,a,o,c))}),l}(e,t,c.path,c.children,r,i,s):(f(c.source.fromServer,"Unknown source."),o=c.source.tagged||t.serverCache.isFiltered(),yd(e,t,c.path,c.children,r,i,o,s))}else if(n.type===tl.ACK_USER_WRITE){var l=n;a=l.revert?function(n,r,i,s,e,a){let o;{if(null!=sd(s,i))return r;{var c=new dd(s,r,e);const u=r.eventCache.getNode();let t;if(fu(i)||".priority"===ou(i)){let e;e=r.serverCache.isFullyInitialized()?nd(s,Uh(r)):(l=r.serverCache.getNode(),f(l instanceof Yu,"serverChildren would be complete if leaf node"),rd(s,l)),e=e,t=n.filter.updateFullNode(u,e,a)}else{var l=ou(i);let e=od(s,l,r.serverCache);null==e&&r.serverCache.isCompleteForChild(l)&&(e=u.getImmediateChild(l)),t=null!=e?n.filter.updateChild(u,l,e,lu(i),c,a):r.eventCache.getNode().hasChild(l)?n.filter.updateChild(u,l,Yu.EMPTY_NODE,lu(i),c,a):u,t.isEmpty()&&r.serverCache.isFullyInitialized()&&(o=nd(s,Uh(r)),o.isLeafNode()&&(t=n.filter.updateFullNode(t,o,a)))}return o=r.serverCache.isFullyInitialized()||null!=sd(s,au()),Mh(r,t,o,n.filter.filtersNodes())}}}(e,t,l.path,r,i,s):function(e,t,i,n,s,a,o){if(null!=sd(s,i))return t;const c=t.serverCache.isFiltered(),l=t.serverCache;{if(null!=n.value){if(fu(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return gd(e,t,i,l.getNode().getChild(i),s,a,c,o);if(fu(i)){let n=new qh(null);return l.getNode().forEachChild(Au,(e,t)=>{n=n.set(new su(e),t)}),yd(e,t,i,n,s,a,c,o)}return t}{let r=new qh(null);return n.foreach((e,t)=>{var n=pu(i,e);l.isCompleteForPath(n)&&(r=r.set(e,l.getNode().getChild(n)))}),yd(e,t,i,r,s,a,c,o)}}}(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==tl.LISTEN_COMPLETE)throw u("Unknown operation type: "+n.type);a=function(e,t,n,r,i){const s=t.serverCache,a=Lh(t,s.getNode(),s.isFullyInitialized()||fu(n),s.isFiltered());return fd(e,a,n,r,hd,i)}(e,t,n.path,r,s)}l=s.getChanges();return function(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty();const s=Fh(e);(0<n.length||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(rh(Fh(t)))}}(t,a,l),{viewCache:a,changes:l}}function fd(r,i,s,a,o,c){const l=i.eventCache;if(null!=sd(a,s))return i;{let t,n;if(fu(s)){var e;f(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=rd(a,(e=Uh(i))instanceof Yu?e:Yu.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=nd(a,Uh(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=ou(s);if(".priority"===u){f(1===cu(s),"Can't have a priority with additional path components");var h=l.getNode();n=i.serverCache.getNode();var d=id(a,s,h,n);t=null!=d?r.filter.updatePriority(h,d):l.getNode()}else{h=lu(s);let e;e=l.isCompleteForChild(u)?(n=i.serverCache.getNode(),null!=(d=id(a,s,l.getNode(),n))?l.getNode().getImmediateChild(u).updateChild(h,d):l.getNode().getImmediateChild(u)):od(a,u,i.serverCache),t=null!=e?r.filter.updateChild(l.getNode(),u,e,h,o,c):l.getNode()}}return Mh(i,t,l.isFullyInitialized()||fu(s),r.filter.filtersNodes())}}function gd(e,t,n,r,i,s,a,o){const c=t.serverCache;let l;const u=a?e.filter:e.filter.getIndexedFilter();if(fu(n))l=u.updateFullNode(c.getNode(),r,null);else if(u.filtersNodes()&&!c.isFiltered()){var h=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),h,null)}else{var d=ou(n);if(!c.isCompleteForPath(n)&&1<cu(n))return t;var p=lu(n);const f=c.getNode().getImmediateChild(d);h=f.updateChild(p,r);l=".priority"===d?u.updatePriority(c.getNode(),h):u.updateChild(c.getNode(),d,h,p,hd,null)}p=Lh(t,l,c.isFullyInitialized()||fu(n),u.filtersNodes());return fd(e,p,n,i,new dd(i,p,s),o)}function md(t,n,r,i,e,s,a){const o=n.eventCache;let c,l;const u=new dd(e,n,s);if(fu(r))l=t.filter.updateFullNode(n.eventCache.getNode(),i,a),c=Mh(n,l,!0,t.filter.filtersNodes());else{var h=ou(r);if(".priority"===h)l=t.filter.updatePriority(n.eventCache.getNode(),i),c=Mh(n,l,o.isFullyInitialized(),o.isFiltered());else{var d=lu(r);const p=o.getNode().getImmediateChild(h);let e;if(fu(d))e=i;else{const f=u.getCompleteChild(h);e=null!=f?".priority"===uu(d)&&f.getChild(du(d)).isEmpty()?f:f.updateChild(d,i):Yu.EMPTY_NODE}c=p.equals(e)?n:Mh(n,t.filter.updateChild(o.getNode(),h,e,d,u,a),o.isFullyInitialized(),t.filter.filtersNodes())}}return c}function vd(e,t){return e.eventCache.isCompleteForChild(t)}function _d(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function yd(r,i,e,t,s,a,o,c){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let l=i,n;n=fu(e)?t:new qh(null).setTree(e,t);const u=i.serverCache.getNode();return n.children.inorderTraversal((e,t)=>{var n;u.hasChild(e)&&(n=_d(0,i.serverCache.getNode().getImmediateChild(e),t),l=gd(r,l,new su(e),n,s,a,o,c))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&null===t.value;u.hasChild(e)||n||(n=_d(0,i.serverCache.getNode().getImmediateChild(e),t),l=gd(r,l,new su(e),n,s,a,o,c))}),l}class wd{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new oh(n.getIndex()),i=(e=n).loadsAllData()?new oh(e.getIndex()):new(e.hasLimit()?lh:ch)(e);this.processor_={filter:i};const s=t.serverCache,a=t.eventCache;var o=r.updateFullNode(Yu.EMPTY_NODE,s.getNode(),null),c=i.updateFullNode(Yu.EMPTY_NODE,a.getNode(),null),o=new Rh(o,s.isFullyInitialized(),r.filtersNodes()),c=new Rh(c,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=Oh(c,o),this.eventGenerator_=new Ph(this.query_)}get query(){return this.query_}}function bd(e){return 0===e.eventRegistrations_.length}function Id(n,r,i){const s=[];if(i){f(null==r,"A cancel should cancel all event registrations.");const a=n.query._path;n.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(i,a);t&&s.push(t)})}if(r){let e=[];for(let t=0;t<n.eventRegistrations_.length;++t){const o=n.eventRegistrations_[t];if(o.matches(r)){if(r.hasAnyCallback()){e=e.concat(n.eventRegistrations_.slice(t+1));break}}else e.push(o)}n.eventRegistrations_=e}else n.eventRegistrations_=[];return s}function Td(e,t,n,r){t.type===tl.MERGE&&null!==t.source.queryId&&(f(Uh(e.viewCache_),"We should always have a full cache before handling merges"),f(Fh(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=pd(e.processor_,i,t,n,r);return n=e.processor_,r=s.viewCache,f(r.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),f(r.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed"),f(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,Ed(e,s.changes,s.viewCache.eventCache.getNode(),null)}function Ed(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return Dh(e.eventGenerator_,t,n,i)}let Cd;class Sd{constructor(){this.views=new Map}}function kd(t,n,r,i){var e=n.source.queryId;if(null!==e){e=t.views.get(e);return f(null!=e,"SyncTree gave us an op for an invalid query."),Td(e,n,r,i)}{let e=[];for(const s of t.views.values())e=e.concat(Td(s,n,r,i));return e}}function Ad(e,n,r,i,s){var a=n._queryIdentifier,a=e.views.get(a);if(a)return a;{let e=nd(r,s?i:null),t=!1;t=!!e||(e=i instanceof Yu?rd(r,i):Yu.EMPTY_NODE,!1);a=Oh(new Rh(e,t,!1),new Rh(i,s,!1));return new wd(n,a)}}function Nd(e,t,n,r,i,s){var a=Ad(e,t,r,i,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,a),a.eventRegistrations_.push(n),function(e,t){const n=e.viewCache_.eventCache,r=[];if(!n.getNode().isLeafNode()){const i=n.getNode();i.forEachChild(Bu,(e,t)=>{r.push(ih(e,t))})}return n.isFullyInitialized()&&r.push(rh(n.getNode())),Ed(e,r,n.getNode(),t)}(a,n)}function Rd(e,t,n,r){var i=t._queryIdentifier;const s=[];let a=[];var o=Md(e);if("default"===i)for(var[c,l]of e.views.entries())a=a.concat(Id(l,n,r)),bd(l)&&(e.views.delete(c),l.query._queryParams.loadsAllData()||s.push(l.query));else{const u=e.views.get(i);u&&(a=a.concat(Id(u,n,r)),bd(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return o&&!Md(e)&&s.push((f(Cd,"Reference.ts has not been loaded"),new Cd(t._repo,t._path))),{removed:s,events:a}}function Pd(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function Dd(e,t){let n=null;for(const r of e.views.values())n=n||function(e,t){const n=Uh(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!fu(t)&&!n.getImmediateChild(ou(t)).isEmpty())?n.getChild(t):null}(r,t);return n}function xd(e,t){const n=t._queryParams;if(n.loadsAllData())return Ld(e);var r=t._queryIdentifier;return e.views.get(r)}function Od(e,t){return null!=xd(e,t)}function Md(e){return null!=Ld(e)}function Ld(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Fd;let Ud=1;class Vd{constructor(e){this.listenProvider_=e,this.syncPointTree_=new qh(null),this.pendingWriteTree_={visibleWrites:jh.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function qd(e,t,n,r,i){var s,a,o,c;return s=e.pendingWriteTree_,a=t,o=n,c=r,r=i,f(c>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:a,snap:o,writeId:c,visible:r=void 0===r?!0:r}),r&&(s.visibleWrites=Bh(s.visibleWrites,a,o)),s.lastWriteId=c,i?Qd(e,new Ah(Th(),t,n)):[]}function jd(e,t,n,r){var i,s,a;i=e.pendingWriteTree_,s=t,a=n,r=r,f(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:a,writeId:r,visible:!0}),i.visibleWrites=zh(i.visibleWrites,s,a),i.lastWriteId=r;var o=qh.fromObject(n);return Qd(e,new Nh(Th(),t,o))}function Bd(e,t,n=!1){var r=function(e,t){for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null}(e.pendingWriteTree_,t);if(Xh(e.pendingWriteTree_,t)){let t=new qh(null);return null!=r.snap?t=t.set(au(),!0):Nl(r.children,e=>{t=t.set(new su(e),!0)}),Qd(e,new Sh(r.path,t,n))}return[]}function zd(e,t,n){return Qd(e,new Ah(Eh(),t,n))}function $d(n,e,t,r,i=!1){var s=e._path,a=n.syncPointTree_.get(s);let o=[];if(a&&("default"===e._queryIdentifier||Od(a,e))){var c=Rd(a,e,t,r);0===a.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(s));const d=c.removed;if(o=c.events,!i){a=-1!==d.findIndex(e=>e._queryParams.loadsAllData()),c=n.syncPointTree_.findOnPath(s,(e,t)=>Md(t));if(a&&!c){const p=n.syncPointTree_.subtree(s);if(!p.isEmpty()){var l=p.fold((e,t,r)=>{if(t&&Md(t))return[Ld(t)];{let n=[];return t&&(n=Pd(t)),Nl(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<l.length;++e){var u=l[e],h=u.query,u=Jd(n,u);n.listenProvider_.startListening(rp(h),Xd(n,h),u.hashFn,u.onComplete)}}}!c&&0<d.length&&!r&&(a?n.listenProvider_.stopListening(rp(e),null):d.forEach(e=>{var t=n.queryToTagMap.get(Zd(e));n.listenProvider_.stopListening(rp(e),t)}))}!function(e,t){for(let i=0;i<t.length;++i){const s=t[i];var n,r;s._queryParams.loadsAllData()||(n=Zd(s),r=e.queryToTagMap.get(n),e.queryToTagMap.delete(n),e.tagToQueryMap.delete(r))}}(n,d)}return o}function Kd(e,t,n,r){var i=ep(e,r);if(null==i)return[];var s=tp(i),a=s.path,i=s.queryId,s=gu(a,t);return np(e,a,new Ah(Ch(i),s,n))}function Wd(e,t,n,r=!1){const i=t._path;let s=null,a=!1;e.syncPointTree_.foreachOnPath(i,(e,t)=>{var n=gu(e,i);s=s||Dd(t,n),a=a||Md(t)});let o=e.syncPointTree_.get(i);o?(a=a||Md(o),s=s||Dd(o,au())):(o=new Sd,e.syncPointTree_=e.syncPointTree_.set(i,o));let c;if(null!=s)c=!0;else{c=!1,s=Yu.EMPTY_NODE;const p=e.syncPointTree_.subtree(i);p.foreachChild((e,t)=>{var n=Dd(t,au());n&&(s=s.updateImmediateChild(e,n))})}var l,u=Od(o,t);u||t._queryParams.loadsAllData()||(h=Zd(t),f(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),l=Ud++,e.queryToTagMap.set(h,l),e.tagToQueryMap.set(l,h));var h=Jh(e.pendingWriteTree_,i);let d=Nd(o,t,n,h,s,c);return u||a||r||(u=xd(o,t),d=d.concat(function(t,e,n){const r=e._path,i=Xd(t,e),s=Jd(t,n),a=t.listenProvider_.startListening(rp(e),i,s.hashFn,s.onComplete),o=t.syncPointTree_.subtree(r);if(i)f(!Md(o.value),"If we're adding a query, it shouldn't be shadowed");else{var c=o.fold((e,t,r)=>{if(!fu(e)&&t&&Md(t))return[Ld(t).query];{let n=[];return t&&(n=n.concat(Pd(t).map(e=>e.query))),Nl(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e];t.listenProvider_.stopListening(rp(l),Xd(t,l))}}return a}(e,t,u))),d}function Gd(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=Dd(t,gu(e,r));if(n)return n});return td(n,r,i,t,!0)}function Hd(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=gu(e,r);i=i||Dd(t,n)});let n=e.syncPointTree_.get(r);n?i=i||Dd(n,au()):(n=new Sd,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i;const a=s?new Rh(i,!0,!1):null;var o=Jh(e.pendingWriteTree_,t._path);return Fh(Ad(n,t,o,s?a.getNode():Yu.EMPTY_NODE,s).viewCache_)}function Qd(e,t){return function t(n,r,i,s){{if(fu(n.path))return Yd(n,r,i,s);{const a=r.get(au());null==i&&null!=a&&(i=Dd(a,au()));let e=[];const o=ou(n.path),c=n.operationForChild(o),l=r.children.get(o);if(l&&c){const u=i?i.getImmediateChild(o):null,h=cd(s,o);e=e.concat(t(c,l,u,h))}return a&&(e=e.concat(kd(a,n,s,i))),e}}}(t,e.syncPointTree_,null,Jh(e.pendingWriteTree_,au()))}function Yd(s,e,a,o){var t=e.get(au());null==a&&null!=t&&(a=Dd(t,au()));let c=[];return e.children.inorderTraversal((e,t)=>{var n=a?a.getImmediateChild(e):null,r=cd(o,e),i=s.operationForChild(e);i&&(c=c.concat(Yd(i,t,n,r)))}),t&&(c=c.concat(kd(t,s,o,a))),c}function Jd(i,t){const s=t.query,a=Xd(i,s);return{hashFn:()=>{const e=t.viewCache_.serverCache.getNode()||Yu.EMPTY_NODE;return e.hash()},onComplete:e=>{if("ok"===e)return a?function(e,t,n){if(s=ep(e,n)){var r=tp(s),i=r.path,s=r.queryId,r=gu(i,t);return np(e,i,new kh(Ch(s),r))}return[]}(i,s._path,a):(t=i,n=s._path,Qd(t,new kh(Eh(),n)));var t,n,r=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(e,s);return $d(i,s,null,r)}}}function Xd(e,t){var n=Zd(t);return e.queryToTagMap.get(n)}function Zd(e){return e._path.toString()+"$"+e._queryIdentifier}function ep(e,t){return e.tagToQueryMap.get(t)}function tp(e){var t=e.indexOf("$");return f(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new su(e.substr(0,t))}}function np(e,t,n){var r=e.syncPointTree_.get(t);return f(r,"Missing sync point for query tag that we're tracking"),kd(r,n,Jh(e.pendingWriteTree_,t),null)}function rp(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(f(Fd,"Reference.ts has not been loaded"),new Fd(e._repo,e._path)):e}class ip{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new ip(t)}node(){return this.node_}}class sp{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=pu(this.path_,e);return new sp(this.syncTree_,t)}node(){return Gd(this.syncTree_,this.path_)}}function ap(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e}function op(e,t,n){return e&&"object"==typeof e?(f(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?cp(e[".sv"],t,n):"object"==typeof e[".sv"]?lp(e[".sv"],t):void f(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const cp=function(e,t,n){if("timestamp"===e)return n.timestamp;f(!1,"Unexpected server value: "+e)},lp=function(e,t,n){e.hasOwnProperty("increment")||f(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment;"number"!=typeof r&&f(!1,"Unexpected increment value: "+r);const i=t.node();if(f(null!==i&&void 0!==i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const s=i;var a=s.getValue();return"number"!=typeof a?r:a+r},up=function(e,t,n,r){return dp(t,new sp(n,e),r)},hp=function(e,t,n){return dp(e,new ip(t),n)};function dp(e,r,i){var t=e.getPriority().val(),n=op(t,r.getImmediateChild(".priority"),i);let s;if(e.isLeafNode()){const a=e;t=op(a.getValue(),r,i);return t!==a.getValue()||n!==a.getPriority().val()?new Vu(t,eh(n)):e}{const o=e;return s=o,n!==o.getPriority().val()&&(s=s.updatePriority(new Vu(n))),o.forEachChild(Bu,(e,t)=>{var n=dp(t,r.getImmediateChild(e),i);n!==t&&(s=s.updateImmediateChild(e,n))}),s}}class pp{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function fp(e,t){let n=t instanceof su?t:new su(t),r=e,i=ou(n);for(;null!==i;){var s=U(r.node.children,i)||{children:{},childCount:0};r=new pp(i,r,s),n=lu(n),i=ou(n)}return r}function gp(e){return e.node.value}function mp(e,t){e.node.value=t,wp(e)}function vp(e){return 0<e.node.childCount}function _p(n,r){Nl(n.node.children,(e,t)=>{r(new pp(e,n,t))})}function yp(e){return new su(null===e.parent?e.name:yp(e.parent)+"/"+e.name)}function wp(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=function(e){return void 0===gp(e)&&!vp(e)}(e=e),i=F(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,wp(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,wp(t)))}function bp(e,t,n,r){r&&void 0===t||Op(J(e,"value"),t,n)}function Ip(e,t,r,n){if(!n||void 0!==t){const i=J(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const s=[];Nl(t,(e,t)=>{const n=new su(e);if(Op(i,t,pu(r,n)),".priority"===uu(n)&&!xp(t))throw new Error(i+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(n)}),function(t,n){let r,i;for(r=0;r<n.length;r++){i=n[r];var s=hu(i);for(let e=0;e<s.length;e++)if((".priority"!==s[e]||e!==s.length-1)&&!Rp(s[e]))throw new Error(t+"contains an invalid key ("+s[e]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}n.sort(mu);let e=null;for(r=0;r<n.length;r++){if(i=n[r],null!==e&&_u(e,i))throw new Error(t+"contains a path "+e.toString()+" that is ancestor of another path "+i.toString());e=i}}(i,s)}}function Tp(e,t,n){if(!n||void 0!==t){if(Cl(t))throw new Error(J(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!xp(t))throw new Error(J(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function Ep(e,t,n,r){if(!(r&&void 0===n||Rp(n)))throw new Error(J(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function Cp(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),Mp(e,t,n,r)}function Sp(e,t){if(".info"===ou(t))throw new Error(e+" failed = Can't modify data under /.info/")}const kp=/[\[\].#$\/\u0000-\u001F\u007F]/,Ap=/[\[\].#$\u0000-\u001F\u007F]/,Np=10485760,Rp=function(e){return"string"==typeof e&&0!==e.length&&!kp.test(e)},Pp=function(e){return"string"==typeof e&&0!==e.length&&!Ap.test(e)},Dp=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),Pp(e)},xp=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!Cl(e)||e&&"object"==typeof e&&F(e,".sv")},Op=function(a,e,t){const o=t instanceof su?new yu(t,a):t;if(void 0===e)throw new Error(a+"contains undefined "+bu(o));if("function"==typeof e)throw new Error(a+"contains a function "+bu(o)+" with contents = "+e.toString());if(Cl(e))throw new Error(a+"contains "+e.toString()+" "+bu(o));if("string"==typeof e&&e.length>Np/3&&te(e)>Np)throw new Error(a+"contains a string greater than "+Np+" utf8 bytes "+bu(o)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(Nl(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!Rp(e)))throw new Error(a+" contains an invalid key ("+e+") "+bu(o)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=o,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=te(e),wu(n),Op(a,t,o),t=o,r=t.parts_.pop(),t.byteLength_-=te(r),0<t.parts_.length&&--t.byteLength_}),i&&s)throw new Error(a+' contains ".value" child '+bu(o)+" in addition to actual children.")}},Mp=function(e,t,n,r){if(!(r&&void 0===n||Pp(n)))throw new Error(J(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Lp=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!Rp(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!Dp(n))throw new Error(J(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class Fp{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Up(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i];var r=s.getPath();null===n||vu(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function Vp(e,t,n){Up(e,n),jp(e,e=>vu(e,t))}function qp(e,t,n){Up(e,n),jp(e,e=>_u(e,t)||_u(t,e))}function jp(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){var r=e.eventLists_[i];r&&(t(r.path)?(function(e){for(let n=0;n<e.events.length;n++){const r=e.events[n];var t;null!==r&&(e.events[n]=null,t=r.getEventRunner(),dl&&bl("event: "+r.toString()),Ll(t))}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}const Bp="repo_interrupt",zp=25;class $p{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Fp,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=_h(),this.transactionQueueTree_=new pp,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Kp(a,e,t){if(a.stats_=Hl(a.repoInfo_),a.forceRestClient_||function(){const e="object"==typeof window&&window.navigator&&window.navigator.userAgent||"";return 0<=e.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)}())a.server_=new mh(a.repoInfo_,(e,t,n,r)=>{Hp(a,e,t,n,r)},a.authTokenProvider_,a.appCheckProvider_),setTimeout(()=>Qp(a,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{M(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}a.persistentConnection_=new Tu(a.repoInfo_,e,(e,t,n,r)=>{Hp(a,e,t,n,r)},e=>{Qp(a,e)},e=>{var n;n=a,Nl(e,(e,t)=>{Yp(n,e,t)})},a.authTokenProvider_,a.appCheckProvider_,t),a.server_=a.persistentConnection_}var n;a.authTokenProvider_.addTokenChangeListener(e=>{a.server_.refreshAuthToken(e)}),a.appCheckProvider_.addTokenChangeListener(e=>{a.server_.refreshAppCheckToken(e.token)}),a.statsReporter_=(e=a.repoInfo_,t=()=>new Ih(a.stats_,a.server_),n=e.toString(),Gl[n]||(Gl[n]=t()),Gl[n]),a.infoData_=new vh,a.infoSyncTree_=new Vd({startListening:(e,t,n,r)=>{let i=[];const s=a.infoData_.getNode(e._path);return s.isEmpty()||(i=zd(a.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),Yp(a,"connected",!1),a.serverSyncTree_=new Vd({startListening:(r,e,t,i)=>(a.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);qp(a.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{a.server_.unlisten(e,t)}})}function Wp(e){const t=e.infoData_.getNode(new su(".info/serverTimeOffset"));var n=t.val()||0;return(new Date).getTime()+n}function Gp(e){return ap({timestamp:Wp(e)})}function Hp(e,t,n,r,i){e.dataUpdateCount++;var s,a,o=new su(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let c=[];c=i?r?(s=q(n,e=>eh(e)),function(e,t,n,r){if(o=ep(e,r)){var i=tp(o),s=i.path,a=i.queryId,o=gu(s,t),i=qh.fromObject(n);return np(e,s,new Nh(Ch(a),o,i))}return[]}(e.serverSyncTree_,o,s,i)):(s=eh(n),Kd(e.serverSyncTree_,o,s,i)):r?(a=q(n,e=>eh(e)),t=e.serverSyncTree_,i=o,r=a,a=qh.fromObject(r),Qd(t,new Nh(Eh(),i,a))):(a=eh(n),zd(e.serverSyncTree_,o,a));let l=o;0<c.length&&(l=cf(e,o)),qp(e.eventQueue_,l,c)}function Qp(e,t){Yp(e,"connected",t),!1===t&&function(r){rf(r,"onDisconnectEvents");const i=Gp(r),s=_h();wh(r.onDisconnect_,au(),(e,t)=>{var n=up(e,t,r.serverSyncTree_,i);yh(s,e,n)});let a=[];wh(s,au(),(e,t)=>{a=a.concat(zd(r.serverSyncTree_,e,t));var n=df(r,e);cf(r,n)}),r.onDisconnect_=_h(),qp(r.eventQueue_,au(),a)}(e)}function Yp(e,t,n){var r=new su("/.info/"+t),i=eh(n);e.infoData_.updateSnapshot(r,i);i=zd(e.infoSyncTree_,r,i);qp(e.eventQueue_,r,i)}function Jp(e){return e.nextWriteId_++}function Xp(r,i,e,t,s){rf(r,"set",{path:i.toString(),value:e,priority:t});var n=Gp(r);const a=eh(e,t);var o=Gd(r.serverSyncTree_,i),n=hp(a,o,n);const c=Jp(r);n=qd(r.serverSyncTree_,i,n,c,!0);Up(r.eventQueue_,n),r.server_.put(i.toString(),a.val(!0),(e,t)=>{var n="ok"===e;n||Tl("set at "+i+" failed: "+e);n=Bd(r.serverSyncTree_,c,!n);qp(r.eventQueue_,i,n),sf(0,s,e,t)});n=df(r,i);cf(r,n),qp(r.eventQueue_,n,[])}function Zp(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(fu(t))return n.value=null,n.children.clear(),!0;if(null!==n.value){if(n.value.isLeafNode())return!1;{const i=n.value;return n.value=null,i.forEachChild(Bu,(e,t)=>{yh(n,new su(e),t)}),e(n,t)}}if(0<n.children.size){var r=ou(t);return t=lu(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size}return!0}(n.onDisconnect_,r),sf(0,i,e,t)})}function ef(n,r,e,i){const s=eh(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&yh(n.onDisconnect_,r,s),sf(0,i,e,t)})}function tf(e,t,n){let r;r=".info"===ou(t._path)?$d(e.infoSyncTree_,t,n):$d(e.serverSyncTree_,t,n),Vp(e.eventQueue_,t._path,r)}function nf(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Bp)}function rf(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),bl(n,...t)}function sf(e,r,i,s){r&&Ll(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);const n=new Error(e);n.code=t,r(n)}})}function af(e,t,n){return Gd(e.serverSyncTree_,t,n)||Yu.EMPTY_NODE}function of(t,e=t.transactionQueueTree_){if(e||hf(t,e),gp(e)){const n=uf(t,e);f(0<n.length,"Sending zero length transaction queue"),n.every(e=>0===e.status)&&function(i,s,a){const e=a.map(e=>e.currentWriteId),t=af(i,s,e);let n=t;var r=t.hash();for(let u=0;u<a.length;u++){const h=a[u];f(0===h.status,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;var o=gu(s,h.path);n=n.updateChild(o,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{rf(i,"transaction put response",{path:l.toString(),status:t});let n=[];if("ok"===t){const r=[];for(let e=0;e<a.length;e++)a[e].status=2,n=n.concat(Bd(i.serverSyncTree_,a[e].currentWriteId)),a[e].onComplete&&r.push(()=>a[e].onComplete(null,!0,a[e].currentOutputSnapshotResolved)),a[e].unwatcher();hf(i,fp(i.transactionQueueTree_,s)),of(i,i.transactionQueueTree_),qp(i.eventQueue_,s,n);for(let t=0;t<r.length;t++)Ll(r[t])}else{if("datastale"===t)for(let e=0;e<a.length;e++)3===a[e].status?a[e].status=4:a[e].status=0;else{Tl("transaction at "+l.toString()+" failed: "+t);for(let e=0;e<a.length;e++)a[e].status=4,a[e].abortReason=t}cf(i,s)}},r)}(t,yp(e),n)}else vp(e)&&_p(e,e=>{of(t,e)})}function cf(e,t){var n=lf(e,t),r=yp(n);return function(i,s,a){if(0!==s.length){const l=[];let n=[];const t=s.filter(e=>0===e.status),u=t.map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){const h=s[r];var o=gu(a,h.path);let e=!1,t;if(f(null!==o,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(Bd(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=zp)e=!0,t="maxretry",n=n.concat(Bd(i.serverSyncTree_,h.currentWriteId,!0));else{const d=af(i,h.path,u);h.currentInputSnapshot=d;var c=s[r].update(d.val());if(void 0!==c){Op("transaction failed: Data returned ",c,h.path);let e=eh(c);"object"==typeof c&&null!=c&&F(c,".priority")||(e=e.updatePriority(d.getPriority()));o=h.currentWriteId,c=Gp(i),c=hp(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=Jp(i),u.splice(u.indexOf(o),1),n=n.concat(qd(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally)),n=n.concat(Bd(i.serverSyncTree_,o,!0))}else e=!0,t="nodata",n=n.concat(Bd(i.serverSyncTree_,h.currentWriteId,!0))}qp(i.eventQueue_,a,n),n=[],e&&(s[r].status=2,function(e){setTimeout(e,Math.floor(0))}(s[r].unwatcher),s[r].onComplete&&("nodata"===t?l.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):l.push(()=>s[r].onComplete(new Error(t),!1,null))))}hf(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)Ll(l[e]);of(i,i.transactionQueueTree_)}}(e,uf(e,n),r),r}function lf(e,t){let n,r=e.transactionQueueTree_;for(n=ou(t);null!==n&&void 0===gp(r);)r=fp(r,n),t=lu(t),n=ou(t);return r}function uf(e,t){const n=[];return function t(n,e,r){const i=gp(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);_p(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function hf(t,n){const r=gp(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,mp(n,0<r.length?r:void 0)}_p(n,e=>{hf(t,e)})}function df(t,e){var n=yp(lf(t,e)),r=fp(t.transactionQueueTree_,e);return function(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return;r=r.parent}}(r,e=>{pf(t,e)}),pf(t,r),function t(e,n,r,i){r&&!i&&n(e),_p(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{pf(t,e)}),n}function pf(i,s){const a=gp(s);if(a){const o=[];let e=[],t=-1;for(let n=0;n<a.length;n++)3===a[n].status||(1===a[n].status?(f(t===n-1,"All SENT items should be at beginning of queue."),t=n,a[n].status=3,a[n].abortReason="set"):(f(0===a[n].status,"Unexpected transaction status in abort"),a[n].unwatcher(),e=e.concat(Bd(i.serverSyncTree_,a[n].currentWriteId,!0)),a[n].onComplete&&o.push(a[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?mp(s,void 0):a.length=t+1,qp(i.eventQueue_,yp(s),e);for(let r=0;r<o.length;r++)Ll(o[r])}}const ff=function(e,t){var n=gf(e),r=n.namespace;"firebase.com"===n.domain&&Il(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||Il("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||El();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new zl(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new su(n.pathString)}},gf=function(r){let i="",s="",a="",o="",c="",l=!0,u="https",h=443;if("string"==typeof r){let e=r.indexOf("//");0<=e&&(u=r.substring(0,e-1),r=r.substring(e+2));let t=r.indexOf("/");-1===t&&(t=r.length);let n=r.indexOf("?");-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(o=function(e){let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t}(r.substring(t,n)));var d,p=function(e){const t={};for(const r of(e="?"===e.charAt(0)?e.substring(1):e).split("&")){var n;0!==r.length&&(2===(n=r.split("=")).length?t[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):Tl(`Invalid query segment '${r}' in query '${e}'`))}return t}(r.substring(Math.min(r.length,n)));e=i.indexOf(":"),0<=e?(l="https"===u||"wss"===u,h=parseInt(i.substring(e+1),10)):e=i.length;const f=i.slice(0,e);"localhost"===f.toLowerCase()?s="localhost":f.split(".").length<=2?s=f:(d=i.indexOf("."),a=i.substring(0,d).toLowerCase(),s=i.substring(d+1),c=a),"ns"in p&&(c=p.ns)}return{host:i,port:h,domain:s,subdomain:a,secure:l,scheme:u,pathString:o,namespace:c}},mf="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",vf=function(){let s=0;const a=[];return function(e){var t=e===s;s=e;let n;const r=new Array(8);for(n=7;0<=n;n--)r[n]=mf.charAt(e%64),e=Math.floor(e/64);f(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===a[n];n--)a[n]=0;a[n]++}else for(n=0;n<12;n++)a[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=mf.charAt(a[n]);return f(20===i.length,"nextPushId: Length should be 20."),i}}();class _f{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+M(this.snapshot.exportVal())}}class yf{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 wf{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return f(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 bf{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new y;return Zp(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){Sp("OnDisconnect.remove",this._path);const e=new y;return ef(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){Sp("OnDisconnect.set",this._path),bp("OnDisconnect.set",e,this._path,!1);const t=new y;return ef(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){Sp("OnDisconnect.setWithPriority",this._path),bp("OnDisconnect.setWithPriority",e,this._path,!1),Tp("OnDisconnect.setWithPriority",t,!1);const n=new y;return function(n,r,e,t,i){const s=eh(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&yh(n.onDisconnect_,r,s),sf(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){Sp("OnDisconnect.update",this._path),Ip("OnDisconnect.update",e,this._path,!1);const t=new y;return function(r,i,n,s){if(V(n))return bl("onDisconnect().update() called with empty data. Don't do anything."),sf(0,s,"ok",void 0);r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&Nl(n,(e,t)=>{var n=eh(t);yh(r.onDisconnect_,pu(i,e),n)}),sf(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class If{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return fu(this._path)?null:uu(this._path)}get ref(){return new Sf(this._repo,this._path)}get _queryIdentifier(){var e=gh(this._queryParams),e=_l(e);return"{}"===e?"default":e}get _queryObject(){return gh(this._queryParams)}isEqual(e){if(!((e=oe(e))instanceof If))return!1;var t=this._repo===e._repo,n=vu(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}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 Tf(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function Ef(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===Au){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="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()!==Sl)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==kl)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===Bu){if(null!=t&&!xp(t)||null!=n&&!xp(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(f(e.getIndex()instanceof th||e.getIndex()===nh,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function Cf(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class Sf extends If{constructor(e,t){super(e,t,new uh,!1)}get parent(){var e=du(this._path);return null===e?null:new Sf(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class kf{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){var t=new su(e),n=Rf(this.ref,e);return new kf(this._node.getChild(t),n,Bu)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){if(this._node.isLeafNode())return!1;const e=this._node;return!!e.forEachChild(this._index,(e,t)=>n(new kf(t,Rf(this.ref,e),Bu)))}hasChild(e){var t=new su(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 Af(e,t){return(e=oe(e))._checkNotDeleted("ref"),void 0!==t?Rf(e._root,t):e._root}function Nf(e,t){(e=oe(e))._checkNotDeleted("refFromURL");const n=ff(t,e._repo.repoInfo_.nodeAdmin);Lp("refFromURL",n);var r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||Il("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),Af(e,n.path.toString())}function Rf(e,t){return(null===ou((e=oe(e))._path)?Cp:Mp)("child","path",t,!1),new Sf(e._repo,pu(e._path,t))}function Pf(e,t){e=oe(e),Sp("set",e._path),bp("set",t,e._path,!1);const n=new y;return Xp(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Df(e,t){Ip("update",t,e._path,!1);const n=new y;return function(i,s,e,a){rf(i,"update",{path:s.toString(),value:e});let n=!0;const r=Gp(i),o={};if(Nl(e,(e,t)=>{n=!1,o[e]=up(pu(s,e),eh(t),i.serverSyncTree_,r)}),n)bl("update() called with empty data. Don't do anything."),sf(0,a,"ok",void 0);else{const c=Jp(i);var t=jd(i.serverSyncTree_,s,o,c);Up(i.eventQueue_,t),i.server_.merge(s.toString(),e,(e,t)=>{var n="ok"===e;n||Tl("update at "+s+" failed: "+e);var r=Bd(i.serverSyncTree_,c,!n),n=0<r.length?cf(i,s):s;qp(i.eventQueue_,n,r),sf(0,a,e,t)}),Nl(e,e=>{var t=df(i,pu(s,e));cf(i,t)}),qp(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function xf(t){t=oe(t);var i,s,a,e=new wf(()=>{}),e=new Of(e);return i=t._repo,s=t,a=e,(null!=(e=Hd(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,n=eh(e).withIndex(s._queryParams.getIndex());Wd(i.serverSyncTree_,s,a,!0);let r;return r=s._queryParams.loadsAllData()?zd(i.serverSyncTree_,s._path,n):(t=Xd(i.serverSyncTree_,s),Kd(i.serverSyncTree_,s._path,n,t)),qp(i.eventQueue_,s._path,r),$d(i.serverSyncTree_,s,a,null,!0),n},e=>(rf(i,"get for query "+M(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new kf(e,new Sf(t._repo,t._path),t._queryParams.getIndex()))}class Of{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new _f("value",this,new kf(e.snapshotNode,new Sf(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 yf(this,e,t):null}matches(e){return e instanceof Of&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Mf{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 yf(this,e,t):null}createEvent(e,t){f(null!=e.childName,"Child events should have a childName.");var n=Rf(new Sf(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new _f(e.type,this,new kf(e.snapshotNode,n,r),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 Mf&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function Lf(n,e,t,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){const c=t;var a=(e,t)=>{tf(n._repo,n,o),c(e,t)};a.userCallback=t.userCallback,a.context=t.context,t=a}a=new wf(t,s||void 0);const o="value"===e?new Of(a):new Mf(e,a);return function(e,t,n){let r;r=".info"===ou(t._path)?Wd(e.infoSyncTree_,t,n):Wd(e.serverSyncTree_,t,n),Vp(e.eventQueue_,t._path,r)}(n._repo,n,o),()=>tf(n._repo,n,o)}function Ff(e,t,n,r){return Lf(e,"value",t,n,r)}function Uf(e,t,n,r){return Lf(e,"child_added",t,n,r)}function Vf(e,t,n,r){return Lf(e,"child_changed",t,n,r)}function qf(e,t,n,r){return Lf(e,"child_moved",t,n,r)}function jf(e,t,n,r){return Lf(e,"child_removed",t,n,r)}function Bf(e,t,n){let r=null;var i=n?new wf(n):null;"value"===t?r=new Of(i):t&&(r=new Mf(t,i)),tf(e._repo,e,r)}class zf{}class $f extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){bp("endAt",this._value,e._path,!0);var t=dh(e._queryParams,this._value,this._key);if(Cf(t),Ef(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new If(e._repo,e._path,t,e._orderByCalled)}}class Kf extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){bp("endBefore",this._value,e._path,!1);var t=function(e,t,n){let r;return r=e.index_===Au||n?dh(e,t,n):dh(e,t,Sl),r.endBeforeSet_=!0,r}(e._queryParams,this._value,this._key);if(Cf(t),Ef(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new If(e._repo,e._path,t,e._orderByCalled)}}class Wf extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){bp("startAt",this._value,e._path,!0);var t=hh(e._queryParams,this._value,this._key);if(Cf(t),Ef(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new If(e._repo,e._path,t,e._orderByCalled)}}class Gf extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){bp("startAfter",this._value,e._path,!1);var t=function(e,t,n){let r;return r=e.index_===Au||n?hh(e,t,n):hh(e,t,kl),r.startAfterSet_=!0,r}(e._queryParams,this._value,this._key);if(Cf(t),Ef(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new If(e._repo,e._path,t,e._orderByCalled)}}class Hf extends zf{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new If(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}class Qf extends zf{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new If(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}class Yf extends zf{constructor(e){super(),this._path=e}_apply(e){Tf(e,"orderByChild");var t=new su(this._path);if(fu(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new th(t),t=ph(e._queryParams,t);return Ef(t),new If(e._repo,e._path,t,!0)}}class Jf extends zf{_apply(e){Tf(e,"orderByKey");var t=ph(e._queryParams,Au);return Ef(t),new If(e._repo,e._path,t,!0)}}class Xf extends zf{_apply(e){Tf(e,"orderByPriority");var t=ph(e._queryParams,Bu);return Ef(t),new If(e._repo,e._path,t,!0)}}class Zf extends zf{_apply(e){Tf(e,"orderByValue");var t=ph(e._queryParams,nh);return Ef(t),new If(e._repo,e._path,t,!0)}}class eg extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(bp("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new $f(this._value,this._key)._apply(new Wf(this._value,this._key)._apply(e))}}function tg(e,...t){let n=oe(e);for(const r of t)n=r._apply(n);return n}nl=Sf,f(!Cd,"__referenceConstructor has already been defined"),Cd=nl,rl=Sf,f(!Fd,"__referenceConstructor has already been defined"),Fd=rl;const ng="FIREBASE_DATABASE_EMULATOR_HOST",rg={};let ig=!1;function sg(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||Il("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),bl("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let a=ff(s,i),o=a.repoInfo,c,l=void 0;"undefined"!=typeof process&&process.env&&(l=process.env[ng]),l?(c=!0,s=`http://${l}?ns=${o.namespace}`,a=ff(s,i),o=a.repoInfo):c=!a.repoInfo.secure;var u=i&&c?new Vl(Vl.OWNER):new Ul(e.name,e.options,t);Lp("Invalid Firebase Database URL",a),fu(a.path)||Il("Database URL must point to the root of a Firebase Database (not including a child path).");u=function(e,t,n,r){let i=rg[t.name];i||(i={},rg[t.name]=i);var s=i[e.toURLString()];s&&Il("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new $p(e,ig,n,r),i[e.toURLString()]=s}(o,e,u,new Fl(e.name,n));return new ag(u,e)}class ag{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Kp(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new Sf(this._repo,au())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=rg[t];n&&n[e.key]===e||Il(`Database ${t}(${e.repoInfo_}) has already been deleted.`),nf(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&Il("Cannot call "+e+" on a deleted database.")}}function og(){eu.IS_TRANSPORT_INITIALIZED&&Tl("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function cg(){og(),Yl.forceDisallow()}function lg(){og(),Zl.forceDisallow(),Yl.forceAllow()}function ug(e,t,n,r={}){(e=oe(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&Il("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let a=void 0;s.repoInfo_.nodeAdmin?(r.mockUserToken&&Il('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),a=new Vl(Vl.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:w(r.mockUserToken,e.app.options.projectId),a=new Vl(i)),r=s,e=t,t=n,n=a,r.repoInfo_=new zl(`${e}:${t}`,!1,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams,!0),n&&(r.authTokenProvider_=n)}function hg(e){(e=oe(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(Bp)}function dg(e,t){wl(e,t)}const pg={".sv":"timestamp"};class fg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function gg(i,e,t){if(i=oe(i),Sp("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=null===(r=null==t?void 0:t.applyLocally)||void 0===r||r;const s=new y;var r=Ff(i,()=>{});return function(t,n,e,r,i,s){rf(t,"transaction on "+n);const a={path:n,update:e,onComplete:r,status:null,order:ul(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},o=af(t,n,void 0);a.currentInputSnapshot=o;var c=a.update(o.val());if(void 0===c)a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete&&a.onComplete(null,!1,a.currentInputSnapshot);else{Op("transaction failed: Data returned ",c,a.path),a.status=0;var l=fp(t.transactionQueueTree_,n);const u=gp(l)||[];u.push(a),mp(l,u);let e;if("object"==typeof c&&null!==c&&F(c,".priority"))e=U(c,".priority"),f(xp(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=Gd(t.serverSyncTree_,n)||Yu.EMPTY_NODE;e=h.getPriority().val()}l=Gp(t),c=eh(c,e),l=hp(c,o,l);a.currentOutputSnapshotRaw=c,a.currentOutputSnapshotResolved=l,a.currentWriteId=Jp(t);l=qd(t.serverSyncTree_,n,l,a.currentWriteId,a.applyLocally);qp(t.eventQueue_,n,l),of(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new kf(n,new Sf(i._repo,i._path),Bu),s.resolve(new fg(t,r)))},r,n),s.promise}Tu.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},Tu.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},Yc(Je),Ge(new ce("database",(e,{instanceIdentifier:t})=>{return sg(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),tt(Hc,"1.0.1",il),tt(Hc,"1.0.1","esm2017");function mg(e){var t="FIREBASE WARNING: "+e;vg.warn(t)}const vg=new ve("@firebase/database-compat");class _g{constructor(e){this._delegate=e}cancel(t){Y("OnDisconnect.cancel",0,1,arguments.length),X("OnDisconnect.cancel","onComplete",t,!0);const e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){Y("OnDisconnect.remove",0,1,arguments.length),X("OnDisconnect.remove","onComplete",t,!0);const e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){Y("OnDisconnect.set",1,2,arguments.length),X("OnDisconnect.set","onComplete",t,!0);const n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){Y("OnDisconnect.setWithPriority",2,3,arguments.length),X("OnDisconnect.setWithPriority","onComplete",n,!0);const r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(Y("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,mg("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}X("OnDisconnect.update","onComplete",n,!0);const e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class yg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return Y("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class wg{constructor(e,t){this._database=e,this._delegate=t}val(){return Y("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return Y("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return Y("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return Y("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return Y("DataSnapshot.child",0,1,arguments.length),e=String(e),Mp("DataSnapshot.child","path",e,!1),new wg(this._database,this._delegate.child(e))}hasChild(e){return Y("DataSnapshot.hasChild",1,1,arguments.length),Mp("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return Y("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return Y("DataSnapshot.forEach",1,1,arguments.length),X("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new wg(this._database,e)))}hasChildren(){return Y("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return Y("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return Y("DataSnapshot.ref",0,0,arguments.length),new Ig(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class bg{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){var i;Y("Query.on",2,4,arguments.length),X("Query.on","callback",n,!1);const s=bg.getCancelAndContextArgs_("Query.on",t,r);var a=(e,t)=>{n.call(s.context,new wg(this.database,e),t)};a.userCallback=n,a.context=s.context;var o=null===(i=s.cancel)||void 0===i?void 0:i.bind(s.context);switch(e){case"value":return Ff(this._delegate,a,o),n;case"child_added":return Uf(this._delegate,a,o),n;case"child_removed":return jf(this._delegate,a,o),n;case"child_changed":return Vf(this._delegate,a,o),n;case"child_moved":return qf(this._delegate,a,o),n;default:throw new Error(J("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){var r;Y("Query.off",0,3,arguments.length),function(e,t,n){if(!n||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(J(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}("Query.off",e,!0),X("Query.off","callback",t,!0),Z("Query.off","context",n,!0),t?((r=()=>{}).userCallback=t,r.context=n,Bf(this._delegate,e,r)):Bf(this._delegate,e)}get(){return xf(this._delegate).then(e=>new wg(this.database,e))}once(e,r,t,n){Y("Query.once",1,4,arguments.length),X("Query.once","callback",r,!0);const i=bg.getCancelAndContextArgs_("Query.once",t,n),s=new y;var a=(e,t)=>{var n=new wg(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)};a.userCallback=r,a.context=i.context;var o=e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)};switch(e){case"value":Ff(this._delegate,a,o,{onlyOnce:!0});break;case"child_added":Uf(this._delegate,a,o,{onlyOnce:!0});break;case"child_removed":jf(this._delegate,a,o,{onlyOnce:!0});break;case"child_changed":Vf(this._delegate,a,o,{onlyOnce:!0});break;case"child_moved":qf(this._delegate,a,o,{onlyOnce:!0});break;default:throw new Error(J("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return Y("Query.limitToFirst",1,1,arguments.length),new bg(this.database,tg(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new Hf(e)}(e)))}limitToLast(e){return Y("Query.limitToLast",1,1,arguments.length),new bg(this.database,tg(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Qf(e)}(e)))}orderByChild(e){return Y("Query.orderByChild",1,1,arguments.length),new bg(this.database,tg(this._delegate,function(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return Mp("orderByChild","path",e,!1),new Yf(e)}(e)))}orderByKey(){return Y("Query.orderByKey",0,0,arguments.length),new bg(this.database,tg(this._delegate,new Jf))}orderByPriority(){return Y("Query.orderByPriority",0,0,arguments.length),new bg(this.database,tg(this._delegate,new Xf))}orderByValue(){return Y("Query.orderByValue",0,0,arguments.length),new bg(this.database,tg(this._delegate,new Zf))}startAt(e=null,t){return Y("Query.startAt",0,2,arguments.length),new bg(this.database,tg(this._delegate,([e=null,t]=[e,t],Ep("startAt","key",t,!0),new Wf(e,t))))}startAfter(e=null,t){return Y("Query.startAfter",0,2,arguments.length),new bg(this.database,tg(this._delegate,(e=e,t=t,Ep("startAfter","key",t,!0),new Gf(e,t))))}endAt(e=null,t){return Y("Query.endAt",0,2,arguments.length),new bg(this.database,tg(this._delegate,(e=e,t=t,Ep("endAt","key",t,!0),new $f(e,t))))}endBefore(e=null,t){return Y("Query.endBefore",0,2,arguments.length),new bg(this.database,tg(this._delegate,(e=e,t=t,Ep("endBefore","key",t,!0),new Kf(e,t))))}equalTo(e,t){return Y("Query.equalTo",1,2,arguments.length),new bg(this.database,tg(this._delegate,(e=e,t=t,Ep("equalTo","key",t,!0),new eg(e,t))))}toString(){return Y("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return Y("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(Y("Query.isEqual",1,1,arguments.length),e instanceof bg)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){const r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,X(e,"cancel",r.cancel,!0),r.context=n,Z(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(J(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new Ig(this.database,new Sf(this._delegate._repo,this._delegate._path))}}class Ig extends bg{constructor(e,t){super(e,new If(t._repo,t._path,new uh,!1)),this.database=e,this._delegate=t}getKey(){return Y("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return Y("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new Ig(this.database,Rf(this._delegate,e))}getParent(){Y("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new Ig(this.database,e):null}getRoot(){return Y("Reference.root",0,0,arguments.length),new Ig(this.database,this._delegate.root)}set(e,t){Y("Reference.set",1,2,arguments.length),X("Reference.set","onComplete",t,!0);const n=Pf(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(Y("Reference.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,mg("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}Sp("Reference.update",this._delegate._path),X("Reference.update","onComplete",n,!0);const e=Df(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){Y("Reference.setWithPriority",2,3,arguments.length),X("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(Sp("setWithPriority",e._path),bp("setWithPriority",t,e._path,!1),Tp("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new y;return Xp(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise}(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){Y("Reference.remove",0,1,arguments.length),X("Reference.remove","onComplete",t,!0);const e=(n=this._delegate,Sp("remove",n._path),Pf(n,null));var n;return t&&e.then(()=>t(null),e=>t(e)),e}transaction(e,t,n){Y("Reference.transaction",1,3,arguments.length),X("Reference.transaction","transactionUpdate",e,!1),X("Reference.transaction","onComplete",t,!0),function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(J(e,t)+"must be a boolean.")}("Reference.transaction","applyLocally",n,!0);const r=gg(this._delegate,e,{applyLocally:n}).then(e=>new yg(e.committed,new wg(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){Y("Reference.setPriority",1,2,arguments.length),X("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=oe(e),Sp("setPriority",e._path),Tp("setPriority",t,!1);const n=new y;return Xp(e._repo,pu(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}push(e,t){Y("Reference.push",0,2,arguments.length),X("Reference.push","onComplete",t,!0);const n=function(e,t){e=oe(e),Sp("push",e._path),bp("push",t,e._path,!0);var n=Wp(e._repo),n=vf(n);const r=Rf(e,n),i=Rf(e,n);let s;return s=null!=t?Pf(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r}(this._delegate,e),r=n.then(e=>new Ig(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new Ig(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return Sp("Reference.onDisconnect",this._delegate._path),new _g(new bf(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class Tg{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:cg,forceLongPolling:lg}}useEmulator(e,t,n={}){ug(this._delegate,e,t,n)}ref(e){if(Y("database.ref",0,1,arguments.length),e instanceof Ig){var t=Nf(this._delegate,e.toString());return new Ig(this,t)}t=Af(this._delegate,e);return new Ig(this,t)}refFromURL(e){Y("database.refFromURL",1,1,arguments.length);var t=Nf(this._delegate,e);return new Ig(this,t)}goOffline(){var e;Y("database.goOffline",0,0,arguments.length),(e=oe(e=this._delegate))._checkNotDeleted("goOffline"),nf(e._repo)}goOnline(){return Y("database.goOnline",0,0,arguments.length),hg(this._delegate)}}Tg.ServerValue={TIMESTAMP:pg,increment:e=>({".sv":{increment:e}})};var Eg,Cg=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:i,namespace:s,nodeAdmin:a=!1}){Yc(n);var o=new he("database-standalone");const c=new ue("auth-internal",o);c.setComponent(new ce("auth-internal",()=>r,"PRIVATE"));let l=void 0;return i&&(l=new ue("app-check-internal",o),l.setComponent(new ce("app-check-internal",()=>i,"PRIVATE"))),{instance:new Tg(sg(e,c,l,t,a),e),namespace:s}}});const Sg=Tg.ServerValue;(Eg=bt).INTERNAL.registerComponent(new ce("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new Tg(r,n)},"PUBLIC").setServiceProps({Reference:Ig,Query:bg,Database:Tg,DataSnapshot:wg,enableLogging:dg,INTERNAL:Cg,ServerValue:Sg}).setMultipleInstances(!0)),Eg.registerVersion("@firebase/database-compat","1.0.1");var yt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},kg={},Ag=yt||self;function Ng(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function Rg(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Pg="closure_uid_"+(1e9*Math.random()>>>0),Dg=0;function xg(e,t,n){return e.call.apply(e.bind,arguments)}function Og(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function Mg(e,t,n){return(Mg=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?xg:Og).apply(null,arguments)}function Lg(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function Fg(e,s){function t(){}t.prototype=s.prototype,e.$=s.prototype,e.prototype=new t,(e.prototype.constructor=e).ac=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function Ug(){this.s=this.s,this.o=this.o}Ug.prototype.s=!1,Ug.prototype.sa=function(){var e;!this.s&&(this.s=!0,this.N(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,Pg)&&e[Pg]||(e[Pg]=++Dg))},Ug.prototype.N=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const Vg=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1};function qg(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function jg(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(Ng(n)){var r=t.length||0,i=n.length||0;t.length=r+i;for(let e=0;e<i;e++)t[r+e]=n[e]}else t.push(n)}}function Bg(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}Bg.prototype.h=function(){this.defaultPrevented=!0};var zg=function(){if(!Ag.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{Ag.addEventListener("test",()=>{},t),Ag.removeEventListener("test",()=>{},t)}catch(e){}return e}();function $g(e){return/^[\s\xa0]*$/.test(e)}function Kg(){var e=Ag.navigator;return(e=e&&e.userAgent)?e:""}function Wg(e){return-1!=Kg().indexOf(e)}function Gg(e){return Gg[" "](e),e}Gg[" "]=function(){};var Hg,Qg=Wg("Opera"),Yg=Wg("Trident")||Wg("MSIE"),Jg=Wg("Edge"),Xg=Jg||Yg,Zg=Wg("Gecko")&&!(-1!=Kg().toLowerCase().indexOf("webkit")&&!Wg("Edge"))&&!(Wg("Trident")||Wg("MSIE"))&&!Wg("Edge"),em=-1!=Kg().toLowerCase().indexOf("webkit")&&!Wg("Edge");function tm(){var e=Ag.document;return e?e.documentMode:void 0}e:{var nm="",rm=(rm=Kg(),Zg?/rv:([^\);]+)(\)|;)/.exec(rm):Jg?/Edge\/([\d\.]+)/.exec(rm):Yg?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(rm):em?/WebKit\/(\S+)/.exec(rm):Qg?/(?:Version)[ \/]?(\S+)/.exec(rm):void 0);if(rm&&(nm=rm?rm[1]:""),Yg){rm=tm();if(null!=rm&&rm>parseFloat(nm)){Hg=String(rm);break e}}Hg=nm}var im=Ag.document&&Yg&&(tm()||parseInt(Hg,10))||void 0;function sm(e,t){if(Bg.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(Zg){e:{try{Gg(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:am[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&sm.$.h.call(this)}}Fg(sm,Bg);var am={2:"touch",3:"pen",4:"mouse"};sm.prototype.h=function(){sm.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var om="closure_listenable_"+(1e6*Math.random()|0),cm=0;function lm(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.la=i,this.key=++cm,this.fa=this.ia=!1}function um(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function hm(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function dm(e){const t={};for(const n in e)t[n]=e[n];return t}const pm="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function fm(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<pm.length;e++)n=pm[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function gm(e){this.src=e,this.g={},this.h=0}function mm(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=Vg(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(um(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function vm(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.fa&&s.listener==t&&s.capture==!!n&&s.la==r)return i}return-1}gm.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=vm(e,t,r,i);return-1<a?(t=e[a],n||(t.ia=!1)):((t=new lm(t,this.src,s,!!r,i)).ia=n,e.push(t)),t};var _m="closure_lm_"+(1e6*Math.random()|0),ym={};function wm(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);return null}r=km(r);return t&&t[om]?t.P(n,r,Rg(i)?!!i.capture:!!i,s):bm(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)wm(e,t[s],n,r,i);return null}return n=km(n),e&&e[om]?e.O(t,n,Rg(r)?!!r.capture:!!r,i):bm(e,t,n,!1,r,i)}function bm(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=Rg(i)?!!i.capture:!!i,o=Cm(e);if(o||(e[_m]=o=new gm(e)),(n=o.add(t,n,r,a,s)).proxy)return n;if(r=function(){const n=Em;return function e(t){return n.call(e.src,e.listener,t)}}(),(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!zg?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(Tm(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function Im(e){var t,n,r;"number"!=typeof e&&e&&!e.fa&&((t=e.src)&&t[om]?mm(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(Tm(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Cm(t))?(mm(n,e),0==n.h&&(n.src=null,t[_m]=null)):um(e)))}function Tm(e){return e in ym?ym[e]:ym[e]="on"+e}function Em(e,t){var n,r;return e=!!e.fa||(t=new sm(t,this),n=e.listener,r=e.la||e.src,e.ia&&Im(e),n.call(r,t))}function Cm(e){return(e=e[_m])instanceof gm?e:null}var Sm="__closure_events_fn_"+(1e9*Math.random()>>>0);function km(t){return"function"==typeof t?t:(t[Sm]||(t[Sm]=function(e){return t.handleEvent(e)}),t[Sm])}function Am(){Ug.call(this),this.i=new gm(this),(this.S=this).J=null}function Nm(e,t){var n,r=e.J;if(r)for(n=[];r;r=r.J)n.push(r);if(e=e.S,r=t.type||t,"string"==typeof t?t=new Bg(t,e):t instanceof Bg?t.target=t.target||e:(a=t,fm(t=new Bg(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=Rm(s,r,!0,t)&&a;if(a=Rm(s=t.g=e,r,!0,t)&&a,a=Rm(s,r,!1,t)&&a,n)for(i=0;i<n.length;i++)a=Rm(s=t.g=n[i],r,!1,t)&&a}function Rm(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a,o,c=t[s];c&&!c.fa&&c.capture==n&&(a=c.listener,o=c.la||c.src,c.ia&&mm(e.i,c),i=!1!==a.call(o,r)&&i)}return i&&!r.defaultPrevented}Fg(Am,Ug),Am.prototype[om]=!0,Am.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);else i=Rg(i)?!!i.capture:!!i,r=km(r),t&&t[om]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=vm(a=t.g[n],r,i,s))&&(um(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&Cm(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?vm(n,r,i,s):t)?n[t]:null)&&Im(r))}(this,e,t,n,r)},Am.prototype.N=function(){if(Am.$.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)um(n[r]);delete t.g[e],t.h--}}this.J=null},Am.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Am.prototype.P=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Pm=Ag.JSON.stringify;var Dm=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new xm,e=>e.reset());class xm{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}let Om,Mm=!1,Lm=new class{constructor(){this.h=this.g=null}add(e,t){const n=Dm.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},Fm=()=>{const e=Ag.Promise.resolve(void 0);Om=()=>{e.then(Um)}};var Um=()=>{for(var e;e=function(){var e=Lm;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){Ag.setTimeout(()=>{throw e},0)}(e)}var t=Dm;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Mm=!1};function Vm(e,t){Am.call(this),this.h=e||1,this.g=t||Ag,this.j=Mg(this.qb,this),this.l=Date.now()}function qm(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function jm(e,t,n){if("function"==typeof e)n&&(e=Mg(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Mg(e.handleEvent,e)}return 2147483647<Number(t)?-1:Ag.setTimeout(e,t||0)}Fg(Vm,Am),(It=Vm.prototype).ga=!1,It.T=null,It.qb=function(){var e;this.ga&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-e):(this.T&&(this.g.clearTimeout(this.T),this.T=null),Nm(this,"tick"),this.ga&&(qm(this),this.start())))},It.start=function(){this.ga=!0,this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now())},It.N=function(){Vm.$.N.call(this),qm(this),delete this.g};class Bm extends Ug{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=jm(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}N(){super.N(),this.g&&(Ag.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function zm(e){Ug.call(this),this.h=e,this.g={}}Fg(zm,Ug);var $m=[];function Km(e,t,n,r){Array.isArray(n)||(n&&($m[0]=n.toString()),n=$m);for(var i=0;i<n.length;i++){var s=wm(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function Wm(e){hm(e.g,function(e,t){this.g.hasOwnProperty(t)&&Im(e)},e),e.g={}}function Gm(){this.g=!0}function Hm(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var a=1;a<i.length;a++)i[a]=""}}}return Pm(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}zm.prototype.N=function(){zm.$.N.call(this),Wm(this)},zm.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},Gm.prototype.Ea=function(){this.g=!1},Gm.prototype.info=function(){};var Qm={},Ym=null;function Jm(){return Ym=Ym||new Am}function Xm(e){Bg.call(this,Qm.Ta,e)}function Zm(){var e=Jm();Nm(e,new Xm(e))}function ev(e,t){Bg.call(this,Qm.STAT_EVENT,e),this.stat=t}function tv(e){var t=Jm();Nm(t,new ev(t,e))}function nv(e,t){Bg.call(this,Qm.Ua,e),this.size=t}function rv(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return Ag.setTimeout(function(){e()},t)}Qm.Ta="serverreachability",Fg(Xm,Bg),Qm.STAT_EVENT="statevent",Fg(ev,Bg),Qm.Ua="timingevent",Fg(nv,Bg);Tt={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9},sl={wb:"complete",Sb:"success",Ra:"error",Qa:"abort",Kb:"ready",Lb:"readystatechange",TIMEOUT:"timeout",Gb:"incrementaldata",Jb:"progress",zb:"downloadprogress",$b:"uploadprogress"};function iv(){}function sv(e){return e.h||(e.h=e.i())}function av(){}iv.prototype.h=null;yt={OPEN:"a",vb:"b",Ra:"c",Hb:"d"};function ov(){Bg.call(this,"d")}function cv(){Bg.call(this,"c")}function lv(){}function uv(e,t,n,r){this.l=e,this.j=t,this.m=n,this.W=r||1,this.U=new zm(this),this.P=pv,this.V=new Vm(e=Xg?125:void 0),this.I=null,this.i=!1,this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null,this.F=[],this.g=null,this.C=0,this.o=this.u=null,this.ca=-1,this.J=!1,this.O=0,this.M=null,this.ba=this.K=this.aa=this.S=!1,this.h=new hv}function hv(){this.i=null,this.g="",this.h=!1}Fg(ov,Bg),Fg(cv,Bg),Fg(lv,iv),lv.prototype.g=function(){return new XMLHttpRequest},lv.prototype.i=function(){return{}};var dv=new lv,pv=45e3,fv={},gv={};function mv(e,t,n){e.L=1,e.v=Ov(Nv(t)),e.s=n,e.S=!0,vv(e,null)}function vv(e,t){e.G=Date.now(),wv(e),e.A=Nv(e.v);var a,o,c,l,u,h,n=e.A,r=e.W;Array.isArray(r)||(r=[String(r)]),Gv(n.i,"t",r),e.C=0,n=e.l.J,e.h=new hv,e.g=W_(e.l,n?t:null,!e.s),0<e.O&&(e.M=new Bm(Mg(e.Pa,e,e.g),e.O)),Km(e.U,e.g,"readystatechange",e.nb),t=e.I?dm(e.I):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ha(e.A,e.u,e.s,t)):(e.u="GET",e.g.ha(e.A,e.u,null,t)),Zm(),a=e.j,o=e.u,c=e.A,l=e.m,u=e.W,h=e.s,a.info(function(){if(a.g)if(h)for(var e="",t=h.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=h;return"XMLHTTP REQ ("+l+") [attempt "+u+"]: "+o+"\n"+c+"\n"+e})}function _v(e){return e.g&&("GET"==e.u&&2!=e.L&&e.l.Ha)}function yv(e,t,n){let r=!0,i;for(;!e.J&&e.C<n.length;){if(i=(a=n,c=o=void 0,o=(s=e).C,-1==(c=a.indexOf("\n",o))?gv:(o=Number(a.substring(o,c)),isNaN(o)?fv:(c+=1)+o>a.length?gv:(a=a.slice(c,c+o),s.C=c+o,a))),i==gv){4==t&&(e.o=4,tv(14),r=!1),Hm(e.j,e.m,null,"[Incomplete Response]");break}if(i==fv){e.o=4,tv(15),Hm(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}Hm(e.j,e.m,i,null),Cv(e,i)}var s,a,o,c;_v(e)&&i!=gv&&i!=fv&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,tv(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.ba&&(e.ba=!0,(t=e.l).g==e&&t.ca&&!t.M&&(t.l.info("Great, no buffering proxy detected. Bytes received: "+n.length),U_(t),t.M=!0,tv(11))):(Hm(e.j,e.m,n,"[Invalid Chunked Response]"),Ev(e),Tv(e))}function wv(e){e.Y=Date.now()+e.P,bv(e,e.P)}function bv(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=rv(Mg(e.lb,e),t)}function Iv(e){e.B&&(Ag.clearTimeout(e.B),e.B=null)}function Tv(e){0==e.l.H||e.J||j_(e.l,e)}function Ev(e){Iv(e);var t=e.M;t&&"function"==typeof t.sa&&t.sa(),e.M=null,qm(e.V),Wm(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.sa())}function Cv(e,t){try{var n=e.l;if(0!=n.H&&(n.g==e||Zv(n.i,e)))if(!e.K&&Zv(n.i,e)&&3==n.H){try{var r=n.Ja.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.G+3e3<e.G))break e;q_(n),R_(n)}F_(n),tv(18)}}else n.Fa=i[1],0<n.Fa-n.V&&i[2]<37500&&n.G&&0==n.A&&!n.v&&(n.v=rv(Mg(n.ib,n),6e3));if(Xv(n.i)<=1&&n.oa){try{n.oa()}catch(e){}n.oa=void 0}}else z_(n,11)}else if(!e.K&&n.g!=e||q_(n),!$g(t))for(i=n.Ja.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.V=s[0],s=s[1],2==n.H)if("c"==s[0]){n.K=s[1],n.pa=s[2];var a=s[3];null!=a&&(n.ra=a,n.l.info("VER="+n.ra));var o=s[4];null!=o&&(n.Ga=o,n.l.info("SVER="+n.Ga));var c,l,u=s[5];null!=u&&"number"==typeof u&&0<u&&(r=1.5*u,n.L=r,n.l.info("backChannelRequestTimeoutMs_="+r)),r=n;const f=e.g;if(f){const g=f.g?f.g.getResponseHeader("X-Client-Wire-Protocol"):null;g&&((c=r.i).g||-1==g.indexOf("spdy")&&-1==g.indexOf("quic")&&-1==g.indexOf("h2")||(c.j=c.l,c.g=new Set,c.h&&(e_(c,c.h),c.h=null))),!r.F||(l=f.g?f.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.Da=l,xv(r.I,r.F,l))}n.H=3,n.h&&n.h.Ba(),n.ca&&(n.S=Date.now()-e.G,n.l.info("Handshake RTT: "+n.S+"ms"));var h,d,p=e;(r=n).wa=K_(r,r.J?r.pa:null,r.Y),p.K?(t_(r.i,p),h=p,(d=r.L)&&h.setTimeout(d),h.B&&(Iv(h),wv(h)),r.g=p):L_(r),0<n.j.length&&D_(n)}else"stop"!=s[0]&&"close"!=s[0]||z_(n,7);else 3==n.H&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?z_(n,7):N_(n):"noop"!=s[0]&&n.h&&n.h.Aa(s),n.A=0)}Zm()}catch(e){}}function Sv(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(Ng(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.ta&&"function"==typeof e.ta)return e.ta();if(!e.Z||"function"!=typeof e.Z){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(Ng(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.Z&&"function"==typeof e.Z)return e.Z();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(Ng(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(It=uv.prototype).setTimeout=function(e){this.P=e},It.nb=function(e){e=e.target;const t=this.M;t&&3==T_(e)?t.l():this.Pa(e)},It.Pa=function(e){try{if(e==this.g)e:{var t=T_(this.g),n=this.g.Ia();this.g.da();if(!(t<3)&&(3!=t||Xg||this.g&&(this.h.h||this.g.ja()||E_(this.g)))){this.J||4!=t||7==n||Zm(),Iv(this);var r=this.g.da();this.ca=r;t:if(_v(this)){var i=E_(this.g);e="";var s=i.length,a=4==T_(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){Ev(this),Tv(this);var o="";break t}this.h.i=new Ag.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:a&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.ja();if(this.i=200==r,h=this.j,d=this.u,p=this.A,f=this.m,g=this.W,m=t,v=r,h.info(function(){return"XMLHTTP RESP ("+f+") [ attempt "+g+"]: "+d+"\n"+p+"\n"+m+" "+v}),this.i){if(this.aa&&!this.K){t:{if(this.g){var c,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!$g(c)){var u=c;break t}}u=null}if(!(r=u)){this.i=!1,this.o=3,tv(12),Ev(this),Tv(this);break e}Hm(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Cv(this,r)}this.S?(yv(this,t,o),Xg&&this.i&&3==t&&(Km(this.U,this.V,"tick",this.mb),this.V.start())):(Hm(this.j,this.m,o,null),Cv(this,o)),4==t&&Ev(this),this.i&&!this.J&&(4==t?j_(this.l,this):(this.i=!1,wv(this)))}else(function(e){const t={};e=(e.g&&2<=T_(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let i=0;i<e.length;i++)if(!$g(e[i])){var n=function(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}(e[i]),r=n[0];if("string"==typeof(n=n[1])){n=n.trim();const s=t[r]||[];t[r]=s,s.push(n)}}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,function(e){return e.join(", ")})})(this.g),400==r&&0<o.indexOf("Unknown SID")?(this.o=3,tv(12)):(this.o=0,tv(13)),Ev(this),Tv(this)}}}catch(e){}var h,d,p,f,g,m,v},It.mb=function(){var e,t;this.g&&(e=T_(this.g),t=this.g.ja(),this.C<t.length&&(Iv(this),yv(this,e,t),this.i&&4!=e&&wv(this)))},It.cancel=function(){this.J=!0,Ev(this)},It.lb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.Y?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(Zm(),tv(17)),Ev(this),this.o=2,Tv(this)):bv(this,this.Y-n)};var kv=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Av(e){var t,n;this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof Av?(this.h=e.h,Rv(this,e.j),this.s=e.s,this.g=e.g,Pv(this,e.m),this.l=e.l,t=e.i,(n=new zv).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),Dv(this,n),this.o=e.o):e&&(t=String(e).match(kv))?(this.h=!1,Rv(this,t[1]||"",!0),this.s=Mv(t[2]||""),this.g=Mv(t[3]||"",!0),Pv(this,t[4]),this.l=Mv(t[5]||"",!0),Dv(this,t[6]||"",!0),this.o=Mv(t[7]||"")):(this.h=!1,this.i=new zv(null,this.h))}function Nv(e){return new Av(e)}function Rv(e,t,n){e.j=n?Mv(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Pv(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.m=t}else e.m=null}function Dv(e,t,n){var r,i;t instanceof zv?(e.i=t,r=e.i,(i=e.h)&&!r.j&&($v(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(Kv(this,t),Gv(this,n,e))},r)),r.j=i):(n||(t=Lv(t,jv)),e.i=new zv(t,e.h))}function xv(e,t,n){e.i.set(t,n)}function Ov(e){return xv(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Mv(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Lv(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Fv),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function Fv(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Av.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Lv(t,Uv,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Lv(t,Uv,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(Lv(n,"/"==n.charAt(0)?qv:Vv,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Lv(n,Bv)),e.join("")};var Uv=/[#\/\?@]/g,Vv=/[#\?:]/g,qv=/[#\?]/g,jv=/[#\?@]/g,Bv=/#/g;function zv(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function $v(n){n.g||(n.g=new Map,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function Kv(e,t){$v(e),t=Hv(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Wv(e,t){return $v(e),t=Hv(e,t),e.g.has(t)}function Gv(e,t,n){Kv(e,t),0<n.length&&(e.i=null,e.g.set(Hv(e,t),qg(n)),e.h+=n.length)}function Hv(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(It=zv.prototype).add=function(e,t){$v(this),this.i=null,e=Hv(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},It.forEach=function(n,r){$v(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},It.ta=function(){$v(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let s=0;s<n.length;s++){var i=t[s];for(let e=0;e<i.length;e++)r.push(n[s])}return r},It.Z=function(t){$v(this);let n=[];if("string"==typeof t)Wv(this,t)&&(n=n.concat(this.g.get(Hv(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},It.set=function(e,t){return $v(this),this.i=null,Wv(this,e=Hv(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},It.get=function(e,t){return e&&0<(e=this.Z(e)).length?String(e[0]):t},It.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),s=this.Z(r),r=0;r<s.length;r++){var a=i;""!==s[r]&&(a+="="+encodeURIComponent(String(s[r]))),e.push(a)}return this.i=e.join("&")};var Qv=class{constructor(e,t){this.g=e,this.map=t}};function Yv(e){this.l=e||10,e=Ag.PerformanceNavigationTiming?0<(e=Ag.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(Ag.g&&Ag.g.Ka&&Ag.g.Ka()&&Ag.g.Ka().ec),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Jv(e){return e.h||e.g&&e.g.size>=e.j}function Xv(e){return e.h?1:e.g?e.g.size:0}function Zv(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function e_(e,t){e.g?e.g.add(t):e.h=t}function t_(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function n_(t){if(null!=t.h)return t.i.concat(t.h.F);if(null==t.g||0===t.g.size)return qg(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.F);return e}}Yv.prototype.cancel=function(){if(this.i=n_(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}};var r_,i_=class{stringify(e){return Ag.JSON.stringify(e,void 0)}parse(e){return Ag.JSON.parse(e,void 0)}};function s_(){this.g=new i_}function a_(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function o_(e){this.l=e.fc||null,this.j=e.ob||!1}function c_(e,t){Am.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=l_,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}Fg(o_,iv),o_.prototype.g=function(){return new c_(this.l,this.j)},o_.prototype.i=(r_={},function(){return r_}),Fg(c_,Am);var l_=0;function u_(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function h_(e){e.readyState=4,e.l=null,e.j=null,e.A=null,d_(e)}function d_(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(It=c_.prototype).open=function(e,t){if(this.readyState!=l_)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,d_(this)},It.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.F||Ag).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},It.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,h_(this)),this.readyState=l_},It.$a=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,d_(this)),this.g&&(this.readyState=3,d_(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if(void 0!==Ag.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;u_(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},It.Xa=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?h_:d_)(this),3==this.readyState&&u_(this))},It.Za=function(e){this.g&&(this.response=this.responseText=e,h_(this))},It.Ya=function(e){this.g&&(this.response=e,h_(this))},It.ka=function(){this.g&&h_(this)},It.setRequestHeader=function(e,t){this.v.append(e,t)},It.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},It.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(c_.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var p_=Ag.JSON.parse;function f_(e){Am.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.I="",this.m=0,this.j="",this.l=this.G=this.v=this.F=!1,this.B=0,this.A=null,this.K=g_,this.L=this.M=!1}Fg(f_,Am);var g_="",m_=/^https?$/i,v_=["POST","PUT"];function __(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,y_(e),b_(e)}function y_(e){e.F||(e.F=!0,Nm(e,"complete"),Nm(e,"error"))}function w_(e){if(e.h&&void 0!==kg&&(!e.C[1]||4!=T_(e)||2!=e.da()))if(e.v&&4==T_(e))jm(e.La,0,e);else if(Nm(e,"readystatechange"),4==T_(e)){e.h=!1;try{var t,n,r,i=e.da();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break e;default:s=!1}if((t=s)||((n=0===i)&&(!(r=String(e.I).match(kv)[1]||null)&&Ag.self&&Ag.self.location&&(r=Ag.self.location.protocol.slice(0,-1)),n=!m_.test(r?r.toLowerCase():"")),t=n),t)Nm(e,"complete"),Nm(e,"success");else{e.m=6;try{var a=2<T_(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.da()+"]",y_(e)}}finally{b_(e)}}}function b_(e,t){if(e.g){I_(e);const n=e.g,r=e.C[0]?()=>{}:null;e.g=null,e.C=null,t||Nm(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function I_(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(Ag.clearTimeout(e.A),e.A=null)}function T_(e){return e.g?e.g.readyState:0}function E_(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case g_:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function C_(e){let n="";return hm(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function S_(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=C_(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):xv(e,t,n))}function k_(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function A_(e){this.Ga=0,this.j=[],this.l=new Gm,this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null,this.fb=this.W=0,this.cb=k_("failFast",!1,e),this.G=this.v=this.u=this.m=this.h=null,this.aa=!0,this.Fa=this.V=-1,this.ba=this.A=this.C=0,this.ab=k_("baseRetryDelayMs",5e3,e),this.hb=k_("retryDelaySeedMs",1e4,e),this.eb=k_("forwardChannelMaxRetries",2,e),this.xa=k_("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.dc||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new Yv(e&&e.concurrentRequestLimit),this.Ja=new s_,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.bb=e&&e.bc||!1,e&&e.Ea&&this.l.Ea(),e&&e.forceLongPolling&&(this.aa=!1),this.ca=!this.P&&this.aa&&e&&e.detectBufferingProxy||!1,this.qa=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.qa=e.longPollingTimeout),this.oa=void 0,this.S=0,this.M=!1,this.ma=this.B=null}function N_(e){if(P_(e),3==e.H){var t=e.W++,n=Nv(e.I);if(xv(n,"SID",e.K),xv(n,"RID",t),xv(n,"TYPE","terminate"),O_(e,n),(t=new uv(e,e.l,t)).L=2,t.v=Ov(Nv(n)),n=!1,Ag.navigator&&Ag.navigator.sendBeacon)try{n=Ag.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&Ag.Image&&((new Image).src=t.v,n=!0),n||(t.g=W_(t.l,null),t.g.ha(t.v)),t.G=Date.now(),wv(t)}$_(e)}function R_(e){e.g&&(U_(e),e.g.cancel(),e.g=null)}function P_(e){R_(e),e.u&&(Ag.clearTimeout(e.u),e.u=null),q_(e),e.i.cancel(),e.m&&("number"==typeof e.m&&Ag.clearTimeout(e.m),e.m=null)}function D_(e){var t;Jv(e.i)||e.m||(e.m=!0,t=e.Na,Om||Fm(),Mm||(Om(),Mm=!0),Lm.add(t,e),e.C=0)}function x_(e,t){var n=t?t.m:e.W++,r=Nv(e.I);xv(r,"SID",e.K),xv(r,"RID",n),xv(r,"AID",e.V),O_(e,r),e.o&&e.s&&S_(r,e.o,e.s),n=new uv(e,e.l,n,e.C+1),null===e.o&&(n.I=e.s),t&&(e.j=t.F.concat(e.j)),t=M_(e,n,1e3),n.setTimeout(Math.round(.5*e.xa)+Math.round(.5*e.xa*Math.random())),e_(e.i,n),mv(n,r,t)}function O_(e,n){e.na&&hm(e.na,function(e,t){xv(n,t,e)}),e.h&&Sv({},function(e,t){xv(n,t,e)})}function M_(e,t,r){r=Math.min(e.j.length,r);var i=e.h?Mg(e.h.Va,e.h,e):null;e:{var s=e.j;let n=-1;for(;;){const c=["count="+r];-1==n?0<r?(n=s[0].g,c.push("ofs="+n)):n=0:c.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=s[t].g,o=s[t].map;if((a-=n)<0)n=Math.max(0,s[t].g-100),e=!1;else try{!function(e,r,t){const i=t||"";try{Sv(e,function(e,t){let n=e;Rg(e)&&(n=Pm(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(o,c,"req"+a+"_")}catch(e){i&&i(o)}}if(e){i=c.join("&");break e}}}return e=e.j.splice(0,r),t.F=e,i}function L_(e){var t;e.g||e.u||(e.ba=1,t=e.Ma,Om||Fm(),Mm||(Om(),Mm=!0),Lm.add(t,e),e.A=0)}function F_(e){return!(e.g||e.u||3<=e.A)&&(e.ba++,e.u=rv(Mg(e.Ma,e),B_(e,e.A)),e.A++,1)}function U_(e){null!=e.B&&(Ag.clearTimeout(e.B),e.B=null)}function V_(e){e.g=new uv(e,e.l,"rpc",e.ba),null===e.o&&(e.g.I=e.s),e.g.O=0;var t=Nv(e.wa);xv(t,"RID","rpc"),xv(t,"SID",e.K),xv(t,"AID",e.V),xv(t,"CI",e.G?"0":"1"),!e.G&&e.qa&&xv(t,"TO",e.qa),xv(t,"TYPE","xmlhttp"),O_(e,t),e.o&&e.s&&S_(t,e.o,e.s),e.L&&e.g.setTimeout(e.L);var n=e.g;e=e.pa,n.L=1,n.v=Ov(Nv(t)),n.s=null,n.S=!0,vv(n,e)}function q_(e){null!=e.v&&(Ag.clearTimeout(e.v),e.v=null)}function j_(e,t){var n,r,i,s=null;if(e.g==t){q_(e),U_(e),e.g=null;var a=2}else{if(!Zv(e.i,t))return;s=t.F,t_(e.i,t),a=1}if(0!=e.H)if(t.i)1==a?(s=t.s?t.s.length:0,t=Date.now()-t.G,n=e.C,Nm(a=Jm(),new nv(a,s)),D_(e)):L_(e);else if(3==(n=t.o)||0==n&&0<t.ca||(1!=a||(i=t,Xv((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.j=i.F.concat(r.j),0):1==r.H||2==r.H||r.C>=(r.cb?0:r.eb)||(r.m=rv(Mg(r.Na,r,i),B_(r,r.C)),r.C++,0))))&&(2!=a||!F_(e)))switch(s&&0<s.length&&(t=e.i,t.i=t.i.concat(s)),n){case 1:z_(e,5);break;case 4:z_(e,10);break;case 3:z_(e,6);break;default:z_(e,2)}}function B_(e,t){let n=e.ab+Math.floor(Math.random()*e.hb);return e.isActive()||(n*=2),n*t}function z_(e,t){var n,r;e.l.info("Error code "+t),2==t?(n=null,e.h&&(n=null),r=Mg(e.pb,e),n||(n=new Av("//www.google.com/images/cleardot.gif"),Ag.location&&"http"==Ag.location.protocol||Rv(n,"https"),Ov(n)),function(e,t){var n=new Gm;if(Ag.Image){const r=new Image;r.onload=Lg(a_,n,r,"TestLoadImage: loaded",!0,t),r.onerror=Lg(a_,n,r,"TestLoadImage: error",!1,t),r.onabort=Lg(a_,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=Lg(a_,n,r,"TestLoadImage: timeout",!1,t),Ag.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):tv(2),e.H=0,e.h&&e.h.za(t),$_(e),P_(e)}function $_(e){var t;e.H=0,e.ma=[],e.h&&(0==(t=n_(e.i)).length&&0==e.j.length||(jg(e.ma,t),jg(e.ma,e.j),e.i.i.length=0,qg(e.j),e.j.length=0),e.h.ya())}function K_(e,t,n){var r,i,s=n instanceof Av?Nv(n):new Av(n);return""!=s.g?(t&&(s.g=t+"."+s.g),Pv(s,s.m)):(s=(r=Ag.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new Av(null),s&&Rv(i,s),t&&(i.g=t),r&&Pv(i,r),n&&(i.l=n),s=i),n=e.F,t=e.Da,n&&t&&xv(s,n,t),xv(s,"VER",e.ra),O_(e,s),s}function W_(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ha&&!e.va?new f_(new o_({ob:!0})):new f_(e.va)).Oa(e.J),t}function G_(){}function H_(){if(Yg&&!(10<=Number(im)))throw Error("Environmental error: no available transport.")}function Q_(e,t){Am.call(this),this.g=new A_(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.Ca&&(e?e["X-WebChannel-Client-Profile"]=t.Ca:e={"X-WebChannel-Client-Profile":t.Ca}),this.g.U=e,(e=t&&t.cc)&&!$g(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!$g(t)&&(this.g.F=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new X_(this)}function Y_(e){ov.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function J_(){cv.call(this),this.status=1}function X_(e){this.g=e}function Z_(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.m=Array(this.blockSize),this.i=this.h=0,this.reset()}function ey(e,t,n){n=n||0;var r=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;i<16;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1];var i=e.g[2],s=e.g[3],a=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+((a=t+(s^n&(i^s))+r[0]+3614090360&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=n+((a=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295;e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function ty(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}(It=f_.prototype).Oa=function(e){this.M=e},It.ha=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.I+"; newUri="+e);t=t?t.toUpperCase():"GET",this.I=e,this.j="",this.m=0,this.F=!1,this.h=!0,this.g=(this.u||dv).g(),this.C=this.u?sv(this.u):sv(dv),this.g.onreadystatechange=Mg(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(e){return void __(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const c of r.keys())n.set(c,r.get(c))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),i=Ag.FormData&&e instanceof Ag.FormData,0<=Vg(v_,t)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,a]of n)this.g.setRequestHeader(s,a);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{I_(this),0<this.B&&((this.L=(o=this.g,Yg&&"number"==typeof o.timeout&&void 0!==o.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=Mg(this.ua,this)):this.A=jm(this.ua,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){__(this,e)}var o},It.ua=function(){void 0!==kg&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Nm(this,"timeout"),this.abort(8))},It.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Nm(this,"complete"),Nm(this,"abort"),b_(this))},It.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),b_(this,!0)),f_.$.N.call(this)},It.La=function(){this.s||(this.G||this.v||this.l?w_(this):this.kb())},It.kb=function(){w_(this)},It.isActive=function(){return!!this.g},It.da=function(){try{return 2<T_(this)?this.g.status:-1}catch(e){return-1}},It.ja=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},It.Wa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),p_(t)}},It.Ia=function(){return this.m},It.Sa=function(){return"string"==typeof this.j?this.j:String(this.j)},(It=A_.prototype).ra=8,It.H=1,It.Na=function(t){if(this.m)if(this.m=null,1==this.H){if(!t){this.W=Math.floor(1e5*Math.random()),t=this.W++;const s=new uv(this,this.l,t);let e=this.s;if(this.U&&(e?(e=dm(e),fm(e,this.U)):e=this.U),null!==this.o||this.O||(s.I=e,e=null),this.P)e:{for(var n=0,r=0;r<this.j.length;r++){var i=this.j[r];if("__data__"in i.map&&"string"==typeof(i=i.map.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.j.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=M_(this,s,n),xv(r=Nv(this.I),"RID",t),xv(r,"CVER",22),this.F&&xv(r,"X-HTTP-Session-Id",this.F),O_(this,r),e&&(this.O?n="headers="+encodeURIComponent(String(C_(e)))+"&"+n:this.o&&S_(r,this.o,e)),e_(this.i,s),this.bb&&xv(r,"TYPE","init"),this.P?(xv(r,"$req",n),xv(r,"SID","null"),s.aa=!0,mv(s,r,null)):mv(s,r,n),this.H=2}}else 3==this.H&&(t?x_(this,t):0==this.j.length||Jv(this.i)||x_(this))},It.Ma=function(){var e;this.u=null,V_(this),this.ca&&!(this.M||null==this.g||this.S<=0)&&(e=2*this.S,this.l.info("BP detection timer enabled: "+e),this.B=rv(Mg(this.jb,this),e))},It.jb=function(){this.B&&(this.B=null,this.l.info("BP detection timeout reached."),this.l.info("Buffering proxy detected and switch to long-polling!"),this.G=!1,this.M=!0,tv(10),R_(this),V_(this))},It.ib=function(){null!=this.v&&(this.v=null,R_(this),F_(this),tv(19))},It.pb=function(e){e?(this.l.info("Successfully pinged google.com"),tv(2)):(this.l.info("Failed to ping google.com"),tv(1))},It.isActive=function(){return!!this.h&&this.h.isActive(this)},(It=G_.prototype).Ba=function(){},It.Aa=function(){},It.za=function(){},It.ya=function(){},It.isActive=function(){return!0},It.Va=function(){},H_.prototype.g=function(e,t){return new Q_(e,t)},Fg(Q_,Am),Q_.prototype.m=function(){this.g.h=this.j,this.A&&(this.g.J=!0);var e=this.g,t=this.l,n=this.h||void 0;tv(0),e.Y=t,e.na=n||{},e.G=e.aa,e.I=K_(e,null,e.Y),D_(e)},Q_.prototype.close=function(){N_(this.g)},Q_.prototype.u=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=Pm(e),e=t),n.j.push(new Qv(n.fb++,e)),3==n.H&&D_(n)},Q_.prototype.N=function(){this.g.h=null,delete this.j,N_(this.g),delete this.g,Q_.$.N.call(this)},Fg(Y_,ov),Fg(J_,cv),Fg(X_,G_),X_.prototype.Ba=function(){Nm(this.g,"a")},X_.prototype.Aa=function(e){Nm(this.g,new Y_(e))},X_.prototype.za=function(e){Nm(this.g,new J_)},X_.prototype.ya=function(){Nm(this.g,"b")},Fg(Z_,function(){this.blockSize=-1}),Z_.prototype.reset=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.i=this.h=0},Z_.prototype.j=function(e,t){for(var n=(t=void 0===t?e.length:t)-this.blockSize,r=this.m,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)ey(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){ey(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){ey(this,r),i=0;break}}this.h=i,this.i+=t},Z_.prototype.l=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;for(var n=8*this.i,t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.j(e),e=Array(16),t=n=0;t<4;++t)for(var r=0;r<32;r+=8)e[n++]=this.g[t]>>>r&255;return e};var ny={};function ry(e){return-128<=e&&e<128?(t=e,n=function(e){return new ty([0|e],e<0?-1:0)},r=ny,Object.prototype.hasOwnProperty.call(r,t)?r[t]:r[t]=n(t)):new ty([0|e],e<0?-1:0);var t,n,r}function iy(e){if(isNaN(e)||!isFinite(e))return ay;if(e<0)return hy(iy(-e));for(var t=[],n=1,r=0;n<=e;r++)t[r]=e/n|0,n*=sy;return new ty(t,0)}var sy=4294967296,ay=ry(0),oy=ry(1),cy=ry(16777216);function ly(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function uy(e){return-1==e.h}function hy(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new ty(n,~e.h).add(oy)}function dy(e,t){return e.add(hy(t))}function py(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function fy(e,t){this.g=e,this.h=t}function gy(e,t){if(ly(t))throw Error("division by zero");if(ly(e))return new fy(ay,ay);if(uy(e))return t=gy(hy(e),t),new fy(hy(t.g),hy(t.h));if(uy(t))return t=gy(e,hy(t)),new fy(hy(t.g),t.h);if(30<e.g.length){if(uy(e)||uy(t))throw Error("slowDivide_ only works with positive integers.");for(var n=oy,r=t;r.X(e)<=0;)n=my(n),r=my(r);for(var i=vy(n,1),s=vy(r,1),r=vy(r,2),n=vy(n,2);!ly(r);){var a=s.add(r);a.X(e)<=0&&(i=i.add(n),s=a),r=vy(r,1),n=vy(n,1)}return t=dy(e,i.R(t)),new fy(i,t)}for(i=ay;0<=e.X(t);){for(n=Math.max(1,Math.floor(e.ea()/t.ea())),r=(r=Math.ceil(Math.log(n)/Math.LN2))<=48?1:Math.pow(2,r-48),a=(s=iy(n)).R(t);uy(a)||0<a.X(e);)a=(s=iy(n-=r)).R(t);ly(s)&&(s=oy),i=i.add(s),e=dy(e,a)}return new fy(i,e)}function my(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.D(r)<<1|e.D(r-1)>>>31;return new ty(n,e.h)}function vy(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.D(s+n)>>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new ty(i,e.h)}(It=ty.prototype).ea=function(){if(uy(this))return-hy(this).ea();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.D(n);e+=(0<=r?r:sy+r)*t,t*=sy}return e},It.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(ly(this))return"0";if(uy(this))return"-"+hy(this).toString(e);for(var t=iy(Math.pow(e,6)),n=this,r="";;){var i=gy(n,t).g,s=((0<(n=dy(n,i.R(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(ly(n=i))return s+r;for(;s.length<6;)s="0"+s;r=s+r}},It.D=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},It.X=function(e){return uy(e=dy(this,e))?-1:ly(e)?0:1},It.abs=function(){return uy(this)?hy(this):this},It.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.D(i))+(65535&e.D(i)),a=(s>>>16)+(this.D(i)>>>16)+(e.D(i)>>>16),r=a>>>16;s&=65535,a&=65535,n[i]=a<<16|s}return new ty(n,-2147483648&n[n.length-1]?-1:0)},It.R=function(e){if(ly(this)||ly(e))return ay;if(uy(this))return uy(e)?hy(this).R(hy(e)):hy(hy(this).R(e));if(uy(e))return hy(this.R(hy(e)));if(this.X(cy)<0&&e.X(cy)<0)return iy(this.ea()*e.ea());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.D(r)>>>16,a=65535&this.D(r),o=e.D(i)>>>16,c=65535&e.D(i);n[2*r+2*i]+=a*c,py(n,2*r+2*i),n[2*r+2*i+1]+=s*c,py(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,py(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,py(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new ty(n,0)},It.gb=function(e){return gy(this,e).h},It.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)&e.D(r);return new ty(n,this.h&e.h)},It.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)|e.D(r);return new ty(n,this.h|e.h)},It.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)^e.D(r);return new ty(n,this.h^e.h)},H_.prototype.createWebChannel=H_.prototype.g,Q_.prototype.send=Q_.prototype.u,Q_.prototype.open=Q_.prototype.m,Tt.NO_ERROR=0,Tt.TIMEOUT=8,Tt.HTTP_ERROR=6,sl.COMPLETE="complete",(av.EventType=yt).OPEN="a",yt.CLOSE="b",yt.ERROR="c",yt.MESSAGE="d",Am.prototype.listen=Am.prototype.O,f_.prototype.listenOnce=f_.prototype.P,f_.prototype.getLastError=f_.prototype.Sa,f_.prototype.getLastErrorCode=f_.prototype.Ia,f_.prototype.getStatus=f_.prototype.da,f_.prototype.getResponseJson=f_.prototype.Wa,f_.prototype.getResponseText=f_.prototype.ja,f_.prototype.send=f_.prototype.ha,f_.prototype.setWithCredentials=f_.prototype.Oa,Z_.prototype.digest=Z_.prototype.l,Z_.prototype.update=Z_.prototype.j,ty.prototype.multiply=ty.prototype.R,ty.prototype.modulo=ty.prototype.gb,ty.prototype.compare=ty.prototype.X,ty.prototype.toNumber=ty.prototype.ea,ty.prototype.getBits=ty.prototype.D,ty.fromNumber=iy,ty.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if((n=n||10)<2||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return hy(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=iy(Math.pow(n,8)),i=ay,s=0;s<t.length;s+=8)var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),n),i=a<8?(a=iy(Math.pow(n,a)),i.R(a).add(iy(o))):(i=i.R(r)).add(iy(o));return i};var _y,yy=Jm,wy=Tt,by=sl,Iy=Qm,Ty=10,Ey=11,Cy=av,Sy=f_,ky=Z_,Ay=ty;const Ny="@firebase/firestore";class Ry{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}Ry.UNAUTHENTICATED=new Ry(null),Ry.GOOGLE_CREDENTIALS=new Ry("google-credentials-uid"),Ry.FIRST_PARTY=new Ry("first-party-uid"),Ry.MOCK_USER=new Ry("mock-user");let Py="10.3.0";const Dy=new ve("@firebase/firestore");function xy(){return Dy.logLevel}function Oy(e,...t){var n;Dy.logLevel<=m.DEBUG&&(n=t.map(Fy),Dy.debug(`Firestore (${Py}): ${e}`,...n))}function My(e,...t){var n;Dy.logLevel<=m.ERROR&&(n=t.map(Fy),Dy.error(`Firestore (${Py}): ${e}`,...n))}function Ly(e,...t){var n;Dy.logLevel<=m.WARN&&(n=t.map(Fy),Dy.warn(`Firestore (${Py}): ${e}`,...n))}function Fy(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function Uy(e="Unexpected state"){var t=`FIRESTORE (${Py}) INTERNAL ASSERTION FAILED: `+e;throw My(t),new Error(t)}function Vy(e){e||Uy()}const qy={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class jy extends P{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class By{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class zy{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class $y{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Ry.UNAUTHENTICATED))}shutdown(){}}class Ky{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class Wy{constructor(e){this.t=e,this.currentUser=Ry.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new By;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new By,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{Oy("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),a()};this.t.onInit(e=>o(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?o(e):(Oy("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new By))},0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(Oy("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(Vy("string"==typeof e.accessToken),new zy(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return Vy(null===e||"string"==typeof e),new Ry(e)}}class Gy{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=Ry.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);var e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class Hy{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Gy(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(Ry.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Qy{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class Yy{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(t,n){const r=e=>{null!=e.error&&Oy("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.R;return this.R=e.token,Oy("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{Oy("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):Oy("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Vy("string"==typeof e.token),this.R=e.token,new Qy(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Jy{static V(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function Xy(e,t){return e<t?-1:t<e?1:0}function Zy(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function ew(e){return e+"\0"}class tw{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new jy(qy.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new jy(qy.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new jy(qy.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new jy(qy.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return tw.fromMillis(Date.now())}static fromDate(e){return tw.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new tw(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Xy(this.nanoseconds,e.nanoseconds):Xy(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class nw{constructor(e){this.timestamp=e}static fromTimestamp(e){return new nw(e)}static min(){return new nw(new tw(0,0))}static max(){return new nw(new tw(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class rw{constructor(e,t,n){void 0===t?t=0:t>e.length&&Uy(),void 0===n?n=e.length-t:n>e.length-t&&Uy(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===rw.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof rw?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class iw extends rw{construct(e,t,n){return new iw(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new jy(qy.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new iw(t)}static emptyPath(){return new iw([])}}const sw=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class aw extends rw{construct(e,t,n){return new aw(e,t,n)}static isValidIdentifier(e){return sw.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!aw.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new aw(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new jy(qy.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new jy(qy.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new jy(qy.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new jy(qy.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new aw(t)}static emptyPath(){return new aw([])}}class ow{constructor(e){this.path=e}static fromPath(e){return new ow(iw.fromString(e))}static fromName(e){return new ow(iw.fromString(e).popFirst(5))}static empty(){return new ow(iw.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===iw.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return iw.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ow(new iw(e.slice()))}}class cw{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function lw(e){return e.fields.find(e=>2===e.kind)}function uw(e){return e.fields.filter(e=>2!==e.kind)}cw.UNKNOWN_ID=-1;class hw{constructor(e,t){this.fieldPath=e,this.kind=t}}class dw{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new dw(0,gw.min())}}function pw(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=nw.fromTimestamp(1e9===r?new tw(n+1,0):new tw(n,r));return new gw(r,ow.empty(),t)}function fw(e){return new gw(e.readTime,e.key,-1)}class gw{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new gw(nw.min(),ow.empty(),-1)}static max(){return new gw(nw.max(),ow.empty(),-1)}}function mw(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ow.comparator(e.documentKey,t.documentKey),0!==n?n:Xy(e.largestBatchId,t.largestBatchId))}const vw="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class _w{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function yw(e){if(e.code!==qy.FAILED_PRECONDITION||e.message!==vw)throw e;Oy("LocalStore","Unexpectedly lost primary lease")}class ww{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,i){return this.callbackAttached&&Uy(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new ww((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof ww?t:ww.resolve(t)}catch(e){return ww.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):ww.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):ww.reject(t)}static resolve(n){return new ww((e,t)=>{e(n)})}static reject(n){return new ww((e,t)=>{t(n)})}static waitFor(e){return new ww((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=ww.resolve(!1);for(const n of e)t=t.next(e=>e?ww.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}static mapArray(o,c){return new ww((t,n)=>{const r=o.length,i=new Array(r);let s=0;for(let e=0;e<r;e++){const a=e;c(o[a]).next(e=>{i[a]=e,++s,s===r&&t(i)},e=>n(e))}})}static doWhile(r,i){return new ww((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class bw{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.m=new By,this.transaction.oncomplete=()=>{this.m.resolve()},this.transaction.onabort=()=>{e.error?this.m.reject(new Ew(n,e.error)):this.m.resolve()},this.transaction.onerror=e=>{var t=Nw(e.target.error);this.m.reject(new Ew(n,t))}}static open(e,t,n,r){try{return new bw(t,e.transaction(r,n))}catch(e){throw new Ew(t,e)}}get g(){return this.m.promise}abort(e){e&&this.m.reject(e),this.aborted||(Oy("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}p(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new Sw(t)}}class Iw{constructor(e,t,n){this.name=e,this.version=t,this.S=n,12.2===Iw.D(b())&&My("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return Oy("SimpleDb","Removing database:",e),kw(window.indexedDB.deleteDatabase(e)).toPromise()}static v(){if(!A())return!1;if(Iw.C())return!0;const e=b(),t=Iw.D(e),n=0<t&&t<10,r=Iw.F(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static C(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.M)}static O(e,t){return e.store(t)}static D(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static F(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async N(s){return this.db||(Oy("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new Ew(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new jy(qy.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new jy(qy.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new Ew(s,t))},i.onupgradeneeded=e=>{Oy("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.S.B(t,i.transaction,e.oldVersion,this.version).next(()=>{Oy("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.L&&(this.db.onversionchange=e=>this.L(e)),this.db}k(t){this.L=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.N(e);const t=bw.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.p(),e)).catch(e=>(t.abort(e),ww.reject(e))).toPromise();return s.catch(()=>{}),await t.g,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(Oy("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class Tw{constructor(e){this.q=e,this.K=!1,this.$=null}get isDone(){return this.K}get U(){return this.$}set cursor(e){this.q=e}done(){this.K=!0}W(e){this.$=e}delete(){return kw(this.q.delete())}}class Ew extends jy{constructor(e,t){super(qy.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function Cw(e){return"IndexedDbTransactionError"===e.name}class Sw{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(Oy("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(Oy("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),kw(n)}add(e){return Oy("SimpleDb","ADD",this.store.name,e,e),kw(this.store.add(e))}get(t){return kw(this.store.get(t)).next(e=>(Oy("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return Oy("SimpleDb","DELETE",this.store.name,e),kw(this.store.delete(e))}count(){return Oy("SimpleDb","COUNT",this.store.name),kw(this.store.count())}G(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.j(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new ww((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}H(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new ww((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}J(e,t){Oy("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Y=!1;var r=this.cursor(n);return this.j(r,(e,t,n)=>n.delete())}Z(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.j(r,t)}X(i){const e=this.cursor({});return new ww((n,r)=>{e.onerror=e=>{var t=Nw(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}j(e,s){const a=[];return new ww((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new Tw(t),r=s(t.primaryKey,t.value,n);if(r instanceof ww){const e=r.catch(e=>(n.done(),ww.reject(e)));a.push(e)}n.isDone?i():null===n.U?t.continue():t.continue(n.U)}else i()}}).next(()=>ww.waitFor(a))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.Y?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function kw(e){return new ww((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=Nw(e.target.error);r(t)}})}let Aw=!1;function Nw(e){const t=Iw.D(b());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new jy("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return Aw||(Aw=!0,setTimeout(()=>{throw e},0)),e}}return e}class Rw{constructor(e,t){this.asyncQueue=e,this.ee=t,this.task=null}start(){this.te(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}te(e){Oy("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{Oy("IndexBackiller",`Documents written: ${await this.ee.ne()}`)}catch(e){Cw(e)?Oy("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await yw(e)}await this.te(6e4)})}}class Pw{constructor(e,t){this.localStore=e,this.persistence=t}async ne(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.re(e,t))}re(e,t){const n=new Set;let r=t,i=!0;return ww.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(Oy("IndexBackiller",`Processing collection: ${t}`),this.ie(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}ie(r,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,i).next(n=>this.localStore.localDocuments.getNextDocuments(r,i,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.se(n,e)).next(e=>(Oy("IndexBackiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}se(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=fw(t);0<mw(n,r)&&(r=n)}),new gw(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class Dw{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.oe(e),this._e=e=>t.writeSequenceNumber(e))}oe(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this._e&&this._e(e),e}}function xw(e){return null==e}function Ow(e){return 0===e&&1/e==-1/0}function Mw(e){return"number"==typeof e&&Number.isInteger(e)&&!Ow(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function Lw(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Fw(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Fw(t)}function Fw(e){return e+""}function Uw(t){const n=t.length;if(Vy(2<=n),2===n)return Vy(""===t.charAt(0)&&""===t.charAt(1)),iw.emptyPath();const __PRIVATE_lastReasonableEscapeIndex=n-2,r=[];let i="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>__PRIVATE_lastReasonableEscapeIndex)&&Uy(),t.charAt(n+1)){case"":var s=t.substring(a,n);let e;0===i.length?e=s:(i+=s,e=i,i=""),r.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:Uy()}a=n+2}return new iw(r)}Dw.ae=-1;const Vw=["userId","batchId"];function qw(e,t){return[e,Lw(t)]}function jw(e,t,n){return[e,Lw(t),n]}const Bw={},zw=["prefixPath","collectionGroup","readTime","documentId"],$w=["prefixPath","collectionGroup","documentId"],Kw=["collectionGroup","readTime","prefixPath","documentId"],Ww=["canonicalId","targetId"],Gw=["targetId","path"],Hw=["path","targetId"],Qw=["collectionId","parent"],Yw=["indexId","uid"],Jw=["uid","sequenceNumber"],Xw=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Zw=["indexId","uid","orderedDocumentKey"],eb=["userId","collectionPath","documentId"],tb=["userId","collectionPath","largestBatchId"],nb=["userId","collectionGroup","largestBatchId"],rb=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],ib=[...rb,"documentOverlays"],sb=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],ab=sb,ob=[...ab,"indexConfiguration","indexState","indexEntries"];class cb extends _w{constructor(e,t){super(),this.ue=e,this.currentSequenceNumber=t}}function lb(e,t){var n=e;return Iw.O(n.ue,t)}function ub(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function hb(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function db(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class pb{constructor(e,t){this.comparator=e,this.root=t||gb.EMPTY}insert(e,t){return new pb(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,gb.BLACK,null,null))}remove(e){return new pb(this.comparator,this.root.remove(e,this.comparator).copy(null,null,gb.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new fb(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new fb(this.root,e,this.comparator,!1)}getReverseIterator(){return new fb(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new fb(this.root,e,this.comparator,!0)}}class fb{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class gb{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:gb.RED,this.left=null!=r?r:gb.EMPTY,this.right=null!=i?i:gb.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new gb(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return gb.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return gb.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,gb.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,gb.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var 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(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw Uy();if(this.right.isRed())throw Uy();var e=this.left.check();if(e!==this.right.check())throw Uy();return e+(this.isRed()?0:1)}}gb.EMPTY=null,gb.RED=!0,gb.BLACK=!1,gb.EMPTY=new class{constructor(){this.size=0}get key(){throw Uy()}get value(){throw Uy()}get color(){throw Uy()}get left(){throw Uy()}get right(){throw Uy()}copy(e,t,n,r,i){return this}insert(e,t,n){return new gb(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class mb{constructor(e){this.comparator=e,this.data=new pb(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new vb(this.data.getIterator())}getIteratorFrom(e){return new vb(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof mb))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new mb(this.comparator);return t.data=e,t}}class vb{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function _b(e){return e.hasNext()?e.getNext():void 0}class yb{constructor(e){(this.fields=e).sort(aw.comparator)}static empty(){return new yb([])}unionWith(e){let t=new mb(aw.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new yb(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Zy(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class wb extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class bb{constructor(e){this.binaryString=e}static fromBase64String(e){var t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new wb("Invalid base64 string: "+e):e}}(e);return new bb(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new bb(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Xy(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}bb.EMPTY_BYTE_STRING=new bb("");const Ib=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Tb(t){if(Vy(!!t),"string"!=typeof t)return{seconds:Eb(t.seconds),nanos:Eb(t.nanos)};{let e=0;var n=Ib.exec(t);Vy(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function Eb(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Cb(e){return"string"==typeof e?bb.fromBase64String(e):bb.fromUint8Array(e)}function Sb(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function kb(e){var t=e.mapValue.fields.__previous_value__;return Sb(t)?kb(t):t}function Ab(e){var t=Tb(e.mapValue.fields.__local_write_time__.timestampValue);return new tw(t.seconds,t.nanos)}class Nb{constructor(e,t,n,r,i,s,a,o,c){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=c}}class Rb{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Rb("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Rb&&e.projectId===this.projectId&&e.database===this.database}}const Pb={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Db={nullValue:"NULL_VALUE"};function xb(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?Sb(e)?4:Wb(e)?9007199254740991:10:Uy()}function Ob(e,t){if(e===t)return!0;var n,r,i=xb(e);if(i!==xb(t))return!1;switch(i){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return Ab(e).isEqual(Ab(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;var n=Tb(e.timestampValue),r=Tb(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return r=t,Cb(e.bytesValue).isEqual(Cb(r.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return n=t,Eb((r=e).geoPointValue.latitude)===Eb(n.geoPointValue.latitude)&&Eb(r.geoPointValue.longitude)===Eb(n.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Eb(e.integerValue)===Eb(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Eb(e.doubleValue),r=Eb(t.doubleValue);return n===r?Ow(n)===Ow(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return Zy(e.arrayValue.values||[],t.arrayValue.values||[],Ob);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(ub(n)!==ub(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Ob(n[e],r[e])))return!1;return!0}(e,t);default:return Uy()}}function Mb(e,t){return void 0!==(e.values||[]).find(e=>Ob(e,t))}function Lb(e,t){if(e===t)return 0;var n,r,i,s,a=xb(e),o=xb(t);if(a!==o)return Xy(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Xy(e.booleanValue,t.booleanValue);case 2:return r=t,i=Eb((n=e).integerValue||n.doubleValue),s=Eb(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Fb(e.timestampValue,t.timestampValue);case 4:return Fb(Ab(e),Ab(t));case 5:return Xy(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Cb(e),r=Cb(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=Xy(n[i],r[i]);if(0!==t)return t}return Xy(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=Xy(Eb(n.latitude),Eb(r.latitude)))?s:Xy(Eb(n.longitude),Eb(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=Lb(n[i],r[i]);if(t)return t}return Xy(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Pb.mapValue&&t===Pb.mapValue)return 0;if(e===Pb.mapValue)return 1;if(t===Pb.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let o=0;o<r.length&&o<s.length;++o){const t=Xy(r[o],s[o]);if(0!==t)return t;var a=Lb(n[r[o]],i[s[o]]);if(0!==a)return a}return Xy(r.length,s.length)}(e.mapValue,t.mapValue);default:throw Uy()}}function Fb(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Xy(e,t);var n=Tb(e),r=Tb(t),i=Xy(n.seconds,r.seconds);return 0!==i?i:Xy(n.nanos,r.nanos)}function Ub(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=Tb(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return Cb(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return ow.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):Uy()}(e)}function Vb(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function qb(e){return!!e&&"integerValue"in e}function jb(e){return!!e&&"arrayValue"in e}function Bb(e){return e&&"nullValue"in e}function zb(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function $b(e){return e&&"mapValue"in e}function Kb(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){const n={mapValue:{fields:{}}};return hb(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Kb(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Kb(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Wb(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Gb(e,t){var n=Lb(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Hb(e,t){var n=Lb(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Qb{constructor(e){this.value=e}static empty(){return new Qb({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!$b(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Kb(t)}setAll(e){let n=aw.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=Kb(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());$b(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ob(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];$b(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){hb(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Qb(Kb(this.value))}}class Yb{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Yb(e,0,nw.min(),nw.min(),nw.min(),Qb.empty(),0)}static newFoundDocument(e,t,n,r){return new Yb(e,1,t,nw.min(),n,r,0)}static newNoDocument(e,t){return new Yb(e,2,t,nw.min(),nw.min(),Qb.empty(),0)}static newUnknownDocument(e,t){return new Yb(e,3,t,nw.min(),nw.min(),Qb.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(nw.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Qb.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Qb.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=nw.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Yb&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new Yb(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Jb{constructor(e,t){this.position=e,this.inclusive=t}}function Xb(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?ow.comparator(ow.fromName(a.referenceValue),n.key):Lb(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function Zb(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Ob(e.position[n],t.position[n]))return!1;return!0}class eI{constructor(e,t="asc"){this.field=e,this.dir=t}}class tI{}class nI extends tI{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new uI(e,t,n):"array-contains"===t?new fI(e,n):"in"===t?new gI(e,n):"not-in"===t?new mI(e,n):"array-contains-any"===t?new vI(e,n):new nI(e,t,n)}static createKeyFieldInFilter(e,t,n){return new("in"===t?hI:dI)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Lb(t,this.value)):null!==t&&xb(this.value)===xb(t)&&this.matchesComparison(Lb(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return Uy()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class rI extends tI{constructor(e,t){super(),this.filters=e,this.op=t,this.ce=null}static create(e,t){return new rI(e,t)}matches(t){return iI(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ce||(this.ce=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ce}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){var e=this.le(e=>e.isInequality());return null!==e?e.field:null}le(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function iI(e){return"and"===e.op}function sI(e){return"or"===e.op}function aI(e){return oI(e)&&iI(e)}function oI(e){for(const t of e.filters)if(t instanceof rI)return!1;return!0}function cI(e,t){var n=e.filters.concat(t);return rI.create(n,e.op)}function lI(e){return e instanceof nI?`${(t=e).field.canonicalString()} ${t.op} ${Ub(t.value)}`:e instanceof rI?(e=e).op.toString()+" {"+e.getFilters().map(lI).join(" ,")+"}":"Filter";var t}class uI extends nI{constructor(e,t,n){super(e,t,n),this.key=ow.fromName(n.referenceValue)}matches(e){var t=ow.comparator(e.key,this.key);return this.matchesComparison(t)}}class hI extends nI{constructor(e,t){super(e,"in",t),this.keys=pI(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class dI extends nI{constructor(e,t){super(e,"not-in",t),this.keys=pI(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function pI(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ow.fromName(e.referenceValue))}class fI extends nI{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return jb(t)&&Mb(t.arrayValue,this.value)}}class gI extends nI{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Mb(this.value.arrayValue,t)}}class mI extends nI{constructor(e,t){super(e,"not-in",t)}matches(e){if(Mb(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Mb(this.value.arrayValue,t)}}class vI extends nI{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!jb(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Mb(this.value.arrayValue,e))}}class _I{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.he=null}}function yI(e,t=null,n=[],r=[],i=null,s=null,a=null){return new _I(e,t,n,r,i,s,a)}function wI(e){const t=e;if(null===t.he){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function t(e){if(e instanceof nI)return e.field.canonicalString()+e.op.toString()+Ub(e.value);if(aI(e))return e.filters.map(e=>t(e)).join(",");var n=e.filters.map(e=>t(e)).join(",");return`${e.op}(${n})`}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),xw(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>Ub(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>Ub(e)).join(",")),t.he=e}return t.he}function bI(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(n=e.orderBy[i],r=t.orderBy[i],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r;if(e.filters.length!==t.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!function r(e,t){return e instanceof nI?(n=e,(s=t)instanceof nI&&n.op===s.op&&n.field.isEqual(s.field)&&Ob(n.value,s.value)):e instanceof rI?(i=t)instanceof rI&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce((e,t,n)=>e&&r(t,i.filters[n]),!0):void Uy();var i,n,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Zb(e.startAt,t.startAt)&&Zb(e.endAt,t.endAt)}function II(e){return ow.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function TI(e,t){return e.filters.filter(e=>e instanceof nI&&e.field.isEqual(t))}function EI(t,n,r){let i=Db,s=!0;for(const r of TI(t,n)){let e=Db,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?Db:"booleanValue"in a?{booleanValue:!1}:"integerValue"in a||"doubleValue"in a?{doubleValue:NaN}:"timestampValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in a?{stringValue:""}:"bytesValue"in a?{bytesValue:""}:"referenceValue"in a?Vb(Rb.empty(),ow.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:Uy();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Db}Gb({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Gb({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function CI(t,n,r){let i=Pb,s=!0;for(const r of TI(t,n)){let e=Pb,t=!0;switch(r.op){case">=":case">":e="nullValue"in(a=r.value)?{booleanValue:!1}:"booleanValue"in a?{doubleValue:NaN}:"integerValue"in a||"doubleValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in a?{stringValue:""}:"stringValue"in a?{bytesValue:""}:"bytesValue"in a?Vb(Rb.empty(),ow.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?Pb:Uy(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=Pb}0<Hb({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Hb({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class SI{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Pe=null,this.Ie=null,this.Te=null,this.startAt,this.endAt}}function kI(e,t,n,r,i,s,a,o){return new SI(e,t,n,r,i,s,a,o)}function AI(e){return new SI(e)}function NI(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function RI(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function PI(e){for(const t of e.filters){const e=t.getFirstInequalityField();if(null!==e)return e}return null}function DI(e){return null!==e.collectionGroup}function xI(t){const n=t;if(null===n.Pe){n.Pe=[];const t=PI(n),e=RI(n);if(null!==t&&null===e)t.isKeyField()||n.Pe.push(new eI(t)),n.Pe.push(new eI(aw.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.Pe.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.Pe.push(new eI(aw.keyField(),t))}}}return n.Pe}function OI(e){const t=e;return t.Ie||(t.Ie=function(e,t){if("F"===e.limitType)return yI(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{var t="desc"===e.dir?"asc":"desc";return new eI(e.field,t)});var n=e.endAt?new Jb(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new Jb(e.startAt.position,e.startAt.inclusive):null;return yI(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(t,xI(e))),t.Ie}function MI(e,t){t.getFirstInequalityField(),PI(e);var n=e.filters.concat([t]);return new SI(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function LI(e,t,n){return new SI(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function FI(e,t){return bI(OI(e),OI(t))&&e.limitType===t.limitType}function UI(e){return`${wI(OI(e))}|lt:${e.limitType}`}function VI(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>lI(e)).join(", ")}]`),xw(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>Ub(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>Ub(e)).join(",")),`Target(${t})`}(OI(e))}; limitType=${e.limitType})`}function qI(e,t){return t.isFoundDocument()&&(i=e,a=(s=t).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):ow.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e,t){for(const n of xI(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return;return 1}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return;return 1}(e,t)&&(i=t,(!(t=e).startAt||(n=t.startAt,e=xI(t),r=Xb(n,e,i),n.inclusive?r<=0:r<0))&&(!t.endAt||(n=t.endAt,t=xI(t),r=Xb(n,t,i),n.inclusive?0<=r:0<r)));var n,r,i,s,a}function jI(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function BI(i){return(e,t)=>{let n=!1;for(const r of xI(i)){const i=function(e,t,n){var r=e.field.isKeyField()?ow.comparator(t.key,n.key):function(e,t,n){var r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Lb(r,i):Uy()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return Uy()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}class zI{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){hb(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return db(this.inner)}size(){return this.innerSize}}const $I=new pb(ow.comparator);const KI=new pb(ow.comparator);function WI(...e){let t=KI;for(const n of e)t=t.insert(n.key,n);return t}function GI(e){let n=KI;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function HI(){return new zI(e=>e.toString(),(e,t)=>e.isEqual(t))}const QI=new pb(ow.comparator),YI=new mb(ow.comparator);function JI(...e){let t=YI;for(const n of e)t=t.add(n);return t}const XI=new mb(Xy);function ZI(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Ow(t)?"-0":t}}function eT(e){return{integerValue:""+e}}function tT(e,t){return Mw(t)?eT(t):ZI(e,t)}class nT{constructor(){this._=void 0}}function rT(e,t){return e instanceof lT?qb(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class iT extends nT{}class sT extends nT{constructor(e){super(),this.elements=e}}function aT(e,t){const n=hT(t);for(const t of e.elements)n.some(e=>Ob(e,t))||n.push(t);return{arrayValue:{values:n}}}class oT extends nT{constructor(e){super(),this.elements=e}}function cT(e,t){let n=hT(t);for(const t of e.elements)n=n.filter(e=>!Ob(e,t));return{arrayValue:{values:n}}}class lT extends nT{constructor(e,t){super(),this.serializer=e,this.Ee=t}}function uT(e){return Eb(e.integerValue||e.doubleValue)}function hT(e){return jb(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class dT{constructor(e,t){this.field=e,this.transform=t}}class pT{constructor(e,t){this.version=e,this.transformResults=t}}class fT{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new fT}static exists(e){return new fT(void 0,e)}static updateTime(e){return new fT(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function gT(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class mT{}function vT(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new ST(e.key,fT.none()):new bT(e.key,e.data,fT.none());{const i=e.data,s=Qb.empty();let t=new mb(aw.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1<r.length&&(r=r.popLast(),e=i.field(r)),null===e?s.delete(r):s.set(r,e),t=t.add(r)}return new IT(e.key,s,new yb(t.toArray()),fT.none())}}function _T(e,t,n){e instanceof bT?function(e,t,n){const r=e.value.clone(),i=ET(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof IT?function(e,t,n){if(!gT(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=ET(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(TT(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function yT(e,t,n,r){return e instanceof bT?function(e,t,n,r){if(!gT(e.precondition,t))return n;const i=e.value.clone(),s=CT(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof IT?function(e,t,n,r){if(!gT(e.precondition,t))return n;const i=CT(e.fieldTransforms,r,t),s=t.data;return s.setAll(TT(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,gT(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function wT(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&Zy(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof sT&&t instanceof sT||e instanceof oT&&t instanceof oT?Zy(e.elements,t.elements,Ob):e instanceof lT&&t instanceof lT?Ob(e.Ee,t.Ee):e instanceof iT&&t instanceof iT)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}class bT extends mT{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class IT extends mT{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function TT(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function ET(e,t,n){const r=new Map;Vy(e.length===n.length);for(let u=0;u<n.length;u++){var i=e[u],s=i.transform,a=t.data.field(i.field);r.set(i.field,(o=s,c=a,l=n[u],o instanceof sT?aT(o,c):o instanceof oT?cT(o,c):l))}var o,c,l;return r}function CT(e,t,n){const r=new Map;for(const l of e){const e=l.transform,u=n.data.field(l.field);r.set(l.field,(i=e,s=u,a=t,c=o=void 0,i instanceof iT?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return(t=t&&Sb(t)?kb(t):t)&&(n.fields.__previous_value__=t),{mapValue:n}}(a,s):i instanceof sT?aT(i,s):i instanceof oT?cT(i,s):(o=rT(i=i,s),c=uT(o)+uT(i.Ee),qb(o)&&qb(i.Ee)?eT(c):ZI(i.serializer,c))))}var i,s,a,o,c;return r}class ST extends mT{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class kT extends mT{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class AT{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&_T(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=yT(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=yT(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,a){const o=HI();return this.mutations.forEach(e=>{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var i=vT(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(nw.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),JI())}isEqual(e){return this.batchId===e.batchId&&Zy(this.mutations,e.mutations,(e,t)=>wT(e,t))&&Zy(this.baseMutations,e.baseMutations,(e,t)=>wT(e,t))}}class NT{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Vy(e.mutations.length===n.length);let r=QI;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new NT(e,t,n,r)}}class RT{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class PT{constructor(e,t){this.count=e,this.unchangedNames=t}}function DT(e){switch(e){default:return Uy();case qy.CANCELLED:case qy.UNKNOWN:case qy.DEADLINE_EXCEEDED:case qy.RESOURCE_EXHAUSTED:case qy.INTERNAL:case qy.UNAVAILABLE:case qy.UNAUTHENTICATED:return!1;case qy.INVALID_ARGUMENT:case qy.NOT_FOUND:case qy.ALREADY_EXISTS:case qy.PERMISSION_DENIED:case qy.FAILED_PRECONDITION:case qy.ABORTED:case qy.OUT_OF_RANGE:case qy.UNIMPLEMENTED:case qy.DATA_LOSS:return!0}}function xT(e){if(void 0===e)return My("GRPC error has no .code"),qy.UNKNOWN;switch(e){case _y.OK:return qy.OK;case _y.CANCELLED:return qy.CANCELLED;case _y.UNKNOWN:return qy.UNKNOWN;case _y.DEADLINE_EXCEEDED:return qy.DEADLINE_EXCEEDED;case _y.RESOURCE_EXHAUSTED:return qy.RESOURCE_EXHAUSTED;case _y.INTERNAL:return qy.INTERNAL;case _y.UNAVAILABLE:return qy.UNAVAILABLE;case _y.UNAUTHENTICATED:return qy.UNAUTHENTICATED;case _y.INVALID_ARGUMENT:return qy.INVALID_ARGUMENT;case _y.NOT_FOUND:return qy.NOT_FOUND;case _y.ALREADY_EXISTS:return qy.ALREADY_EXISTS;case _y.PERMISSION_DENIED:return qy.PERMISSION_DENIED;case _y.FAILED_PRECONDITION:return qy.FAILED_PRECONDITION;case _y.ABORTED:return qy.ABORTED;case _y.OUT_OF_RANGE:return qy.OUT_OF_RANGE;case _y.UNIMPLEMENTED:return qy.UNIMPLEMENTED;case _y.DATA_LOSS:return qy.DATA_LOSS;default:return Uy()}}function OT(){return new TextEncoder}(Tt=_y=_y||{})[Tt.OK=0]="OK",Tt[Tt.CANCELLED=1]="CANCELLED",Tt[Tt.UNKNOWN=2]="UNKNOWN",Tt[Tt.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Tt[Tt.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Tt[Tt.NOT_FOUND=5]="NOT_FOUND",Tt[Tt.ALREADY_EXISTS=6]="ALREADY_EXISTS",Tt[Tt.PERMISSION_DENIED=7]="PERMISSION_DENIED",Tt[Tt.UNAUTHENTICATED=16]="UNAUTHENTICATED",Tt[Tt.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Tt[Tt.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Tt[Tt.ABORTED=10]="ABORTED",Tt[Tt.OUT_OF_RANGE=11]="OUT_OF_RANGE",Tt[Tt.UNIMPLEMENTED=12]="UNIMPLEMENTED",Tt[Tt.INTERNAL=13]="INTERNAL",Tt[Tt.UNAVAILABLE=14]="UNAVAILABLE",Tt[Tt.DATA_LOSS=15]="DATA_LOSS";const MT=new Ay([4294967295,4294967295],0);function LT(e){const t=OT().encode(e),n=new ky;return n.update(t),new Uint8Array(n.digest())}function FT(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new Ay([n,r],0),new Ay([i,s],0)]}class UT{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||8<=t)throw new VT(`Invalid padding: ${t}`);if(n<0)throw new VT(`Invalid hash count: ${n}`);if(0<e.length&&0===this.hashCount)throw new VT(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new VT(`Invalid padding when bitmap length is 0: ${t}`);this.Ae=8*e.length-t,this.Re=Ay.fromNumber(this.Ae)}Ve(e,t,n){let r=e.add(t.multiply(Ay.fromNumber(n)));return 1===r.compare(MT)&&(r=new Ay([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Re).toNumber()}me(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ae)return!1;const t=LT(e),[n,r]=FT(t);for(let i=0;i<this.hashCount;i++){const t=this.Ve(n,r,i);if(!this.me(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new UT(i,r,t);return n.forEach(e=>s.insert(e)),s}insert(t){if(0!==this.Ae){const n=LT(t),[r,i]=FT(n);for(let e=0;e<this.hashCount;e++){const n=this.Ve(r,i,e);this.fe(n)}}}fe(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class VT extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class qT{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,jT.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new qT(nw.min(),r,new pb(Xy),$I,JI())}}class jT{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new jT(n,t,JI(),JI(),JI())}}class BT{constructor(e,t,n,r){this.ge=e,this.removedTargetIds=t,this.key=n,this.pe=r}}class zT{constructor(e,t){this.targetId=e,this.ye=t}}class $T{constructor(e,t,n=bb.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class KT{constructor(){this.we=0,this.Se=HT(),this.be=bb.EMPTY_BYTE_STRING,this.De=!1,this.ve=!0}get current(){return this.De}get resumeToken(){return this.be}get Ce(){return 0!==this.we}get Fe(){return this.ve}Me(e){0<e.approximateByteSize()&&(this.ve=!0,this.be=e)}xe(){let n=JI(),r=JI(),i=JI();return this.Se.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:Uy()}}),new jT(this.be,this.De,n,r,i)}Oe(){this.ve=!1,this.Se=HT()}Ne(e,t){this.ve=!0,this.Se=this.Se.insert(e,t)}Be(e){this.ve=!0,this.Se=this.Se.remove(e)}Le(){this.we+=1}ke(){--this.we}qe(){this.ve=!0,this.De=!0}}class WT{constructor(e){this.Qe=e,this.Ke=new Map,this.$e=$I,this.Ue=GT(),this.We=new pb(Xy)}Ge(e){for(const t of e.ge)e.pe&&e.pe.isFoundDocument()?this.ze(t,e.pe):this.je(t,e.key,e.pe);for(const n of e.removedTargetIds)this.je(n,e.key,e.pe)}He(n){this.forEachTarget(n,e=>{const t=this.Je(e);switch(n.state){case 0:this.Ye(e)&&t.Me(n.resumeToken);break;case 1:t.ke(),t.Ce||t.Oe(),t.Me(n.resumeToken);break;case 2:t.ke(),t.Ce||this.removeTarget(e);break;case 3:this.Ye(e)&&(t.qe(),t.Me(n.resumeToken));break;case 4:this.Ye(e)&&(this.Ze(e),t.Me(n.resumeToken));break;default:Uy()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Ke.forEach((e,t)=>{this.Ye(t)&&n(t)})}Xe(e){const t=e.targetId,n=e.ye.count,r=this.et(t);if(r){var i=r.target;if(II(i))if(0===n){const e=new ow(i.path);this.je(t,e,Yb.newNoDocument(e,nw.min()))}else Vy(1===n);else{const r=this.tt(t);if(r!==n){const n=this.nt(e),s=n?this.rt(n,e,r):1;if(0!==s){this.Ze(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.We=this.We.insert(t,e)}}}}}nt(e){var t=e.ye.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:n="",padding:r=0},hashCount:t=0}=t;let i,s;try{i=Cb(n).toUint8Array()}catch(e){if(e instanceof wb)return Ly("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{s=new UT(i,r,t)}catch(e){return Ly(e instanceof VT?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ae?null:s}rt(e,t,n){return t.ye.count===n-this.ot(e,t.targetId)?0:2}ot(n,r){const e=this.Qe.getRemoteKeysForTarget(r);let i=0;return e.forEach(e=>{var t=this.Qe.st(),t=`projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`;n.mightContain(t)||(this.je(r,e,null),i++)}),i}_t(r){const i=new Map;this.Ke.forEach((e,t)=>{var n=this.et(t);if(n){if(e.current&&II(n.target)){const i=new ow(n.target.path);null!==this.$e.get(i)||this.ut(t,i)||this.je(t,i,Yb.newNoDocument(i,r))}e.Fe&&(i.set(t,e.xe()),e.Oe())}});let s=JI();this.Ue.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.et(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.$e.forEach((e,t)=>t.setReadTime(r));var e=new qT(r,i,this.We,this.$e,s);return this.$e=$I,this.Ue=GT(),this.We=new pb(Xy),e}ze(e,t){var n;this.Ye(e)&&(n=this.ut(e,t.key)?2:0,this.Je(e).Ne(t.key,n),this.$e=this.$e.insert(t.key,t),this.Ue=this.Ue.insert(t.key,this.ct(t.key).add(e)))}je(e,t,n){if(this.Ye(e)){const r=this.Je(e);this.ut(e,t)?r.Ne(t,1):r.Be(t),this.Ue=this.Ue.insert(t,this.ct(t).delete(e)),n&&(this.$e=this.$e.insert(t,n))}}removeTarget(e){this.Ke.delete(e)}tt(e){var t=this.Je(e).xe();return this.Qe.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Le(e){this.Je(e).Le()}Je(e){let t=this.Ke.get(e);return t||(t=new KT,this.Ke.set(e,t)),t}ct(e){let t=this.Ue.get(e);return t||(t=new mb(Xy),this.Ue=this.Ue.insert(e,t)),t}Ye(e){var t=null!==this.et(e);return t||Oy("WatchChangeAggregator","Detected inactive target",e),t}et(e){var t=this.Ke.get(e);return t&&t.Ce?null:this.Qe.lt(e)}Ze(t){this.Ke.set(t,new KT),this.Qe.getRemoteKeysForTarget(t).forEach(e=>{this.je(t,e,null)})}ut(e,t){return this.Qe.getRemoteKeysForTarget(e).has(t)}}function GT(){return new pb(ow.comparator)}function HT(){return new pb(ow.comparator)}const QT={asc:"ASCENDING",desc:"DESCENDING"},YT={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},JT={and:"AND",or:"OR"};class XT{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function ZT(e,t){return e.useProto3Json||xw(t)?t:{value:t}}function e0(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function t0(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function n0(e){return Vy(!!e),nw.fromTimestamp((t=Tb(e),new tw(t.seconds,t.nanos)));var t}function r0(e,t){return e=e,new iw(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function i0(e){var t=iw.fromString(e);return Vy(I0(t)),t}function s0(e,t){return r0(e.databaseId,t.path)}function a0(e,t){const n=i0(t);if(n.get(1)!==e.databaseId.projectId)throw new jy(qy.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new jy(qy.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ow(u0(n))}function o0(e,t){return r0(e.databaseId,t)}function c0(e){var t=i0(e);return 4===t.length?iw.emptyPath():u0(t)}function l0(e){return new iw(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function u0(e){return Vy(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function h0(e,t,n){return{name:s0(e,t),fields:n.value.mapValue.fields}}function d0(e,t,n){const r=a0(e,t.name),i=n0(t.updateTime),s=t.createTime?n0(t.createTime):nw.min(),a=new Qb({mapValue:{fields:t.fields}}),o=Yb.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function p0(e,t){let n;if(t instanceof bT)n={update:h0(e,t.key,t.value)};else if(t instanceof ST)n={delete:s0(e,t.key)};else if(t instanceof IT)n={update:h0(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof kT))return Uy();n={verify:s0(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof iT)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof sT)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof oT)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof lT)return{fieldPath:e.field.canonicalString(),increment:t.Ee};throw Uy()}(e))),t.precondition.isNone||(n.currentDocument=(r=e,void 0!==(e=t.precondition).updateTime?{updateTime:(t=e.updateTime,e0(r,t.toTimestamp()))}:void 0!==e.exists?{exists:e.exists}:Uy())),n;var r}function f0(t,e){const n=e.currentDocument?void 0!==(i=e.currentDocument).updateTime?fT.updateTime(n0(i.updateTime)):void 0!==i.exists?fT.exists(i.exists):fT.none():fT.none(),r=e.updateTransforms?e.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)Vy("REQUEST_TIME"===t.setToServerValue),n=new iT;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new sT(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new oT(e)}else"increment"in t?n=new lT(e,t.increment):Uy();var r=aw.fromServerFormat(t.fieldPath);return new dT(r,n)}(t,e)):[];var i;if(e.update){e.update.name;var s=a0(t,e.update.name),a=new Qb({mapValue:{fields:e.update.fields}});if(e.updateMask){const t=function(e){const t=e.fieldPaths||[];return new yb(t.map(e=>aw.fromServerFormat(e)))}(e.updateMask);return new IT(s,a,t,n,r)}return new bT(s,a,n,r)}if(e.delete){const r=a0(t,e.delete);return new ST(r,n)}if(e.verify){const r=a0(t,e.verify);return new kT(r,n)}return Uy()}function g0(e,t){return{documents:[o0(e,t.path)]}}function m0(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=o0(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=o0(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length)return function n(e){return e instanceof nI?function(e){if("=="===e.op){if(zb(e.value))return{unaryFilter:{field:w0(e.field),op:"IS_NAN"}};if(Bb(e.value))return{unaryFilter:{field:w0(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(zb(e.value))return{unaryFilter:{field:w0(e.field),op:"IS_NOT_NAN"}};if(Bb(e.value))return{unaryFilter:{field:w0(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:w0(e.field),op:_0(e.op),value:e.value}}}(e):e instanceof rI?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:y0(e.op),filters:t}}}(e):Uy()}(rI.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:w0(e.field),direction:(e=e.dir,QT[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);i=ZT(e,t.limit);return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt={before:(e=t.startAt).inclusive,values:e.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function v0(e){let t=c0(e.parent);var n,r,i,s=e.structuredQuery,a=s.from?s.from.length:0;let o=null;if(0<a){Vy(1===a);const p=s.from[0];p.allDescendants?o=p.collectionId:t=t.child(p.collectionId)}let c=[];s.where&&(c=function(e){const t=function t(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=b0(e.unaryFilter.field);return nI.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=b0(e.unaryFilter.field);return nI.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=b0(e.unaryFilter.field);return nI.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=b0(e.unaryFilter.field);return nI.create(i,"!=",{nullValue:"NULL_VALUE"});default:return Uy()}}(e):void 0!==e.fieldFilter?function(e){return nI.create(b0(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return Uy()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return rI.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return Uy()}}(e.compositeFilter.op))}(e):Uy()}(e);return t instanceof rI&&aI(t)?t.getFilters():[t]}(s.where));let l=[];s.orderBy&&(l=s.orderBy.map(e=>function(e){return new eI(b0(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)));let u=null;s.limit&&(u=(e=s.limit,xw(n="object"==typeof e?e.value:e)?null:n));let h=null;s.startAt&&(h=(r=s.startAt,i=!!r.before,n=r.values||[],new Jb(n,i)));let d=null;return s.endAt&&(d=(r=s.endAt,i=!r.before,s=r.values||[],new Jb(s,i))),kI(t,o,l,c,u,"F",h,d)}function _0(e){return YT[e]}function y0(e){return JT[e]}function w0(e){return{fieldPath:e.canonicalString()}}function b0(e){return aw.fromServerFormat(e.fieldPath)}function I0(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class T0{constructor(e,t,n,r,i=nw.min(),s=nw.min(),a=bb.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new T0(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new T0(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new T0(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new T0(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class E0{constructor(e){this.ht=e}}function C0(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:S0(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:s0(i=e.ht,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:e0(i,e.version.toTimestamp()),createTime:e0(i,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:k0(t.version)};else{if(!t.isUnknownDocument())return Uy();r.unknownDocument={path:n.path.toArray(),version:k0(t.version)}}var i;return r}function S0(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function k0(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function A0(e){var t=new tw(e.seconds,e.nanoseconds);return nw.fromTimestamp(t)}function N0(t,e){const n=(e.baseMutations||[]).map(e=>f0(t.ht,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>f0(t.ht,e)),i=tw.fromMillis(e.localWriteTimeMs);return new AT(e.batchId,i,n,r)}function R0(e){var t,n=A0(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?A0(e.lastLimboFreeSnapshotVersion):nw.min(),i=void 0!==e.query.documents?(Vy(1===(t=e.query).documents.length),OI(AI(c0(t.documents[0])))):OI(v0(e.query));return new T0(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,bb.fromBase64String(e.resumeToken))}function P0(e,t){var n=k0(t.snapshotVersion),r=k0(t.lastLimboFreeSnapshotVersion),i=(II(t.target)?g0:m0)(e.ht,t.target),s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:wI(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function D0(e){var t=v0({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?LI(t,t.limit,"L"):t}function x0(e,t){return new RT(t.largestBatchId,f0(e.ht,t.overlayMutation))}function O0(e,t){var n=t.path.lastSegment();return[e,Lw(t.path.popLast()),n]}function M0(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:k0(r.readTime),documentKey:Lw(r.documentKey.path),largestBatchId:r.largestBatchId}}class L0{getBundleMetadata(e,t){return F0(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:A0(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return F0(e).put({bundleId:(t=t).id,createTime:k0(n0(t.createTime)),version:t.version})}getNamedQuery(e,t){return U0(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:D0(e.bundledQuery),readTime:A0(e.readTime)}})}saveNamedQuery(e,t){return U0(e).put({name:(t=t).name,readTime:k0(n0(t.readTime)),bundledQuery:t.bundledQuery})}}function F0(e){return lb(e,"bundles")}function U0(e){return lb(e,"namedQueries")}class V0{constructor(e,t){this.serializer=e,this.userId=t}static Pt(e,t){var n=t.uid||"";return new V0(e,n)}getOverlay(e,t){return q0(e).get(O0(this.userId,t)).next(e=>e?x0(this.serializer,e):null)}getOverlays(e,t){const n=HI();return ww.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new RT(i,t);s.push(this.It(r,n))}),ww.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Lw(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(q0(n).J("collectionPathOverlayIndex",t))}),ww.waitFor(i)}getOverlaysForCollection(e,t,n){const r=HI(),i=Lw(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return q0(e).G("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=x0(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=HI();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return q0(e).Z({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=x0(this.serializer,t);s.size()<i||r.largestBatchId===a?(s.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>s)}It(e,t){return q0(e).put(function(e,t,n){var[,r,i]=O0(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:p0(e.ht,n.mutation)}}(this.serializer,this.userId,t))}}function q0(e){return lb(e,"documentOverlays")}class j0{constructor(){}Tt(e,t){this.Et(e,t),t.dt()}Et(e,t){var n,r;"nullValue"in e?this.At(t,5):"booleanValue"in e?(this.At(t,10),t.Rt(e.booleanValue?1:0)):"integerValue"in e?(this.At(t,15),t.Rt(Eb(e.integerValue))):"doubleValue"in e?(n=Eb(e.doubleValue),isNaN(n)?this.At(t,13):(this.At(t,15),Ow(n)?t.Rt(0):t.Rt(n))):"timestampValue"in e?(r=e.timestampValue,this.At(t,20),"string"==typeof r?t.Vt(r):(t.Vt(`${r.seconds||""}`),t.Rt(r.nanos||0))):"stringValue"in e?(this.ft(e.stringValue,t),this.gt(t)):"bytesValue"in e?(this.At(t,30),t.yt(Cb(e.bytesValue)),this.gt(t)):"referenceValue"in e?this.wt(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.At(t,45),t.Rt(r.latitude||0),t.Rt(r.longitude||0)):"mapValue"in e?Wb(e)?this.At(t,Number.MAX_SAFE_INTEGER):(this.St(e.mapValue,t),this.gt(t)):"arrayValue"in e?(this.bt(e.arrayValue,t),this.gt(t)):Uy()}ft(e,t){this.At(t,25),this.Dt(e,t)}Dt(e,t){t.Vt(e)}St(e,t){var n=e.fields||{};this.At(t,55);for(const e of Object.keys(n))this.ft(e,t),this.Et(n[e],t)}bt(e,t){var n=e.values||[];this.At(t,50);for(const e of n)this.Et(e,t)}wt(e,t){this.At(t,37),ow.fromName(e).path.forEach(e=>{this.At(t,60),this.Dt(e,t)})}At(e,t){e.Rt(t)}gt(e){e.Rt(2)}}function B0(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}j0.vt=new j0;class z0{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Ct(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ft(n.value),n=t.next();this.Mt()}xt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ot(n.value),n=t.next();this.Nt()}Bt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ft(e);else if(e<2048)this.Ft(960|e>>>6),this.Ft(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ft(480|e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e);else{const e=t.codePointAt(0);this.Ft(240|e>>>18),this.Ft(128|63&e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e)}}this.Mt()}Lt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ot(e);else if(e<2048)this.Ot(960|e>>>6),this.Ot(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ot(480|e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e);else{const e=t.codePointAt(0);this.Ot(240|e>>>18),this.Ot(128|63&e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e)}}this.Nt()}kt(e){var t=this.qt(e),n=B0(t);this.Qt(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}Kt(e){var t=this.qt(e),n=B0(t);this.Qt(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}$t(){this.Ut(255),this.Ut(255)}Wt(){this.Gt(255),this.Gt(255)}reset(){this.position=0}seed(e){this.Qt(e.length),this.buffer.set(e,this.position),this.position+=e.length}zt(){return this.buffer.slice(0,this.position)}qt(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}Ft(e){var t=255&e;0==t?(this.Ut(0),this.Ut(255)):255==t?(this.Ut(255),this.Ut(0)):this.Ut(t)}Ot(e){var t=255&e;0==t?(this.Gt(0),this.Gt(255)):255==t?(this.Gt(255),this.Gt(0)):this.Gt(e)}Mt(){this.Ut(0),this.Ut(1)}Nt(){this.Gt(0),this.Gt(1)}Ut(e){this.Qt(1),this.buffer[this.position++]=e}Gt(e){this.Qt(1),this.buffer[this.position++]=~e}Qt(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class $0{constructor(e){this.jt=e}yt(e){this.jt.Ct(e)}Vt(e){this.jt.Bt(e)}Rt(e){this.jt.kt(e)}dt(){this.jt.$t()}}class K0{constructor(e){this.jt=e}yt(e){this.jt.xt(e)}Vt(e){this.jt.Lt(e)}Rt(e){this.jt.Kt(e)}dt(){this.jt.Wt()}}class W0{constructor(){this.jt=new z0,this.Ht=new $0(this.jt),this.Jt=new K0(this.jt)}seed(e){this.jt.seed(e)}Yt(e){return 0===e?this.Ht:this.Jt}zt(){return this.jt.zt()}reset(){this.jt.reset()}}class G0{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Zt(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new G0(this.indexId,this.documentKey,this.arrayValue,n)}}function H0(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=Q0(e.arrayValue,t.arrayValue),0!==n?n:(n=Q0(e.directionalValue,t.directionalValue),0!==n?n:ow.comparator(e.documentKey,t.documentKey)))}function Q0(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class Y0{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Xt=e.orderBy,this.en=[];for(const t of e.filters){const e=t;e.isInequality()?this.tn=e:this.en.push(e)}}nn(e){Vy(e.collectionGroup===this.collectionId);var t=lw(e);if(void 0!==t&&!this.rn(t))return!1;const n=uw(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.rn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(void 0!==this.tn){if(!r.has(this.tn.field.canonicalString())){const e=n[i];if(!this.sn(this.tn,e)||!this.on(this.Xt[s++],e))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.Xt.length||!this.on(this.Xt[s++],e))return!1}return!0}rn(e){for(const t of this.en)if(this.sn(t,e))return!0;return!1}sn(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}on(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function J0(e){if(0===e.getFilters().length)return[];const t=function t(e){if(Vy(e instanceof nI||e instanceof rI),e instanceof nI)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=rI.create(n,e.op);return r=rE(r),eE(r)?r:(Vy(r instanceof rI),Vy(iI(r)),Vy(1<r.filters.length),r.filters.reduce((e,t)=>tE(e,t)))}(function t(n){var e;if(Vy(n instanceof nI||n instanceof rI),n instanceof nI){if(n instanceof gI){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>nI.create(n.field,"==",e)))||[];return rI.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return rI.create(r,n.op)}(e));return Vy(eE(t)),X0(t)||Z0(t)?[t]:t.getFilters()}function X0(e){return e instanceof nI}function Z0(e){return e instanceof rI&&aI(e)}function eE(e){return X0(e)||Z0(e)||function(e){if(e instanceof rI&&sI(e)){for(const t of e.getFilters())if(!X0(t)&&!Z0(t))return!1;return!0}return!1}(e)}function tE(e,t){var n,r;return Vy(e instanceof nI||e instanceof rI),Vy(t instanceof nI||t instanceof rI),rE(e instanceof nI?t instanceof nI?(n=e,r=t,rI.create([n,r],"and")):nE(e,t):t instanceof nI?nE(t,e):function(e,t){if(Vy(0<e.filters.length&&0<t.filters.length),iI(e)&&iI(t))return cI(e,t.getFilters());const n=sI(e)?e:t,r=sI(e)?t:e,i=n.filters.map(e=>tE(e,r));return rI.create(i,"or")}(e,t))}function nE(t,e){if(iI(e))return cI(e,t.getFilters());var n=e.filters.map(e=>tE(t,e));return rI.create(n,"or")}function rE(t){if(Vy(t instanceof nI||t instanceof rI),t instanceof nI)return t;const e=t.getFilters();if(1===e.length)return rE(e[0]);if(oI(t))return t;const n=e.map(e=>rE(e)),r=[];return n.forEach(e=>{e instanceof nI?r.push(e):e instanceof rI&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:rI.create(r,t.op)}class iE{constructor(){this._n=new sE}addToCollectionParentIndex(e,t){return this._n.add(t),ww.resolve()}getCollectionParents(e,t){return ww.resolve(this._n.getEntries(t))}addFieldIndex(e,t){return ww.resolve()}deleteFieldIndex(e,t){return ww.resolve()}getDocumentsMatchingTarget(e,t){return ww.resolve(null)}getIndexType(e,t){return ww.resolve(0)}getFieldIndexes(e,t){return ww.resolve([])}getNextCollectionGroupToUpdate(e){return ww.resolve(null)}getMinOffset(e,t){return ww.resolve(gw.min())}getMinOffsetFromCollectionGroup(e,t){return ww.resolve(gw.min())}updateCollectionGroup(e,t,n){return ww.resolve()}updateIndexEntries(e,t){return ww.resolve()}}class sE{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new mb(iw.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new mb(iw.comparator)).toArray()}}const aE=new Uint8Array(0);class oE{constructor(e,t){this.user=e,this.databaseId=t,this.an=new sE,this.un=new zI(e=>wI(e),(e,t)=>bI(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.an.has(t))return ww.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.an.add(t)});r={collectionId:n,parent:Lw(r)};return cE(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[ew(n),""],!1,!0);return cE(e).G(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Uw(t.parent))}return r})}addFieldIndex(e,t){const n=uE(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const i=n.add(r);if(t.indexState){const n=hE(e);return i.next(e=>{n.put(M0(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=uE(e),r=hE(e),i=lE(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}getDocumentsMatchingTarget(e,u){const h=lE(e);let d=!0;const n=new Map;return ww.forEach(this.cn(u),t=>this.ln(e,t).next(e=>{d=d&&!!e,n.set(t,e)})).next(()=>{if(d){let l=JI();const d=[];return ww.forEach(n,(e,t)=>{var n;Oy("IndexedDbIndexManager",`Using index ${n=e,`id=${n.indexId}|cg=${n.collectionGroup}|f=${n.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${wI(u)}`);var r=function(e,t){var n=lw(t);if(void 0===n)return null;for(const t of TI(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),i=function(e,t){const n=new Map;for(const r of uw(t))for(const t of TI(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of uw(t)){const t=(0===i.kind?EI:CI)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new Jb(n,r)}(t,e),a=function(e,t){const n=[];let r=!0;for(const i of uw(t)){const t=(0===i.kind?CI:EI)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new Jb(n,r)}(t,e),o=this.hn(e,t,s),c=this.hn(e,t,a),i=this.Pn(e,t,i),i=this.In(e.indexId,r,o,s.inclusive,c,a.inclusive,i);return ww.forEach(i,e=>h.H(e,u.limit).next(e=>{e.forEach(e=>{var t=ow.fromSegments(e.documentKey);l.has(t)||(l=l.add(t),d.push(t))})}))}).next(()=>d)}return ww.resolve(null)})}cn(t){let e=this.un.get(t);return e||(e=0===t.filters.length?[t]:J0(rI.create(t.filters,"and")).map(e=>yI(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.un.set(t,e),e)}In(t,e,n,r,i,s,a){const o=(null!=e?e.length:1)*Math.max(n.length,i.length),c=o/(null!=e?e.length:1),l=[];for(let u=0;u<o;++u){const o=e?this.Tn(e[u/c]):aE,h=this.En(t,o,n[u%c],r),d=this.dn(t,o,i[u%c],s),p=a.map(e=>this.En(t,o,e,!0));l.push(...this.createRange(h,d,p))}return l}En(e,t,n,r){const i=new G0(e,ow.empty(),t,n);return r?i:i.Zt()}dn(e,t,n,r){const i=new G0(e,ow.empty(),t,n);return r?i.Zt():i}ln(e,t){const r=new Y0(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.nn(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.cn(t);return ww.forEach(r,t=>this.ln(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new mb(aw.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>function(e){return null!==e.limit}(t)&&1<r.length&&2===n?1:n)}An(e,t){const n=new W0;for(const i of uw(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.Yt(i.kind);j0.vt.Tt(e,r)}return n.zt()}Tn(e){const t=new W0;return j0.vt.Tt(e,t.Yt(0)),t.zt()}Rn(e,t){const n=new W0;return j0.vt.Tt(Vb(this.databaseId,t),n.Yt(0===(r=uw(e)).length?0:r[r.length-1].kind)),n.zt();var r}Pn(e,t,n){if(null===n)return[];let r=[];r.push(new W0);let i=0;for(const s of uw(e)){const e=n[i++];for(const n of r)if(this.Vn(t,s.fieldPath)&&jb(e))r=this.mn(r,s,e);else{const t=n.Yt(s.kind);j0.vt.Tt(e,t)}}return this.fn(r)}hn(e,t,n){return this.Pn(e,t,n.position)}fn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].zt();return t}mn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new W0;r.seed(n.zt()),j0.vt.Tt(e,r.Yt(t.kind)),i.push(r)}return i}Vn(e,t){return!!e.filters.find(e=>e instanceof nI&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=uE(e),r=hE(e);return(t?n.G("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.G()).next(e=>{const s=[];return ww.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new dw(e.sequenceNumber,new gw(A0(e.readTime),new ow(Uw(e.documentKey)),e.largestBatchId)):dw.empty(),r=t.fields.map(([e,t])=>new hw(aw.fromServerFormat(e),t)),new cw(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:Xy(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=uE(e),s=hE(e);return this.gn(e).next(t=>i.G("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>ww.forEach(e,e=>s.put(M0(e.indexId,this.user,t,r)))))}updateIndexEntries(i,e){const n=new Map;return ww.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?ww.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),ww.forEach(e,n=>this.pn(i,t,n).next(e=>{var t=this.yn(r,n);return e.isEqual(t)?ww.resolve():this.wn(i,r,n,e,t)}))))})}Sn(e,t,n,r){return lE(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.Rn(n,t.key),documentKey:t.key.path.toArray()})}bn(e,t,n,r){return lE(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.Rn(n,t.key),t.key.path.toArray()])}pn(e,n,r){const t=lE(e);let i=new mb(H0);return t.Z({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.Rn(r,n)])},(e,t)=>{i=i.add(new G0(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}yn(e,t){let n=new mb(H0);var r=this.An(t,e);if(null==r)return n;const i=lw(t);if(null!=i){var s=e.data.field(i.fieldPath);if(jb(s))for(const i of s.arrayValue.values||[])n=n.add(new G0(t.indexId,e.key,this.Tn(i),r))}else n=n.add(new G0(t.indexId,e.key,aE,r));return n}wn(t,n,r,e,i){Oy("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,t,n,r,i){var s=e.getIterator(),a=t.getIterator();let o=_b(s),c=_b(a);for(;o||c;){let e=!1,t=!1;if(o&&c){const r=n(o,c);r<0?t=!0:0<r&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(c),c=_b(a)):t?(i(o),o=_b(s)):(o=_b(s),c=_b(a))}}(e,i,H0,e=>{s.push(this.Sn(t,n,r,e))},e=>{s.push(this.bn(t,n,r,e))}),ww.waitFor(s)}gn(e){let r=1;return hE(e).Z({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>H0(e,t)).filter((e,t,n)=>!t||0!==H0(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=H0(i,e),s=H0(i,t);if(0===n)r[0]=e.Zt();else if(0<n&&s<0)r.push(i),r.push(i.Zt());else if(0<s)break}r.push(t);const i=[];for(let a=0;a<r.length;a+=2){if(this.Dn(r[a],r[a+1]))return[];const t=[r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,aE,[]],n=[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,aE,[]];i.push(IDBKeyRange.bound(t,n))}return i}Dn(e,t){return 0<H0(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(dE)}getMinOffset(t,e){return ww.mapArray(this.cn(e),e=>this.ln(t,e).next(e=>e||Uy())).next(dE)}}function cE(e){return lb(e,"collectionParents")}function lE(e){return lb(e,"indexEntries")}function uE(e){return lb(e,"indexConfiguration")}function hE(e){return lb(e,"indexState")}function dE(e){Vy(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i<e.length;i++){var r=e[i].indexState.offset;mw(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new gw(t.readTime,t.documentKey,n)}const pE={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class fE{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new fE(e,fE.DEFAULT_COLLECTION_PERCENTILE,fE.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function gE(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId);let o=0;const c=r.Z({range:a},(e,t,n)=>(o++,n.delete()));s.push(c.next(()=>{Vy(1===o)}));const l=[];for(const e of n.mutations){const r=jw(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return ww.waitFor(s).next(()=>l)}function mE(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw Uy();t=e.noDocument}return JSON.stringify(t).length}fE.DEFAULT_COLLECTION_PERCENTILE=10,fE.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,fE.DEFAULT=new fE(41943040,fE.DEFAULT_COLLECTION_PERCENTILE,fE.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),fE.DISABLED=new fE(-1,0,0);class vE{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.vn={}}static Pt(e,t,n,r){Vy(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new vE(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return yE(e).Z({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,p){const f=wE(u),g=yE(u);return g.add({}).next(e=>{Vy("number"==typeof e);const t=new AT(e,h,d,p),n=(i=this.serializer,s=this.userId,a=t,o=a.baseMutations.map(e=>p0(i.ht,e)),c=a.mutations.map(e=>p0(i.ht,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:c}),r=[];var i,s,a,o,c;let l=new mb((e,t)=>Xy(e.canonicalString(),t.canonicalString()));for(const u of p){const h=jw(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(f.put(h,Bw))}return l.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.vn[e]=t.keys()}),ww.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return yE(e).get(t).next(e=>e?(Vy(e.userId===this.userId),N0(this.serializer,e)):null)}Cn(e,n){return this.vn[n]?ww.resolve(this.vn[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.vn[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return yE(e).Z({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(Vy(t.batchId>=r),i=N0(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return yE(e).Z({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return yE(e).G("userMutationsIndex",t).next(e=>e.map(e=>N0(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=qw(this.userId,o.path),t=IDBKeyRange.lowerBound(e),c=[];return wE(a).Z({range:t},(e,t,n)=>{var[r,i,s]=e,i=Uw(i);if(r===this.userId&&o.path.isEqual(i))return yE(a).get(s).next(e=>{if(!e)throw Uy();Vy(e.userId===this.userId),c.push(N0(this.serializer,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new mb(Xy);const n=[];return e.forEach(a=>{var e=qw(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=wE(t).Z({range:e},(e,t,n)=>{var[r,i,s]=e,i=Uw(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),ww.waitFor(n).next(()=>this.Fn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=qw(this.userId,a),r=IDBKeyRange.lowerBound(n);let c=new mb(Xy);return wE(e).Z({range:r},(e,t,n)=>{var[r,i,s]=e,i=Uw(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(c=c.add(s)):n.done()}).next(()=>this.Fn(e,c))}Fn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(yE(t).get(e).next(e=>{if(null===e)throw Uy();Vy(e.userId===this.userId),n.push(N0(this.serializer,e))}))}),ww.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return gE(t.ue,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.Mn(n.batchId)}),ww.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}Mn(e){delete this.vn[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return ww.resolve();const t=IDBKeyRange.lowerBound([this.userId]),r=[];return wE(n).Z({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Uw(e[1]);r.push(t)}else n.done()}).next(()=>{Vy(0===r.length)})})}containsKey(e,t){return _E(e,this.userId,t)}xn(e){return bE(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function _E(e,s,t){const n=qw(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return wE(e).Z({range:r,Y:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function yE(e){return lb(e,"mutations")}function wE(e){return lb(e,"documentMutations")}function bE(e){return lb(e,"mutationQueues")}class IE{constructor(e){this.On=e}next(){return this.On+=2,this.On}static Nn(){return new IE(0)}static Bn(){return new IE(-1)}}class TE{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(n){return this.Ln(n).next(e=>{const t=new IE(e.highestTargetId);return e.highestTargetId=t.next(),this.kn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.Ln(e).next(e=>nw.fromTimestamp(new tw(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.Ln(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.Ln(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.kn(t,e)))}addTargetData(t,n){return this.qn(t,n).next(()=>this.Ln(t).next(e=>(e.targetCount+=1,this.Qn(n,e),this.kn(t,e))))}updateTargetData(e,t){return this.qn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>EE(t).delete(e.targetId)).next(()=>this.Ln(t)).next(e=>(Vy(0<e.targetCount),--e.targetCount,this.kn(t,e)))}removeTargets(r,i,s){let a=0;const o=[];return EE(r).Z((e,t)=>{var n=R0(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>ww.waitFor(o)).next(()=>a)}forEachTarget(e,r){return EE(e).Z((e,t)=>{var n=R0(t);r(n)})}Ln(e){return CE(e).get("targetGlobalKey").next(e=>(Vy(null!==e),e))}kn(e,t){return CE(e).put("targetGlobalKey",t)}qn(e,t){return EE(e).put(P0(this.serializer,t))}Qn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Ln(e).next(e=>e.targetCount)}getTargetData(e,i){var t=wI(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return EE(e).Z({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=R0(t);bI(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=SE(n);return e.forEach(e=>{var t=Lw(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),ww.waitFor(i)}removeMatchingKeys(n,e,r){const i=SE(n);return ww.forEach(e,e=>{var t=Lw(e.path);return ww.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=SE(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=SE(e);let i=JI();return r.Z({range:n,Y:!0},(e,t,n)=>{var r=Uw(e[1]),r=new ow(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=Lw(t.path),n=IDBKeyRange.bound([n],[ew(n)],!1,!0);let r=0;return SE(e).Z({index:"documentTargetsIndex",Y:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}lt(e,t){return EE(e).get(t).next(e=>e?R0(e):null)}}function EE(e){return lb(e,"targets")}function CE(e){return lb(e,"targetGlobal")}function SE(e){return lb(e,"targetDocuments")}function kE([e,t],[n,r]){var i=Xy(e,n);return 0===i?Xy(t,r):i}class AE{constructor(e){this.Kn=e,this.buffer=new mb(kE),this.$n=0}Un(){return++this.$n}Wn(e){var t=[e,this.Un()];if(this.buffer.size<this.Kn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();kE(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class NE{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Gn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.zn(6e4)}stop(){this.Gn&&(this.Gn.cancel(),this.Gn=null)}get started(){return null!==this.Gn}zn(e){Oy("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Gn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Gn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){Cw(e)?Oy("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await yw(e)}await this.zn(3e5)})}}class RE{constructor(e,t){this.jn=e,this.params=t}calculateTargetCount(e,t){return this.jn.Hn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return ww.resolve(Dw.ae);const n=new AE(t);return this.jn.forEachTarget(e,e=>n.Wn(e.sequenceNumber)).next(()=>this.jn.Jn(e,e=>n.Wn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.jn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.jn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Oy("LruGarbageCollector","Garbage collection skipped; disabled"),ww.resolve(pE)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(Oy("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),pE):this.Yn(t,n))}getCacheSize(e){return this.jn.getCacheSize(e)}Yn(t,n){let r,i,s,a,o,c,l;const u=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(Oy("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,c=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(l=Date.now(),xy()<=m.DEBUG&&Oy("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-u}ms\n\tDetermined least recently used ${i} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(c-o)+"ms\n"+`\tRemoved ${e} documents in `+(l-c)+"ms\n"+`Total Duration: ${l-u}ms`),ww.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class PE{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new RE(e,t))}Hn(e){const n=this.Zn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Zn(e){let t=0;return this.Jn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Jn(e,n){return this.Xn(e,(e,t)=>n(t))}addReference(e,t,n){return DE(e,n)}removeReference(e,t,n){return DE(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return DE(e,t)}er(t,n){let r=!1;return bE(t).X(e=>_E(t,e,n).next(e=>(e&&(r=!0),ww.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.Xn(n,(t,e)=>{if(e<=r){const r=this.er(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,nw.min()),SE(n).delete(function(e){return[0,Lw(e.path)]}(t))))});s.push(r)}}).next(()=>ww.waitFor(s)).next(()=>i.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return DE(e,t)}Xn(e,r){const t=SE(e);let i,s=Dw.ae;return t.Z({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==Dw.ae&&r(new ow(Uw(i)),s),s=n,i=t):s=Dw.ae}).next(()=>{s!==Dw.ae&&r(new ow(Uw(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function DE(e,t){return SE(e).put((e=e.currentSequenceNumber,{targetId:0,path:Lw(t.path),sequenceNumber:e}))}class xE{constructor(){this.changes=new zI(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Yb.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?ww.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class OE{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return UE(e).put(n)}removeEntry(e,t,n){return UE(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],S0(t),n[n.length-1]]}(t,n))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.tr(t,e)))}getEntry(e,n){let r=Yb.newInvalidDocument(n);return UE(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(VE(n))},(e,t)=>{r=this.nr(n,t)}).next(()=>r)}rr(e,n){let r={size:0,document:Yb.newInvalidDocument(n)};return UE(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(VE(n))},(e,t)=>{r={document:this.nr(n,t),size:mE(t)}}).next(()=>r)}getEntries(e,t){let r=$I;return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n)}).next(()=>r)}sr(e,t){let r=$I,i=new pb(ow.comparator);return this.ir(e,t,(e,t)=>{var n=this.nr(e,t);r=r.insert(e,n),i=i.insert(e,mE(t))}).next(()=>({documents:r,_r:i}))}ir(e,t,i){if(t.isEmpty())return ww.resolve();let n=new mb(jE);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(VE(n.first()),VE(n.last())),s=n.getIterator();let a=s.getNext();return UE(e).Z({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ow.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&jE(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.W(VE(a)):n.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,r,t,i){const n=r.path,s=[n.popLast().toArray(),n.lastSegment(),S0(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],a=[n.popLast().toArray(),n.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return UE(e).G(IDBKeyRange.bound(s,a,!0)).next(e=>{let t=$I;for(const n of e){const e=this.nr(ow.fromSegments(n.prefixPath.concat(n.collectionGroup,n.documentId)),n);e.isFoundDocument()&&(qI(r,e)||i.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,i){let s=$I;var r=qE(t,n),a=qE(t,gw.max());return UE(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.nr(ow.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new LE(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return FE(e).get("remoteDocumentGlobalKey").next(e=>(Vy(!!e),e))}tr(e,t){return FE(e).put("remoteDocumentGlobalKey",t)}nr(e,t){if(t){const e=function(e,t){let n;if(t.document)n=d0(e.ht,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ow.fromSegments(t.noDocument.path),i=A0(t.noDocument.readTime);n=Yb.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Uy();{const e=ow.fromSegments(t.unknownDocument.path),s=A0(t.unknownDocument.version);n=Yb.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new tw(t[0],t[1]),nw.fromTimestamp(r))),n;var r}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(nw.min()))return e}return Yb.newInvalidDocument(e)}}function ME(e){return new OE(e)}class LE extends xE{constructor(e,t){super(),this.ar=e,this.trackRemovals=t,this.ur=new zI(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,c=new mb((e,t)=>Xy(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.ur.get(e);if(a.push(this.ar.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=C0(this.ar.serializer,t);c=c.add(e.path.popLast());var i=mE(r);o+=i-n.size,a.push(this.ar.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=C0(this.ar.serializer,t.convertToNoDocument(nw.min()));a.push(this.ar.addEntry(s,e,o))}}),c.forEach(e=>{a.push(this.ar.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.ar.updateMetadata(s,o)),ww.waitFor(a)}getFromCache(e,t){return this.ar.rr(e,t).next(e=>(this.ur.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.ar.sr(e,t).next(({documents:n,_r:e})=>(e.forEach((e,t)=>{this.ur.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function FE(e){return lb(e,"remoteDocumentGlobal")}function UE(e){return lb(e,"remoteDocumentsV14")}function VE(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function qE(e,t){const n=t.documentKey.path.toArray();return[e,S0(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function jE(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=Xy(n[s],r[s]),i)return i;return i=Xy(n.length,r.length),i||(i=Xy(n[n.length-2],r[r.length-2]),i||Xy(n[n.length-1],r[r.length-1]))}class BE{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class zE{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(t,n){let r=null;return this.documentOverlayCache.getOverlay(t,n).next(e=>(r=e,this.remoteDocumentCache.getEntry(t,n))).next(e=>(null!==r&&yT(r.mutation,e,yb.empty(),tw.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,JI()).next(()=>e))}getLocalViewOfDocuments(e,t,n=JI()){const r=HI();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=WI();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=HI();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,JI()))}populateOverlays(e,n,t){const r=[];return t.forEach(e=>{n.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,t)=>{n.set(e,t)})})}computeViews(e,t,r,i){let s=$I;const a=HI(),o=HI();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof IT)?s=s.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),yT(n.mutation,t,n.mutation.getFieldMask(),tw.now())):a.set(t.key,yb.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new BE(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=HI();let c=new pb((e,t)=>e-t),l=JI();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||yb.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(c.get(r.batchId)||JI()).add(e),c=c.insert(r.batchId,t))})}).next(()=>{const e=[],t=c.getReverseIterator();for(;t.hasNext();){const c=t.getNext(),n=c.key,r=c.value,i=HI();r.forEach(e=>{var t;l.has(e)||(null!==(t=vT(a.get(e),o.get(e)))&&i.set(e,t),l=l.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return ww.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,ow.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):DI(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n):this.getDocumentsMatchingCollectionQuery(e,t,n);var r}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(n=>{const e=0<o-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-n.size):ww.resolve(HI());let r=-1,i=n;return e.next(e=>ww.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?ww.resolve():this.remoteDocumentCache.getEntry(s,t).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,JI())).next(e=>({batchId:r,changes:GI(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new ow(t)).next(e=>{let t=WI();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s){const a=i.collectionGroup;let o=WI();return this.indexManager.getCollectionParents(r,a).next(e=>ww.forEach(e,e=>{var t,n=(t=i,e=e.child(a),new SI(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s).next(e=>{e.forEach((e,t)=>{o=o.insert(e,t)})})}).next(()=>o))}getDocumentsMatchingCollectionQuery(t,s,n){let a;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,n,a))).next(r=>{a.forEach((e,t)=>{var n=t.getKey();null===r.get(n)&&(r=r.insert(n,Yb.newInvalidDocument(n)))});let i=WI();return r.forEach((e,t)=>{var n=a.get(e);void 0!==n&&yT(n.mutation,t,yb.empty(),tw.now()),qI(s,t)&&(i=i.insert(e,t))}),i})}}class $E{constructor(e){this.serializer=e,this.cr=new Map,this.lr=new Map}getBundleMetadata(e,t){return ww.resolve(this.cr.get(t))}saveBundleMetadata(e,t){return this.cr.set(t.id,{id:t.id,version:t.version,createTime:n0(t.createTime)}),ww.resolve()}getNamedQuery(e,t){return ww.resolve(this.lr.get(t))}saveNamedQuery(e,t){return this.lr.set(t.name,{name:(t=t).name,query:D0(t.bundledQuery),readTime:n0(t.readTime)}),ww.resolve()}}class KE{constructor(){this.overlays=new pb(ow.comparator),this.hr=new Map}getOverlay(e,t){return ww.resolve(this.overlays.get(t))}getOverlays(e,t){const n=HI();return ww.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.It(n,r,t)}),ww.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.hr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.hr.delete(n)),ww.resolve()}getOverlaysForCollection(e,t,n){const r=HI(),i=t.length+1,s=new ow(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return ww.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new pb((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=HI(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=HI(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return ww.resolve(a)}It(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.hr.get(r.largestBatchId).delete(n.key);this.hr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new RT(t,n));let i=this.hr.get(t);void 0===i&&(i=JI(),this.hr.set(t,i)),this.hr.set(t,i.add(n.key))}}class WE{constructor(){this.Pr=new mb(GE.Ir),this.Tr=new mb(GE.Er)}isEmpty(){return this.Pr.isEmpty()}addReference(e,t){var n=new GE(e,t);this.Pr=this.Pr.add(n),this.Tr=this.Tr.add(n)}dr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Ar(new GE(e,t))}Rr(e,t){e.forEach(e=>this.removeReference(e,t))}Vr(e){const t=new ow(new iw([])),n=new GE(t,e),r=new GE(t,e+1),i=[];return this.Tr.forEachInRange([n,r],e=>{this.Ar(e),i.push(e.key)}),i}mr(){this.Pr.forEach(e=>this.Ar(e))}Ar(e){this.Pr=this.Pr.delete(e),this.Tr=this.Tr.delete(e)}gr(e){var t=new ow(new iw([])),n=new GE(t,e),t=new GE(t,e+1);let r=JI();return this.Tr.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new GE(e,0),t=this.Pr.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class GE{constructor(e,t){this.key=e,this.pr=t}static Ir(e,t){return ow.comparator(e.key,t.key)||Xy(e.pr,t.pr)}static Er(e,t){return Xy(e.pr,t.pr)||ow.comparator(e.key,t.key)}}class HE{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.yr=1,this.wr=new mb(GE.Ir)}checkEmpty(e){return ww.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.yr;this.yr++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new AT(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.wr=this.wr.add(new GE(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return ww.resolve(s)}lookupMutationBatch(e,t){return ww.resolve(this.Sr(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.br(t+1),n=n<0?0:n;return ww.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return ww.resolve(0===this.mutationQueue.length?-1:this.yr-1)}getAllMutationBatches(e){return ww.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new GE(t,0),r=new GE(t,Number.POSITIVE_INFINITY),i=[];return this.wr.forEachInRange([n,r],e=>{var t=this.Sr(e.pr);i.push(t)}),ww.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new mb(Xy);return t.forEach(e=>{var t=new GE(e,0),n=new GE(e,Number.POSITIVE_INFINITY);this.wr.forEachInRange([t,n],e=>{r=r.add(e.pr)})}),ww.resolve(this.Dr(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;ow.isDocumentKey(i)||(i=i.child(""));var s=new GE(new ow(i),0);let a=new mb(Xy);return this.wr.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.pr)),!0)},s),ww.resolve(this.Dr(a))}Dr(e){const n=[];return e.forEach(e=>{var t=this.Sr(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Vy(0===this.vr(r.batchId,"removed")),this.mutationQueue.shift();let i=this.wr;return ww.forEach(r.mutations,e=>{var t=new GE(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.wr=i})}Mn(e){}containsKey(e,t){var n=new GE(t,0),n=this.wr.firstAfterOrEqual(n);return ww.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,ww.resolve()}vr(e,t){return this.br(e)}br(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Sr(e){var t=this.br(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class QE{constructor(e){this.Cr=e,this.docs=new pb(ow.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Cr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return ww.resolve(n?n.document.mutableCopy():Yb.newInvalidDocument(t))}getEntries(e,t){let n=$I;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Yb.newInvalidDocument(e))}),ww.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=$I;const s=t.path,a=new ow(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||mw(fw(a),n)<=0||(r.has(a.key)||qI(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return ww.resolve(i)}getAllFromCollectionGroup(e,t,n,r){Uy()}Fr(e,t){return ww.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new YE(this)}getSize(e){return ww.resolve(this.size)}}class YE extends xE{constructor(e){super(),this.ar=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.ar.addEntry(n,t)):this.ar.removeEntry(e)}),ww.waitFor(r)}getFromCache(e,t){return this.ar.getEntry(e,t)}getAllFromCache(e,t){return this.ar.getEntries(e,t)}}class JE{constructor(e){this.persistence=e,this.Mr=new zI(e=>wI(e),bI),this.lastRemoteSnapshotVersion=nw.min(),this.highestTargetId=0,this.Or=0,this.Nr=new WE,this.targetCount=0,this.Br=IE.Nn()}forEachTarget(e,n){return this.Mr.forEach((e,t)=>n(t)),ww.resolve()}getLastRemoteSnapshotVersion(e){return ww.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return ww.resolve(this.Or)}allocateTargetId(e){return this.highestTargetId=this.Br.next(),ww.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Or&&(this.Or=t),ww.resolve()}qn(e){this.Mr.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Br=new IE(t),this.highestTargetId=t),e.sequenceNumber>this.Or&&(this.Or=e.sequenceNumber)}addTargetData(e,t){return this.qn(t),this.targetCount+=1,ww.resolve()}updateTargetData(e,t){return this.qn(t),ww.resolve()}removeTargetData(e,t){return this.Mr.delete(t.target),this.Nr.Vr(t.targetId),--this.targetCount,ww.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Mr.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Mr.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),ww.waitFor(a).next(()=>s)}getTargetCount(e){return ww.resolve(this.targetCount)}getTargetData(e,t){var n=this.Mr.get(t)||null;return ww.resolve(n)}addMatchingKeys(e,t,n){return this.Nr.dr(t,n),ww.resolve()}removeMatchingKeys(t,e,n){this.Nr.Rr(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),ww.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Nr.Vr(t),ww.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Nr.gr(t);return ww.resolve(n)}containsKey(e,t){return ww.resolve(this.Nr.containsKey(t))}}class XE{constructor(e,t){this.Lr={},this.overlays={},this.kr=new Dw(0),this.qr=!1,this.qr=!0,this.referenceDelegate=e(this),this.Qr=new JE(this),this.indexManager=new iE,this.remoteDocumentCache=(e=e=>this.referenceDelegate.Kr(e),new QE(e)),this.serializer=new E0(t),this.$r=new $E(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.qr=!1,Promise.resolve()}get started(){return this.qr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new KE,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Lr[e.toKey()];return n||(n=new HE(t,this.referenceDelegate),this.Lr[e.toKey()]=n),n}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.$r}runTransaction(e,t,n){Oy("MemoryPersistence","Starting transaction:",e);const r=new ZE(this.kr.next());return this.referenceDelegate.Ur(),n(r).next(e=>this.referenceDelegate.Wr(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Gr(t,n){return ww.or(Object.values(this.Lr).map(e=>()=>e.containsKey(t,n)))}}class ZE extends _w{constructor(e){super(),this.currentSequenceNumber=e}}class eC{constructor(e){this.persistence=e,this.zr=new WE,this.jr=null}static Hr(e){return new eC(e)}get Jr(){if(this.jr)return this.jr;throw Uy()}addReference(e,t,n){return this.zr.addReference(n,t),this.Jr.delete(n.toString()),ww.resolve()}removeReference(e,t,n){return this.zr.removeReference(n,t),this.Jr.add(n.toString()),ww.resolve()}markPotentiallyOrphaned(e,t){return this.Jr.add(t.toString()),ww.resolve()}removeTarget(e,t){this.zr.Vr(t.targetId).forEach(e=>this.Jr.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Jr.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ur(){this.jr=new Set}Wr(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return ww.forEach(this.Jr,e=>{const t=ow.fromPath(e);return this.Yr(n,t).next(e=>{e||r.removeEntry(t,nw.min())})}).next(()=>(this.jr=null,r.apply(n)))}updateLimboDocument(e,t){return this.Yr(e,t).next(e=>{e?this.Jr.delete(t.toString()):this.Jr.add(t.toString())})}Kr(e){return 0}Yr(e,t){return ww.or([()=>ww.resolve(this.zr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Gr(e,t)])}}class tC{constructor(e){this.serializer=e}B(t,e,n,r){const i=new bw("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Vw,{unique:!0}),s.createObjectStore("documentMutations"),nC(t),t.createObjectStore("remoteDocuments"));let a=ww.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),nC(t)),a=a.next(()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:nw.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i))),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,i){return i.store("mutations").G().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Vw,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return ww.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.Xr(i))),n<6&&6<=r&&(a=a.next(()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(t),this.ei(i)))),n<7&&7<=r&&(a=a.next(()=>this.ti(i))),n<8&&8<=r&&(a=a.next(()=>this.ni(t,i))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.ri(i))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:eb});t.createIndex("collectionPathOverlayIndex",tb,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",nb,{unique:!1})}(t)})),n<13&&13<=r&&(a=a.next(()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:zw});t.createIndex("documentKeyIndex",$w),t.createIndex("collectionGroupIndex",Kw)}(t)).next(()=>this.ii(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.si(t,i))),n<15&&15<=r&&(a=a.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Yw}).createIndex("sequenceNumberIndex",Jw,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Xw}).createIndex("documentKeyIndex",Zw,{unique:!1})}(t))),a}ei(t){let n=0;return t.store("remoteDocuments").Z((e,t)=>{n+=mE(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}Xr(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.G().next(e=>ww.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.G("userMutationsIndex",e).next(e=>ww.forEach(e,e=>{Vy(e.userId===n.userId);var t=N0(this.serializer,e);return gE(r,n.userId,t).next(()=>{})}))}))}ti(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.Z((e,t)=>{const n=new iw(e),r=[0,Lw(n)];s.push(a.get(r).next(e=>e?ww.resolve():(e=>a.put({targetId:0,path:Lw(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>ww.waitFor(s))})}ni(e,t){e.createObjectStore("collectionParents",{keyPath:Qw});const n=t.store("collectionParents"),r=new sE,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Lw(r)})}};return t.store("remoteDocuments").Z({Y:!0},(e,t)=>{const n=new iw(e);return i(n.popLast())}).next(()=>t.store("documentMutations").Z({Y:!0},([,e],t)=>{const n=Uw(e);return i(n.popLast())}))}ri(e){const r=e.store("targets");return r.Z((e,t)=>{var n=R0(t),n=P0(this.serializer,n);return r.put(n)})}ii(e,a){const t=a.store("remoteDocuments"),o=[];return t.Z((e,t)=>{const n=a.store("remoteDocumentsV14"),r=((s=t).document?new ow(iw.fromString(s.document.name).popFirst(5)):s.noDocument?ow.fromSegments(s.noDocument.path):s.unknownDocument?ow.fromSegments(s.unknownDocument.path):Uy()).path.toArray(),i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};var s;o.push(n.put(i))}).next(()=>ww.waitFor(o))}si(e,s){const t=s.store("mutations"),a=ME(this.serializer),o=new XE(eC.Hr,this.serializer.ht);return t.G().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:JI();N0(this.serializer,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),ww.forEach(r,(e,t)=>{var n=new Ry(t),r=V0.Pt(this.serializer,n),i=o.getIndexManager(n),n=vE.Pt(n,this.serializer,i,o.referenceDelegate);return new zE(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new cb(s,Dw.ae),e).next()})})}}function nC(e){e.createObjectStore("targetDocuments",{keyPath:Gw}).createIndex("documentTargetsIndex",Hw,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Ww,{unique:!0}),e.createObjectStore("targetGlobal")}const rC="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class iC{constructor(e,t,n,r,i,s,a,o,c,l,u=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.oi=i,this.window=s,this.document=a,this._i=c,this.ai=l,this.ui=u,this.kr=null,this.qr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.ci=null,this.inForeground=!1,this.li=null,this.hi=null,this.Pi=Number.NEGATIVE_INFINITY,this.Ii=e=>Promise.resolve(),!iC.v())throw new jy(qy.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new PE(this,r),this.Ti=t+"main",this.serializer=new E0(o),this.Ei=new Iw(this.Ti,this.ui,new tC(this.serializer)),this.Qr=new TE(this.referenceDelegate,this.serializer),this.remoteDocumentCache=ME(this.serializer),this.$r=new L0,this.window&&this.window.localStorage?this.di=this.window.localStorage:(this.di=null,!1===l&&My("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.Ai().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new jy(qy.FAILED_PRECONDITION,rC);return this.Ri(),this.Vi(),this.mi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Qr.getHighestSequenceNumber(e))}).then(e=>{this.kr=new Dw(e,this._i)}).then(()=>{this.qr=!0}).catch(e=>(this.Ei&&this.Ei.close(),Promise.reject(e)))}fi(t){return this.Ii=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ei.k(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.oi.enqueueAndForget(async()=>{this.started&&await this.Ai()}))}Ai(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>aC(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.gi(t).next(e=>{e||(this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)))})}).next(()=>this.pi(t)).next(e=>this.isPrimary&&!e?this.yi(t).next(()=>!1):!!e&&this.wi(t).next(()=>!0))).catch(e=>{if(Cw(e))return Oy("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Oy("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.oi.enqueueRetryable(()=>this.Ii(e)),this.isPrimary=e})}gi(e){return sC(e).get("owner").next(e=>ww.resolve(this.Si(e)))}bi(e){return aC(e).delete(this.clientId)}async Di(){if(this.isPrimary&&!this.vi(this.Pi,18e5)){this.Pi=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=lb(e,"clientMetadata");return r.G().next(e=>{const t=this.Ci(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return ww.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.di)for(const t of e)this.di.removeItem(this.Fi(t.clientId))}}mi(){this.hi=this.oi.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ai().then(()=>this.Di()).then(()=>this.mi()))}Si(e){return!!e&&e.ownerId===this.clientId}pi(t){return this.ai?ww.resolve(!0):sC(t).get("owner").next(e=>{if(null!==e&&this.vi(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)){if(this.Si(e)&&this.networkEnabled)return!0;if(!this.Si(e)){if(!e.allowTabSynchronization)throw new jy(qy.FAILED_PRECONDITION,rC);return!1}}return!(!this.networkEnabled||!this.inForeground)||aC(t).G().next(e=>void 0===this.Ci(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&Oy("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.qr=!1,this.xi(),this.hi&&(this.hi.cancel(),this.hi=null),this.Oi(),this.Ni(),await this.Ei.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new cb(e,Dw.ae);return this.yi(t).next(()=>this.bi(t))}),this.Ei.close(),this.Bi()}Ci(e,t){return e.filter(e=>this.vi(e.updateTimeMs,t)&&!this.Mi(e.clientId))}Li(){return this.runTransaction("getActiveClients","readonly",e=>aC(e).G().next(e=>this.Ci(e,18e5).map(e=>e.clientId)))}get started(){return this.qr}getMutationQueue(e,t){return vE.Pt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Qr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new oE(e,this.serializer.ht.databaseId)}getDocumentOverlayCache(e){return V0.Pt(this.serializer,e)}getBundleCache(){return this.$r}runTransaction(t,n,r){Oy("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",s=15===(e=this.ui)?ob:14===e?ab:13===e?sb:12===e?ib:11===e?rb:void Uy();let a;return this.Ei.runTransaction(t,i,s,e=>(a=new cb(e,this.kr?this.kr.next():Dw.ae),"readwrite-primary"===n?this.gi(a).next(e=>!!e||this.pi(a)).next(e=>{if(!e)throw My(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.oi.enqueueRetryable(()=>this.Ii(!1)),new jy(qy.FAILED_PRECONDITION,vw);return r(a)}).next(e=>this.wi(a).next(()=>e)):this.ki(a).next(()=>r(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}ki(e){return sC(e).get("owner").next(e=>{if(null!==e&&this.vi(e.leaseTimestampMs,5e3)&&!this.Mi(e.ownerId)&&!this.Si(e)&&!(this.ai||this.allowTabSynchronization&&e.allowTabSynchronization))throw new jy(qy.FAILED_PRECONDITION,rC)})}wi(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return sC(e).put("owner",t)}static v(){return Iw.v()}yi(e){const t=sC(e);return t.get("owner").next(e=>this.Si(e)?(Oy("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):ww.resolve())}vi(e,t){var n=Date.now();return!(e<n-t||n<e&&(My(`Detected an update time that is in the future: ${e} > ${n}`),1))}Ri(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.li=()=>{this.oi.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ai()))},this.document.addEventListener("visibilitychange",this.li),this.inForeground="visible"===this.document.visibilityState)}Oi(){this.li&&(this.document.removeEventListener("visibilitychange",this.li),this.li=null)}Vi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.ci=()=>{this.xi();var e=/(?:Version|Mobile)\/1[456]/;T()||!navigator.userAgent.includes("Safari")||navigator.userAgent.includes("Chrome")||!navigator.appVersion.match(e)&&!navigator.userAgent.match(e)||this.oi.enterRestrictedMode(!0),this.oi.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.ci))}Ni(){this.ci&&(this.window.removeEventListener("pagehide",this.ci),this.ci=null)}Mi(e){var t;try{var n=null!==(null===(t=this.di)||void 0===t?void 0:t.getItem(this.Fi(e)));return Oy("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return My("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}xi(){if(this.di)try{this.di.setItem(this.Fi(this.clientId),String(Date.now()))}catch(e){My("Failed to set zombie client id.",e)}}Bi(){if(this.di)try{this.di.removeItem(this.Fi(this.clientId))}catch(e){}}Fi(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function sC(e){return lb(e,"owner")}function aC(e){return lb(e,"clientMetadata")}function oC(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class cC{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.qi=n,this.Qi=r}static Ki(e,t){let n=JI(),r=JI();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new cC(e,t.fromCache,n,r)}}class lC{constructor(){this.$i=!1}initialize(e,t){this.Ui=e,this.indexManager=t,this.$i=!0}getDocumentsMatchingQuery(t,n,r,i){return this.Wi(t,n).next(e=>e||this.Gi(t,n,i,r)).next(e=>e||this.zi(t,n))}Wi(i,s){if(NI(s))return ww.resolve(null);let t=OI(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=LI(s,null,"F"),t=OI(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=JI(...e);return this.Ui.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.ji(s,n);return this.Hi(s,t,r,e.readTime)?this.Wi(i,LI(s,null,"F")):this.Ji(i,t,s,e)}))})))}Gi(n,r,i,s){return NI(r)||s.isEqual(nw.min())?this.zi(n,r):this.Ui.getDocuments(n,i).next(e=>{var t=this.ji(r,e);return this.Hi(r,t,i,s)?this.zi(n,r):(xy()<=m.DEBUG&&Oy("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),VI(r)),this.Ji(n,t,r,pw(s,-1)))})}ji(n,e){let r=new mb(BI(n));return e.forEach((e,t)=>{qI(n,t)&&(r=r.add(t))}),r}Hi(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}zi(e,t){return xy()<=m.DEBUG&&Oy("QueryEngine","Using full collection scan to execute query:",VI(t)),this.Ui.getDocumentsMatchingQuery(e,t,gw.min())}Ji(e,n,t,r){return this.Ui.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class uC{constructor(e,t,n,r){this.persistence=e,this.Yi=t,this.serializer=r,this.Zi=new pb(Xy),this.Xi=new zI(e=>wI(e),bI),this.es=new Map,this.ts=e.getRemoteDocumentCache(),this.Qr=e.getTargetCache(),this.$r=e.getBundleCache(),this.ns(n)}ns(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new zE(this.ts,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.ts.setIndexManager(this.indexManager),this.Yi.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.Zi))}}function hC(e,t,n,r){return new uC(e,t,n,r)}async function dC(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",i=>{let s;return a.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,a.ns(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=JI();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(i,r).next(e=>({rs:e,removedBatchIds:t,addedBatchIds:n}))})})}function pC(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Qr.getLastRemoteSnapshotVersion(e))}function fC(e,l){const u=e,h=l.snapshotVersion;let d=u.Zi;return u.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=u.ts.newChangeBuffer({trackRemovals:!0});d=u.Zi;const c=[];l.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){c.push(u.Qr.removeMatchingKeys(o,t.removedDocuments,n).next(()=>u.Qr.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;null!==l.targetMismatches.get(n)?e=e.withResumeToken(bb.EMPTY_BYTE_STRING,nw.min()).withLastLimboFreeSnapshotVersion(nw.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,h)),d=d.insert(n,e),i=r,s=e,a=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||c.push(u.Qr.updateTargetData(o,e))}});let t=$I,n=JI();if(l.documentUpdates.forEach(e=>{l.resolvedLimboDocuments.has(e)&&c.push(u.persistence.referenceDelegate.updateLimboDocument(o,e))}),c.push(gC(o,e,l.documentUpdates).next(e=>{t=e.ss,n=e.os})),!h.isEqual(nw.min())){const l=u.Qr.getLastRemoteSnapshotVersion(o).next(e=>u.Qr.setTargetsMetadata(o,o.currentSequenceNumber,h));c.push(l)}return ww.waitFor(c).next(()=>e.apply(o)).next(()=>u.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(u.Zi=d,e))}function gC(e,s,t){let n=JI(),a=JI();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=$I;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(nw.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):Oy("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{ss:i,os:a}})}function mC(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Qr.getTargetData(t,r).next(e=>e?(n=e,ww.resolve(n)):i.Qr.allocateTargetId(t).next(e=>(n=new T0(r,e,"TargetPurposeListen",t.currentSequenceNumber),i.Qr.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.Zi.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.Zi=i.Zi.insert(e.targetId,e),i.Xi.set(r,e.targetId)),e})}async function vC(e,t,n){const r=e,i=r.Zi.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!Cw(e))throw e;Oy("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.Zi=r.Zi.remove(t),r.Xi.delete(i.target)}function _C(e,n,r){const i=e;let s=nw.min(),a=JI();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.Xi.get(n);return void 0!==i?ww.resolve(r.Zi.get(i)):r.Qr.getTargetData(t,n)}(i,t,OI(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Qr.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.Yi.getDocumentsMatchingQuery(t,n,r?s:nw.min(),r?a:JI())).next(e=>(bC(i,jI(n),e),{documents:e,_s:a})))}function yC(e,t){const n=e,r=n.Qr,i=n.Zi.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.lt(e,t).next(e=>e?e.target:null))}function wC(e,t){const n=e,r=n.es.get(t)||nw.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.ts.getAllFromCollectionGroup(e,t,pw(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(bC(n,t,e),e))}function bC(e,t,n){let r=e.es.get(t)||nw.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.es.set(t,r)}function IC(e,t){return`firestore_clients_${e}_${t}`}function TC(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function EC(e,t){return`firestore_targets_${e}_${t}`}class CC{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static hs(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new jy(r.error.code,r.error.message))),s?new CC(e,t,r.state,i):(My("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Ps(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class SC{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static hs(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new jy(n.error.code,n.error.message))),i?new SC(e,n.state,r):(My("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Ps(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class kC{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static hs(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=XI;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=Mw(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new kC(e,i):(My("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class AC{constructor(e,t){this.clientId=e,this.onlineState=t}static hs(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new AC(t.clientId,t.onlineState):(My("SharedClientState",`Failed to parse online state: ${e}`),null)}}class NC{constructor(){this.activeTargetIds=XI}Is(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ts(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ps(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class RC{constructor(e,t,n,r,i){this.window=e,this.oi=t,this.persistenceKey=n,this.Es=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ds=this.As.bind(this),this.Rs=new pb(Xy),this.started=!1,this.Vs=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.fs=IC(this.persistenceKey,this.Es),this.gs=`firestore_sequence_number_${this.persistenceKey}`,this.Rs=this.Rs.insert(this.Es,new NC),this.ps=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.ys=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.ws=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.Ss=`firestore_online_state_${this.persistenceKey}`,this.bs=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.ds)}static v(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Li();for(const n of e)if(n!==this.Es){const e=this.getItem(IC(this.persistenceKey,n));var t;!e||(t=kC.hs(n,e))&&(this.Rs=this.Rs.insert(t.clientId,t))}this.Ds();const n=this.storage.getItem(this.Ss);if(n){const e=this.vs(n);e&&this.Cs(e)}for(const e of this.Vs)this.As(e);this.Vs=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.gs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Fs(this.Rs)}isActiveQueryTarget(n){let r=!1;return this.Rs.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Ms(e,"pending")}updateMutationState(e,t,n){this.Ms(e,t,n),this.xs(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(EC(this.persistenceKey,e)))||(n=SC.hs(e,n))&&(t=n.state)),this.Os.Is(e),this.Ds(),t}removeLocalQueryTarget(e){this.Os.Ts(e),this.Ds()}isLocalQueryTarget(e){return this.Os.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(EC(this.persistenceKey,e))}updateQueryState(e,t,n){this.Ns(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.xs(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Bs(e)}notifyBundleLoaded(e){this.Ls(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ds),this.removeItem(this.fs),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return Oy("SharedClientState","READ",e,t),t}setItem(e,t){Oy("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Oy("SharedClientState","REMOVE",e),this.storage.removeItem(e)}As(e){const i=e;i.storageArea===this.storage&&(Oy("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.fs?this.oi.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.ps.test(i.key)){if(null==i.newValue){var e=this.ks(i.key);return this.qs(e,null)}e=this.Qs(i.key,i.newValue);if(e)return this.qs(e.clientId,e)}else if(this.ys.test(i.key)){if(null!==i.newValue){var t=this.Ks(i.key,i.newValue);if(t)return this.$s(t)}}else if(this.ws.test(i.key)){if(null!==i.newValue){t=this.Us(i.key,i.newValue);if(t)return this.Ws(t)}}else if(i.key===this.Ss){if(null!==i.newValue){var n=this.vs(i.newValue);if(n)return this.Cs(n)}}else if(i.key===this.gs){n=function(e){let t=Dw.ae;if(null!=e)try{var n=JSON.parse(e);Vy("number"==typeof n),t=n}catch(e){My("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==Dw.ae&&this.sequenceNumberHandler(n)}else if(i.key===this.bs){const r=this.Gs(i.newValue);await Promise.all(r.map(e=>this.syncEngine.zs(e)))}}else this.Vs.push(i)}):My("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Os(){return this.Rs.get(this.Es)}Ds(){this.setItem(this.fs,this.Os.Ps())}Ms(e,t,n){const r=new CC(this.currentUser,e,t,n),i=TC(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Ps())}xs(e){var t=TC(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Bs(e){var t={clientId:this.Es,onlineState:e};this.storage.setItem(this.Ss,JSON.stringify(t))}Ns(e,t,n){const r=EC(this.persistenceKey,e),i=new SC(e,t,n);this.setItem(r,i.Ps())}Ls(e){var t=JSON.stringify(Array.from(e));this.setItem(this.bs,t)}ks(e){var t=this.ps.exec(e);return t?t[1]:null}Qs(e,t){var n=this.ks(e);return kC.hs(n,t)}Ks(e,t){var n=this.ys.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return CC.hs(new Ry(n),r,t)}Us(e,t){var n=this.ws.exec(e),n=Number(n[1]);return SC.hs(n,t)}vs(e){return AC.hs(e)}Gs(e){return JSON.parse(e)}async $s(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.js(e.batchId,e.state,e.error);Oy("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Ws(e){return this.syncEngine.Hs(e.targetId,e.state,e.error)}qs(e,t){const n=t?this.Rs.insert(e,t):this.Rs.remove(e),r=this.Fs(this.Rs),i=this.Fs(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.Js(s,a).then(()=>{this.Rs=n})}Cs(e){this.Rs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Fs(e){let n=XI;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class PC{constructor(){this.Ys=new NC,this.Zs={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Ys.Is(e),this.Zs[e]||"not-current"}updateQueryState(e,t,n){this.Zs[e]=t}removeLocalQueryTarget(e){this.Ys.Ts(e)}isLocalQueryTarget(e){return this.Ys.activeTargetIds.has(e)}clearQueryState(e){delete this.Zs[e]}getAllActiveQueryTargets(){return this.Ys.activeTargetIds}isActiveQueryTarget(e){return this.Ys.activeTargetIds.has(e)}start(){return this.Ys=new NC,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class DC{Xs(e){}shutdown(){}}class xC{constructor(){this.eo=()=>this.no(),this.ro=()=>this.io(),this.so=[],this.oo()}Xs(e){this.so.push(e)}shutdown(){window.removeEventListener("online",this.eo),window.removeEventListener("offline",this.ro)}oo(){window.addEventListener("online",this.eo),window.addEventListener("offline",this.ro)}no(){Oy("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.so)e(0)}io(){Oy("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.so)e(1)}static v(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let OC=null;function MC(){return null===OC?OC=268435456+Math.round(2147483648*Math.random()):OC++,"0x"+OC.toString(16)}const LC={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class FC{constructor(e){this._o=e._o,this.ao=e.ao}uo(e){this.co=e}lo(e){this.ho=e}onMessage(e){this.Po=e}close(){this.ao()}send(e){this._o(e)}Io(){this.co()}To(e){this.ho(e)}Eo(e){this.Po(e)}}const UC="WebChannelConnection";class VC extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.Ao=t+"://"+e.host,this.Ro=`projects/${n}/databases/${r}`,this.Vo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}get mo(){return!1}fo(t,e,n,r,i){const s=MC(),a=this.po(t,e);Oy("RestConnection",`Sending RPC '${t}' ${s}:`,a,n);var o={"google-cloud-resource-prefix":this.Ro,"x-goog-request-params":this.Vo};return this.yo(o,r,i),this.wo(t,a,o,n).then(e=>(Oy("RestConnection",`Received RPC '${t}' ${s}: `,e),e),e=>{throw Ly("RestConnection",`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",n),e})}So(e,t,n,r,i,s){return this.fo(e,t,n,r,i)}yo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+Py,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}po(e,t){var n=LC[e];return`${this.Ao}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}wo(c,t,n,r){const l=MC();return new Promise((s,a)=>{const o=new Sy;o.setWithCredentials(!0),o.listenOnce(by.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case wy.NO_ERROR:var e=o.getResponseJson();Oy(UC,`XHR for RPC '${c}' ${l} received:`,JSON.stringify(e)),s(e);break;case wy.TIMEOUT:Oy(UC,`RPC '${c}' ${l} timed out`),a(new jy(qy.DEADLINE_EXCEEDED,"Request time out"));break;case wy.HTTP_ERROR:var t=o.getStatus();if(Oy(UC,`RPC '${c}' ${l} failed with status:`,t,"response text:",o.getResponseText()),0<t){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);var n=null==e?void 0:e.error;if(n&&n.status&&n.message){const c=(r=n.status,i=r.toLowerCase().replace(/_/g,"-"),0<=Object.values(qy).indexOf(i)?i:qy.UNKNOWN);a(new jy(c,n.message))}else a(new jy(qy.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new jy(qy.UNAVAILABLE,"Connection failed."));break;default:Uy()}}finally{Oy(UC,`RPC '${c}' ${l} completed.`)}var r,i});var e=JSON.stringify(r);Oy(UC,`RPC '${c}' ${l} sending request:`,r),o.send(t,"POST",e,n,15)})}bo(i,e,t){const s=MC(),n=[this.Ao,"/","google.firestore.v1.Firestore","/",i,"/channel"],r=new H_,a=yy(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},c=this.longPollingOptions.timeoutSeconds;void 0!==c&&(o.longPollingTimeout=Math.round(1e3*c)),this.useFetchStreams&&(o.useFetchStreams=!0),this.yo(o.initMessageHeaders,e,t),o.encodeInitMessageHeaders=!0;var l=n.join("");Oy(UC,`Creating RPC '${i}' stream ${s}: ${l}`,o);const u=r.createWebChannel(l,o);let h=!1,d=!1;const p=new FC({_o:e=>{d?Oy(UC,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(h||(Oy(UC,`Opening RPC '${i}' stream ${s} transport.`),u.open(),h=!0),Oy(UC,`RPC '${i}' stream ${s} sending:`,e),u.send(e))},ao:()=>u.close()}),f=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return f(u,Cy.EventType.OPEN,()=>{d||Oy(UC,`RPC '${i}' stream ${s} transport opened.`)}),f(u,Cy.EventType.CLOSE,()=>{d||(d=!0,Oy(UC,`RPC '${i}' stream ${s} transport closed`),p.To())}),f(u,Cy.EventType.ERROR,e=>{d||(d=!0,Ly(UC,`RPC '${i}' stream ${s} transport errored:`,e),p.To(new jy(qy.UNAVAILABLE,"The operation could not be completed")))}),f(u,Cy.EventType.MESSAGE,n=>{if(!d){var e=n.data[0];Vy(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){Oy(UC,`RPC '${i}' stream ${s} received error:`,r);const n=r.status;let e=function(e){var t=_y[e];if(void 0!==t)return xT(t)}(n),t=r.message;void 0===e&&(e=qy.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),d=!0,p.To(new jy(e,t)),u.close()}else Oy(UC,`RPC '${i}' stream ${s} received:`,e),p.Eo(e)}}),f(a,Iy.STAT_EVENT,e=>{e.stat===Ty?Oy(UC,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===Ey&&Oy(UC,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{p.Io()},0),p}}function qC(){return"undefined"!=typeof window?window:null}function jC(){return"undefined"!=typeof document?document:null}function BC(e){return new XT(e,!0)}class zC{constructor(e,t,n=1e3,r=1.5,i=6e4){this.oi=e,this.timerId=t,this.Do=n,this.vo=r,this.Co=i,this.Fo=0,this.Mo=null,this.xo=Date.now(),this.reset()}reset(){this.Fo=0}Oo(){this.Fo=this.Co}No(e){this.cancel();var t=Math.floor(this.Fo+this.Bo()),n=Math.max(0,Date.now()-this.xo),r=Math.max(0,t-n);0<r&&Oy("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Fo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Mo=this.oi.enqueueAfterDelay(this.timerId,r,()=>(this.xo=Date.now(),e())),this.Fo*=this.vo,this.Fo<this.Do&&(this.Fo=this.Do),this.Fo>this.Co&&(this.Fo=this.Co)}Lo(){null!==this.Mo&&(this.Mo.skipDelay(),this.Mo=null)}cancel(){null!==this.Mo&&(this.Mo.cancel(),this.Mo=null)}Bo(){return(Math.random()-.5)*this.Fo}}class $C{constructor(e,t,n,r,i,s,a,o){this.oi=e,this.ko=n,this.qo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Qo=0,this.Ko=null,this.$o=null,this.stream=null,this.Uo=new zC(e,t)}Wo(){return 1===this.state||5===this.state||this.Go()}Go(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.zo()}async stop(){this.Wo()&&await this.close(0)}jo(){this.state=0,this.Uo.reset()}Ho(){this.Go()&&null===this.Ko&&(this.Ko=this.oi.enqueueAfterDelay(this.ko,6e4,()=>this.Jo()))}Yo(e){this.Zo(),this.stream.send(e)}async Jo(){if(this.Go())return this.close(0)}Zo(){this.Ko&&(this.Ko.cancel(),this.Ko=null)}Xo(){this.$o&&(this.$o.cancel(),this.$o=null)}async close(e,t){this.Zo(),this.Xo(),this.Uo.cancel(),this.Qo++,4!==e?this.Uo.reset():t&&t.code===qy.RESOURCE_EXHAUSTED?(My(t.toString()),My("Using maximum backoff delay to prevent overloading the backend."),this.Uo.Oo()):t&&t.code===qy.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.e_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.lo(t)}e_(){}auth(){this.state=1;const e=this.t_(this.Qo),n=this.Qo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Qo===n&&this.n_(e,t)},t=>{e(()=>{var e=new jy(qy.UNKNOWN,"Fetching auth token failed: "+t.message);return this.r_(e)})})}n_(e,t){const n=this.t_(this.Qo);this.stream=this.i_(e,t),this.stream.uo(()=>{n(()=>(this.state=2,this.$o=this.oi.enqueueAfterDelay(this.qo,1e4,()=>(this.Go()&&(this.state=3),Promise.resolve())),this.listener.uo()))}),this.stream.lo(e=>{n(()=>this.r_(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}zo(){this.state=5,this.Uo.No(async()=>{this.state=0,this.start()})}r_(e){return Oy("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}t_(t){return e=>{this.oi.enqueueAndForget(()=>this.Qo===t?e():(Oy("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class KC extends $C{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}i_(e,t){return this.connection.bo("Listen",e,t)}onMessage(e){this.Uo.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(p=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===p?1:"REMOVE"===p?2:"CURRENT"===p?3:"RESET"===p?4:Uy(),i=t.targetChange.targetIds||[],s=(p=t.targetChange.resumeToken,e.useProto3Json?(Vy(void 0===p||"string"==typeof p),bb.fromBase64String(p||"")):(Vy(void 0===p||p instanceof Uint8Array),bb.fromUint8Array(p||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(p=a).code?qy.UNKNOWN:xT(p.code),new jy(o,p.message||""));n=new $T(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;var c=t.documentChange;c.document,c.document.name,c.document.updateTime;var s=a0(e,c.document.name),o=n0(c.document.updateTime),l=c.document.createTime?n0(c.document.createTime):nw.min(),u=new Qb({mapValue:{fields:c.document.fields}}),l=Yb.newFoundDocument(s,o,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new BT(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=a0(e,u.document),l=u.readTime?n0(u.readTime):nw.min(),l=Yb.newNoDocument(c,l),u=u.removedTargetIds||[];n=new BT([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=a0(e,h.document),h=h.removedTargetIds||[];n=new BT([],h,d,null)}else{if(!("filter"in t))return Uy();{t.filter;const e=t.filter;e.targetId;var{count:h=0,unchangedNames:d}=e,h=new PT(h,d),d=e.targetId;n=new zT(d,h)}}var o,p;return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return nw.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?n0(t.readTime):nw.min()}(e);return this.listener.s_(t,n)}o_(e){const t={};t.database=l0(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=II(r)?{documents:g0(e,r)}:{query:m0(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()){n.resumeToken=t0(e,t.resumeToken);const r=ZT(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(0<t.snapshotVersion.compareTo(nw.min())){n.readTime=e0(e,t.snapshotVersion.toTimestamp());const r=ZT(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);var n,n=(this.serializer,e,null==(n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return Uy()}}(e.purpose))?null:{"goog-listen-tags":n});n&&(t.labels=n),this.Yo(t)}__(e){const t={};t.database=l0(this.serializer),t.removeTarget=e,this.Yo(t)}}class WC extends $C{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.a_=!1}get u_(){return this.a_}start(){this.a_=!1,this.lastStreamToken=void 0,super.start()}e_(){this.a_&&this.c_([])}i_(e,t){return this.connection.bo("Write",e,t)}onMessage(e){if(Vy(!!e.streamToken),this.lastStreamToken=e.streamToken,this.a_){this.Uo.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(Vy(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?n0(e.updateTime):n0(t);return n.isEqual(nw.min())&&(n=n0(t)),new pT(n,e.transformResults||[])}(e,i))):[]),n=n0(e.commitTime);return this.listener.l_(n,t)}var r,i;return Vy(!e.writeResults||0===e.writeResults.length),this.a_=!0,this.listener.h_()}P_(){const e={};e.database=l0(this.serializer),this.Yo(e)}c_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>p0(this.serializer,e))};this.Yo(t)}}class GC extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.I_=!1}T_(){if(this.I_)throw new jy(qy.FAILED_PRECONDITION,"The client has already been terminated.")}fo(n,r,i){return this.T_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.fo(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===qy.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new jy(qy.UNKNOWN,e.toString())})}So(n,r,i,s){return this.T_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.So(n,r,i,e,t,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===qy.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new jy(qy.UNKNOWN,e.toString())})}terminate(){this.I_=!0}}class HC{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.d_=0,this.A_=null,this.R_=!0}V_(){0===this.d_&&(this.m_("Unknown"),this.A_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.A_=null,this.f_("Backend didn't respond within 10 seconds."),this.m_("Offline"),Promise.resolve())))}g_(e){"Online"===this.state?this.m_("Unknown"):(this.d_++,1<=this.d_&&(this.p_(),this.f_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.m_("Offline")))}set(e){this.p_(),this.d_=0,"Online"===e&&(this.R_=!1),this.m_(e)}m_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}f_(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.R_?(My(t),this.R_=!1):Oy("OnlineStateTracker",t)}p_(){null!==this.A_&&(this.A_.cancel(),this.A_=null)}}class QC{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.y_=[],this.w_=new Map,this.S_=new Set,this.b_=[],this.D_=i,this.D_.Xs(e=>{n.enqueueAndForget(async()=>{iS(this)&&(Oy("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.S_.add(4),await JC(t),t.v_.set("Unknown"),t.S_.delete(4),await YC(t)}(this))})}),this.v_=new HC(n,r)}}async function YC(e){if(iS(e))for(const t of e.b_)await t(!0)}async function JC(e){for(const t of e.b_)await t(!1)}function XC(e,t){const n=e;n.w_.has(t.targetId)||(n.w_.set(t.targetId,t),rS(n)?nS(n):fS(n).Go()&&eS(n,t))}function ZC(e,t){const n=e,r=fS(n);n.w_.delete(t),r.Go()&&tS(n,t),0===n.w_.size&&(r.Go()?r.Ho():iS(n)&&n.v_.set("Unknown"))}function eS(e,t){var n;e.C_.Le(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(nw.min()))&&(n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(n)),fS(e).o_(t)}function tS(e,t){e.C_.Le(t),fS(e).__(t)}function nS(t){t.C_=new WT({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),lt:e=>t.w_.get(e)||null,st:()=>t.datastore.serializer.databaseId}),fS(t).start(),t.v_.V_()}function rS(e){return iS(e)&&!fS(e).Wo()&&0<e.w_.size}function iS(e){return 0===e.S_.size}function sS(e){e.C_=void 0}async function aS(e,t,n){if(!Cw(t))throw t;e.S_.add(1),await JC(e),e.v_.set("Offline"),n=n||(()=>pC(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Oy("RemoteStore","Retrying IndexedDB access"),await n(),e.S_.delete(1),await YC(e)})}function oS(t,n){return n().catch(e=>aS(t,e,n))}async function cS(e){const t=e,n=gS(t);let r=0<t.y_.length?t.y_[t.y_.length-1].batchId:-1;for(;iS(i=t)&&i.y_.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.y_.length&&n.Ho();break}r=e.batchId,function(e,t){e.y_.push(t);const n=gS(e);n.Go()&&n.u_&&n.c_(t.mutations)}(t,e)}catch(e){await aS(t,e)}var i;lS(t)&&uS(t)}function lS(e){return iS(e)&&!gS(e).Wo()&&0<e.y_.length}function uS(e){gS(e).start()}async function hS(e,t){t&&gS(e).u_&&await async function(e,t){if(DT(n=t.code)&&n!==qy.ABORTED){const r=e.y_.shift();gS(e).jo(),await oS(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await cS(e)}var n}(e,t),lS(e)&&uS(e)}async function dS(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Oy("RemoteStore","RemoteStore received new credentials");var r=iS(n);n.S_.add(3),await JC(n),r&&n.v_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.S_.delete(3),await YC(n)}async function pS(e,t){const n=e;t?(n.S_.delete(2),await YC(n)):(n.S_.add(2),await JC(n),n.v_.set("Unknown"))}function fS(t){return t.F_||(t.F_=function(e,t,n){const r=e;return r.T_(),new KC(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{uo:(async function(n){n.w_.forEach((e,t)=>{eS(n,e)})}).bind(null,t),lo:(async function(e,t){sS(e),rS(e)?(e.v_.g_(t),nS(e)):e.v_.set("Unknown")}).bind(null,t),s_:(async function(e,t,n){if(e.v_.set("Online"),t instanceof $T&&2===t.state&&t.cause)try{await async function(e,t){var n=t.cause;for(const r of t.targetIds)e.w_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.w_.delete(r),e.C_.removeTarget(r))}(e,t)}catch(n){Oy("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await aS(e,n)}else if(t instanceof BT?e.C_.Ge(t):t instanceof zT?e.C_.Xe(t):e.C_.He(t),!n.isEqual(nw.min()))try{const t=await pC(e.localStore);0<=n.compareTo(t)&&await function(i,r){const e=i.C_._t(r);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=i.w_.get(t);n&&i.w_.set(t,n.withResumeToken(e.resumeToken,r))}}),e.targetMismatches.forEach((e,t)=>{const n=i.w_.get(e);var r;n&&(i.w_.set(e,n.withResumeToken(bb.EMPTY_BYTE_STRING,n.snapshotVersion)),tS(i,e),r=new T0(n.target,e,t,n.sequenceNumber),eS(i,r))}),i.remoteSyncer.applyRemoteEvent(e)}(e,n)}catch(t){Oy("RemoteStore","Failed to raise snapshot:",t),await aS(e,t)}}).bind(null,t)}),t.b_.push(async e=>{e?(t.F_.jo(),rS(t)?nS(t):t.v_.set("Unknown")):(await t.F_.stop(),sS(t))})),t.F_}function gS(t){return t.M_||(t.M_=function(e,t,n){const r=e;return r.T_(),new WC(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{uo:(async function(e){gS(e).P_()}).bind(null,t),lo:hS.bind(null,t),h_:(async function(e){const t=gS(e);for(const n of e.y_)t.c_(n.mutations)}).bind(null,t),l_:(async function(e,t,n){const r=e.y_.shift(),i=NT.from(r,t,n);await oS(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await cS(e)}).bind(null,t)}),t.b_.push(async e=>{e?(t.M_.jo(),await cS(t)):(await t.M_.stop(),0<t.y_.length&&(Oy("RemoteStore",`Stopping write stream with ${t.y_.length} pending writes`),t.y_=[]))})),t.M_}class mS{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new By,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new mS(e,t,s,r,i);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new jy(qy.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function vS(e,t){if(My("AsyncQueue",`${t}: ${e}`),Cw(e))return new jy(qy.UNAVAILABLE,`${t}: ${e}`);throw e}class _S{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ow.comparator(e.key,t.key):(e,t)=>ow.comparator(e.key,t.key),this.keyedMap=WI(),this.sortedSet=new pb(this.comparator)}static emptySet(e){return new _S(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof _S))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new _S;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class yS{constructor(){this.x_=new pb(ow.comparator)}track(e){var t=e.doc.key,n=this.x_.get(t);!n||0!==e.type&&3===n.type?this.x_=this.x_.insert(t,e):3===e.type&&1!==n.type?this.x_=this.x_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.x_=this.x_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.x_=this.x_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.x_=this.x_.remove(t):1===e.type&&2===n.type?this.x_=this.x_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.x_=this.x_.insert(t,{type:2,doc:e.doc}):Uy()}O_(){const n=[];return this.x_.inorderTraversal((e,t)=>{n.push(t)}),n}}class wS{constructor(e,t,n,r,i,s,a,o,c){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=c}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new wS(e,t,_S.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&FI(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class bS{constructor(){this.N_=void 0,this.listeners=[]}}class IS{constructor(){this.queries=new zI(e=>UI(e),FI),this.onlineState="Unknown",this.B_=new Set}}async function TS(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new bS),i)try{s.N_=await n.onListen(r)}catch(e){const n=vS(e,`Initialization of query '${VI(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.L_(n.onlineState),!s.N_||t.k_(s.N_)&&CS(n)}async function ES(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function CS(e){e.B_.forEach(e=>{e.next()})}class SS{constructor(e,t,n){this.query=e,this.q_=t,this.Q_=!1,this.K_=null,this.onlineState="Unknown",this.options=n||{}}k_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new wS(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Q_?this.U_(e)&&(this.q_.next(e),t=!0):this.W_(e,this.onlineState)&&(this.G_(e),t=!0),this.K_=e,t}onError(e){this.q_.error(e)}L_(e){this.onlineState=e;let t=!1;return this.K_&&!this.Q_&&this.W_(this.K_,e)&&(this.G_(this.K_),t=!0),t}W_(e,t){return!e.fromCache||(!this.options.z_||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}U_(e){if(0<e.docChanges.length)return!0;var t=this.K_&&this.K_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}G_(e){e=wS.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Q_=!0,this.q_.next(e)}}class kS{constructor(e,t){this.j_=e,this.byteLength=t}H_(){return"metadata"in this.j_}}class AS{constructor(e){this.serializer=e}us(e){return a0(this.serializer,e)}cs(e){return e.metadata.exists?d0(this.serializer,e.document,!1):Yb.newNoDocument(this.us(e.metadata.name),this.ls(e.metadata.readTime))}ls(e){return n0(e)}}class NS{constructor(e,t,n){this.J_=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=RS(e)}Y_(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.j_.namedQuery)this.queries.push(e.j_.namedQuery);else if(e.j_.documentMetadata){this.documents.push({metadata:e.j_.documentMetadata}),e.j_.documentMetadata.exists||++t;const n=iw.fromString(e.j_.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.j_.document&&(this.documents[this.documents.length-1].document=e.j_.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Z_(e){const t=new Map,n=new AS(this.serializer);for(const i of e)if(i.metadata.queries){const e=n.us(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||JI()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=JI(),a=$I;for(const e of n){const n=t.us(e.metadata.name);e.document&&(s=s.add(n));const l=t.cs(e);l.setReadTime(t.ls(e.metadata.readTime)),a=a.insert(n,l)}const o=i.ts.newChangeBuffer({trackRemovals:!0}),c=await mC(i,(r=r,OI(AI(iw.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>gC(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Qr.removeMatchingKeysForTargetId(t,c.targetId).next(()=>i.Qr.addMatchingKeys(t,s,c.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.ss,e.os)).next(()=>e.ss)))}(this.localStore,new AS(this.serializer),this.documents,this.J_.id),t=this.Z_(this.documents);for(const e of this.queries)await async function(e,n,r=JI()){const i=await mC(e,OI(D0(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=n0(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.$r.saveNamedQuery(e,n);t=i.withResumeToken(bb.EMPTY_BYTE_STRING,t);return s.Zi=s.Zi.insert(t.targetId,t),s.Qr.updateTargetData(e,t).next(()=>s.Qr.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Qr.addMatchingKeys(e,r,i.targetId)).next(()=>s.$r.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,X_:this.collectionGroups,ea:e}}}function RS(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class PS{constructor(e){this.key=e}}class DS{constructor(e){this.key=e}}class xS{constructor(e,t){this.query=e,this.ta=t,this.na=null,this.hasCachedResults=!1,this.current=!1,this.ra=JI(),this.mutatedKeys=JI(),this.ia=BI(e),this.sa=new _S(this.ia)}get oa(){return this.ta}_a(e,t){const o=t?t.aa:new yS,c=(t||this).sa;let l=(t||this).mutatedKeys,u=c,h=!1;const d="F"===this.query.limitType&&c.size===this.query.limit?c.last():null,p="L"===this.query.limitType&&c.size===this.query.limit?c.first():null;if(e.inorderTraversal((e,t)=>{const n=c.get(e),r=qI(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(o.track({type:3,doc:r}),a=!0):this.ua(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.ia(r,d)||p&&this.ia(r,p)<0)&&(h=!0)):!n&&r?(o.track({type:0,doc:r}),a=!0):n&&!r&&(o.track({type:1,doc:n}),a=!0,(d||p)&&(h=!0)),a&&(l=r?(u=u.add(r),s?l.add(e):l.delete(e)):(u=u.delete(e),l.delete(e)))}),null!==this.query.limit)for(;u.size>this.query.limit;){const e="F"===this.query.limitType?u.last():u.first();u=u.delete(e.key),l=l.delete(e.key),o.track({type:1,doc:e})}return{sa:u,aa:o,Hi:h,mutatedKeys:l}}ua(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.sa;this.sa=e.sa,this.mutatedKeys=e.mutatedKeys;const i=e.aa.O_();i.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Uy()}};return n(e)-n(t)}(e.type,t.type)||this.ia(e.doc,t.doc)),this.ca(n);var s=t?this.la():[],a=0===this.ra.size&&this.current?1:0,o=a!==this.na;return this.na=a,0!==i.length||o?{snapshot:new wS(this.query,e.sa,r,i,e.mutatedKeys,0==a,o,!1,!!n&&0<n.resumeToken.approximateByteSize()),ha:s}:{ha:s}}L_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({sa:this.sa,aa:new yS,mutatedKeys:this.mutatedKeys,Hi:!1},!1)):{ha:[]}}Pa(e){return!this.ta.has(e)&&!!this.sa.has(e)&&!this.sa.get(e).hasLocalMutations}ca(e){e&&(e.addedDocuments.forEach(e=>this.ta=this.ta.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.ta=this.ta.delete(e)),this.current=e.current)}la(){if(!this.current)return[];const t=this.ra;this.ra=JI(),this.sa.forEach(e=>{this.Pa(e.key)&&(this.ra=this.ra.add(e.key))});const n=[];return t.forEach(e=>{this.ra.has(e)||n.push(new DS(e))}),this.ra.forEach(e=>{t.has(e)||n.push(new PS(e))}),n}Ia(e){this.ta=e._s,this.ra=JI();var t=this._a(e.documents);return this.applyChanges(t,!0)}Ta(){return wS.fromInitialDocuments(this.query,this.sa,this.mutatedKeys,0===this.na,this.hasCachedResults)}}class OS{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class MS{constructor(e){this.key=e,this.Ea=!1}}class LS{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.da={},this.Aa=new zI(e=>UI(e),FI),this.Ra=new Map,this.Va=new Set,this.ma=new pb(ow.comparator),this.fa=new Map,this.ga=new WE,this.pa={},this.ya=new Map,this.wa=IE.Bn(),this.onlineState="Unknown",this.Sa=void 0}get isPrimaryClient(){return!0===this.Sa}}async function FS(r,e,t,n,i){r.ba=(e,t,n)=>async function(e,t,n,r){let i=t.view._a(n);i.Hi&&(i=await _C(e.localStore,t.query,!1).then(({documents:e})=>t.view._a(e,i)));var s=r&&r.targetChanges.get(t.targetId),s=t.view.applyChanges(i,e.isPrimaryClient,s);return WS(e,t.targetId,s.ha),s.snapshot}(r,e,t,n);const s=await _C(r.localStore,e,!0),a=new xS(e,s._s),o=a._a(s.documents),c=jT.createSynthesizedTargetChangeForCurrentChange(t,n&&"Offline"!==r.onlineState,i),l=a.applyChanges(o,r.isPrimaryClient,c);WS(r,t,l.ha);var u=new OS(e,t,a);return r.Aa.set(e,u),r.Ra.has(t)?r.Ra.get(t).push(e):r.Ra.set(t,[e]),l.snapshot}async function US(e,t,n){const r=ZS(e);try{const e=await function(e,i){const s=e,a=tw.now(),o=i.reduce((e,t)=>e.add(t.key),JI());let c,l;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=$I,r=JI();return s.ts.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{c=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=rT(r.transform,e||null);null!=i&&(null===n&&(n=Qb.empty()),n.set(r.field,i))}return n||null}(n,c.get(n.key).overlayedDocument);null!=i&&t.push(new IT(n.key,i,function r(e){const i=[];return hb(e.fields,(e,t)=>{const n=new aw([e]);if($b(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new yb(i)}(i.value.mapValue),fT.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(l=e).applyToLocalDocumentSet(c,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:l.batchId,changes:GI(c)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.pa[e.currentUser.toKey()];r=r||new pb(Xy),r=r.insert(t,n),e.pa[e.currentUser.toKey()]=r}(r,e.batchId,n),await HS(r,e.changes),await cS(r.remoteStore)}catch(e){const t=vS(e,"Failed to persist write");n.reject(t)}}async function VS(e,t){const r=e;try{const e=await fC(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.fa.get(t);n&&(Vy(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.Ea=!0:0<e.modifiedDocuments.size?Vy(n.Ea):0<e.removedDocuments.size&&(Vy(n.Ea),n.Ea=!1))}),await HS(r,e,t)}catch(e){await yw(e)}}function qS(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.Aa.forEach((e,t)=>{var n=t.view.L_(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.L_(n)&&(r=!0)}),r&&CS(t)}(t.eventManager,i),r.length&&t.da.s_(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function jS(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.ts.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=ww.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);Vy(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=JI();for(let n=0;n<e.mutationResults.length;++n)0<e.mutationResults[n].transformResults.length&&(t=t.add(e.batch.mutations[n].key));return t}(r))).next(()=>i.localDocuments.getDocuments(e,t))})}(n.localStore,t);zS(n,r,null),BS(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await HS(n,e)}catch(e){await yw(e)}}function BS(e,t){(e.ya.get(t)||[]).forEach(e=>{e.resolve()}),e.ya.delete(t)}function zS(e,t,n){const r=e;let i=r.pa[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.pa[r.currentUser.toKey()]=i}}function $S(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Ra.get(e))t.Aa.delete(r),n&&t.da.Da(r,n);t.Ra.delete(e),t.isPrimaryClient&&t.ga.Vr(e).forEach(e=>{t.ga.containsKey(e)||KS(t,e)})}function KS(e,t){e.Va.delete(t.path.canonicalString());var n=e.ma.get(t);null!==n&&(ZC(e.remoteStore,n),e.ma=e.ma.remove(t),e.fa.delete(n),GS(e))}function WS(e,t,n){for(const r of n)r instanceof PS?(e.ga.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.ma.get(n)||e.Va.has(r)||(Oy("SyncEngine","New document in limbo: "+n),e.Va.add(r),GS(e))}(e,r)):r instanceof DS?(Oy("SyncEngine","Document no longer in limbo: "+r.key),e.ga.removeReference(r.key,t),e.ga.containsKey(r.key)||KS(e,r.key)):Uy()}function GS(e){for(;0<e.Va.size&&e.ma.size<e.maxConcurrentLimboResolutions;){var t=e.Va.values().next().value;e.Va.delete(t);var n=new ow(iw.fromString(t)),t=e.wa.next();e.fa.set(t,new MS(n)),e.ma=e.ma.insert(n,t),XC(e.remoteStore,new T0(OI(AI(n.path)),t,"TargetPurposeLimboResolution",Dw.ae))}}async function HS(e,t,r){const i=e,s=[],a=[],o=[];i.Aa.isEmpty()||(i.Aa.forEach((e,n)=>{o.push(i.ba(n,t,r).then(e=>{var t;(e||r)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(s.push(e),t=cC.Ki(n.targetId,e),a.push(t))}))}),await Promise.all(o),i.da.s_(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>ww.forEach(t,t=>ww.forEach(t.qi,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>ww.forEach(t.Qi,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!Cw(e))throw e;Oy("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.Zi.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.Zi=r.Zi.insert(t,i)}}}(i.localStore,a))}async function QS(r,e){const i=r;if(XS(i),ZS(i),!0===e&&!0!==i.Sa){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await YS(i,r.toArray());i.Sa=!0,await pS(i.remoteStore,!0);for(const r of e)XC(i.remoteStore,r)}else if(!1===e&&!1!==i.Sa){const r=[];let n=Promise.resolve();i.Ra.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>($S(i,t),vC(i.localStore,t,!0))),ZC(i.remoteStore,t)}),await n,await YS(i,r),function(e){const n=e;n.fa.forEach((e,t)=>{ZC(n.remoteStore,t)}),n.ga.mr(),n.fa=new Map,n.ma=new pb(ow.comparator)}(i),i.Sa=!1,await pS(i.remoteStore,!1)}}async function YS(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.Ra.get(t);if(u&&0!==u.length){e=await mC(r.localStore,OI(u[0]));for(const t of u){const n=r.Aa.get(t),u=(a=r,o=n,l=c=void 0,l=await _C((c=a).localStore,o.query,!0),l=o.view.Ia(l),c.isPrimaryClient&&WS(c,o.targetId,l.ha),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await yC(r.localStore,t);e=await mC(r.localStore,u),await FS(r,JS(u),t,!1,e.resumeToken)}i.push(e)}var a,o,c,l;return r.da.s_(s),i}function JS(e){return kI(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function XS(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=VS.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.fa.get(t);if(r&&r.Ea)return JI().add(r.key);{let e=JI();const r=n.Ra.get(t);if(!r)return e;for(const t of r){const r=n.Aa.get(t);e=e.unionWith(r.view.oa)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.fa.get(t),s=i&&i.key;if(s){let e=new pb(ow.comparator);e=e.insert(s,Yb.newNoDocument(s,nw.min()));const n=JI().add(s),i=new qT(nw.min(),new Map,new pb(Xy),e,n);await VS(r,i),r.ma=r.ma.remove(s),r.fa.delete(t),GS(r)}else await vC(r.localStore,t,!1).then(()=>$S(r,t,n)).catch(yw)}).bind(null,t),t.da.s_=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.k_(e)&&(r=!0);i.N_=e}}r&&CS(n)}).bind(null,t.eventManager),t.da.Da=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function ZS(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=jS.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.mutationQueue.lookupMutationBatch(t,r).next(e=>(Vy(null!==e),n=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>i.localDocuments.getDocuments(t,n))})}(r.localStore,t);zS(r,t,n),BS(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await HS(r,e)}catch(n){await yw(n)}}).bind(null,t),t}class ek{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=BC(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return hC(this.persistence,new lC,e.initialUser,this.serializer)}createPersistence(e){return new XE(eC.Hr,this.serializer)}createSharedClientState(e){return new PC}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class tk extends ek{constructor(e,t,n){super(),this.Ca=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ca.initialize(this,e),await ZS(this.Ca.syncEngine),await cS(this.Ca.remoteStore),await this.persistence.fi(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(e){return hC(this.persistence,new lC,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new NE(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){var n=new Pw(t,this.persistence);return new Rw(e.asyncQueue,n)}createPersistence(e){var t=oC(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?fE.withCacheSize(this.cacheSizeBytes):fE.DEFAULT;return new iC(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,qC(),jC(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new PC}}class nk extends tk{constructor(e,t){super(e,t,!1),this.Ca=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Ca.syncEngine;this.sharedClientState instanceof RC&&(this.sharedClientState.syncEngine={js:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Cn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):ww.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await cS(i.remoteStore):"acknowledged"===n||"rejected"===n?(zS(i,t,r||null),BS(i,t),i.localStore.mutationQueue.Mn(t)):Uy(),await HS(i,s)):Oy("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),Hs:(async function(e,t,n,r){const i=e;if(i.Sa)Oy("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.Ra.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await wC(i.localStore,jI(s[0])),r=qT.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,bb.EMPTY_BYTE_STRING);await HS(i,e,r);break}case"rejected":await vC(i.localStore,t,!0),$S(i,t,r);break;default:Uy()}}}).bind(null,t),Js:(async function(e,t,n){const r=XS(e);if(r.Sa){for(const e of t)if(r.Ra.has(e))Oy("SyncEngine","Adding an already active target "+e);else{const t=await yC(r.localStore,e),n=await mC(r.localStore,t);await FS(r,JS(t),n.targetId,!1,n.resumeToken),XC(r.remoteStore,n)}for(const e of n)r.Ra.has(e)&&await vC(r.localStore,e,!1).then(()=>{ZC(r.remoteStore,e),$S(r,e)}).catch(yw)}}).bind(null,t),Li:(function(e){return e.localStore.persistence.Li()}).bind(null,t),zs:(async function(e,t){const n=e;return wC(n.localStore,t).then(e=>HS(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.fi(async e=>{await QS(this.Ca.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}createSharedClientState(e){var t=qC();if(!RC.v(t))throw new jy(qy.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=oC(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new RC(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class rk{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>qS(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){Oy("SyncEngine","User change. New user:",t.toKey());const i=await dC(n.localStore,t);n.currentUser=t,e=n,r="'waitForPendingWrites' promise is rejected due to a user change.",e.ya.forEach(e=>{e.forEach(e=>{e.reject(new jy(qy.CANCELLED,r))})}),e.ya.clear(),n.sharedClientState.handleUserChange(t,i.removedBatchIds,i.addedBatchIds),await HS(n,i.rs)}var r}).bind(null,this.syncEngine),await pS(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new IS}createDatastore(e){var t,n,r,i=BC(e.databaseInfo.databaseId),s=(r=e.databaseInfo,new VC(r));return t=e.authCredentials,n=e.appCheckCredentials,r=s,e=i,new GC(t,n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>qS(this.syncEngine,e,0),e=new(xC.v()?xC:DC),new QC(t,n,r,i,e);var t,n,r,i}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new LS(e,t,n,r,i,s);return a&&(o.Sa=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;Oy("RemoteStore","RemoteStore shutting down."),t.S_.add(5),await JC(t),t.D_.shutdown(),t.v_.set("Unknown")}(this.remoteStore)}}function ik(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}class sk{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Fa(this.observer.next,e)}error(e){this.observer.error?this.Fa(this.observer.error,e):My("Uncaught Error in snapshot listener:",e.toString())}Ma(){this.muted=!0}Fa(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class ak{constructor(e,t){this.xa=e,this.serializer=t,this.metadata=new By,this.buffer=new Uint8Array,this.Oa=new TextDecoder("utf-8"),this.Na().then(e=>{e&&e.H_()?this.metadata.resolve(e.j_.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.j_)}`))},e=>this.metadata.reject(e))}close(){return this.xa.cancel()}async getMetadata(){return this.metadata.promise}async va(){return await this.getMetadata(),this.Na()}async Na(){var e=await this.Ba();if(null===e)return null;var t=this.Oa.decode(e),n=Number(t);isNaN(n)&&this.La(`length string (${t}) is not valid number`);t=await this.ka(n);return new kS(JSON.parse(t),e.length+n)}qa(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Ba(){for(;this.qa()<0&&!await this.Qa(););if(0===this.buffer.length)return null;var e=this.qa();e<0&&this.La("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async ka(e){for(;this.buffer.length<e;)await this.Qa()&&this.La("Reached the end of bundle when more is expected.");var t=this.Oa.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}La(e){throw this.xa.cancel(),new Error(`Invalid bundle format: ${e}`)}async Qa(){var e=await this.xa.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class ok{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new jy(qy.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=l0(r.serializer)+"/documents",i={documents:t.map(e=>s0(r.serializer,e))},s=await r.So("BatchGetDocuments",n,i,t.length),a=new Map;s.forEach(e=>{const t=(n=r.serializer,"found"in(e=e)?function(e,t){Vy(!!t.found),t.found.name,t.found.updateTime;var n=a0(e,t.found.name),r=n0(t.found.updateTime),i=t.found.createTime?n0(t.found.createTime):nw.min(),s=new Qb({mapValue:{fields:t.found.fields}});return Yb.newFoundDocument(n,r,i,s)}(n,e):"missing"in e?function(e,t){Vy(!!t.missing),Vy(!!t.readTime);var n=a0(e,t.missing),r=n0(t.readTime);return Yb.newNoDocument(n,r)}(n,e):Uy());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());Vy(!!t),o.push(t)}),o}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new ST(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=ow.fromPath(t);this.mutations.push(new kT(n,this.precondition(n)))}),await async function(e,t){const n=e,r=l0(n.serializer)+"/documents",i={writes:t.map(e=>p0(n.serializer,e))};await n.fo("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw Uy();t=nw.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new jy(qy.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(nw.min())?fT.exists(!1):fT.updateTime(t):fT.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return fT.exists(!0);if(t.isEqual(nw.min()))throw new jy(qy.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return fT.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class ck{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.Ka=n.maxAttempts,this.Uo=new zC(this.asyncQueue,"transaction_retry")}run(){--this.Ka,this.$a()}$a(){this.Uo.No(async()=>{const t=new ok(this.datastore),e=this.Ua(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Wa(e)}))}).catch(e=>{this.Wa(e)})})}Ua(e){try{var t=this.updateFunction(e);return!xw(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Wa(e){0<this.Ka&&this.Ga(e)?(--this.Ka,this.asyncQueue.enqueueAndForget(()=>(this.$a(),Promise.resolve()))):this.deferred.reject(e)}Ga(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!DT(t)}}class lk{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=Ry.UNAUTHENTICATED,this.clientId=Jy.V(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{Oy("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(Oy("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new jy(qy.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new By;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=vS(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function uk(e,t){e.asyncQueue.verifyOperationInProgress(),Oy("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await dC(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function hk(e,n){e.asyncQueue.verifyOperationInProgress();var t=await pk(e);Oy("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>dS(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>dS(n.remoteStore,t)),e._onlineComponents=n}function dk(e){return"FirebaseError"===e.name?e.code===qy.FAILED_PRECONDITION||e.code===qy.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function pk(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){Oy("FirestoreClient","Using user provided OfflineComponentProvider");try{await uk(t,t._uninitializedComponentsProvider._offline)}catch(e){var n=e;if(!dk(n))throw n;Ly("Error using user provided cache. Falling back to memory cache: "+n),await uk(t,new ek)}}else Oy("FirestoreClient","Using default OfflineComponentProvider"),await uk(t,new ek);return t._offlineComponents}async function fk(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(Oy("FirestoreClient","Using user provided OnlineComponentProvider"),await hk(e,e._uninitializedComponentsProvider._online)):(Oy("FirestoreClient","Using default OnlineComponentProvider"),await hk(e,new rk))),e._onlineComponents}function gk(e){return pk(e).then(e=>e.persistence)}function mk(e){return pk(e).then(e=>e.localStore)}function vk(e){return fk(e).then(e=>e.remoteStore)}function _k(e){return fk(e).then(e=>e.syncEngine)}async function yk(e){const t=await fk(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=XS(e);let r,i;const s=n.Aa.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.Ta();else{const e=await mC(n.localStore,OI(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await FS(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&XC(n.remoteStore,e)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.Aa.get(t),i=n.Ra.get(r.targetId);if(1<i.length)return n.Ra.set(r.targetId,i.filter(e=>!FI(e,t))),void n.Aa.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await vC(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),ZC(n.remoteStore,r.targetId),$S(n,r.targetId)}).catch(yw)):($S(n,r.targetId),await vC(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function wk(e,t,n={}){const r=new By;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const e=new sk({next:e=>{r.enqueueAndForget(()=>ES(n,o));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new jy(qy.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new jy(qy.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):a.resolve(e)},error:e=>a.reject(e)}),o=new SS(AI(i.path),e,{includeMetadataChanges:!0,z_:!0});return TS(n,o)}(await yk(e),e.asyncQueue,t,n,r)),r.promise}function bk(e,t,n={}){const r=new By;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new sk({next:e=>{n.enqueueAndForget(()=>ES(t,a)),e.fromCache&&"server"===r.source?i.reject(new jy(qy.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(e)},error:e=>i.reject(e)}),a=new SS(e,s,{includeMetadataChanges:!0,z_:!0});return TS(t,a)}(await yk(e),e.asyncQueue,t,n,r)),r.promise}function Ik(e,t,n,r){const i=(n=n,t=BC(t),s="string"==typeof n?OT().encode(n):n,n=function(e,t){if(e instanceof Uint8Array)return ik(e,t);if(e instanceof ArrayBuffer)return ik(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new ak(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=n0(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.$r.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(RS(i));const a=new NS(i,t.localStore,n.serializer);let e=await n.va();for(;e;){const t=await a.Y_(e);t&&r._updateProgress(t),e=await n.va()}var s=await a.complete();return await HS(t,s.ea,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.$r.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.X_)}catch(t){return Ly("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await _k(e),i,r)})}function Tk(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Ek=new Map;function Ck(e,t,n){if(!n)throw new jy(qy.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function Sk(e,t,n,r){if(!0===t&&!0===r)throw new jy(qy.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function kk(e){if(!ow.isDocumentKey(e))throw new jy(qy.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Ak(e){if(ow.isDocumentKey(e))throw new jy(qy.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Nk(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":Uy();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function Rk(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new jy(qy.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=Nk(e);throw new jy(qy.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function Pk(e,t){if(t<=0)throw new jy(qy.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Dk{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new jy(qy.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new jy(qy.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}Sk("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Tk(null!==(t=e.experimentalLongPollingOptions)&&void 0!==t?t:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new jy(qy.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new jy(qy.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(30<e.timeoutSeconds)throw new jy(qy.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,n}}class xk{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Dk({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new jy(qy.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new jy(qy.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Dk(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new $y;switch(e.type){case"firstParty":return new Hy(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new jy(qy.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=Ek.get(e);t&&(Oy("ComponentProvider","Removing Datastore"),Ek.delete(e),t.terminate())}(this),Promise.resolve()}}class Ok{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Ok(this.firestore,e,this._query)}}class Mk{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Lk(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Mk(this.firestore,e,this._key)}}class Lk extends Ok{constructor(e,t,n){super(e,t,AI(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new Mk(this.firestore,null,new ow(e))}withConverter(e){return new Lk(this.firestore,e,this._path)}}function Fk(e,t,...n){if(e=oe(e),Ck("collection","path",t),e instanceof xk){var r=iw.fromString(t,...n);return Ak(r),new Lk(e,null,r)}if(!(e instanceof Mk||e instanceof Lk))throw new jy(qy.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(iw.fromString(t,...n));return Ak(r),new Lk(e.firestore,null,r)}function Uk(e,t,...n){if(e=oe(e),Ck("doc","path",t=1===arguments.length?Jy.V():t),e instanceof xk){var r=iw.fromString(t,...n);return kk(r),new Mk(e,null,new ow(r))}if(!(e instanceof Mk||e instanceof Lk))throw new jy(qy.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(iw.fromString(t,...n));return kk(r),new Mk(e.firestore,e instanceof Lk?e.converter:null,new ow(r))}function Vk(e,t){return e=oe(e),t=oe(t),(e instanceof Mk||e instanceof Lk)&&(t instanceof Mk||t instanceof Lk)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function qk(e,t){return e=oe(e),t=oe(t),e instanceof Ok&&t instanceof Ok&&e.firestore===t.firestore&&FI(e._query,t._query)&&e.converter===t.converter}class jk{constructor(){this.za=Promise.resolve(),this.ja=[],this.Ha=!1,this.Ja=[],this.Ya=null,this.Za=!1,this.Xa=!1,this.eu=[],this.Uo=new zC(this,"async_queue_retry"),this.tu=()=>{var e=jC();e&&Oy("AsyncQueue","Visibility state changed to "+e.visibilityState),this.Uo.Lo()};const e=jC();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.tu)}get isShuttingDown(){return this.Ha}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.nu(),this.ru(e)}enterRestrictedMode(e){if(!this.Ha){this.Ha=!0,this.Xa=e||!1;const t=jC();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.tu)}}enqueue(e){if(this.nu(),this.Ha)return new Promise(()=>{});const t=new By;return this.ru(()=>this.Ha&&this.Xa?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.ja.push(e),this.iu()))}async iu(){if(0!==this.ja.length){try{await this.ja[0](),this.ja.shift(),this.Uo.reset()}catch(e){if(!Cw(e))throw e;Oy("AsyncQueue","Operation failed with retryable error: "+e)}0<this.ja.length&&this.Uo.No(()=>this.iu())}}ru(e){var t=this.za.then(()=>(this.Za=!0,e().catch(e=>{throw this.Ya=e,this.Za=!1,My("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.Za=!1,e))));return this.za=t}enqueueAfterDelay(e,t,n){this.nu(),-1<this.eu.indexOf(e)&&(t=0);var r=mS.createAndSchedule(this,e,t,n,e=>this.su(e));return this.Ja.push(r),r}nu(){this.Ya&&Uy()}verifyOperationInProgress(){}async ou(){for(var e;await(e=this.za),e!==this.za;);}_u(e){for(const t of this.Ja)if(t.timerId===e)return!0;return!1}au(t){return this.ou().then(()=>{this.Ja.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.Ja)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.ou()})}uu(e){this.eu.push(e)}su(e){var t=this.Ja.indexOf(e);this.Ja.splice(t,1)}}function Bk(e){return function(e,t){if("object"==typeof e&&null!==e){var n=e;for(const e of t)if(e in n&&"function"==typeof n[e])return 1}}(e,["next","error","complete"])}class zk{constructor(){this._progressObserver={},this._taskCompletionResolver=new By,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var $k,Kk,Wk,Gk,Hk,Qk;class Yk extends xk{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new jk,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||Xk(this),this._firestoreClient.terminate()}}function Jk(e){return e._firestoreClient||Xk(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function Xk(e){var t,n,r,i,s,a=e._freezeSettings(),o=(n=e._databaseId,r=(null===(o=e._app)||void 0===o?void 0:o.options.appId)||"",i=e._persistenceKey,s=a,new Nb(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,Tk(s.experimentalLongPollingOptions),s.useFetchStreams));e._firestoreClient=new lk(e._authCredentials,e._appCheckCredentials,e._queue,o),null!==(o=a.localCache)&&void 0!==o&&o._offlineComponentProvider&&null!==(t=a.localCache)&&void 0!==t&&t._onlineComponentProvider&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:a.localCache.kind,_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider})}function Zk(e,t,n){const r=new By;return e.asyncQueue.enqueue(async()=>{try{await uk(e,n),await hk(e,t),r.resolve()}catch(e){const t=e;if(!dk(t))throw t;Ly("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}}).then(()=>r.promise)}function eA(e){return function(e){const t=new By;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;iS(n.remoteStore)||Oy("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=e;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}(n.localStore);if(-1===e)return void t.resolve();const r=n.ya.get(e)||[];r.push(t),n.ya.set(e,r)}catch(e){const n=vS(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await _k(e),t)),t.promise}(Jk(e=Rk(e,Yk)))}function tA(e){return(n=Jk(e=Rk(e,Yk))).asyncQueue.enqueue(async()=>{const e=await gk(n),t=await vk(n);return e.setNetworkEnabled(!0),function(e){const t=e;return t.S_.delete(0),YC(t)}(t)});var n}function nA(e){return(n=Jk(e=Rk(e,Yk))).asyncQueue.enqueue(async()=>{const e=await gk(n),t=await vk(n);return e.setNetworkEnabled(!1),async function(e){const t=e;t.S_.add(0),await JC(t),t.v_.set("Offline")}(t)});var n}function rA(t,e){return n=Jk(t=Rk(t,Yk)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.$r.getNamedQuery(e,t))}(await mk(n),r)).then(e=>e?new Ok(t,null,e.query):null);var n,r}function iA(e){if(e._initialized||e._terminated)throw new jy(qy.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class sA{constructor(e){this._byteString=e}static fromBase64String(e){try{return new sA(bb.fromBase64String(e))}catch(e){throw new jy(qy.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new sA(bb.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class aA{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new jy(qy.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new aw(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class oA{constructor(e){this._methodName=e}}class cA{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new jy(qy.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new jy(qy.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return Xy(this._lat,e._lat)||Xy(this._long,e._long)}}const lA=/^__.*__$/;class uA{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new IT(e,this.data,this.fieldMask,t,this.fieldTransforms):new bT(e,this.data,t,this.fieldTransforms)}}class hA{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new IT(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function dA(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw Uy()}}class pA{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.cu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get lu(){return this.settings.lu}hu(e){return new pA(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Pu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.hu({path:n,Iu:!1});return r.Tu(e),r}Eu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.hu({path:n,Iu:!1});return r.cu(),r}du(e){return this.hu({path:void 0,Iu:!0})}Au(e){return xA(e,this.settings.methodName,this.settings.Ru||!1,this.path,this.settings.Vu)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}cu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Tu(this.path.get(e))}Tu(e){if(0===e.length)throw this.Au("Document fields must not be empty");if(dA(this.lu)&&lA.test(e))throw this.Au('Document fields cannot begin and end with "__"')}}class fA{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||BC(e)}mu(e,t,n,r=!1){return new pA({lu:e,methodName:t,Vu:n,path:aw.emptyPath(),Iu:!1,Ru:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function gA(e){var t=e._freezeSettings(),n=BC(e._databaseId);return new fA(e._databaseId,!!t.ignoreUndefinedProperties,n)}function mA(e,t,n,r,i,s={}){const a=e.mu(s.merge||s.mergeFields?2:0,t,n,i);NA("Data must be an object, but it was:",a,r);var o=kA(r,a);let c,l;if(s.merge)c=new yb(a.fieldMask),l=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=RA(t,r,n);if(!a.contains(i))throw new jy(qy.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);OA(e,i)||e.push(i)}c=new yb(e),l=a.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=a.fieldTransforms;return new uA(new Qb(o),c,l)}class vA extends oA{_toFieldTransform(e){if(2!==e.lu)throw 1===e.lu?e.Au(`${this._methodName}() can only appear at the top level of your update data`):e.Au(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof vA}}function _A(e,t,n){return new pA({lu:3,Vu:t.settings.Vu,methodName:e._methodName,Iu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class yA extends oA{_toFieldTransform(e){return new dT(e.path,new iT)}isEqual(e){return e instanceof yA}}class wA extends oA{constructor(e,t){super(e),this.fu=t}_toFieldTransform(e){const t=_A(this,e,!0),n=this.fu.map(e=>SA(e,t)),r=new sT(n);return new dT(e.path,r)}isEqual(e){return this===e}}class bA extends oA{constructor(e,t){super(e),this.fu=t}_toFieldTransform(e){const t=_A(this,e,!0),n=this.fu.map(e=>SA(e,t)),r=new oT(n);return new dT(e.path,r)}isEqual(e){return this===e}}class IA extends oA{constructor(e,t){super(e),this.gu=t}_toFieldTransform(e){var t=new lT(e.serializer,tT(e.serializer,this.gu));return new dT(e.path,t)}isEqual(e){return this===e}}function TA(e,i,s,t){const a=e.mu(1,i,s);NA("Data must be an object, but it was:",a,t);const o=[],c=Qb.empty();hb(t,(e,t)=>{var n=DA(i,e,s);t=oe(t);var r=a.Eu(n);if(t instanceof vA)o.push(n);else{const e=SA(t,r);null!=e&&(o.push(n),c.set(n,e))}});var n=new yb(o);return new hA(c,n,a.fieldTransforms)}function EA(e,t,n,r,i,s){const a=e.mu(1,t,n),o=[RA(t,r,n)],c=[i];if(s.length%2!=0)throw new jy(qy.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let p=0;p<s.length;p+=2)o.push(RA(t,s[p])),c.push(s[p+1]);const l=[],u=Qb.empty();for(let f=o.length-1;0<=f;--f)if(!OA(l,o[f])){const t=o[f];var h=oe(h=c[f]);const r=a.Eu(t);if(h instanceof vA)l.push(t);else{const e=SA(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new yb(l);return new hA(u,d,a.fieldTransforms)}function CA(e,t,n,r=!1){return SA(n,e.mu(r?4:3,t))}function SA(e,t){if(AA(e=oe(e)))return NA("Unsupported field value:",t,e),kA(e,t);if(e instanceof oA)return function(e,t){if(!dA(t.lu))throw t.Au(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Au(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Iu&&4!==t.lu)throw t.Au("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=SA(i,t.du(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=oe(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return tT(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=tw.fromDate(e);return{timestampValue:e0(t.serializer,n)}}if(e instanceof tw){n=new tw(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:e0(t.serializer,n)}}if(e instanceof cA)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof sA)return{bytesValue:t0(t.serializer,e._byteString)};if(e instanceof Mk){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.Au(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:r0(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.Au(`Unsupported field value: ${Nk(e)}`)}(e,t)}function kA(e,r){const i={};return db(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):hb(e,(e,t)=>{var n=SA(t,r.Pu(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function AA(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof tw||e instanceof cA||e instanceof sA||e instanceof Mk||e instanceof oA)}function NA(e,t,n){if(!AA(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=Nk(n);throw"an object"===r?t.Au(e+" a custom object"):t.Au(e+" "+r)}var i}function RA(e,t,n){if((t=oe(t))instanceof aA)return t._internalPath;if("string"==typeof t)return DA(e,t);throw xA("Field path arguments must be of type string or ",e,!1,void 0,n)}const PA=new RegExp("[~\\*/\\[\\]]");function DA(t,n,r){if(0<=n.search(PA))throw xA(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new aA(...n.split("."))._internalPath}catch(e){throw xA(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function xA(e,t,n,r,i){var s=r&&!r.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let c="";return(s||a)&&(c+=" (found",s&&(c+=` in field ${r}`),a&&(c+=` in document ${i}`),c+=")"),new jy(qy.INVALID_ARGUMENT,o+e+c)}function OA(e,t){return e.some(e=>e.isEqual(t))}class MA{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Mk(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new LA(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(FA("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class LA extends MA{data(){return super.data()}}function FA(e,t){return"string"==typeof t?DA(e,t):(t instanceof aA?t:t._delegate)._internalPath}function UA(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new jy(qy.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class VA{}class qA extends VA{}function jA(e,t,...n){let r=[];t instanceof VA&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof zA).length,n=e.filter(e=>e instanceof BA).length;if(1<t||0<t&&0<n)throw new jy(qy.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const t of r)e=t._apply(e);return e}class BA extends qA{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new BA(e,t,n)}_apply(e){var t=this._parse(e);return JA(e._query,t),new Ok(e.firestore,e.converter,MI(e._query,t))}_parse(e){var t=gA(e.firestore);return function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new jy(qy.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){YA(a,s);const t=[];for(const n of a)t.push(QA(r,e,n));o={arrayValue:{values:t}}}else o=QA(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||YA(a,s),o=CA(n,t,a,"in"===s||"not-in"===s);return nI.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}class zA extends VA{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new zA(e,t)}_parse(t){var e=this._queryConstraints.map(e=>e._parse(t)).filter(e=>0<e.getFilters().length);return 1===e.length?e[0]:rI.create(e,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;for(const e of t.getFlattenedFilters())JA(n,e),n=MI(n,e)}(e._query,t),new Ok(e.firestore,e.converter,MI(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class $A extends qA{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new $A(e,t)}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new jy(qy.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new jy(qy.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new eI(t,n);return n=i,null!==RI(e=e)||null!==(r=PI(e))&&XA(0,r,n.field),i}(e._query,this._field,this._direction);return new Ok(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new SI(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class KA extends qA{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new KA(e,t,n)}_apply(e){return new Ok(e.firestore,e.converter,LI(e._query,this._limit,this._limitType))}}class WA extends qA{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new WA(e,t,n)}_apply(e){var t,n=HA(e,this.type,this._docOrFields,this._inclusive);return new Ok(e.firestore,e.converter,(t=e._query,e=n,new SI(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class GA extends qA{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new GA(e,t,n)}_apply(e){var t,n=HA(e,this.type,this._docOrFields,this._inclusive);return new Ok(e.firestore,e.converter,(t=e._query,e=n,new SI(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function HA(e,t,n,r){if(n[0]=oe(n[0]),n[0]instanceof MA)return function(e,t,n,r,i){if(!r)throw new jy(qy.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of xI(e))if(n.field.isKeyField())s.push(Vb(t,r.key));else{const e=r.data.field(n.field);if(Sb(e))throw new jy(qy.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new jy(qy.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new Jb(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=gA(e.firestore);return function(e,t,n,r,i,s){const a=e.explicitOrderBy;if(i.length>a.length)throw new jy(qy.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let c=0;c<i.length;c++){const l=i[c];if(a[c].field.isKeyField()){if("string"!=typeof l)throw new jy(qy.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!DI(e)&&-1!==l.indexOf("/"))throw new jy(qy.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(iw.fromString(l));if(!ow.isDocumentKey(n))throw new jy(qy.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new ow(n);o.push(Vb(t,i))}else{const e=CA(n,r,l);o.push(e)}}return new Jb(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function QA(e,t,n){if("string"==typeof(n=oe(n))){if(""===n)throw new jy(qy.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!DI(t)&&-1!==n.indexOf("/"))throw new jy(qy.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(iw.fromString(n));if(!ow.isDocumentKey(r))throw new jy(qy.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Vb(e,new ow(r))}if(n instanceof Mk)return Vb(e,n._key);throw new jy(qy.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Nk(n)}.`)}function YA(e,t){if(!Array.isArray(e)||0===e.length)throw new jy(qy.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function JA(e,t){if(t.isInequality()){const r=PI(e),i=t.field;if(null!==r&&!r.isEqual(i))throw new jy(qy.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${i.toString()}'`);var n=RI(e);null!==n&&XA(0,i,n)}const r=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(0<=t.indexOf(e.op))return e.op;return null}(e.filters,function(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==r)throw r===t.op?new jy(qy.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new jy(qy.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}function XA(e,t,n){if(!n.isEqual(t))throw new jy(qy.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class ZA{convertValue(e,t="none"){switch(xb(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Eb(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(Cb(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw Uy()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,n="none"){const r={};return hb(e,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new cA(Eb(e.latitude),Eb(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=kb(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ab(e));default:return null}}convertTimestamp(e){var t=Tb(e);return new tw(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=iw.fromString(e);Vy(I0(n));const r=new Rb(n.get(1),n.get(3)),i=new ow(n.popFirst(5));return r.isEqual(t)||My(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function eN(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class tN extends ZA{constructor(e){super(),this.firestore=e}convertBytes(e){return new sA(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Mk(this.firestore,null,t)}}class nN{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class rN extends MA{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new iN(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(FA("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class iN extends rN{data(e={}){return super.data(e)}}class sN{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new nN(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new iN(this._firestore,this._userDataWriter,e.key,e,new nN(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new jy(qy.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let n=0;return s._snapshot.docChanges.map(e=>{var t=new iN(s._firestore,s._userDataWriter,e.doc.key,e.doc,new nN(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new iN(s._firestore,s._userDataWriter,e.doc.key,e.doc,new nN(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Uy()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function aN(e,t){return e instanceof rN&&t instanceof rN?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof sN&&t instanceof sN&&e._firestore===t._firestore&&qk(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class oN extends ZA{constructor(e){super(),this.firestore=e}convertBytes(e){return new sA(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new Mk(this.firestore,null,t)}}function cN(t){t=Rk(t,Mk);const n=Rk(t.firestore,Yk),e=Jk(n),r=new oN(n);return function(e,t){const n=new By;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(e,t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(e,t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new jy(qy.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){var r=vS(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await mk(e),t,n)),n.promise}(e,t._key).then(e=>new rN(n,r,t._key,e,new nN(null!==e&&e.hasLocalMutations,!0),t.converter))}function lN(t){t=Rk(t,Ok);const n=Rk(t.firestore,Yk),e=Jk(n),r=new oN(n);return function(e,t){const n=new By;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await _C(e,t,!0),s=new xS(t,i._s),a=s._a(i.documents),o=s.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=vS(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await mk(e),t,n)),n.promise}(e,t._query).then(e=>new sN(n,r,t,e))}function uN(e,t,n){e=Rk(e,Mk);var r=Rk(e.firestore,Yk),i=eN(e.converter,t,n);return fN(r,[mA(gA(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,fT.none())])}function hN(e,t,n,...r){e=Rk(e,Mk);var i=Rk(e.firestore,Yk),s=gA(i);let a;return a="string"==typeof(t=oe(t))||t instanceof aA?EA(s,"updateDoc",e._key,t,n,r):TA(s,"updateDoc",e._key,t),fN(i,[a.toMutation(e._key,fT.exists(!0))])}function dN(t,...n){var e;t=oe(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||Bk(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(Bk(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,c;if(t instanceof Mk)o=Rk(t.firestore,Yk),c=AI(t._key.path),a={next:e=>{n[i]&&n[i](gN(o,t,e))},error:n[i+1],complete:n[i+2]};else{const l=Rk(t,Ok);o=Rk(l.firestore,Yk),c=l._query;const u=new oN(o);a={next:e=>{n[i]&&n[i](new sN(o,u,l,e))},error:n[i+1],complete:n[i+2]},UA(t._query)}return function(e,t,n,r){const i=new sk(r),s=new SS(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>TS(await yk(e),s)),()=>{i.Ma(),e.asyncQueue.enqueueAndForget(async()=>ES(await yk(e),s))}}(Jk(o),c,s,a)}function pN(e,t){return function(e,t){const n=new sk(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.B_.add(t),t.next()}(await yk(e),n)),()=>{n.Ma(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.B_.delete(t)}(await yk(e),n))}}(Jk(e=Rk(e,Yk)),Bk(t)?t:{next:t})}function fN(e,t){return function(e,t){const n=new By;return e.asyncQueue.enqueueAndForget(async()=>US(await _k(e),t,n)),n.promise}(Jk(e),t)}function gN(e,t,n){var r=n.docs.get(t._key),i=new oN(e);return new rN(e,i,t._key,r,new nN(n.hasPendingWrites,n.fromCache),t.converter)}const mN={maxAttempts:5};class vN{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=gA(e)}set(e,t,n){this._verifyNotCommitted();const r=_N(e,this._firestore),i=eN(r.converter,t,n),s=mA(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,fT.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=_N(e,this._firestore);let s;return s="string"==typeof(t=oe(t))||t instanceof aA?EA(this._dataReader,"WriteBatch.update",i._key,t,n,r):TA(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,fT.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=_N(e,this._firestore);return this._mutations=this._mutations.concat(new ST(t._key,fT.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new jy(qy.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function _N(e,t){if((e=oe(e)).firestore!==t)throw new jy(qy.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class yN extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=gA(e)}get(e){const n=_N(e,this._firestore),r=new tN(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return Uy();const t=e[0];if(t.isFoundDocument())return new MA(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new MA(this._firestore,r,n._key,null,n.converter);throw Uy()})}set(e,t,n){var r=_N(e,this._firestore),i=eN(r.converter,t,n),i=mA(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=_N(e,this._firestore),s="string"==typeof(t=oe(t))||t instanceof aA?EA(this._dataReader,"Transaction.update",i._key,t,n,r):TA(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=_N(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=_N(e,this._firestore),n=new oN(this._firestore);return super.get(e).then(e=>new rN(this._firestore,n,t._key,e._document,new nN(!1,!1),t.converter))}}function wN(t,n,e){t=Rk(t,Yk);var r=Object.assign(Object.assign({},mN),e);return function(e){if(e.maxAttempts<1)throw new jy(qy.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(t,n,r){const i=new By;return t.asyncQueue.enqueueAndForget(async()=>{var e=await fk(t).then(e=>e.datastore);new ck(t.asyncQueue,e,r,n,i).run()}),i.promise}(Jk(t),e=>n(new yN(t,e)),r)}$k=!0,Kk=Je,Py=Kk,Ge(new ce("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new Yk(new Wy(e.getProvider("auth-internal")),new Yy(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new jy(qy.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Rb(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:$k},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),tt(Ny,"4.1.2",oR),tt(Ny,"4.1.2","esm2017");function bN(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new jy("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function IN(){if("undefined"==typeof Uint8Array)throw new jy("unimplemented","Uint8Arrays are not available in this environment.")}function TN(){if("undefined"==typeof atob)throw new jy("unimplemented","Blobs are unavailable in Firestore in this environment.")}class EN{constructor(e){this._delegate=e}static fromBase64String(e){return TN(),new EN(sA.fromBase64String(e))}static fromUint8Array(e){return IN(),new EN(sA.fromUint8Array(e))}toBase64(){return TN(),this._delegate.toBase64()}toUint8Array(){return IN(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function CN(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class SN{enableIndexedDbPersistence(e,t){return function(e,t){iA(e=Rk(e,Yk));var n=Jk(e);if(n._uninitializedComponentsProvider)throw new jy(qy.FAILED_PRECONDITION,"SDK cache is already specified.");Ly("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var r=e._freezeSettings(),i=new rk;return Zk(n,i,new tk(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){iA(e=Rk(e,Yk));var t=Jk(e);if(t._uninitializedComponentsProvider)throw new jy(qy.FAILED_PRECONDITION,"SDK cache is already specified.");Ly("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var n=e._freezeSettings(),r=new rk;return Zk(t,r,new nk(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new jy(qy.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new By;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Iw.v())return Promise.resolve();var t=e+"main";await Iw.delete(t)}(oC(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class kN{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Rb||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||Ly("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){!function(n,e,t,r={}){var i;const s=(n=Rk(n,xk))._getSettings(),a=`${e}:${t}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&Ly("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),n._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=Ry.MOCK_USER;else{e=w(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new jy(qy.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new Ry(s)}n._authCredentials=new Ky(new zy(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return tA(this._delegate)}disableNetwork(){return nA(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,Sk("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return eA(this._delegate)}onSnapshotsInSync(e){return pN(this._delegate,e)}get app(){if(!this._appCompat)throw new jy("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new jN(this,Fk(this._delegate,e))}catch(e){throw xN(e,"collection()","Firestore.collection()")}}doc(e){try{return new DN(this,Uk(this._delegate,e))}catch(e){throw xN(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new UN(this,function(e,t){if(e=Rk(e,xk),Ck("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new jy(qy.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Ok(e,null,(t=t,new SI(iw.emptyPath(),t)))}(this._delegate,e))}catch(e){throw xN(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return wN(this._delegate,e=>t(new NN(this,e)))}batch(){return Jk(this._delegate),new RN(new vN(this._delegate,e=>fN(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=Jk(t=Rk(t,Yk)),r=new zk,Ik(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return rA(this._delegate,e).then(e=>e?new UN(this,e):null)}}class AN extends ZA{constructor(e){super(),this.firestore=e}convertBytes(e){return new EN(new sA(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return DN.forKey(t,this.firestore,null)}}class NN{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new AN(e)}get(e){const t=BN(e);return this._delegate.get(t).then(e=>new LN(this._firestore,new rN(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=BN(e);return n?(bN("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=BN(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=BN(e);return this._delegate.delete(t),this}}class RN{constructor(e){this._delegate=e}set(e,t,n){var r=BN(e);return n?(bN("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=BN(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=BN(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class PN{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new iN(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new FN(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=PN.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new PN(e,new AN(e),t),r.set(t,i)),i}}PN.INSTANCES=new WeakMap;class DN{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new AN(e)}static forPath(e,t,n){if(e.length%2!=0)throw new jy("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new DN(t,new Mk(t._delegate,n,new ow(e)))}static forKey(e,t,n){return new DN(t,new Mk(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new jN(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new jN(this.firestore,Fk(this._delegate,e))}catch(e){throw xN(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=oe(e))instanceof Mk&&Vk(this._delegate,e)}set(e,t){t=bN("DocumentReference.set",t);try{return t?uN(this._delegate,e,t):uN(this._delegate,e)}catch(e){throw xN(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?hN(this._delegate,e):hN(this._delegate,e,t,...n)}catch(e){throw xN(e,"updateDoc()","DocumentReference.update()")}}delete(){return fN(Rk((e=this._delegate).firestore,Yk),[new ST(e._key,fT.none())]);var e}onSnapshot(...e){var t=ON(e),n=MN(e,e=>new LN(this.firestore,new rN(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return dN(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?cN:"server"===(null==e?void 0:e.source)?function(t){t=Rk(t,Mk);const n=Rk(t.firestore,Yk);return wk(Jk(n),t._key,{source:"server"}).then(e=>gN(n,t,e))}:function(t){t=Rk(t,Mk);const n=Rk(t.firestore,Yk);return wk(Jk(n),t._key).then(e=>gN(n,t,e))})(this._delegate),t.then(e=>new LN(this.firestore,new rN(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new DN(this.firestore,e?this._delegate.withConverter(PN.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function xN(e,t,n){return e.message=e.message.replace(t,n),e}function ON(e){for(const t of e)if("object"==typeof t&&!CN(t))return t;return{}}function MN(e,t){var n;let r;return r=CN(e[0])?e[0]:CN(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class LN{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new DN(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return aN(this._delegate,e._delegate)}}class FN extends LN{data(e){var t=this._delegate.data(e);return void 0!==t||Uy(),t}}class UN{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new AN(e)}where(e,t,n){try{return new UN(this.firestore,jA(this._delegate,(r=n,i=t,s=FA("where",e),BA._create(s,i,r))))}catch(e){throw xN(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new UN(this.firestore,jA(this._delegate,([n,r="asc"]=[e,t],i=r,s=FA("orderBy",n),$A._create(s,i))))}catch(e){throw xN(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new UN(this.firestore,jA(this._delegate,(Pk("limit",t=e),KA._create("limit",t,"F"))))}catch(e){throw xN(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new UN(this.firestore,jA(this._delegate,(Pk("limitToLast",t=e),KA._create("limitToLast",t,"L"))))}catch(e){throw xN(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new UN(this.firestore,jA(this._delegate,function(...e){return WA._create("startAt",e,!0)}(...e)))}catch(e){throw xN(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new UN(this.firestore,jA(this._delegate,function(...e){return WA._create("startAfter",e,!1)}(...e)))}catch(e){throw xN(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new UN(this.firestore,jA(this._delegate,function(...e){return GA._create("endBefore",e,!1)}(...e)))}catch(e){throw xN(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new UN(this.firestore,jA(this._delegate,function(...e){return GA._create("endAt",e,!0)}(...e)))}catch(e){throw xN(e,"endAt()","Query.endAt()")}}isEqual(e){return qk(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?lN:"server"===(null==e?void 0:e.source)?function(t){t=Rk(t,Ok);const n=Rk(t.firestore,Yk),e=Jk(n),r=new oN(n);return bk(e,t._query,{source:"server"}).then(e=>new sN(n,r,t,e))}:function(t){t=Rk(t,Ok);const n=Rk(t.firestore,Yk),e=Jk(n),r=new oN(n);return UA(t._query),bk(e,t._query).then(e=>new sN(n,r,t,e))})(this._delegate),t.then(e=>new qN(this.firestore,new sN(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=ON(e),n=MN(e,e=>new qN(this.firestore,new sN(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return dN(this._delegate,t,n)}withConverter(e){return new UN(this.firestore,e?this._delegate.withConverter(PN.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class VN{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new FN(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class qN{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new UN(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new FN(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new VN(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new FN(this._firestore,e))})}isEqual(e){return aN(this._delegate,e._delegate)}}class jN extends UN{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new DN(this.firestore,e):null}doc(e){try{return void 0===e?new DN(this.firestore,Uk(this._delegate)):new DN(this.firestore,Uk(this._delegate,e))}catch(e){throw xN(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=Rk(e.firestore,Yk),r=Uk(e),i=eN(e.converter,t);return fN(n,[mA(gA(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,fT.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new DN(this.firestore,e))}isEqual(e){return Vk(this._delegate,e._delegate)}withConverter(e){return new jN(this.firestore,e?this._delegate.withConverter(PN.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function BN(e){return Rk(e,Mk)}const zN={Firestore:kN,GeoPoint:cA,Timestamp:tw,Blob:EN,Transaction:NN,WriteBatch:RN,DocumentReference:DN,DocumentSnapshot:LN,Query:UN,QueryDocumentSnapshot:FN,QuerySnapshot:qN,CollectionReference:jN,FieldPath:class X1{constructor(...e){this._delegate=new aA(...e)}static documentId(){return new X1(aw.keyField().canonicalString())}isEqual(e){return(e=oe(e))instanceof aA&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Z1{constructor(e){this._delegate=e}static serverTimestamp(){const e=new yA("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Z1(e)}static delete(){const e=new vA("deleteField");return e._methodName="FieldValue.delete",new Z1(e)}static arrayUnion(...e){const t=function(...e){return new wA("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Z1(t)}static arrayRemove(...e){const t=function(...e){return new bA("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Z1(t)}static increment(e){const t=new IA("increment",e);return t._methodName="FieldValue.increment",new Z1(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,Dy.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};Wk=bt,Gk=(e,t)=>new kN(e,t,new SN),Wk.INTERNAL.registerComponent(new ce("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return Gk(t,n)},"PUBLIC").setServiceProps(Object.assign({},zN))),Wk.registerVersion("@firebase/firestore-compat","0.3.16");const $N="type.googleapis.com/google.protobuf.Int64Value",KN="type.googleapis.com/google.protobuf.UInt64Value";function WN(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function GN(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case $N:case KN:var t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t;default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(e=>GN(e)):"function"==typeof e||"object"==typeof e?WN(e,e=>GN(e)):e}const HN="functions",QN={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class YN extends P{constructor(e,t,n){super(`${HN}/${e}`,t||""),this.details=n}}function JN(e,t){let n=function(e){if(200<=e&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),r=n,i=void 0;try{var s=t&&t.error;if(s){const e=s.status;if("string"==typeof e){if(!QN[e])return new YN("internal","internal");n=QN[e],r=e}var a=s.message;"string"==typeof a&&(r=a),i=s.details,void 0!==i&&(i=GN(i))}}catch(e){}return"ok"===n?null:new YN(n,r,i)}class XN{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then(e=>this.auth=e,()=>{}),this.messaging||t.get().then(e=>this.messaging=e,()=>{}),this.appCheck||n.get().then(e=>this.appCheck=e,()=>{})}async getAuthToken(){if(this.auth)try{var e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return this.messaging.getToken()}catch(e){return}}async getAppCheckToken(e){if(this.appCheck){var t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}const ZN="us-central1";class eR{constructor(e,t,n,r,i=ZN,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new XN(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var a=new URL(i);this.customDomain=a.origin,this.region=ZN}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){var t=this.app.options.projectId;return null===this.emulatorOrigin?null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`:`${this.emulatorOrigin}/${t}/${this.region}/${e}`}}function tR(i,s,a){return e=>{return t=e,n=a||{},r=(e=i)._url(s),nR(e,r,t,n);var t,n,r}}async function nR(e,t,n,r){var i={data:n=function t(e){if(null==e)return null;if("number"==typeof(e=e instanceof Number?e.valueOf():e)&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>t(e));if("function"==typeof e||"object"==typeof e)return WN(e,e=>t(e));throw new Error("Data cannot be encoded in JSON: "+e)}(n)};const s={};var a=await e.contextProvider.getContext(r.limitedUseAppCheckTokens);a.authToken&&(s.Authorization="Bearer "+a.authToken),a.messagingToken&&(s["Firebase-Instance-ID-Token"]=a.messagingToken),null!==a.appCheckToken&&(s["X-Firebase-AppCheck"]=a.appCheckToken);const o=function(n){let r=null;return{promise:new Promise((e,t)=>{r=setTimeout(()=>{t(new YN("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{r&&clearTimeout(r)}}}(r.timeout||7e4);a=await Promise.race([async function(e,t,n,r){n["Content-Type"]="application/json";let i;try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}}(t,i,s,e.fetchImpl),o.promise,e.cancelAllRequests]);if(o.cancel(),!a)throw new YN("cancelled","Firebase Functions instance was deleted.");i=JN(a.status,a.json);if(i)throw i;if(!a.json)throw new YN("internal","Response is not valid JSON object.");let c=a.json.data;if(void 0===c&&(c=a.json.result),void 0===c)throw new YN("internal","Response is missing data field.");return{data:GN(c)}}const rR="@firebase/functions";function iR(e,t,n){oe(e).emulatorOrigin=`http://${t}:${n}`}function sR(e,t,n){return r=oe(e),i=t,s=n,e=>nR(r,i,e,s||{});var r,i,s}Hk=fetch.bind(self),Ge(new ce(HN,(e,{instanceIdentifier:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new eR(n,r,i,s,t,Hk)},"PUBLIC").setMultipleInstances(!0)),tt(rR,"0.10.0",Qk),tt(rR,"0.10.0","esm2017");var aR,oR,cR,lR,uR;class hR{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return tR(oe(this._delegate),e,t)}httpsCallableFromURL(e,t){return sR(this._delegate,e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new P("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new P("functions","Port missing in origin provided to useFunctionsEmulator()");return iR(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return iR(this._delegate,e,t)}}const dR="us-central1",pR=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:dR});return new hR(n,r)};aR={Functions:hR},bt.INTERNAL.registerComponent(new ce("functions-compat",pR,"PUBLIC").setServiceProps(aR).setMultipleInstances(!0)),bt.registerVersion("@firebase/functions-compat","0.3.5");const fR="/firebase-messaging-sw.js",gR="/firebase-cloud-messaging-push-scope",mR="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",vR="https://fcmregistrations.googleapis.com/v1",_R="google.c.a.c_id",yR="google.c.a.e";function wR(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(oR=Ox=Ox||{})[oR.DATA_MESSAGE=1]="DATA_MESSAGE",oR[oR.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(sl=cR=cR||{}).PUSH_RECEIVED="push-received",sl.NOTIFICATION_CLICKED="notification-clicked";const bR="fcm_token_details_db",IR="fcm_token_object_Store";async function TR(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(bR))return null}let l=null;const e=await Pe(bR,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(IR)){const o=r.objectStore(IR);var s,a=await o.index("fcmSenderId").get(c);await o.clear(),a&&(2===t?(s=a).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:wR(s.vapidKey)}}):3===t?(s=a,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:wR(s.auth),p256dh:wR(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:wR(s.vapidKey)}}):4===t&&(a=a,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:wR(a.auth),p256dh:wR(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:wR(a.vapidKey)}}))}}});return e.close(),await De(bR),await De("fcm_vapid_details_db"),await De("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(l)?l:null}const ER="firebase-messaging-database",CR=1,SR="firebase-messaging-store";let kR=null;function AR(){return kR=kR||Pe(ER,CR,{upgrade:(e,t)=>{0===t&&e.createObjectStore(SR)}}),kR}async function NR(e){var t=PR(e);const n=await AR();t=await n.transaction(SR).objectStore(SR).get(t);if(t)return t;t=await TR(e.appConfig.senderId);return t?(await RR(e,t),t):void 0}async function RR(e,t){var n=PR(e);const r=await AR(),i=r.transaction(SR,"readwrite");return await i.objectStore(SR).put(t,n),await i.done,t}function PR({appConfig:e}){return e.appId}const DR=new D("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function xR(e,t){var n={method:"DELETE",headers:await MR(e)};try{const s=await fetch(`${OR(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw DR.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw DR.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function OR({projectId:e}){return`${vR}/projects/${e}/registrations`}async function MR({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function LR({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==mR&&(i.web.applicationPubKey=r),i}const FR=6048e5;async function UR(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,a,o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:wR(t.getKey("auth")),p256dh:wR(t.getKey("p256dh"))},c=await NR(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=o.vapidKey===n.vapidKey,i=o.endpoint===n.endpoint,s=o.auth===n.auth,a=o.p256dh===n.p256dh,r&&i&&s&&a)return Date.now()>=c.createTime+FR?async function(t,e){try{var n=await async function(e,t){var n=await MR(e),r=LR(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${OR(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw DR.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw DR.create("token-update-failed",{errorInfo:r})}if(!i.token)throw DR.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await RR(t.firebaseDependencies,r),n}catch(e){throw await VR(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await xR(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return qR(e.firebaseDependencies,o)}return qR(e.firebaseDependencies,o)}async function VR(e){var t=await NR(e.firebaseDependencies);t&&(await xR(e.firebaseDependencies,t.token),await async function(e){var t=PR(e);const n=await AR(),r=n.transaction(SR,"readwrite");await r.objectStore(SR).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function qR(e,t){var n={token:await async function(e,t){var n=await MR(e),r=LR(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(OR(e.appConfig),r);i=await s.json()}catch(e){throw DR.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw DR.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw DR.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await RR(e,n),n.token}function jR(e){var t,n,r,i,s,a={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return r=a,(n=e).notification&&(r.notification={},(t=n.notification.title)&&(r.notification.title=t),(t=n.notification.body)&&(r.notification.body=t),(t=n.notification.image)&&(r.notification.image=t),(t=n.notification.icon)&&(r.notification.icon=t)),n=a,(r=e).data&&(n.data=r.data),r=a,((e=e).fcmOptions||null!==(i=e.notification)&&void 0!==i&&i.click_action)&&(r.fcmOptions={},(s=null!==(i=null===(i=e.fcmOptions)||void 0===i?void 0:i.link)&&void 0!==i?i:null===(s=e.notification)||void 0===s?void 0:s.click_action)&&(r.fcmOptions.link=s),(s=null===(s=e.fcmOptions)||void 0===s?void 0:s.analytics_label)&&(r.fcmOptions.analyticsLabel=s)),a}function BR(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}function zR(e){return DR.create("missing-app-config-values",{valueName:e})}BR("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),BR("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class $R{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw zR("App Configuration Object");if(!e.name)throw zR("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw zR(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}async function KR(e){try{e.swRegistration=await navigator.serviceWorker.register(fR,{scope:gR}),e.swRegistration.update().catch(()=>{})}catch(e){throw DR.create("failed-service-worker-registration",{browserErrorMessage:null==e?void 0:e.message})}}async function WR(e,t){if(!navigator)throw DR.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw DR.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=mR)),await async function(e,t){if(t||e.swRegistration||await KR(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw DR.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),UR(e)}async function GR(e,t,n){var r=function(e){switch(e){case cR.NOTIFICATION_CLICKED:return"notification_open";case cR.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[_R],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}async function HR(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===cR.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(jR(r)):e.onMessageHandler.next(jR(r))),n=r.data,"object"==typeof(t=n)&&t&&_R in t&&"1"===n[yR]&&await GR(e,r.messageType,n))}const QR="@firebase/messaging",YR=e=>{const t=new $R(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>HR(t,e)),t},JR=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>WR(t,e)}};function XR(e){return async function(e){if(!navigator)throw DR.create("only-available-in-window");return e.swRegistration||await KR(e),VR(e)}(e=oe(e))}function ZR(e,t){return function(e,t){if(!navigator)throw DR.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=oe(e),t)}Ge(new ce("messaging",YR,"PUBLIC")),Ge(new ce("messaging-internal",JR,"PRIVATE")),tt(QR,"0.12.4"),tt(QR,"0.12.4","esm2017");const eP="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",tP="https://fcmregistrations.googleapis.com/v1",nP="FCM_MSG",rP="google.c.a.c_id",iP=3,sP=1;function aP(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(sl=lR=lR||{})[sl.DATA_MESSAGE=1]="DATA_MESSAGE",sl[sl.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(sl=uR=uR||{}).PUSH_RECEIVED="push-received",sl.NOTIFICATION_CLICKED="notification-clicked";const oP="fcm_token_details_db",cP="fcm_token_object_Store";async function lP(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(oP))return null}let l=null;const e=await Pe(oP,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(cP)){const o=r.objectStore(cP);var s,a=await o.index("fcmSenderId").get(c);await o.clear(),a&&(2===t?(s=a).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:aP(s.vapidKey)}}):3===t?(s=a,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:aP(s.auth),p256dh:aP(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:aP(s.vapidKey)}}):4===t&&(a=a,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:aP(a.auth),p256dh:aP(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:aP(a.vapidKey)}}))}}});return e.close(),await De(oP),await De("fcm_vapid_details_db"),await De("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(l)?l:null}const uP="firebase-messaging-database",hP=1,dP="firebase-messaging-store";let pP=null;function fP(){return pP=pP||Pe(uP,hP,{upgrade:(e,t)=>{0===t&&e.createObjectStore(dP)}}),pP}async function gP(e){var t=vP(e);const n=await fP();t=await n.transaction(dP).objectStore(dP).get(t);if(t)return t;t=await lP(e.appConfig.senderId);return t?(await mP(e,t),t):void 0}async function mP(e,t){var n=vP(e);const r=await fP(),i=r.transaction(dP,"readwrite");return await i.objectStore(dP).put(t,n),await i.done,t}function vP({appConfig:e}){return e.appId}const _P=new D("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function yP(e,t){var n={method:"DELETE",headers:await bP(e)};try{const s=await fetch(`${wP(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw _P.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw _P.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function wP({projectId:e}){return`${tP}/projects/${e}/registrations`}async function bP({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function IP({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==eP&&(i.web.applicationPubKey=r),i}async function TP(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,a,o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:aP(t.getKey("auth")),p256dh:aP(t.getKey("p256dh"))},c=await gP(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=o.vapidKey===n.vapidKey,i=o.endpoint===n.endpoint,s=o.auth===n.auth,a=o.p256dh===n.p256dh,r&&i&&s&&a)return Date.now()>=c.createTime+6048e5?async function(t,e){try{var n=await async function(e,t){var n=await bP(e),r=IP(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${wP(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw _P.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw _P.create("token-update-failed",{errorInfo:r})}if(!i.token)throw _P.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await mP(t.firebaseDependencies,r),n}catch(e){throw await EP(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await yP(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return CP(e.firebaseDependencies,o)}return CP(e.firebaseDependencies,o)}async function EP(e){var t=await gP(e.firebaseDependencies);t&&(await yP(e.firebaseDependencies,t.token),await async function(e){var t=vP(e);const n=await fP(),r=n.transaction(dP,"readwrite");await r.objectStore(dP).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function CP(e,t){var n={token:await async function(e,t){var n=await bP(e),r=IP(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(wP(e.appConfig),r);i=await s.json()}catch(e){throw _P.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw _P.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw _P.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await mP(e,n),n.token}async function SP(e,t){var n=function(e,t){var n;const r={};e.from&&(r.project_number=e.from);e.fcmMessageId&&(r.message_id=e.fcmMessageId);r.instance_id=t,e.notification?r.message_type=lR.DISPLAY_NOTIFICATION.toString():r.message_type=lR.DATA_MESSAGE.toString();r.sdk_platform=iP.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=sP.toString(),null!==(n=e.fcmOptions)&&void 0!==n&&n.analytics_label&&(r.analytics_label=null===(n=e.fcmOptions)||void 0===n?void 0:n.analytics_label);return r}(t,await e.firebaseDependencies.installations.getId());!function(e,t){const n={};n.event_time_ms=Math.floor(Date.now()).toString(),n.source_extension_json_proto3=JSON.stringify(t),e.logEvents.push(n)}(e,n)}function kP(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}async function AP(e,t){var n=function({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(n){t.deliveryMetricsExportedToBigQueryEnabled&&await SP(t,n);var r,i,s,a,o=await RP();if(o.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=uR.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(o,n);n.notification&&await function(e){var t=e["actions"],n=Notification["maxActions"];t&&n&&t.length>n&&console.warn(`This browser only supports ${n} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(null!==(n=e.title)&&void 0!==n?n:"",e)}(function(e){const t=Object.assign({},e.notification);return t.data={[nP]:e},t}(n)),t&&t.onBackgroundMessageHandler&&(a={from:(r=n).from,collapseKey:r.collapse_key,messageId:r.fcmMessageId},o=a,(e=r).notification&&(o.notification={},(n=e.notification.title)&&(o.notification.title=n),(n=e.notification.body)&&(o.notification.body=n),(n=e.notification.image)&&(o.notification.image=n),(n=e.notification.icon)&&(o.notification.icon=n)),e=a,(o=r).data&&(e.data=o.data),o=a,((r=r).fcmOptions||null!==(i=r.notification)&&void 0!==i&&i.click_action)&&(o.fcmOptions={},(s=null!==(i=null===(i=r.fcmOptions)||void 0===i?void 0:i.link)&&void 0!==i?i:null===(s=r.notification)||void 0===s?void 0:s.click_action)&&(o.fcmOptions.link=s),(s=null===(s=r.fcmOptions)||void 0===s?void 0:s.analytics_label)&&(o.fcmOptions.analyticsLabel=s)),a=a,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(a):t.onBackgroundMessageHandler.next(a))}}async function NP(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[nP];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var n=function(e){var t;var n=null!==(t=null===(t=e.fcmOptions)||void 0===t?void 0:t.link)&&void 0!==t?t:null===(n=e.notification)||void 0===n?void 0:n.click_action;if(n)return n;return function(e){return"object"==typeof e&&e&&rP in e}(e.data)?self.location.origin:null}(t);if(n){var r,i=new URL(n,self.location.href),s=new URL(self.location.origin);if(i.host===s.host){let e=await async function(e){var t=await RP();for(const r of t){var n=new URL(r.url,self.location.href);if(e.host===n.host)return r}return null}(i);if(e?e=await e.focus():(e=await self.clients.openWindow(n),r=3e3,await new Promise(e=>{setTimeout(e,r)})),e)return t.messageType=uR.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function RP(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function PP(e){return _P.create("missing-app-config-values",{valueName:e})}kP("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),kP("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class DP{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw PP("App Configuration Object");if(!e.name)throw PP("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw PP(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}const xP=e=>{const t=new DP(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(AP(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await gP(t.firebaseDependencies),await EP(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:eP,await TP(t)):await EP(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(NP(e))}),t};function OP(e,t){return function(e,t){if(void 0!==self.document)throw _P.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=oe(e),t)}Ge(new ce("messaging-sw",xP,"PUBLIC"));var MP,LP,FP,UP;class VP{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return WR(e=oe(e),t)}(this._delegate,e)}async deleteToken(){return XR(this._delegate)}onMessage(e){return ZR(this._delegate,e)}onBackgroundMessage(e){return OP(this._delegate,e)}}const qP=e=>self&&"ServiceWorkerGlobalScope"in self?new VP(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new VP(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),jP={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?A()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&A()&&R()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};bt.INTERNAL.registerComponent(new ce("messaging-compat",qP,"PUBLIC").setServiceProps(jP)),bt.registerVersion("@firebase/messaging-compat","0.2.4");const BP="firebasestorage.googleapis.com",zP="storageBucket";class $P extends P{constructor(e,t,n=0){super(KP(e),`Firebase Storage: ${t} (${KP(e)})`),this.status_=n,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,$P.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return KP(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}function KP(e){return"storage/"+e}function WP(){return new $P(MP.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function GP(){return new $P(MP.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function HP(){return new $P(MP.CANCELED,"User canceled the upload/download.")}function QP(){return new $P(MP.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function YP(e){return new $P(MP.INVALID_ARGUMENT,e)}function JP(){return new $P(MP.APP_DELETED,"The Firebase app was deleted.")}function XP(e){return new $P(MP.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function ZP(e,t){return new $P(MP.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function eD(e){throw new $P(MP.INTERNAL_ERROR,"Internal error: "+e)}(Tt=MP=MP||{}).UNKNOWN="unknown",Tt.OBJECT_NOT_FOUND="object-not-found",Tt.BUCKET_NOT_FOUND="bucket-not-found",Tt.PROJECT_NOT_FOUND="project-not-found",Tt.QUOTA_EXCEEDED="quota-exceeded",Tt.UNAUTHENTICATED="unauthenticated",Tt.UNAUTHORIZED="unauthorized",Tt.UNAUTHORIZED_APP="unauthorized-app",Tt.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",Tt.INVALID_CHECKSUM="invalid-checksum",Tt.CANCELED="canceled",Tt.INVALID_EVENT_NAME="invalid-event-name",Tt.INVALID_URL="invalid-url",Tt.INVALID_DEFAULT_BUCKET="invalid-default-bucket",Tt.NO_DEFAULT_BUCKET="no-default-bucket",Tt.CANNOT_SLICE_BLOB="cannot-slice-blob",Tt.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",Tt.NO_DOWNLOAD_URL="no-download-url",Tt.INVALID_ARGUMENT="invalid-argument",Tt.INVALID_ARGUMENT_COUNT="invalid-argument-count",Tt.APP_DELETED="app-deleted",Tt.INVALID_ROOT_OPERATION="invalid-root-operation",Tt.INVALID_FORMAT="invalid-format",Tt.INTERNAL_ERROR="internal-error",Tt.UNSUPPORTED_ENVIRONMENT="unsupported-environment";class tD{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let n;try{n=tD.makeFromUrl(t,e)}catch(e){return new tD(t,"")}if(""===n.path)return n;throw t=t,new $P(MP.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+t+"'.")}static makeFromUrl(e,t){let n=null;var r="([A-Za-z0-9.\\-_]+)";var i=new RegExp("^gs://"+r+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}var a=t.replace(/[.]/g,"\\."),o=new RegExp(`^https?://${a}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),a=t===BP?"(?:storage.googleapis.com|storage.cloud.google.com)":t,c=[{regex:i,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:o,indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${a}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let h=0;h<c.length;h++){const d=c[h];var l=d.regex.exec(e);if(l){var u=l[d.indices.bucket];let e=l[d.indices.path];e=e||"",n=new tD(u,e),d.postModify(n);break}}if(null==n)throw t=e,new $P(MP.INVALID_URL,"Invalid URL '"+t+"'.");return n}}class nD{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function rD(e){return"string"==typeof e||e instanceof String}function iD(e){return sD()&&e instanceof Blob}function sD(){return"undefined"!=typeof Blob&&!T()}function aD(e,t,n,r){if(r<t)throw YP(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw YP(`Invalid value for '${e}'. Expected ${n} or less.`)}function oD(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function cD(e){const t=encodeURIComponent;let n="?";for(const i in e){var r;e.hasOwnProperty(i)&&(r=t(i)+"="+t(e[i]),n=n+r+"&")}return n=n.slice(0,-1),n}function lD(e,t){var n=500<=e&&e<600,r=-1!==[408,429].indexOf(e),i=-1!==t.indexOf(e);return n||r||i}(Tt=LP=LP||{})[Tt.NO_ERROR=0]="NO_ERROR",Tt[Tt.NETWORK_ERROR=1]="NETWORK_ERROR",Tt[Tt.ABORT=2]="ABORT";class uD{constructor(e,t,n,r,i,s,a,o,c,l,u,h=!0){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=a,this.errorCallback_=o,this.timeout_=c,this.progressCallback_=l,this.connectionFactory_=u,this.retry=h,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()})}start_(){var e=(n,e)=>{if(e)n(!1,new hD(!1,null,!0));else{const r=this.connectionFactory_();this.pendingConnection_=r;const i=e=>{var t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&r.addUploadProgressListener(i),r.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&r.removeUploadProgressListener(i),this.pendingConnection_=null;var e=r.getErrorCode()===LP.NO_ERROR,t=r.getStatus();!e||lD(t,this.additionalRetryCodes_)&&this.retry?(e=r.getErrorCode()===LP.ABORT,n(!1,new hD(!1,null,e))):(t=-1!==this.successCodes_.indexOf(t),n(!0,new hD(t,r)))})}},t=(e,t)=>{const n=this.resolve_,r=this.reject_,i=t.connection;if(t.wasSuccessCode)try{var s=this.callback_(i,i.getResponse());void 0!==s?n(s):n()}catch(e){r(e)}else if(null!==i){const o=WP();o.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,o)):r(o)}else{var a;t.canceled?(a=(this.appDelete_?JP:HP)(),r(a)):(a=GP(),r(a))}};this.canceled_?t(0,new hD(!1,null,!0)):this.backoffId_=function(t,n,e){let r=1,i=null,s=null,a=!1,o=0;function c(){return 2===o}let l=!1;function u(...e){l||(l=!0,n.apply(null,e))}function h(e){i=setTimeout(()=>{i=null,t(p,c())},e)}function d(){s&&clearTimeout(s)}function p(t,...n){if(l)d();else{if(t)return d(),void u.call(null,t,...n);if(c()||a)return d(),void u.call(null,t,...n);r<64&&(r*=2);let e;e=1===o?(o=2,0):1e3*(r+Math.random()),h(e)}}let f=!1;function g(e){f||(f=!0,d(),l||(null!==i?(e||(o=2),clearTimeout(i),h(0)):e||(o=1)))}return h(0),s=setTimeout(()=>{g(a=!0)},e),g}(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class hD{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function dD(...t){const n="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==n){const r=new n;for(let e=0;e<t.length;e++)r.append(t[e]);return r.getBlob()}if(sD())return new Blob(t);throw new $P(MP.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function pD(e){if("undefined"==typeof atob)throw new $P(MP.UNSUPPORTED_ENVIRONMENT,"base-64 is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.");return atob(e)}const fD={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class gD{constructor(e,t){this.data=e,this.contentType=t||null}}function mD(e,t){switch(e){case fD.RAW:return new gD(vD(t));case fD.BASE64:case fD.BASE64URL:return new gD(_D(e,t));case fD.DATA_URL:return new gD((n=t,(r=new yD(n)).base64?_D(fD.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw ZP(fD.DATA_URL,"Malformed data URL.")}return vD(t)}(r.rest)),(n=t,new yD(n).contentType))}var n,r;throw WP()}function vD(t){const n=[];for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);var r,i;e<=127?n.push(e):e<=2047?n.push(192|e>>6,128|63&e):55296==(64512&e)?s<t.length-1&&56320==(64512&t.charCodeAt(s+1))?(r=e,i=t.charCodeAt(++s),e=65536|(1023&r)<<10|1023&i,n.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):n.push(239,191,189):56320==(64512&e)?n.push(239,191,189):n.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(n)}function _D(t,e){switch(t){case fD.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw ZP(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case fD.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw ZP(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=pD(e)}catch(e){if(e.message.includes("polyfill"))throw e;throw ZP(t,"Invalid character found")}const s=new Uint8Array(i.length);for(let a=0;a<i.length;a++)s[a]=i.charCodeAt(a);return s}class yD{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw ZP(fD.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const i=r[1]||null;null!=i&&(this.base64=(t=i,n=";base64",t.length>=n.length&&t.substring(t.length-n.length)===n),this.contentType=this.base64?i.substring(0,i.length-";base64".length):i),this.rest=e.substring(e.indexOf(",")+1)}}class wD{constructor(e,t){let n=0,r="";iD(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(iD(this.data_)){var n=this.data_,n=(i=e,s=t,(r=n).webkitSlice?r.webkitSlice(i,s):r.mozSlice?r.mozSlice(i,s):r.slice?r.slice(i,s):null);return null===n?null:new wD(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new wD(n,!0)}static getBlob(...e){if(sD()){var t=e.map(e=>e instanceof wD?e.data_:e);return new wD(dD.apply(null,t))}{const r=e.map(e=>rD(e)?mD(fD.RAW,e).data:e.data_);let t=0;r.forEach(e=>{t+=e.byteLength});const i=new Uint8Array(t);let n=0;return r.forEach(e=>{for(let t=0;t<e.length;t++)i[n++]=e[t]}),new wD(i,!0)}}uploadData(){return this.data_}}function bD(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function ID(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function TD(e,t){return t}class ED{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||TD}}let CD=null;function SD(){if(CD)return CD;const e=[];e.push(new ED("bucket")),e.push(new ED("generation")),e.push(new ED("metageneration")),e.push(new ED("name","fullPath",!0));const t=new ED("name");t.xform=function(e,t){return!rD(t=t)||t.length<2?t:ID(t)},e.push(t);const n=new ED("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new ED("timeCreated")),e.push(new ED("updated")),e.push(new ED("md5Hash",null,!0)),e.push(new ED("cacheControl",null,!0)),e.push(new ED("contentDisposition",null,!0)),e.push(new ED("contentEncoding",null,!0)),e.push(new ED("contentLanguage",null,!0)),e.push(new ED("contentType",null,!0)),e.push(new ED("metadata","customMetadata",!0)),CD=e,CD}function kD(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new tD(e,t);return r._makeStorageReference(t)}})}function AD(e,t,n){var r=bD(t);return null===r?null:function(e,t,n){const r={type:"file"};var i=n.length;for(let s=0;s<i;s++){const a=n[s];r[a.local]=a.xform(r,t[a.server])}return kD(r,e),r}(e,r,n)}function ND(e,t){const n={};var r=t.length;for(let s=0;s<r;s++){var i=t[s];i.writable&&(n[i.server]=e[i.local])}return JSON.stringify(n)}const RD="prefixes";function PD(e,t,n){var r=bD(n);return null===r?null:function(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n[RD])for(const a of n[RD]){var i=a.replace(/\/$/,""),i=e._makeStorageReference(new tD(t,i));r.prefixes.push(i)}if(n.items)for(const o of n.items){var s=e._makeStorageReference(new tD(t,o.name));r.items.push(s)}return r}(e,t,r)}class DD{constructor(e,t,n,r){this.url=e,this.method=t,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function xD(e){if(!e)throw WP()}function OD(r,i){return function(e,t){var n=AD(r,t,i);return xD(null!==n),n}}function MD(r,i){return function(e,t){var n=PD(r,i,t);return xD(null!==n),n}}function LD(r,i){return function(e,t){var n=AD(r,t,i);return xD(null!==n),function(r,e,i,s){var t=bD(e);if(null===t)return null;if(!rD(t.downloadTokens))return null;const n=t.downloadTokens;if(0===n.length)return null;const a=encodeURIComponent,o=n.split(",");return o.map(e=>{var t=r.bucket,n=r.fullPath;return oD("/b/"+a(t)+"/o/"+a(n),i,s)+cD({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function FD(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new $P(MP.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project."):new $P(MP.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new $P(MP.QUOTA_EXCEEDED,"Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(r=i.path,new $P(MP.UNAUTHORIZED,"User does not have permission to access '"+r+"'.")):t,n.status=e.getStatus(),n.serverResponse=t.serverResponse,n}}function UD(r){const i=FD(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new $P(MP.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function VD(e,t,n){var r=oD(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new DD(r,"GET",OD(e,n),i);return s.errorHandler=UD(t),s}function qD(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=(e=t,(t=null)&&t.contentType||e&&e.type()||"application/octet-stream")),r}function jD(e,t,n,r,i){var s=t.bucketOnlyServerUrl();const a={"X-Goog-Upload-Protocol":"multipart"};var o=function(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();a["Content-Type"]="multipart/related; boundary="+o;var c=qD(t,r,i),l="--"+o+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+ND(c,n)+"\r\n--"+o+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",o="\r\n--"+o+"--";const u=wD.getBlob(l,r,o);if(null===u)throw QP();o={name:c.fullPath},c=oD(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new DD(c,"POST",OD(e,n),s);return h.urlParams=o,h.headers=a,h.body=u.uploadData(),h.errorHandler=FD(t),h}class BD{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function zD(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){xD(!1)}const r=t||["active"];return xD(!!n&&-1!==r.indexOf(n)),n}function $D(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),a=qD(t,r,i),o={name:a.fullPath},c=oD(s,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},s=ND(a,n),a=e.maxUploadRetryTime;const u=new DD(c,"POST",function(e){zD(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){xD(!1)}return xD(rD(t)),t},a);return u.urlParams=o,u.headers=l,u.body=s,u.errorHandler=FD(t),u}function KD(e,t,n,i){var r=e.maxUploadRetryTime;const s=new DD(n,"POST",function(e){var t=zD(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){xD(!1)}n||xD(!1);var r=Number(n);return xD(!isNaN(r)),new BD(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=FD(t),s}function WD(e,a,t,o,n,c,r,i){const l=new BD(0,0);if(r?(l.current=r.current,l.total=r.total):(l.current=0,l.total=o.size()),o.size()!==l.total)throw new $P(MP.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var s=l.total-l.current;let u=s;0<n&&(u=Math.min(u,n));var h=l.current,d=h+u;let p="";p=0===u?"finalize":s===u?"upload, finalize":"upload";s={"X-Goog-Upload-Command":p,"X-Goog-Upload-Offset":`${l.current}`};const f=o.slice(h,d);if(null===f)throw QP();d=a.maxUploadRetryTime;const g=new DD(t,"POST",function(e,t){var n=zD(e,["active","final"]),r=l.current+u,i=o.size();let s;return s="final"===n?OD(a,c)(e,t):null,new BD(r,i,"final"===n,s)},d);return g.headers=s,g.body=f.uploadData(),g.progressCallback=i||null,g.errorHandler=FD(e),g}const GD={STATE_CHANGED:"state_changed"},HD={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function QD(e){switch(e){case"running":case"pausing":case"canceling":return HD.RUNNING;case"paused":return HD.PAUSED;case"success":return HD.SUCCESS;case"canceled":return HD.CANCELED;default:return HD.ERROR}}class YD{constructor(e,t,n){var r;"function"==typeof e||null!=t||null!=n?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0):(this.next=(r=e).next,this.error=r.error,this.complete=r.complete)}}function JD(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class XD extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=LP.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=LP.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=LP.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw eD("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const i in r)r.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,r[i].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw eD("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw eD("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw eD("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw eD("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}{initXhr(){this.xhr_.responseType="text"}}function ZD(){return new XD}class ex{constructor(e,t,n=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=n,this._mappings=SD(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(MP.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{var t=this.isExponentialBackoffExpired();if(lD(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=GP()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(MP.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t,this._start()}),this._promise.then(null,()=>{})}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){const t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(n){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":n(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var n=$D(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,ZD,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const i=this._uploadUrl;this._resolveToken((e,t)=>{var n=KD(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,ZD,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){const i=262144*this._chunkMultiplier,s=new BD(this._transferred,this._blob.size()),a=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=WD(this._ref._location,this._ref.storage,a,this._blob,i,this._mappings,s,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const r=this._ref.storage._makeRequest(n,ZD,e,t,!1);this._request=r,r.getPromise().then(e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){2*(262144*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{var n=VD(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,ZD,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var n=jD(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,ZD,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=HP(),this._state=e,this._notifyObservers();break;case"error":case"success":this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){var e=QD(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const i=new YD(t||void 0,n||void 0,r||void 0);return this._addObserver(i),()=>{this._removeObserver(i)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){var t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();const e=this._observers.slice();e.forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(QD(this._state)){case HD.SUCCESS:JD(this._resolve.bind(null,this.snapshot))();break;case HD.CANCELED:case HD.ERROR:const t=this._reject;JD(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(QD(this._state)){case HD.RUNNING:case HD.PAUSED:e.next&&JD(e.next.bind(e,this.snapshot))();break;case HD.SUCCESS:e.complete&&JD(e.complete.bind(e))();break;case HD.CANCELED:case HD.ERROR:default:e.error&&JD(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class tx{constructor(e,t){this._service=e,t instanceof tD?this._location=t:this._location=tD.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new tx(e,t)}get root(){var e=new tD(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return ID(this._location.path)}get storage(){return this._service}get parent(){var e=function(e){if(0===e.length)return null;var t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;e=new tD(this._location.bucket,e);return new tx(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw XP(e)}}function nx(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await rx(t,i);n.prefixes.push(...s.prefixes);n.items.push(...s.items);null!=s.nextPageToken&&await e(t,n,s.nextPageToken)}(e,t).then(()=>t)}function rx(e,t){null!=t&&"number"==typeof t.maxResults&&aD("options.maxResults",1,1e3,t.maxResults);var n=t||{},n=function(e,t,n,r,i){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&0<n.length&&(s.delimiter=n),r&&(s.pageToken=r),i&&(s.maxResults=i);var a=oD(t.bucketOnlyServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime;const c=new DD(a,"GET",MD(e,t.bucket),o);return c.urlParams=s,c.errorHandler=FD(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,ZD)}function ix(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=oD(t.fullServerUrl(),e.host,e._protocol),s=ND(n,r),a=e.maxOperationRetryTime;const o=new DD(i,"PATCH",OD(e,r),a);return o.headers={"Content-Type":"application/json; charset=utf-8"},o.body=s,o.errorHandler=UD(t),o}(e.storage,e._location,t,SD());return e.storage.makeRequestWithTokens(n,ZD)}function sx(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=oD(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new DD(r,"GET",LD(e,n),i);return s.errorHandler=UD(t),s}(e.storage,e._location,SD());return e.storage.makeRequestWithTokens(t,ZD).then(e=>{if(null===e)throw new $P(MP.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return e})}function ax(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=oD(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new DD(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=UD(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,ZD)}function ox(e,t){var n,r=(n=e._location.path,r=t.split("/").filter(e=>0<e.length).join("/"),0===n.length?r:n+"/"+r),r=new tD(e._location.bucket,r);return new tx(e.storage,r)}function cx(e,t){if(e instanceof hx){var n=e;if(null==n._bucket)throw new $P(MP.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+zP+"' property when initializing the app?");n=new tx(n,n._bucket);return null!=t?cx(n,t):n}return void 0!==t?ox(e,t):e}function lx(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof hx)return n=e,r=t,new tx(n,r);throw YP("To use ref(service, url), the first argument must be a Storage instance.")}return cx(e,t);var n,r}function ux(e,t){var n=null==t?void 0:t[zP];return null==n?null:tD.makeFromBucketSpec(n,e)}class hx{constructor(e,t,n,r,i){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=i,this._bucket=null,this._host=BP,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?tD.makeFromBucketSpec(r,this._host):ux(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=tD.makeFromBucketSpec(this._url,e):this._bucket=ux(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){aD("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){aD("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){var t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new tx(this,e)}_makeRequest(e,t,n,r,i=!0){if(this._deleted)return new nD(JP());{const u=([s,a,o,e,n,r,t=!0]=[e,this._appId,n,r,t,this._firebaseVersion,i],c=cD(s.urlParams),l=s.url+c,c=Object.assign({},s.headers),i=c,(a=a)&&(i["X-Firebase-GMPID"]=a),a=c,null!==(o=o)&&0<o.length&&(a.Authorization="Firebase "+o),r=r,c["X-Firebase-Storage-Version"]="webjs/"+(null!=r?r:"AppManager"),r=c,null!==(e=e)&&(r["X-Firebase-AppCheck"]=e),new uD(l,s.method,c,s.body,s.successCodes,s.additionalRetryCodes,s.handler,s.errorHandler,s.timeout,s.progressCallback,n,t));return this._requests.add(u),u.getPromise().then(()=>this._requests.delete(u),()=>this._requests.delete(u)),u}var s,a,o,c,l}async makeRequestWithTokens(e,t){var[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const dx="@firebase/storage";function px(e,t,n){return e=oe(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new ex(e,new wD(t),n)}function fx(e){return function(e){e._throwIfRoot("getMetadata");var t=VD(e.storage,e._location,SD());return e.storage.makeRequestWithTokens(t,ZD)}(e=oe(e))}function gx(e,t){return lx(e=oe(e),t)}function mx(e,t,n,r={}){!function(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";var i=r["mockUserToken"];i&&(e._overrideAuthToken="string"==typeof i?i:w(i,e.app.options.projectId))}(e,t,n,r)}function vx(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new hx(n,r,i,t,Je)}Ge(new ce("storage",vx,"PUBLIC").setMultipleInstances(!0)),tt(dx,"0.11.2",""),tt(dx,"0.11.2","esm2017");class _x{constructor(e,t,n){this._delegate=e,this.task=t,this.ref=n}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class yx{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new _x(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new _x(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new _x(e,this,this._ref)):{next:t.next?e=>t.next(new _x(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,n||void 0,r||void 0)}}class wx{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new bx(e,this._service))}get items(){return this._delegate.items.map(e=>new bx(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class bx{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=ox(this._delegate,e);return new bx(t,this.storage)}get root(){return new bx(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new bx(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new yx(px(this._delegate,e,t),this)}putString(e,t=fD.RAW,n){this._throwIfRoot("putString");var r=mD(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new yx(new ex(this._delegate,new wD(r.data,!0),i),this)}listAll(){return nx(oe(this._delegate)).then(e=>new wx(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,rx(t=oe(t),e).then(e=>new wx(e,this.storage));var t}getMetadata(){return fx(this._delegate)}updateMetadata(e){return ix(oe(this._delegate),e)}getDownloadURL(){return sx(oe(this._delegate))}delete(){return this._throwIfRoot("delete"),ax(oe(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw XP(e)}}class Ix{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(Tx(e))throw YP("ref() expected a child path but got a URL, use refFromURL instead.");return new bx(gx(this._delegate,e),this)}refFromURL(e){if(!Tx(e))throw YP("refFromURL() expected a full URL but got a child path, use ref() instead.");try{tD.makeFromUrl(e,this._delegate.host)}catch(e){throw YP("refFromUrl() expected a valid full URL but got an invalid one.")}return new bx(gx(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){mx(this._delegate,e,t,n)}}function Tx(e){return/^[A-Za-z]+:\/\//.test(e)}function Ex(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new Ix(n,r)}FP=bt,UP={TaskState:HD,TaskEvent:GD,StringFormat:fD,Storage:Ix,Reference:bx},FP.INTERNAL.registerComponent(new ce("storage-compat",Ex,"PUBLIC").setServiceProps(UP).setMultipleInstances(!0)),FP.registerVersion("@firebase/storage-compat","0.3.2");const Cx="@firebase/performance",Sx="0.6.4",kx=Sx,Ax="FB-PERF-TRACE-MEASURE",Nx="@firebase/performance/config",Rx="@firebase/performance/configexpire";var Px,Dx,xx,Ox="Performance";const Mx=new D("performance",Ox,{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"initializePerformance() has already been called with different options. To avoid this error, call initializePerformance() with the same options as when it was originally called, or call getPerformance() to return the already initialized instance."}),Lx=new ve(Ox);Lx.logLevel=m.INFO;let Fx,Ux;class Vx{constructor(e){if(!(this.window=e))throw Mx.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)}getEntriesByType(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]}getEntriesByName(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&R()?!!A()||(Lx.info("IndexedDB is not supported by current browser"),!1):(Lx.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,n){if(this.PerformanceObserver){const t=new this.PerformanceObserver(e=>{for(const t of e.getEntries())n(t)});t.observe({entryTypes:[e]})}}static getInstance(){return void 0===Fx&&(Fx=new Vx(Ux)),Fx}}let qx;function jx(e,t){var n=e.length-t.length;if(n<0||1<n)throw Mx.create("invalid String merger input");const r=[];for(let i=0;i<e.length;i++)r.push(e.charAt(i)),t.length>i&&r.push(t.charAt(i));return r.join("")}let Bx;class zx{constructor(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=jx("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=jx("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===Bx&&(Bx=new zx),Bx}}(Tt=Px=Px||{})[Tt.UNKNOWN=0]="UNKNOWN",Tt[Tt.VISIBLE=1]="VISIBLE",Tt[Tt.HIDDEN=2]="HIDDEN";const $x=["firebase_","google_","ga_"],Kx=new RegExp("^[a-zA-Z]\\w*$");function Wx(){switch(Vx.getInstance().document.visibilityState){case"visible":return Px.VISIBLE;case"hidden":return Px.HIDDEN;default:return Px.UNKNOWN}}function Gx(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw Mx.create("no app id");return t}const Hx="0.0.1",Qx={loggingEnabled:!0},Yx="FIREBASE_INSTALLATIONS_AUTH";function Jx(e,t){var r,i,n=function(){const e=Vx.getInstance().localStorage;if(e){var t=e.getItem(Rx);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(Nx);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?(Zx(n),Promise.resolve()):(i=t,function(e){const t=e.getToken();return t.then(e=>{}),t}((r=e).installations).then(e=>{var t=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.projectId;if(!t)throw Mx.create("no project id");return t}(r.app),n=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.apiKey;if(!t)throw Mx.create("no api key");return t}(r.app),n=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${t}/namespaces/fireperf:fetch?key=${n}`,{method:"POST",headers:{Authorization:`${Yx} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:Gx(r.app),app_version:kx,sdk_version:Hx})});return fetch(n).then(e=>{if(e.ok)return e.json();throw Mx.create("RC response not ok")})}).catch(()=>{Lx.info(Xx)}).then(Zx).then(e=>function(e){const t=Vx.getInstance().localStorage;e&&t&&(t.setItem(Nx,JSON.stringify(e)),t.setItem(Rx,String(Date.now()+60*zx.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const Xx="Could not fetch config, will use default configs";function Zx(e){if(!e)return e;const t=zx.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=Qx.loggingEnabled,n.fpr_log_source?t.logSource=Number(n.fpr_log_source):Qx.logSource&&(t.logSource=Qx.logSource),n.fpr_log_endpoint_url?t.logEndPointUrl=n.fpr_log_endpoint_url:Qx.logEndPointUrl&&(t.logEndPointUrl=Qx.logEndPointUrl),n.fpr_log_transport_key?t.transportKey=n.fpr_log_transport_key:Qx.transportKey&&(t.transportKey=Qx.transportKey),void 0!==n.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate):void 0!==Qx.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=Qx.networkRequestsSamplingRate),void 0!==n.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate):void 0!==Qx.tracesSamplingRate&&(t.tracesSamplingRate=Qx.tracesSamplingRate),t.logTraceAfterSampling=e1(t.tracesSamplingRate),t.logNetworkAfterSampling=e1(t.networkRequestsSamplingRate),e}function e1(e){return Math.random()<=e}let t1=1,n1;function r1(e){var t;return t1=2,n1=n1||(t=e,function(){const n=Vx.getInstance().document;return new Promise(e=>{if(n&&"complete"!==n.readyState){const t=()=>{"complete"===n.readyState&&(n.removeEventListener("readystatechange",t),e())};n.addEventListener("readystatechange",t)}else e()})}().then(()=>function(e){const t=e.getId();return t.then(e=>{qx=e}),t}(t.installations)).then(e=>Jx(t,e)).then(()=>i1(),()=>i1())),n1}function i1(){t1=3}const s1=1e4,a1=3,o1=1e3;let c1=a1,l1=[],u1=!1;function h1(e){setTimeout(()=>{if(0!==c1)return l1.length?void function(){const e=l1.splice(0,o1),t=e.map(e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)})),n={request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:zx.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=zx.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||Lx.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=s1;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(l1=[...r,...l1],Lx.info("Retry transport request later.")),c1=a1,h1(n)})}(n,e).catch(()=>{l1=[...e,...l1],c1--,Lx.info(`Tries left: ${c1}.`),h1(s1)})}():h1(s1)},e)}function d1(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw Mx.create("invalid cc log");l1=[...l1,e]}({message:t(...e),eventTime:Date.now()})}}let p1;function f1(e,t){p1=p1||d1(v1),p1(e,t)}function g1(e){var t=zx.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&Vx.getInstance().requiredApisAvailable()&&(e.isAuto&&Wx()!==Px.VISIBLE||(3===t1?m1(e):r1(e.performanceController).then(()=>m1(e),()=>m1(e))))}function m1(e){var t;!qx||(t=zx.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>f1(e,1),0)}function v1(e,t){return 0===t?(n={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},n={application_info:_1(e.performanceController.app),network_request_metric:n},JSON.stringify(n)):function(e){const t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);var n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);n={application_info:_1(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function _1(e){return{google_app_id:Gx(e),app_instance_id:qx,web_app_info:{sdk_version:kx,page_url:Vx.getInstance().getUrl(),service_worker_status:null!=(t=Vx.getInstance().navigator)&&t.serviceWorker?t.serviceWorker.controller?2:3:1,visibility_state:Wx(),effective_connection_type:function(){var e=Vx.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}()},application_process_state:0};var t}const y1=["_fp","_fcp","_fid"];class w1{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=Vx.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark=`FB-PERF-TRACE-START-${this.randomId}-${this.name}`,this.traceStopMark=`FB-PERF-TRACE-STOP-${this.randomId}-${this.name}`,this.traceMeasure=r||`${Ax}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw Mx.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw Mx.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),g1(this)}record(e,t,n){if(e<=0)throw Mx.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw Mx.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const r of Object.keys(n.metrics))isNaN(Number(n.metrics[r]))||(this.counters[r]=Math.floor(Number(n.metrics[r])));g1(this)}incrementMetric(e,t=1){void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)}putMetric(e,t){if(r=e,i=this.name,0===r.length||100<r.length||!(i&&i.startsWith("_wt_")&&-1<y1.indexOf(r))&&r.startsWith("_"))throw Mx.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=null!=t?t:0,(n=Math.floor(t))<t&&Lx.info(`Metric value should be an Integer, setting the value as : ${n}.`),n)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){var n,r,i=!(0===(n=e).length||40<n.length)&&(!$x.some(e=>n.startsWith(e))&&!!n.match(Kx)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw Mx.create("invalid attribute name",{attributeName:e});if(!s)throw Mx.create("invalid attribute value",{attributeValue:t})}}getAttribute(e){return this.customAttributes[e]}removeAttribute(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]}getAttributes(){return Object.assign({},this.customAttributes)}setStartTime(e){this.startTimeUs=e}setDuration(e){this.durationUs=e}calculateTraceMetrics(){var e=this.api.getEntriesByName(this.traceMeasure),e=e&&e[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))}static createOobTrace(e,t,n,r){var i=Vx.getInstance().getUrl();if(i){const s=new w1(e,"_wt_"+i,!0);i=Math.floor(1e3*Vx.getInstance().getTimeOrigin());s.setStartTime(i),t&&t[0]&&(s.setDuration(Math.floor(1e3*t[0].duration)),s.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),s.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),s.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));n&&((i=n.find(e=>"first-paint"===e.name))&&i.startTime&&s.putMetric("_fp",Math.floor(1e3*i.startTime)),(i=n.find(e=>"first-contentful-paint"===e.name))&&i.startTime&&s.putMetric("_fcp",Math.floor(1e3*i.startTime)),r&&s.putMetric("_fid",Math.floor(1e3*r))),g1(s)}}static createUserTimingTrace(e,t){g1(new w1(e,t,!1,t))}}function b1(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=Vx.getInstance().getTimeOrigin(),r=Math.floor(1e3*(n.startTime+s)),i=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,s=Math.floor(1e3*(n.responseEnd-n.startTime)),function(e){const t=zx.getInstance();var n,r,i;t.instrumentationEnabled&&(n=e.url,r=t.logEndPointUrl.split("?")[0],i=t.flTransportEndpointUrl.split("?")[0],n!==r&&n!==i&&t.loggingEnabled&&t.logNetworkAfterSampling&&setTimeout(()=>f1(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const I1=5e3;function T1(e){qx&&(setTimeout(()=>function(n){const e=Vx.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{w1.createOobTrace(n,r,i),t=void 0},I1);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),w1.createOobTrace(n,r,i,e))})}else w1.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=Vx.getInstance(),n=e.getEntriesByType("resource");for(const r of n)b1(t,r);e.setupObserver("resource",e=>b1(t,e))}(e),0),setTimeout(()=>function(t){const e=Vx.getInstance(),n=e.getEntriesByType("measure");for(const r of n)E1(t,r);e.setupObserver("measure",e=>E1(t,e))}(e),0))}function E1(e,t){const n=t.name;n.substring(0,Ax.length)!==Ax&&w1.createUserTimingTrace(e,n)}class C1{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),Vx.getInstance().requiredApisAvailable()?N().then(e=>{e&&(u1||(h1(5500),u1=!0),r1(this).then(()=>T1(this),()=>T1(this)),this.initialized=!0)}).catch(e=>{Lx.info(`Environment doesn't support IndexedDB: ${e}`)}):Lx.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){zx.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return zx.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){zx.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return zx.getInstance().dataCollectionEnabled}}const S1="[DEFAULT]";const k1=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==S1)throw Mx.create("FB not default");if("undefined"==typeof window)throw Mx.create("no window");e=window,Ux=e;const i=new C1(n,r);return i._init(t),i};Ge(new ce("performance",k1,"PUBLIC")),tt(Cx,Sx),tt(Cx,Sx,"esm2017");class A1{constructor(e,t){this.app=e,this._delegate=t}get instrumentationEnabled(){return this._delegate.instrumentationEnabled}set instrumentationEnabled(e){this._delegate.instrumentationEnabled=e}get dataCollectionEnabled(){return this._delegate.dataCollectionEnabled}set dataCollectionEnabled(e){this._delegate.dataCollectionEnabled=e}trace(e){return t=this._delegate,e=e,t=oe(t),new w1(t,e);var t}}function N1(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new A1(t,n)}(Dx=bt).INTERNAL.registerComponent(new ce("performance-compat",N1,"PUBLIC")),Dx.registerVersion("@firebase/performance-compat","0.2.4");const R1="@firebase/remote-config";class P1{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const D1=new D("remoteconfig","Remote Config",{"registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser"});const x1=["1","true","t","yes","y","on"];class O1{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=x1.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}async function M1(e){const t=oe(e);var[n,r]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.eTag!==r)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.eTag)]),!0)}function L1(e){const t=oe(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function F1(t){const n=oe(t),e=new P1;setTimeout(async()=>{e.abort()},n.settings.fetchTimeoutMillis);try{await n._client.fetch({cacheMaxAgeMillis:n.settings.minimumFetchIntervalMillis,signal:e}),await n._storageCache.setLastFetchStatus("success")}catch(e){var r=(i="fetch-throttle",(t=e)instanceof P&&-1!==t.code.indexOf(i)?"throttle":"failure");throw await n._storageCache.setLastFetchStatus(r),e}var i}function U1(n){const e=oe(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=V1(n,t),e),{});var t,r}function V1(e,t){const n=oe(e);n._isInitializationComplete||n._logger.debug(`A value was requested for key "${t}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value.");var r=n._storageCache.getActiveConfig();return r&&void 0!==r[t]?new O1("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new O1("default",String(n.defaultConfig[t])):(n._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new O1("static"))}class q1{constructor(e,t,n,r){this.client=e,this.storage=t,this.storageCache=n,this.logger=r}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;var n=Date.now()-t,r=n<=e;return this.logger.debug("Config fetch cache check."+` Cache age millis: ${n}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${r}.`),r}async fetch(e){var[t,n]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(n&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return n;e.eTag=n&&n.eTag;n=await this.client.fetch(e);const r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===n.status&&r.push(this.storage.setLastSuccessfulFetchResponse(n)),await Promise.all(r),n}}class j1{constructor(e,t,n,r,i,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=r,this.apiKey=i,this.appId=s}async fetch(n){var e,[t,r]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,s={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":n.eTag||"*"},r={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:r,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language},r={method:"POST",headers:s,body:JSON.stringify(r)},i=fetch(i,r),r=new Promise((e,t)=>{n.signal.addEventListener(()=>{const e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let a;try{await Promise.race([i,r]),a=await i}catch(e){let t="fetch-client-network";throw"AbortError"===(null==e?void 0:e.name)&&(t="fetch-timeout"),D1.create(t,{originalErrorMessage:null==e?void 0:e.message})}let o=a.status;i=a.headers.get("ETag")||void 0;let c,l;if(200===a.status){let e;try{e=await a.json()}catch(e){throw D1.create("fetch-client-parse",{originalErrorMessage:null==e?void 0:e.message})}c=e.entries,l=e.state}if("INSTANCE_STATE_UNSPECIFIED"===l?o=500:"NO_CHANGE"===l?o=304:"NO_TEMPLATE"!==l&&"EMPTY_CONFIG"!==l||(c={}),304!==o&&200!==o)throw D1.create("fetch-status",{httpStatus:o});return{status:o,eTag:i,config:c}}}class B1{constructor(e,t){this.client=e,this.storage=t}async fetch(e){var t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:n}){var i,s;i=t.signal,s=e,await new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(D1.create("fetch-throttle",{throttleEndTimeMillis:s}))})});try{var r=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),r}catch(e){if(!function(e){if(e instanceof P&&e.customData){var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}}(e))throw e;r={throttleEndTimeMillis:Date.now()+ae(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class z1{constructor(e,t,n,r,i){this.app=e,this._client=t,this._storageCache=n,this._storage=r,this._logger=i,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function $1(e,t){var n=e.target.error||void 0;return D1.create(t,{originalErrorMessage:n&&(null==n?void 0:n.message)})}const K1="app_namespace_store";class W1{constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n($1(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(K1,{keyPath:"compositeKey"})}}catch(e){n(D1.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}})}()){this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=r}getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}async get(a){const o=await this.openDbPromise;return new Promise((n,t)=>{const e=o.transaction([K1],"readonly"),r=e.objectStore(K1);var i=this.createCompositeKey(a);try{const s=r.get(i);s.onerror=e=>{t($1(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(D1.create("storage-get",{originalErrorMessage:null==e?void 0:e.message}))}})}async set(a,o){const c=await this.openDbPromise;return new Promise((e,t)=>{const n=c.transaction([K1],"readwrite"),r=n.objectStore(K1);var i=this.createCompositeKey(a);try{const s=r.put({compositeKey:i,value:o});s.onerror=e=>{t($1(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(D1.create("storage-set",{originalErrorMessage:null==e?void 0:e.message}))}})}async delete(a){const o=await this.openDbPromise;return new Promise((e,t)=>{const n=o.transaction([K1],"readwrite"),r=n.objectStore(K1);var i=this.createCompositeKey(a);try{const s=r.delete(i);s.onerror=e=>{t($1(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(D1.create("storage-delete",{originalErrorMessage:null==e?void 0:e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class G1{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),n=this.storage.getActiveConfig(),e=await e;e&&(this.lastFetchStatus=e);t=await t;t&&(this.lastSuccessfulFetchTimestampMillis=t);n=await n;n&&(this.activeConfig=n)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}}async function H1(){if(!A())return!1;try{return await N()}catch(e){return!1}}Ge(new ce("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw D1.create("registration-window");if(!A())throw D1.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:a}=n.options;if(!i)throw D1.create("registration-project-id");if(!s)throw D1.create("registration-api-key");if(!a)throw D1.create("registration-app-id");t=t||"firebase";const o=new W1(a,n.name,t),c=new G1(o),l=new ve(R1);l.logLevel=m.ERROR;a=new j1(r,Je,t,i,s,a),a=new B1(a,o),a=new q1(a,o,c,l),a=new z1(n,a,c,o,l);return L1(a),a},"PUBLIC").setMultipleInstances(!0)),tt(R1,"0.4.4"),tt(R1,"0.4.4","esm2017");class Q1{constructor(e,t){this.app=e,this._delegate=t}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(e){this._delegate.defaultConfig=e}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(e){this._delegate.settings=e}activate(){return M1(this._delegate)}ensureInitialized(){return L1(this._delegate)}fetch(){return F1(this._delegate)}fetchAndActivate(){return async function(e){return await F1(e=oe(e)),M1(e)}(this._delegate)}getAll(){return U1(this._delegate)}getBoolean(e){return V1(oe(this._delegate),e).asBoolean()}getNumber(e){return V1(oe(this._delegate),e).asNumber()}getString(e){return V1(oe(this._delegate),e).asString()}getValue(e){return V1(this._delegate,e)}setLogLevel(e){!function(e,t){const n=oe(e);switch(t){case"debug":n._logger.logLevel=m.DEBUG;break;case"silent":n._logger.logLevel=m.SILENT;break;default:n._logger.logLevel=m.ERROR}}(this._delegate,e)}}function Y1(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new Q1(n,r)}return(xx=bt).INTERNAL.registerComponent(new ce("remoteConfig-compat",Y1,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:H1})),xx.registerVersion("@firebase/remote-config-compat","0.2.4"),console.warn("\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n"),bt.registerVersion("firebase","10.3.0","compat-cdn"),bt});
|
|
9
|
+
`)}const Ar={error:"UNKNOWN_ERROR"};async function Nr(e,t=!1){var n=e.app;cr(n);const r=tr(n);let i=r.token,s=void 0;if(i&&!Or(i)&&(r.token=void 0,i=void 0),i||(o=await r.cachedTokenPromise)&&(Or(o)?i=o:await Er(n,void 0)),!t&&i&&Or(i))return{token:i.token};let a=!1;if(kr()){r.exchangeTokenPromise||(r.exchangeTokenPromise=hr(dr(n,await Sr()),e.heartbeatServiceProvider).finally(()=>{r.exchangeTokenPromise=void 0}),a=!0);var o=await r.exchangeTokenPromise;return await Er(n,o),{token:(r.token=o).token}}try{r.exchangeTokenPromise||(r.exchangeTokenPromise=r.provider.getToken().finally(()=>{r.exchangeTokenPromise=void 0}),a=!0),i=await tr(n).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?Ir.warn(e.message):Ir.error(e),s=e}let c;return i?s?c=Or(i)?{token:i.token,internalError:s}:Mr(s):(c={token:i.token},r.token=i,await Er(n,i)):c=Mr(s),a&&xr(n,c),c}function Rr(e,t,n,r){var i=e["app"];const s=tr(i);i={next:n,error:r,type:t};if(s.tokenObservers=[...s.tokenObservers,i],s.token&&Or(s.token)){const a=s.token;Promise.resolve().then(()=>{n({token:a.token}),Dr(e)}).catch(()=>{})}s.cachedTokenPromise.then(()=>Dr(e))}function Pr(e,t){const n=tr(e);var r=n.tokenObservers.filter(e=>e.next!==t);0===r.length&&n.tokenRefresher&&n.tokenRefresher.isRunning()&&n.tokenRefresher.stop(),n.tokenObservers=r}function Dr(e){var t=e["app"];const n=tr(t);let r=n.tokenRefresher;r||(r=function(n){const r=n["app"];return new sr(async()=>{var e=tr(r);let t;if(t=e.token?await Nr(n,!0):await Nr(n),t.error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e=tr(r);if(e.token){var t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5,e=e.token.expireTimeMillis-3e5,t=Math.min(t,e);return Math.max(0,t-Date.now())}return 0},ir.RETRIAL_MIN_WAIT,ir.RETRIAL_MAX_WAIT)}(e),n.tokenRefresher=r),!r.isRunning()&&n.isTokenAutoRefreshEnabled&&r.start()}function xr(e,t){for(const n of tr(e).tokenObservers)try{"EXTERNAL"===n.type&&null!=t.error?n.error(t.error):n.next(t)}catch(e){}}function Or(e){return 0<e.expireTimeMillis-Date.now()}function Mr(e){return{token:(t=Ar,r.encodeString(JSON.stringify(t),!1)),error:e};var t}class Lr{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e=tr(this.app)["tokenObservers"];for(const t of e)Pr(this.app,t.next);return Promise.resolve()}}function Fr(t){return{getToken:e=>Nr(t,e),getLimitedUseToken:()=>async function(e){var t=e.app;cr(t);const n=tr(t)["provider"];if(kr()){var r=(await hr(dr(t,await Sr()),e.heartbeatServiceProvider))["token"];return{token:r}}return{token:r=(await n.getToken())["token"]}}(t),addTokenListener:e=>Rr(t,"INTERNAL",e),removeTokenListener:e=>Pr(t.app,e)}}const Ur="https://www.google.com/recaptcha/api.js",Vr="https://www.google.com/recaptcha/enterprise.js";function qr(t,n){const r=new y,e=tr(t);e.reCAPTCHAState={initialized:r};const i=zr(t);var s=or(!1);return s?jr(t,n,s,i,r):function(e){const t=document.createElement("script");t.src=Ur,t.onload=e,document.head.appendChild(t)}(()=>{var e=or(!1);if(!e)throw new Error("no recaptcha");jr(t,n,e,i,r)}),r.promise}function Br(t,n){const r=new y,e=tr(t);e.reCAPTCHAState={initialized:r};const i=zr(t);var s=or(!0);return s?jr(t,n,s,i,r):function(e){const t=document.createElement("script");t.src=Vr,t.onload=e,document.head.appendChild(t)}(()=>{var e=or(!0);if(!e)throw new Error("no recaptcha");jr(t,n,e,i,r)}),r.promise}function jr(e,t,n,r,i){n.ready(()=>{!function(e,t,n,r){const i=n.render(r,{sitekey:t,size:"invisible",callback:()=>{tr(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{tr(e).reCAPTCHAState.succeeded=!1}}),s=tr(e);s.reCAPTCHAState=Object.assign(Object.assign({},s.reCAPTCHAState),{widgetId:i})}(e,t,n,r),i.resolve(n)})}function zr(e){var t=`fire_app_check_${e.name}`;const n=document.createElement("div");return n.id=t,n.style.display="none",document.body.appendChild(n),t}async function $r(r){cr(r);const i=await tr(r).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const n=tr(r).reCAPTCHAState;i.ready(()=>{e(i.execute(n.widgetId,{action:"fire_app_check"}))})})}class Kr{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;Qr(this._throttleData);var t=await $r(this._app).catch(e=>{throw ar.create("recaptcha-error")});if(null===(e=tr(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw ar.create("recaptcha-error");let n;try{n=await hr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${nr}/projects/${n}/apps/${r}:exchangeRecaptchaV3Token?key=${i}`,body:{recaptcha_v3_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=Hr(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),ar.create("throttled",{time:lr(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,n}initialize(e){this._app=e,this._heartbeatServiceProvider=He(e,"heartbeat"),qr(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Kr&&this._siteKey===e._siteKey}}class Gr{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;Qr(this._throttleData);var t=await $r(this._app).catch(e=>{throw ar.create("recaptcha-error")});if(null===(e=tr(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw ar.create("recaptcha-error");let n;try{n=await hr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${nr}/projects/${n}/apps/${r}:exchangeRecaptchaEnterpriseToken?key=${i}`,body:{recaptcha_enterprise_token:t}}}(this._app,t),this._heartbeatServiceProvider)}catch(e){throw null!==(t=e.code)&&void 0!==t&&t.includes("fetch-status-error")?(this._throttleData=Hr(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),ar.create("throttled",{time:lr(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,n}initialize(e){this._app=e,this._heartbeatServiceProvider=He(e,"heartbeat"),Br(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Gr&&this._siteKey===e._siteKey}}class Wr{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=function(e){const t=L(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null}(e.token),t=null!==t&&t<Date.now()&&0<t?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:t})}initialize(e){this._app=e}isEqual(e){return e instanceof Wr&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function Hr(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var n=t?t.backoffCount:0,r=ae(n,1e3,2);return{backoffCount:n+1,allowRequestsAfter:Date.now()+r,httpStatus:e}}function Qr(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw ar.create("throttled",{time:lr(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function Yr(e=Ze(),t){const n=He(e=oe(e),"app-check");if(er.initialized||function(){var e=o();const t=er;if(t.initialized=!0,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN||!0===e.FIREBASE_APPCHECK_DEBUG_TOKEN){t.enabled=!0;const n=new y;t.token=n,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?n.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):n.resolve(Cr())}}(),kr()&&Sr().then(e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)),n.isInitialized()){var r=n.getImmediate();const i=n.getOptions();if(i.isTokenAutoRefreshEnabled===t.isTokenAutoRefreshEnabled&&i.provider.isEqual(t.provider))return r;throw ar.create("already-initialized",{appName:e.name})}r=n.initialize({options:t});return function(t,e,n){const r=function(e,t){return Xn.set(e,t),Xn.get(e)}(t,Object.assign({},Zn));r.activated=!0,r.provider=e,r.cachedTokenPromise=Tr(t).then(e=>(e&&Or(e)&&(r.token=e,xr(t,{token:e.token})),e)),r.isTokenAutoRefreshEnabled=void 0===n?t.automaticDataCollectionEnabled:n,r.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),tr(e).isTokenAutoRefreshEnabled&&Rr(r,"INTERNAL",()=>{}),r}const Jr="app-check-internal";We(new ce("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat");return t=n,e=r,new Lr(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(Jr).initialize()})),We(new ce(Jr,e=>{return Fr(e.getProvider("app-check").getImmediate())},"PUBLIC").setInstantiationMode("EXPLICIT")),tt("@firebase/app-check","0.8.0");const Xr=new D("appCheck","AppCheck",{"use-before-activation":"App Check is being used before activate() is called for FirebaseApp {$appName}. Call activate() before instantiating other Firebase services."});class Zr{constructor(e){this.app=e}activate(e,t){let n;n="string"==typeof e?new Kr(e):e instanceof Gr||e instanceof Kr||e instanceof Wr?e:new Wr({getToken:e.getToken}),this._delegate=Yr(this.app,{provider:n,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw Xr.create("use-before-activation",{appName:this.app.name});!function(e,t){const n=tr(e.app);n.tokenRefresher&&(!0===t?n.tokenRefresher.start():n.tokenRefresher.stop()),n.isTokenAutoRefreshEnabled=t}(this._delegate,e)}getToken(e){if(!this._delegate)throw Xr.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await Nr(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw Xr.create("use-before-activation",{appName:this.app.name});return function(e,t,n){let r=()=>{},i=()=>{};return r=null!=t.next?t.next.bind(t):t,null!=t.error?i=t.error.bind(t):n&&(i=n),Rr(e,"EXTERNAL",r,i),()=>Pr(e.app,r)}(this._delegate,e,t)}}const ei=e=>{var t=e.getProvider("app-compat").getImmediate();return new Zr(t)};function ti(e,t){var n={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}bt.INTERNAL.registerComponent(new ce("appCheck-compat",ei,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:Gr,ReCaptchaV3Provider:Kr,CustomProvider:Wr})),bt.registerVersion("@firebase/app-check-compat","0.3.7");const ni={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},ri={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function ii(e){return void 0!==e&&void 0!==e.getResponse}function si(e){return void 0!==e&&void 0!==e.enterprise}class ai{constructor(e){if(this.siteKey="",this.emailPasswordEnabled=!1,void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.emailPasswordEnabled=e.recaptchaEnforcementState.some(e=>"EMAIL_PASSWORD_PROVIDER"===e.provider&&"OFF"!==e.enforcementState)}}function oi(){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."}}function ci(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","login-blocked":"Login blocked by user-provided method: {$originalMessage}","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-password":"A non-empty password must be provided","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted. Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance.","missing-recaptcha-token":"The reCAPTCHA token is missing when sending request to the backend.","invalid-recaptcha-token":"The reCAPTCHA token is invalid when sending request to the backend.","invalid-recaptcha-action":"The reCAPTCHA action is invalid when sending request to the backend.","recaptcha-not-enabled":"reCAPTCHA Enterprise integration is not enabled for this project.","missing-client-type":"The reCAPTCHA client type is missing when sending request to the backend.","missing-recaptcha-version":"The reCAPTCHA version is missing when sending request to the backend.","invalid-req-type":"Invalid request parameters.","invalid-recaptcha-version":"The reCAPTCHA version is invalid when sending request to the backend.","unsupported-password-policy-schema-version":"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.","password-does-not-meet-requirements":"The password does not meet the requirements."}}const li=oi,ui=new D("auth","Firebase",oi()),hi=new ve("@firebase/auth");function di(e,...t){hi.logLevel<=m.ERROR&&hi.error(`Auth (${Je}): ${e}`,...t)}function pi(e,...t){throw vi(e,...t)}function fi(e,...t){return vi(e,...t)}function gi(e,t,n){var r=Object.assign(Object.assign({},li()),{[t]:n});const i=new D("auth","Firebase",r);return i.create(t,{appName:e.name})}function mi(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&pi(e,"argument-error"),gi(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function vi(e,...t){if("string"==typeof e)return ui.create(e,...t);{var n=t[0];const r=[...t.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(n,...r)}}function _i(e,t,...n){if(!e)throw vi(t,...n)}function yi(e){var t="INTERNAL ASSERTION FAILED: "+e;throw di(t),new Error(t)}function wi(e,t){e||yi(t)}function bi(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Ii(){return"http:"===Ti()||"https:"===Ti()}function Ti(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Ei{constructor(e,t){wi((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=I()||C()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(Ii()||E()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function Ci(e,t){wi(e.emulator,"Emulator should always be set here");var n=e.emulator["url"];return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class ki{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:void yi("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static headers(){return this.headersImpl||("undefined"!=typeof self&&"Headers"in self?self.Headers:void yi("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static response(){return this.responseImpl||("undefined"!=typeof self&&"Response"in self?self.Response:void yi("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}const Si={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",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},Ai=new Ei(3e4,6e4);function Ni(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function Ri(i,s,a,o,e={}){return Pi(i,e,async()=>{let e={},t={};o&&("GET"===s?t=o:e={body:JSON.stringify(o)});var n=z(Object.assign({key:i.config.apiKey},t)).slice(1);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/json",i.languageCode&&(r["X-Firebase-Locale"]=i.languageCode),ki.fetch()(xi(i,i.config.apiHost,a,n),Object.assign({method:s,headers:r,referrerPolicy:"no-referrer"},e))})}async function Pi(t,e,n){t._canInitEmulator=!1;var r=Object.assign(Object.assign({},Si),e);try{const a=new Oi(t),o=await Promise.race([n(),a.promise]);a.clearNetworkTimeout();var i=await o.json();if("needConfirmation"in i)throw Mi(t,"account-exists-with-different-credential",i);if(o.ok&&!("errorMessage"in i))return i;{const c=o.ok?i.errorMessage:i.error.message,[l,u]=c.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===l)throw Mi(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===l)throw Mi(t,"email-already-in-use",i);if("USER_DISABLED"===l)throw Mi(t,"user-disabled",i);var s=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw gi(t,s,u);pi(t,s)}}catch(e){if(e instanceof P)throw e;pi(t,"network-request-failed",{message:String(e)})}}async function Di(e,t,n,r,i={}){var s=await Ri(e,t,n,r,i);return"mfaPendingCredential"in s&&pi(e,"multi-factor-auth-required",{_serverResponse:s}),s}function xi(e,t,n,r){var i=`${t}${n}?${r}`;return e.config.emulator?Ci(e.config,i):`${e.config.apiScheme}://${i}`}class Oi{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(fi(this.auth,"network-request-failed")),Ai.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function Mi(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=fi(e,t,r);return i.customData._tokenResponse=n,i}function Li(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Fi(e){return 1e3*Number(e)}function Ui(e){var[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return di("JWT malformed, contained fewer than 3 sections"),null;try{var i=a(n);return i?JSON.parse(i):(di("Failed to decode base64 JWT payload"),null)}catch(e){return di("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}async function Vi(t,n,e=!1){if(e)return n;try{return n}catch(e){throw e instanceof P&&(n=[e["code"]][0],"auth/user-disabled"===n||"auth/user-token-expired"===n)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class qi{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){if(e){var t=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t}this.errorBackoff=3e4;t=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,t)}schedule(e=!1){var t;this.isRunning&&(t=this.getInterval(e),this.timerId=setTimeout(async()=>{await this.iteration()},t))}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===(null==e?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class Bi{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Li(this.lastLoginAt),this.creationTime=Li(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function ji(e){var t=e.auth,n=await e.getIdToken(),r=await Vi(e,async function(e,t){return Ri(e,"POST","/v1/accounts:lookup",t)}(t,{idToken:n}));_i(null==r?void 0:r.users.length,t,"internal-error");var i=r.users[0];e._notifyReloadListener(i);var s,a,t=null!==(n=i.providerUserInfo)&&void 0!==n&&n.length?i.providerUserInfo.map(e=>{var t=e["providerId"],n=ti(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}}):[],r=(s=e.providerData,a=t,[...s.filter(t=>!a.some(e=>e.providerId===t.providerId)),...a]),n=e.isAnonymous,t=!(e.email&&i.passwordHash||null!==r&&r.length),t=!!n&&t,t={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 Bi(i.createdAt,i.lastLoginAt),isAnonymous:t};Object.assign(e,t)}class zi{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){_i(e.idToken,"internal-error"),_i(void 0!==e.idToken,"internal-error"),_i(void 0!==e.refreshToken,"internal-error");var t,n,n="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):(t=e.idToken,_i(n=Ui(t),"internal-error"),_i(void 0!==n.exp,"internal-error"),_i(void 0!==n.iat,"internal-error"),Number(n.exp)-Number(n.iat));this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}async getToken(e,t=!1){return _i(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){var i,s,{accessToken:n,refreshToken:r,expiresIn:a}=(s=t,await{accessToken:(a=await Pi(i=e,{},async()=>{var e=z({grant_type:"refresh_token",refresh_token:s}).slice(1),{tokenApiHost:t,apiKey:n}=i.config,n=xi(i,t,"/v1/token",`key=${n}`);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",ki.fetch()(n,{method:"POST",headers:r,body:e})})).access_token,expiresIn:a.expires_in,refreshToken:a.refresh_token});this.updateTokensAndExpiration(n,r,Number(a))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){var{refreshToken:n,accessToken:r,expirationTime:i}=t;const s=new zi;return n&&(_i("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(_i("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(_i("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new zi,this.toJSON())}_performRefresh(){return yi("not implemented")}}function $i(e,t){_i("string"==typeof e||void 0===e,"internal-error",{appName:t})}class Ki{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=ti(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new qi(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new Bi(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await Vi(this,this.stsTokenManager.getToken(this.auth,e));return _i(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return async function(e,t=!1){const n=oe(e);var r=await n.getIdToken(t),i=Ui(r);_i(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");var s="object"==typeof i.firebase?i.firebase:void 0,a=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:Li(Fi(i.auth_time)),issuedAtTime:Li(Fi(i.iat)),expirationTime:Li(Fi(i.exp)),signInProvider:a||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=oe(e);await ji(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(_i(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){const t=new Ki(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){_i(!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 ji(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e=await this.getIdToken();return await Vi(this,async function(e,t){return Ri(e,"POST","/v1/accounts:delete",t)}(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,isAnonymous: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=null!==(a=t.displayName)&&void 0!==a?a:void 0,r=null!==(g=t.email)&&void 0!==g?g:void 0,i=null!==(o=t.phoneNumber)&&void 0!==o?o:void 0,s=null!==(l=t.photoURL)&&void 0!==l?l:void 0,a=null!==(c=t.tenantId)&&void 0!==c?c:void 0,o=null!==(g=t._redirectEventId)&&void 0!==g?g:void 0,c=null!==(l=t.createdAt)&&void 0!==l?l:void 0,l=null!==(g=t.lastLoginAt)&&void 0!==g?g:void 0;const{uid:u,emailVerified:h,isAnonymous:d,providerData:p,stsTokenManager:f}=t;_i(u&&f,e,"internal-error");var g=zi.fromJSON(this.name,f);_i("string"==typeof u,e,"internal-error"),$i(n,e.name),$i(r,e.name),_i("boolean"==typeof h,e,"internal-error"),_i("boolean"==typeof d,e,"internal-error"),$i(i,e.name),$i(s,e.name),$i(a,e.name),$i(o,e.name),$i(c,e.name),$i(l,e.name);const m=new Ki({uid:u,auth:e,email:r,emailVerified:h,displayName:n,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:a,stsTokenManager:g,createdAt:c,lastLoginAt:l});return p&&Array.isArray(p)&&(m.providerData=p.map(e=>Object.assign({},e))),o&&(m._redirectEventId=o),m}static async _fromIdTokenResponse(e,t,n=!1){const r=new zi;r.updateFromServerResponse(t);var i=new Ki({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await ji(i),i}}const Gi=new Map;function Wi(e){wi(e instanceof Function,"Expected a class definition");let t=Gi.get(e);return t?wi(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Gi.set(e,t)),t}class Hi{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){var t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}Hi.type="NONE";const Qi=Hi;function Yi(e,t,n){return`firebase:${e}:${t}:${n}`}class Ji{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;var{config:r,name:i}=this.auth;this.fullUserKey=Yi(this.userKey,r.apiKey,i),this.fullPersistenceKey=Yi("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){var e=await this.persistence._get(this.fullUserKey);return e?Ki._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){var t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length)return new Ji(Wi(Qi),e,n);const r=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let i=r[0]||Wi(Qi);const s=Yi(n,e.config.apiKey,e.name);let a=null;for(const u of t)try{var o=await u._get(s);if(o){var c=Ki._fromJSON(e,o);u!==i&&(a=c),i=u;break}}catch(e){}var l=r.filter(e=>e._shouldAllowMigration);return i._shouldAllowMigration&&l.length&&(i=l[0],a&&await i._set(s,a.toJSON()),await Promise.all(t.map(async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new Ji(i,e,n)}}function Xi(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(ns(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(Zi(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(is(t))return"Blackberry";if(ss(t))return"Webos";if(es(t))return"Safari";if((t.includes("chrome/")||ts(t))&&!t.includes("edge/"))return"Chrome";if(rs(t))return"Android";var n=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);return 2===(null==n?void 0:n.length)?n[1]:"Other"}function Zi(e=b()){return/firefox\//i.test(e)}function es(e=b()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function ts(e=b()){return/crios\//i.test(e)}function ns(e=b()){return/iemobile/i.test(e)}function rs(e=b()){return/android/i.test(e)}function is(e=b()){return/blackberry/i.test(e)}function ss(e=b()){return/webos/i.test(e)}function as(e=b()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function os(e=b()){return as(e)||rs(e)||ss(e)||is(e)||/windows phone/i.test(e)||ns(e)}function cs(e,t=[]){let n;switch(e){case"Browser":n=Xi(b());break;case"Worker":n=`${Xi(b())}-${e}`;break;default:n=e}var r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${Je}/${r}`}class ls{constructor(e){this.auth=e,this.queue=[]}pushCallback(r,e){var t=n=>new Promise((e,t)=>{try{e(r(n))}catch(e){t(e)}});t.onAbort=e,this.queue.push(t);const n=this.queue.length-1;return()=>{this.queue[n]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser!==e){const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){t.reverse();for(const r of t)try{r()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==e?void 0:e.message})}}}}class us{constructor(e){var t,n=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(t=n.minPasswordLength)&&void 0!==t?t:6,n.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=n.maxPasswordLength),void 0!==n.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=n.containsLowercaseCharacter),void 0!==n.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=n.containsUppercaseCharacter),void 0!==n.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=n.containsNumericCharacter),void 0!==n.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=n.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!==(n=null===(n=e.allowedNonAlphanumericCharacters)||void 0===n?void 0:n.join(""))&&void 0!==n?n:"",this.forceUpgradeOnSignin=null!==(n=e.forceUpgradeOnSignin)&&void 0!==n&&n,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,n,r;const i={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,i),this.validatePasswordCharacterOptions(e,i),i.isValid&&(i.isValid=null===(t=i.meetsMinPasswordLength)||void 0===t||t),i.isValid&&(i.isValid=null===(t=i.meetsMaxPasswordLength)||void 0===t||t),i.isValid&&(i.isValid=null===(n=i.containsLowercaseLetter)||void 0===n||n),i.isValid&&(i.isValid=null===(n=i.containsUppercaseLetter)||void 0===n||n),i.isValid&&(i.isValid=null===(r=i.containsNumericCharacter)||void 0===r||r),i.isValid&&(i.isValid=null===(r=i.containsNonAlphanumericCharacter)||void 0===r||r),i}validatePasswordLengthOptions(e,t){var n=this.customStrengthOptions.minPasswordLength,r=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),r&&(t.meetsMaxPasswordLength=e.length<=r)}validatePasswordCharacterOptions(e,t){var n;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let r=0;r<e.length;r++)n=e.charAt(r),this.updatePasswordCharacterOptionsStatuses(t,"a"<=n&&n<="z","A"<=n&&n<="Z","0"<=n&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,r,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=r)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class hs{constructor(e,t,n,r){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=r,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new ps(this),this.idTokenSubscription=new ps(this),this.beforeStateQueue=new ls(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=ui,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=r.sdkClientVersion}_initializeWithPersistence(t,n){return n&&(this._popupRedirectResolver=Wi(n)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await Ji.create(this,t),!this._deleted)){if(null!==(e=this._popupRedirectResolver)&&void 0!==e&&e._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(n),this.lastNotifiedUid=(null===(e=this.currentUser)||void 0===e?void 0:e.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(!this._deleted){var e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e)return this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0)}}async initializeCurrentUser(e){var t,n,r,i=await this.assertedPersistence.getCurrentUser();let s=i,a=!1;if(e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=null===(r=this.redirectUser)||void 0===r?void 0:r._redirectEventId,n=null===s||void 0===s?void 0:s._redirectEventId,r=await this.tryRedirectSignIn(e),t&&t!==n||null==r||!r.user||(s=r.user,a=!0)),!s)return this.directlySetCurrentUser(null);if(s._redirectEventId)return _i(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===s._redirectEventId?this.directlySetCurrentUser(s):this.reloadAndSetCurrentUserOrClear(s);if(a)try{await this.beforeStateQueue.runMiddleware(s)}catch(e){s=i,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return s?this.reloadAndSetCurrentUserOrClear(s):this.directlySetCurrentUser(null)}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 ji(e)}catch(e){if("auth/network-request-failed"!==(null==e?void 0:e.code))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;var e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?oe(e):null;return t&&_i(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&&_i(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 await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0)}setPersistence(e){return this.queue(async()=>{await this.assertedPersistence.setPersistence(Wi(e))})}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const 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(){var e,t=await Ri(e=this,"GET","/v2/passwordPolicy",Ni(e,{})),t=new us(t);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new D("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{const n=this.onAuthStateChanged(()=>{n(),e()},t)}})}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(_i(t=e&&Wi(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await Ji.create(this,[Wi(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){var t;return this._isInitialized&&await this.queue(async()=>{}),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(t=this.redirectUser)||void 0===t?void 0:t._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;this._isInitialized&&(this.idTokenSubscription.next(this.currentUser),e=null!==(e=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==e?e:null,this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser)))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t);let s=!1;const a=this._isInitialized?Promise.resolve():this._initializationPromise;if(_i(a,this,"internal-error"),a.then(()=>{s||i(this.currentUser)}),"function"==typeof t){const o=e.addObserver(t,n,r);return()=>{s=!0,o()}}{const c=e.addObserver(t);return()=>{s=!0,c()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),(this.currentUser=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 _i(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=cs(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);var t=await(null===(t=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===t?void 0:t.getHeartbeatsHeader());t&&(e["X-Firebase-Client"]=t);t=await this._getAppCheckToken();return t&&(e["X-Firebase-AppCheck"]=t),e}async _getAppCheckToken(){var e,t,n=await(null===(n=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===n?void 0:n.getToken());return null!=n&&n.error&&(e=`Error while retrieving App Check token: ${n.error}`,t=[],hi.logLevel<=m.WARN&&hi.warn(`Auth (${Je}): ${e}`,...t)),null==n?void 0:n.token}}function ds(e){return oe(e)}class ps{constructor(e){this.auth=e,this.observer=null,this.addObserver=W(e=>this.observer=e)}get next(){return _i(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function fs(i){return new Promise((e,n)=>{const t=document.createElement("script");var r;t.setAttribute("src",i),t.onload=e,t.onerror=e=>{const t=fi("internal-error");t.customData=e,n(t)},t.type="text/javascript",t.charset="UTF-8",(null!==(r=null===(r=document.getElementsByTagName("head"))||void 0===r?void 0:r[0])&&void 0!==r?r:document).appendChild(t)})}function gs(e){return`__${e}${Math.floor(1e6*Math.random())}`}class ms{constructor(e){this.type="recaptcha-enterprise",this.auth=ds(e)}async verify(i="verify",r=!1){async function e(i){if(!r){if(null==i.tenantId&&null!=i._agentRecaptchaConfig)return i._agentRecaptchaConfig.siteKey;if(null!=i.tenantId&&void 0!==i._tenantRecaptchaConfigs[i.tenantId])return i._tenantRecaptchaConfigs[i.tenantId].siteKey}return new Promise(async(n,r)=>{!async function(e,t){return Ri(e,"GET","/v2/recaptchaConfig",Ni(e,t))}(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(e=>{if(void 0!==e.recaptchaKey){var t=new ai(e);return null==i.tenantId?i._agentRecaptchaConfig=t:i._tenantRecaptchaConfigs[i.tenantId]=t,n(t.siteKey)}r(new Error("recaptcha Enterprise site key undefined"))}).catch(e=>{r(e)})})}function s(e,t,n){const r=window.grecaptcha;si(r)?r.enterprise.ready(()=>{r.enterprise.execute(e,{action:i}).then(e=>{t(e)}).catch(()=>{t("NO_RECAPTCHA")})}):n(Error("No reCAPTCHA enterprise script loaded."))}return new Promise((t,n)=>{e(this.auth).then(e=>{!r&&si(window.grecaptcha)?s(e,t,n):"undefined"!=typeof window?fs("https://www.google.com/recaptcha/enterprise.js?render="+e).then(()=>{s(e,t,n)}).catch(e=>{n(e)}):n(new Error("RecaptchaVerifier is only supported in browser"))}).catch(e=>{n(e)})})}}async function vs(e,t,n,r=!1){const i=new ms(e);let s;try{s=await i.verify(n)}catch(e){s=await i.verify(n,!0)}var a=Object.assign({},t);return r?Object.assign(a,{captchaResp:s}):Object.assign(a,{captchaResponse:s}),Object.assign(a,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(a,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),a}function _s(e,t,n){const r=ds(e);_i(r._canInitEmulator,r,"emulator-config-failed"),_i(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");var i=!(null==n||!n.disableWarnings);const s=ys(t);var{host:a,port:o}=function(e){const t=ys(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);{if(i){var s=i[1];return{host:s,port:ws(r.substr(s.length+1))}}var[a,s]=r.split(":");return{host:a,port:ws(s)}}}(t);r.config.emulator={url:`${s}//${a}${null===o?"":`:${o}`}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:a,port:o,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const 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)}"undefined"!=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.");"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}function ys(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function ws(e){if(!e)return null;var t=Number(e);return isNaN(t)?null:t}class bs{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return yi("not implemented")}_getIdTokenResponse(e){return yi("not implemented")}_linkToIdToken(e,t){return yi("not implemented")}_getReauthenticationResolver(e){return yi("not implemented")}}async function Is(e,t){return Ri(e,"POST","/v1/accounts:resetPassword",Ni(e,t))}async function Ts(e,t){return Ri(e,"POST","/v1/accounts:update",t)}async function Es(e,t){return Di(e,"POST","/v1/accounts:signInWithPassword",Ni(e,t))}async function Cs(e,t){return Ri(e,"POST","/v1/accounts:sendOobCode",Ni(e,t))}async function ks(e,t){return Cs(e,t)}async function Ss(e,t){return Cs(e,t)}class As extends bs{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new As(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new As(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e;if(null!=t&&t.email&&null!=t&&t.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(n){switch(this.signInMethod){case"password":const r={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};if(null!==(e=n._getRecaptchaConfig())&&void 0!==e&&e.emailPasswordEnabled){var e=await vs(n,r,"signInWithPassword");return Es(n,e)}return Es(n,r).catch(async e=>{if("auth/missing-recaptcha-token"!==e.code)return Promise.reject(e);console.log("Sign-in with email address and password is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.");var t=await vs(n,r,"signInWithPassword");return Es(n,t)});case"emailLink":return async function(e,t){return Di(e,"POST","/v1/accounts:signInWithEmailLink",Ni(e,t))}(n,{email:this._email,oobCode:this._password});default:pi(n,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Ts(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Di(e,"POST","/v1/accounts:signInWithEmailLink",Ni(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:pi(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Ns(e,t){return Di(e,"POST","/v1/accounts:signInWithIdp",Ni(e,t))}class Rs extends bs{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new Rs(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):pi("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){var t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:r}=t,t=ti(t,["providerId","signInMethod"]);if(!n||!r)return null;const i=new Rs(n,r);return i.idToken=t.idToken||void 0,i.accessToken=t.accessToken||void 0,i.secret=t.secret,i.nonce=t.nonce,i.pendingToken=t.pendingToken||null,i}_getIdTokenResponse(e){return Ns(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Ns(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Ns(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const 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=z(t)}return e}}const Ps={USER_NOT_FOUND:"user-not-found"};class Ds extends bs{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Ds({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Ds({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return Di(e,"POST","/v1/accounts:signInWithPhoneNumber",Ni(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await Di(e,"POST","/v1/accounts:signInWithPhoneNumber",Ni(e,t));if(n.temporaryProof)throw Mi(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return Di(e,"POST","/v1/accounts:signInWithPhoneNumber",Ni(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Ps)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const 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){var{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e="string"==typeof e?JSON.parse(e):e;return n||t||r||i?new Ds({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class xs{constructor(e){var t=$(K(e)),n=null!==(r=t.apiKey)&&void 0!==r?r:null,r=null!==(i=t.oobCode)&&void 0!==i?i:null,i=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(i=t.mode)&&void 0!==i?i:null);_i(n&&r&&i,"argument-error"),this.apiKey=n,this.operation=i,this.code=r,this.continueUrl=null!==(r=t.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(r=t.languageCode)&&void 0!==r?r:null,this.tenantId=null!==(t=t.tenantId)&&void 0!==t?t:null}static parseLink(e){var t,n,r,t=(t=$(K(e=e)).link,n=t?$(K(t)).deep_link_id:null,((r=$(K(e)).deep_link_id)?$(K(r)).link:null)||r||n||t||e);try{return new xs(t)}catch(e){return null}}}class Os{constructor(){this.providerId=Os.PROVIDER_ID}static credential(e,t){return As._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var n=xs.parseLink(t);return _i(n,"argument-error"),As._fromEmailAndCode(e,n.code,n.tenantId)}}Os.PROVIDER_ID="password",Os.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Os.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Ms{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 Ls extends Ms{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Fs extends Ls{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return _i("providerId"in t&&"signInMethod"in t,"argument-error"),Rs._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return _i(e.idToken||e.accessToken,"argument-error"),Rs._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return Fs.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return Fs.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:a}=e;if(!(n||r||t||i))return null;if(!a)return null;try{return new Fs(a)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class Us extends Ls{constructor(){super("facebook.com")}static credential(e){return Rs._fromParams({providerId:Us.PROVIDER_ID,signInMethod:Us.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Us.credentialFromTaggedObject(e)}static credentialFromError(e){return Us.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Us.credential(e.oauthAccessToken)}catch(e){return null}}}Us.FACEBOOK_SIGN_IN_METHOD="facebook.com",Us.PROVIDER_ID="facebook.com";class Vs extends Ls{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Rs._fromParams({providerId:Vs.PROVIDER_ID,signInMethod:Vs.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Vs.credentialFromTaggedObject(e)}static credentialFromError(e){return Vs.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return Vs.credential(t,n)}catch(e){return null}}}Vs.GOOGLE_SIGN_IN_METHOD="google.com",Vs.PROVIDER_ID="google.com";class qs extends Ls{constructor(){super("github.com")}static credential(e){return Rs._fromParams({providerId:qs.PROVIDER_ID,signInMethod:qs.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return qs.credentialFromTaggedObject(e)}static credentialFromError(e){return qs.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return qs.credential(e.oauthAccessToken)}catch(e){return null}}}qs.GITHUB_SIGN_IN_METHOD="github.com",qs.PROVIDER_ID="github.com";class Bs extends bs{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return Ns(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Ns(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Ns(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:n,pendingToken:r}="string"==typeof e?JSON.parse(e):e;return t&&n&&r&&t===n?new Bs(t,r):null}static _create(e,t){return new Bs(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class js extends Ms{constructor(e){_i(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return js.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return js.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=Bs.fromJSON(e);return _i(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return Bs._create(n,t)}catch(e){return null}}}class zs extends Ls{constructor(){super("twitter.com")}static credential(e,t){return Rs._fromParams({providerId:zs.PROVIDER_ID,signInMethod:zs.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return zs.credentialFromTaggedObject(e)}static credentialFromError(e){return zs.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return zs.credential(t,n)}catch(e){return null}}}async function $s(e,t){return Di(e,"POST","/v1/accounts:signUp",Ni(e,t))}zs.TWITTER_SIGN_IN_METHOD="twitter.com",zs.PROVIDER_ID="twitter.com";class Ks{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){var i=await Ki._fromIdTokenResponse(e,n,r),s=Gs(n);return new Ks({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);var r=Gs(n);return new Ks({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function Gs(e){return e.providerId||("phoneNumber"in e?"phone":null)}class Ws extends P{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,Ws.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new Ws(e,t,n,r)}}function Hs(t,n,e,r){const i="reauthenticate"===n?e._getReauthenticationResolver(t):e._getIdTokenResponse(t);return i.catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw Ws._fromErrorAndOperation(t,e,n,r);throw e})}function Qs(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Ys(e,t){const n=oe(e);await Xs(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await Ri(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=Qs(r||[]);return n.providerData=n.providerData.filter(e=>i.has(e.providerId)),i.has("phone")||(n.phoneNumber=null),await n.auth._persistUserIfCurrent(n),n}async function Js(e,t,n=!1){var r=await Vi(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Ks._forOperation(e,"link",r)}async function Xs(e,t,n){await ji(t);const r=Qs(t.providerData);var i=!1===e?"provider-already-linked":"no-such-provider";_i(r.has(n)===e,t.auth,i)}async function Zs(e,t,n=!1){var r=e["auth"],i="reauthenticate";try{var s=await Vi(e,Hs(r,i,t,e),n);_i(s.idToken,r,"internal-error");var a=Ui(s.idToken);_i(a,r,"internal-error");var o=a["sub"];return _i(e.uid===o,r,"user-mismatch"),Ks._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&pi(r,"user-mismatch"),e}}async function ea(e,t,n=!1){var r=await Hs(e,"signIn",t),r=await Ks._fromIdTokenResponse(e,"signIn",r);return n||await e._updateCurrentUser(r.user),r}async function ta(e,t){return ea(ds(e),t)}async function na(e,t){var n=oe(e);return await Xs(!1,n,t.providerId),Js(n,t)}async function ra(e,t){return Zs(oe(e),t)}async function ia(e,t){const n=ds(e);var r=await Di(n,"POST","/v1/accounts:signInWithCustomToken",Ni(n,{token:t,returnSecureToken:!0})),r=await Ks._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(r.user),r}class sa{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?aa._fromServerResponse(e,t):"totpInfo"in t?oa._fromServerResponse(e,t):pi(e,"internal-error")}}class aa extends sa{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new aa(t)}}class oa extends sa{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new oa(t)}}function ca(e,t,n){var r;_i(0<(null===(r=n.url)||void 0===r?void 0:r.length),e,"invalid-continue-uri"),_i(void 0===n.dynamicLinkDomain||0<n.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(_i(0<n.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(_i(0<n.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function la(e){const t=ds(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function ua(e,t){await Ri(e=oe(e),"POST","/v1/accounts:update",Ni(e,{oobCode:t}))}async function ha(e,t){var n=oe(e),r=await Is(n,{oobCode:t}),i=r.requestType;switch(_i(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":_i(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":_i(r.mfaInfo,n,"internal-error");default:_i(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=sa._fromServerResponse(ds(n),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:s},operation:i}}async function da(e,t){var n=Ii()?bi():"http://localhost",n=(await Ri(e=oe(e),"POST","/v1/accounts:createAuthUri",Ni(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function pa(e,t){var n=oe(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&ca(n.auth,r,t);var r=(await Cs(n.auth,r))["email"];r!==e.email&&await e.reload()}async function fa(e,t,n){var r=oe(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&ca(r.auth,i,n);var i=(await Cs(r.auth,i))["email"];i!==e.email&&await e.reload()}async function ga(e,{displayName:t,photoURL:n}){if(void 0!==t||void 0!==n){const i=oe(e);var r=await i.getIdToken(),r=await Vi(i,async function(e,t){return Ri(e,"POST","/v1/accounts:update",t)}(i.auth,{idToken:r,displayName:t,photoUrl:n,returnSecureToken:!0}));i.displayName=r.displayName||null,i.photoURL=r.photoUrl||null;const s=i.providerData.find(({providerId:e})=>"password"===e);s&&(s.displayName=i.displayName,s.photoURL=i.photoURL),await i._updateTokensIfNecessary(r)}}async function ma(e,t,n){var r=e["auth"];const i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),n&&(i.password=n);r=await Vi(e,Ts(r,i));await e._updateTokensIfNecessary(r,!0)}class va{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class _a extends va{constructor(e,t,n,r){super(e,t,n),this.username=r}}class ya extends va{constructor(e,t){super(e,"facebook.com",t)}}class wa extends _a{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class ba extends va{constructor(e,t){super(e,"google.com",t)}}class Ia extends _a{constructor(e,t,n){super(e,"twitter.com",t,n)}}function Ta(e){var{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:function(e){if(!e)return null;var t=e["providerId"],n=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},r=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&null!=e&&e.idToken){var i=null===(i=null===(i=Ui(e.idToken))||void 0===i?void 0:i.firebase)||void 0===i?void 0:i.sign_in_provider;if(i){i="anonymous"!==i&&"custom"!==i?i:null;return new va(r,i)}}if(!t)return null;switch(t){case"facebook.com":return new ya(r,n);case"github.com":return new wa(r,n);case"google.com":return new ba(r,n);case"twitter.com":return new Ia(r,n,e.screenName||null);case"custom":case"anonymous":return new va(r,null);default:return new va(r,t,n)}}(n)}class Ea{constructor(e,t,n){this.type=e,this.credential=t,this.user=n}static _fromIdtoken(e,t){return new Ea("enroll",e,t)}static _fromMfaPendingCredential(e){return new Ea("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t;if(null!=e&&e.multiFactorSession){if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.pendingCredential)return Ea._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.idToken)return Ea._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Ca{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,i){const s=ds(e),a=i.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>sa._fromServerResponse(s,e));_i(a.mfaPendingCredential,s,"internal-error");const o=Ea._fromMfaPendingCredential(a.mfaPendingCredential);return new Ca(o,t,async e=>{var t=await e._process(s,o);delete a.mfaInfo,delete a.mfaPendingCredential;var n=Object.assign(Object.assign({},a),{idToken:t.idToken,refreshToken:t.refreshToken});switch(i.operationType){case"signIn":var r=await Ks._fromIdTokenResponse(s,i.operationType,n);return await s._updateCurrentUser(r.user),r;case"reauthenticate":return _i(i.user,s,"internal-error"),Ks._forOperation(i.user,i.operationType,n);default:pi(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}class ka{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>sa._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new ka(e)}async getSession(){return Ea._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const n=e;var r=await this.getSession(),r=await Vi(this.user,n._process(this.user.auth,r,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid;var n,r,i=await this.user.getIdToken();try{var s=await Vi(this.user,(n=this.user.auth,r={idToken:i,mfaEnrollmentId:t},Ri(n,"POST","/v2/accounts/mfaEnrollment:withdraw",Ni(n,r))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(s),await this.user.reload()}catch(e){throw e}}}const Sa=new WeakMap;const Aa="__sak";class Na{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Aa,"1"),this.storage.removeItem(Aa),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){var 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 Ra extends Na{constructor(){var e;super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=(es(e=b())||as(e))&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=os(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const r of Object.keys(this.listeners)){var t=this.storage.getItem(r),n=this.localCache[r];t!==n&&e(r,n,t)}}onStorageEvent(e,t=!1){if(e.key){const r=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(r);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(r,e.newValue):this.storage.removeItem(r);else if(this.localCache[r]===e.newValue&&!t)return}var n=()=>{var e=this.storage.getItem(r);!t&&this.localCache[r]===e||this.notifyListeners(r,e)};const i=this.storage.getItem(r);k()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}else this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)})}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t&&JSON.parse(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){var t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}Ra.type="LOCAL";const Pa=Ra;class Da extends Na{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}Da.type="SESSION";const xa=Da;class Oa{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){var e=this.receivers.find(e=>e.isListeningto(t));if(e)return e;e=new Oa(t);return this.receivers.push(e),e}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data;var s=this.handlersMap[r];null!=s&&s.size&&(t.ports[0].postMessage({status:"ack",eventId:n,eventType:r}),s=Array.from(s).map(async e=>e(t.origin,i)),s=await Promise.all(s.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})),t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:s}))}_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 Ma(e="",t=10){let n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}Oa.receivers=[];class La{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,a=50){const o="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!o)throw new Error("connection_unavailable");let c,l;return new Promise((n,r)=>{const i=Ma("",20);o.port1.start();const s=setTimeout(()=>{r(new Error("unsupported_event"))},a);l={messageChannel:o,onMessage(e){var t=e;if(t.data.eventId===i)switch(t.data.status){case"ack":clearTimeout(s),c=setTimeout(()=>{r(new Error("timeout"))},3e3);break;case"done":clearTimeout(c),n(t.data.response);break;default:clearTimeout(s),clearTimeout(c),r(new Error("invalid_response"))}}},this.handlers.add(l),o.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:e,eventId:i,data:t},[o.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}}function Fa(){return window}function Ua(){return void 0!==Fa().WorkerGlobalScope&&"function"==typeof Fa().importScripts}const Va="firebaseLocalStorageDb",qa="firebaseLocalStorage",Ba="fbase_key";class ja{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 za(e,t){return e.transaction([qa],t?"readwrite":"readonly").objectStore(qa)}function $a(){const r=indexedDB.open(Va,1);return new Promise((n,t)=>{r.addEventListener("error",()=>{t(r.error)}),r.addEventListener("upgradeneeded",()=>{const e=r.result;try{e.createObjectStore(qa,{keyPath:Ba})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains(qa)?n(e):(e.close(),t=indexedDB.deleteDatabase(Va),await new ja(t).toPromise(),n(await $a()))})})}async function Ka(e,t,n){var r=za(e,!0).put({fbase_key:t,value:n});return new ja(r).toPromise()}function Ga(e,t){var n=za(e,!0).delete(t);return new ja(n).toPromise()}class Wa{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 $a(),this.db)}async _withRetries(e){let t=0;for(;;)try{return e(await this._openDb())}catch(e){if(3<t++)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Ua()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Oa._getInstance(Ua()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>{const n=await this._poll();return{keyProcessed:n.includes(t.key)}}),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t,n;this.activeServiceWorker=await async function(){if(null===navigator||void 0===navigator||!navigator.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),this.activeServiceWorker&&(this.sender=new La(this.activeServiceWorker),(n=await this.sender._send("ping",{},800))&&null!==(e=n[0])&&void 0!==e&&e.fulfilled&&null!==(t=n[0])&&void 0!==t&&t.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0))}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?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;var e=await $a();return await Ka(e,Aa,"1"),await Ga(e,Aa),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,n){return this._withPendingWrite(async()=>(await this._withRetries(e=>Ka(e,t,n)),this.localCache[t]=n,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>async function(e,t){var n=za(e,!1).get(t);return void 0===(n=await new ja(n).toPromise())?null:n.value}(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>Ga(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e,t,n=await this._withRetries(e=>{var t=za(e,!1).getAll();return new ja(t).toPromise()});if(!n)return[];if(0!==this.pendingWrites)return[];const r=[],i=new Set;for({fbase_key:e,value:t}of n)i.add(e),JSON.stringify(this.localCache[e])!==JSON.stringify(t)&&(this.notifyListeners(e,t),r.push(e));for(const s of Object.keys(this.localCache))this.localCache[s]&&!i.has(s)&&(this.notifyListeners(s,null),r.push(s));return r}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(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()}}Wa.type="LOCAL";const Ha=Wa;class Qa{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var n=this.counter;return this._widgets.set(n,new Ya(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t,n=e||1e12;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;return(null===(t=this._widgets.get(e||1e12))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;return null===(t=this._widgets.get(e||1e12))||void 0===t||t.execute(),""}}class Ya{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var r="string"==typeof e?document.getElementById(e):e;_i(r,"argument-error",{appName:t}),this.container=r,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=function(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()},6e4)},500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}const Ja=gs("rcb"),Xa=new Ei(3e4,6e4);class Za{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!(null===(e=Fa().grecaptcha)||void 0===e||!e.render)}load(s,a=""){var e;return _i((e=a).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),s,"argument-error"),this.shouldResolveImmediately(a)&&ii(Fa().grecaptcha)?Promise.resolve(Fa().grecaptcha):new Promise((t,n)=>{const i=Fa().setTimeout(()=>{n(fi(s,"network-request-failed"))},Xa.get());Fa()[Ja]=()=>{Fa().clearTimeout(i),delete Fa()[Ja];const e=Fa().grecaptcha;if(e&&ii(e)){const r=e.render;e.render=(e,t)=>{var n=r(e,t);return this.counter++,n},this.hostLanguage=a,t(e)}else n(fi(s,"internal-error"))},fs(`https://www.google.com/recaptcha/api.js??${z({onload:Ja,render:"explicit",hl:a})}`).catch(()=>{clearTimeout(i),n(fi(s,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!(null===(t=Fa().grecaptcha)||void 0===t||!t.render)&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class eo{async load(e){return new Qa(e)}clearedOneInstance(){}}const to="recaptcha",no={theme:"light",type:"image"};class ro{constructor(e,t,n=Object.assign({},no)){this.parameters=n,this.type=to,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=ds(e),this.isInvisible="invisible"===this.parameters.size,_i("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var r="string"==typeof t?document.getElementById(t):t;_i(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?eo:Za),this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),r=this.getAssertedRecaptcha();var t=r.getResponse(e);return t||new Promise(t=>{const n=e=>{e&&(this.tokenChangeListeners.delete(n),t(e))};this.tokenChangeListeners.add(n),this.isInvisible&&r.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e}),this.renderPromise)}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){_i(!this.parameters.sitekey,this.auth,"argument-error"),_i(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),_i("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(n){return t=>{if(this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof n)n(t);else if("string"==typeof n){const e=Fa()[n];"function"==typeof e&&e(t)}}}assertNotDestroyed(){_i(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;var t;this.isInvisible||(t=document.createElement("div"),e.appendChild(t),e=t),this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){_i(Ii()&&!Ua(),this.auth,"internal-error"),await function(){let t=null;return new Promise(e=>{"complete"!==document.readyState?(t=()=>e(),window.addEventListener("load",t)):e()}).catch(e=>{throw t&&window.removeEventListener("load",t),e})}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);var e=await((await Ri(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");_i(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return _i(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class io{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Ds._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function so(t,n,r){var i,s,a,o,c,l,u=await r.verify();try{_i("string"==typeof u,t,"argument-error"),_i(r.type===to,t,"argument-error");let e;if(e="string"==typeof n?{phoneNumber:n}:n,"session"in e){var h=e.session;if("phoneNumber"in e)return _i("enroll"===h.type,t,"internal-error"),(c=t,l={idToken:h.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,recaptchaToken:u}},await Ri(c,"POST","/v2/accounts/mfaEnrollment:start",Ni(c,l))).phoneSessionInfo.sessionInfo;_i("signin"===h.type,t,"internal-error");var d=(null===(i=e.multiFactorHint)||void 0===i?void 0:i.uid)||e.multiFactorUid;return _i(d,t,"missing-multi-factor-info"),(o={mfaPendingCredential:h.credential,mfaEnrollmentId:d,phoneSignInInfo:{recaptchaToken:u}},await Ri(t,"POST","/v2/accounts/mfaSignIn:start",Ni(t,o))).phoneResponseInfo.sessionInfo}var p=(s=t,a={phoneNumber:e.phoneNumber,recaptchaToken:u},await Ri(s,"POST","/v1/accounts:sendVerificationCode",Ni(s,a)))["sessionInfo"];return p}finally{r._reset()}}class ao{constructor(e){this.providerId=ao.PROVIDER_ID,this.auth=ds(e)}verifyPhoneNumber(e,t){return so(this.auth,e,oe(t))}static credential(e,t){return Ds._fromVerification(e,t)}static credentialFromResult(e){var t=e;return ao.credentialFromTaggedObject(t)}static credentialFromError(e){return ao.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{phoneNumber:t,temporaryProof:n}=e;return t&&n?Ds._fromTokenResponse(t,n):null}}function oo(e,t){return t?Wi(t):(_i(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}ao.PROVIDER_ID="phone",ao.PHONE_SIGN_IN_METHOD="phone";class co extends bs{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Ns(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Ns(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Ns(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function lo(e){return ea(e.auth,new co(e),e.bypassAuthState)}function uo(e){var{auth:t,user:n}=e;return _i(n,t,"internal-error"),Zs(n,new co(e),e.bypassAuthState)}async function ho(e){var{auth:t,user:n}=e;return _i(n,t,"internal-error"),Js(n,new co(e),e.bypassAuthState)}class po{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){var{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:a}=e;if(s)this.reject(s);else{r={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(r))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return lo;case"linkViaPopup":case"linkViaRedirect":return ho;case"reauthViaPopup":case"reauthViaRedirect":return uo;default:pi(this.auth,"internal-error")}}resolve(e){wi(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){wi(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const fo=new Ei(2e3,1e4);class go extends po{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,go.currentPopupAction&&go.currentPopupAction.cancel(),go.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return _i(e,this.auth,"internal-error"),e}async onExecution(){wi(1===this.filter.length,"Popup operations only handle one event");var e=Ma();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(fi(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(fi(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,go.currentPopupAction=null}pollUserCancellation(){const t=()=>{var e;null!==(e=null===(e=this.authWindow)||void 0===e?void 0:e.window)&&void 0!==e&&e.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(fi(this.auth,"popup-closed-by-user"))},8e3):this.pollId=window.setTimeout(t,fo.get())};t()}}go.currentPopupAction=null;const mo="pendingRedirect",vo=new Map;class _o extends po{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let t=vo.get(this.auth._key());if(!t){try{const e=await async function(e,t){const n=Io(t),r=bo(e);if(!await r._isAvailable())return!1;var i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}vo.set(this.auth._key(),t)}return this.bypassAuthState||vo.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function yo(e,t){return bo(e)._set(Io(t),"true")}function wo(e,t){vo.set(e._key(),t)}function bo(e){return Wi(e._redirectPersistence)}function Io(e){return Yi(mo,e.config.apiKey,e.name)}function To(e,t,n){return async function(e,t,n){var r=ds(e);mi(e,t,Ms),await r._initializationPromise;const i=oo(r,n);return await yo(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function Eo(e,t,n){return async function(e,t,n){var r=oe(e);mi(r.auth,t,Ms),await r.auth._initializationPromise;const i=oo(r.auth,n);await yo(i,r.auth);var s=await So(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function Co(e,t,n){return async function(e,t,n){var r=oe(e);mi(r.auth,t,Ms),await r.auth._initializationPromise;const i=oo(r.auth,n);await Xs(!1,r,t.providerId),await yo(i,r.auth);var s=await So(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function ko(e,t,n=!1){const r=ds(e);var i=oo(r,t);const s=new _o(r,i,n),a=await s.execute();return a&&!n&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,t)),a}async function So(e){var t=Ma(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class Ao{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(t){if(this.hasEventBeenHandled(t))return!1;let n=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(n=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return Ro(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!Ro(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(fi(this.auth,n))):t.onAuthEvent(e)}isEventForConsumer(e,t){var n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(No(e))}saveEventToCache(e){this.cachedEventUids.add(No(e)),this.lastProcessedEventTime=Date.now()}}function No(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function Ro({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function Po(e,t={}){return Ri(e,"GET","/v1/projects",t)}const Do=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,xo=/^https?/;async function Oo(e){if(!e.config.emulator){var t=(await Po(e))["authorizedDomains"];for(const n of t)try{if(function(e){const t=bi(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){var i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!xo.test(n))return!1;if(Do.test(e))return r===e;const s=e.replace(/\./g,"\\."),a=new RegExp("^(.+\\."+s+"|"+s+")$","i");return a.test(r)}(n))return}catch(e){}pi(e,"unauthorized-domain")}}const Mo=new Ei(3e4,6e4);function Lo(){const t=Fa().___jsl;if(null!==t&&void 0!==t&&t.H)for(const n of Object.keys(t.H))if(t.H[n].r=t.H[n].r||[],t.H[n].L=t.H[n].L||[],t.H[n].r=[...t.H[n].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}let Fo=null;function Uo(e){var i;return Fo=Fo||(i=e,new Promise((e,t)=>{function n(){Lo(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{Lo(),t(fi(i,"network-request-failed"))},timeout:Mo.get()})}if(null!==(r=null===(r=Fa().gapi)||void 0===r?void 0:r.iframes)&&void 0!==r&&r.Iframe)e(gapi.iframes.getContext());else{if(null===(r=Fa().gapi)||void 0===r||!r.load){var r=gs("iframefcb");return Fa()[r]=()=>{gapi.load?n():t(fi(i,"network-request-failed"))},fs(`https://apis.google.com/js/api.js?onload=${r}`).catch(e=>t(e))}n()}}).catch(e=>{throw Fo=null,e})),Fo}const Vo=new Ei(5e3,15e3),qo="__/auth/iframe",Bo="emulator/auth/iframe",jo={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},zo=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function $o(a){const e=await Uo(a);var t=Fa().gapi;return _i(t,a,"internal-error"),e.open({where:document.body,url:function(e){var t=e.config;_i(t.authDomain,e,"auth-domain-config-required");var n=t.emulator?Ci(t,Bo):`https://${e.config.authDomain}/${qo}`;const r={apiKey:t.apiKey,appName:e.name,v:Je};(t=zo.get(e.config.apiHost))&&(r.eid=t);const i=e._getFrameworks();return i.length&&(r.fw=i.join(",")),`${n}?${z(r).slice(1)}`}(a),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:jo,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=fi(a,"network-request-failed"),r=Fa().setTimeout(()=>{t(n)},Vo.get());function i(){Fa().clearTimeout(r),e(s)}s.ping(i).then(i,()=>{t(n)})}))}const Ko={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Go{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Wo(e,t,n,r=500,i=600){var s=Math.max((window.screen.availHeight-i)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString();let o="";const c=Object.assign(Object.assign({},Ko),{width:r.toString(),height:i.toString(),top:s,left:a});s=b().toLowerCase();n&&(o=ts(s)?"_blank":n),Zi(s)&&(t=t||"http://localhost",c.scrollbars="yes");var l,a=Object.entries(c).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if([n=b()]=[s],as(n)&&null!==(l=window.navigator)&&void 0!==l&&l.standalone&&"_self"!==o)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",o),new Go(null);const u=window.open(t||"",o,a);_i(u,e,"popup-blocked");try{u.focus()}catch(e){}return new Go(u)}const Ho="__/auth/handler",Qo="emulator/auth/handler",Yo=encodeURIComponent("fac");async function Jo(e,t,n,r,i,s){_i(e.config.authDomain,e,"auth-domain-config-required"),_i(e.config.apiKey,e,"invalid-api-key");const a={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:Je,eventId:i};if(t instanceof Ms){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",V(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,c]of Object.entries(s||{}))a[o]=c}if(t instanceof Ls){const h=t.getScopes().filter(e=>""!==e);0<h.length&&(a.scopes=h.join(","))}e.tenantId&&(a.tid=e.tenantId);const l=a;for(const d of Object.keys(l))void 0===l[d]&&delete l[d];var u=await e._getAppCheckToken(),u=u?`#${Yo}=${encodeURIComponent(u)}`:"";return`${e=[e["config"]][0],e.emulator?Ci(e,Qo):`https://${e.authDomain}/${Ho}`}?${z(l).slice(1)}${u}`}const Xo="webStorageSupport";const Zo=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=xa,this._completeRedirectFn=ko,this._overrideRedirectResult=wo}async _openPopup(e,t,n,r){var i;return wi(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),Wo(e,await Jo(e,t,n,bi(),r),Ma())}async _openRedirect(e,t,n,r){await this._originValidation(e);var i=await Jo(e,t,n,bi(),r);return Fa().location.href=i,new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:r,promise:n}=this.eventManagers[t];return r?Promise.resolve(r):(wi(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch(()=>{delete this.eventManagers[t]}),n}async initAndGetManager(t){const e=await $o(t),n=new Ao(t);return e.register("authEvent",e=>{return _i(null==e?void 0:e.authEvent,t,"invalid-auth-event"),{status:n.onEvent(e.authEvent)?"ACK":"ERROR"}},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:n},this.iframes[t._key()]=e,n}_isIframeWebStorageSupported(n,r){const e=this.iframes[n._key()];e.send(Xo,{type:Xo},e=>{var t=null===(t=null==e?void 0:e[0])||void 0===t?void 0:t[Xo];void 0!==t&&r(!!t),pi(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=Oo(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return os()||es()||as()}};class ec extends class{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return yi("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new ec(e)}_finalizeEnroll(e,t,n){return e=e,n={idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()},Ri(e,"POST","/v2/accounts/mfaEnrollment:finalize",Ni(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},Ri(e,"POST","/v2/accounts/mfaSignIn:finalize",Ni(e,t))}}class tc{constructor(){}static assertion(e){return ec._fromCredential(e)}}tc.FACTOR_ID="phone";var nc="@firebase/auth";class rc{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?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(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t((null==e?void 0:e.stsTokenManager.accessToken)||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){_i(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}var ic,sc,ac;function oc(){return window}ic="authIdTokenMaxAge",null===(sc=p())||void 0===sc||sc[`_${ic}`],ac="Browser",We(new ce("auth",(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat"),i=e.getProvider("app-check-internal");const{apiKey:s,authDomain:a}=n.options;_i(s&&!s.includes(":"),"invalid-api-key",{appName:n.name});var o={apiKey:s,authDomain:a,clientPlatform:ac,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:cs(ac)},o=new hs(n,r,i,o);return function(e,t){const n=(null==t?void 0:t.persistence)||[];var r=(Array.isArray(n)?n:[n]).map(Wi);null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(o,t),o},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{const r=e.getProvider("auth-internal");r.initialize()})),We(new ce("auth-internal",e=>{var t=ds(e.getProvider("auth").getImmediate());return e=t,new rc(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),tt(nc,"1.3.0",function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(ac)),tt(nc,"1.3.0","esm2017");async function cc(e,t,n){var r=oc()["BuildInfo"];wi(t.sessionId,"AuthEvent did not contain a session ID");var i=await async function(e){const t=function(e){if(wi(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}(e),n=await crypto.subtle.digest("SHA-256",t),r=Array.from(new Uint8Array(n));return r.map(e=>e.toString(16).padStart(2,"0")).join("")}(t.sessionId);const s={};return as()?s.ibi=r.packageName:rs()?s.apn=r.packageName:pi(e,"operation-not-supported-in-this-environment"),r.displayName&&(s.appDisplayName=r.displayName),s.sessionId=i,Jo(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,s)}function lc(r){const i=oc()["cordova"];return new Promise(n=>{i.plugins.browsertab.isAvailable(e=>{let t=null;e?i.plugins.browsertab.openUrl(r):t=i.InAppBrowser.open(r,(e=b(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),n(t)})})}const uc=20;class hc extends Ao{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function dc(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:function(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<uc;r++){var n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}(),postBody:null,tenantId:e.tenantId,error:fi(e,"no-auth-event")}}async function pc(e){var t=await gc()._get(mc(e));return t&&await gc()._remove(mc(e)),t}function fc(e,t){var n,r,i;const s=(n=vc(t=t),a=n.link?decodeURIComponent(n.link):void 0,r=vc(a).link,i=n.deep_link_id?decodeURIComponent(n.deep_link_id):void 0,(n=vc(i).link)||i||r||a||t);if(s.includes("/__/auth/callback")){var a=vc(s),a=a.firebaseError?function(e){try{return JSON.parse(e)}catch(e){return null}}(decodeURIComponent(a.firebaseError)):null,a=null===(a=null===(a=null==a?void 0:a.code)||void 0===a?void 0:a.split("auth/"))||void 0===a?void 0:a[1],a=a?fi(a):null;return a?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:a,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:s,postBody:null}}return null}function gc(){return Wi(Pa)}function mc(e){return Yi("authEvent",e.config.apiKey,e.name)}function vc(e){if(null==e||!e.includes("?"))return{};const[,...t]=e.split("?");return $(t.join("?"))}const _c=class{constructor(){this._redirectPersistence=xa,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=ko,this._overrideRedirectResult=wo}async _initialize(e){var t=e._key();let n=this.eventManagers.get(t);return n||(n=new hc(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){pi(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){var i,s;i=e,o=oc(),_i("function"==typeof(null===(s=null==o?void 0:o.universalLinks)||void 0===s?void 0:s.subscribe),i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),_i(void 0!==(null===(s=null==o?void 0:o.BuildInfo)||void 0===s?void 0:s.packageName),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),_i("function"==typeof(null===(s=null===(s=null===(s=null==o?void 0:o.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.openUrl),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),_i("function"==typeof(null===(s=null===(s=null===(s=null==o?void 0:o.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.isAvailable),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),_i("function"==typeof(null===(o=null===(o=null==o?void 0:o.cordova)||void 0===o?void 0:o.InAppBrowser)||void 0===o?void 0:o.open),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});const a=await this._initialize(e);await a.initialized(),a.resetRedirect(),vo.clear(),await this._originValidation(e);var o=dc(e,n,r);n=e,r=o,await gc()._set(mc(n),r);o=await lc(await cc(e,o,t));return async function(a,o,c){const l=oc()["cordova"];let u=()=>{};try{await new Promise((n,e)=>{let t=null;function r(){var e;n();const t=null===(e=l.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==c?void 0:c.close)&&c.close()}function i(){t=t||window.setTimeout(()=>{e(fi(a,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&i()}o.addPassiveListener(r),document.addEventListener("resume",i,!1),rs()&&document.addEventListener("visibilitychange",s,!1),u=()=>{o.removePassiveListener(r),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),t&&window.clearTimeout(t)}})}finally{u()}}(e,a,o)}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){var t=oc()["BuildInfo"];const n={};as()?n.iosBundleId=t.packageName:rs()?n.androidPackageName=t.packageName:pi(e,"operation-not-supported-in-this-environment"),await Po(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=oc(),s=setTimeout(async()=>{await pc(r),i.onEvent(yc())},500),a=async e=>{clearTimeout(s);var t=await pc(r);let n=null;t&&null!=e&&e.url&&(n=fc(t,e.url)),i.onEvent(n||yc())};void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a);const o=t,c=`${n.packageName.toLowerCase()}://`;oc().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}};function yc(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:fi("no-auth-event")}}var wc;function bc(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function Ic(e=b()){return!("file:"!==bc()&&"ionic:"!==bc()&&"capacitor:"!==bc()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function Tc(e=b()){return k()&&11===(null===document||void 0===document?void 0:document.documentMode)||([e=b()]=[e],/Edge\/\d+/.test(e))}function Ec(){try{const t=self.localStorage;var e=Ma();if(t)return t.setItem(e,"1"),t.removeItem(e),!Tc()||A()}catch(e){return Cc()&&A()}return!1}function Cc(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function kc(){return("http:"===bc()||"https:"===bc()||E()||Ic())&&!(C()||T())&&Ec()&&!Cc()}function Sc(){return Ic()&&"undefined"!=typeof document}const Ac={LOCAL:"local",NONE:"none",SESSION:"session"},Nc=_i,Rc="persistence";async function Pc(e){await e._initializationPromise;const t=Dc();var n=Yi(Rc,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function Dc(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}const xc=_i;class Oc{constructor(){this.browserResolver=Wi(Zo),this.cordovaResolver=Wi(_c),this.underlyingResolver=null,this._redirectPersistence=xa,this._completeRedirectFn=ko,this._overrideRedirectResult=wo}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,n,r)}async _openRedirect(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,n,r)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return Sc()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return xc(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!Sc()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function Mc(e){return e.unwrap()}function Lc(e,t){var n,r,i,s=null===(r=t.customData)||void 0===r?void 0:r._tokenResponse;if("auth/multi-factor-auth-required"===(null==t?void 0:t.code)){const o=t;o.resolver=new qc(e,(n=t,i=oe(e),_i((a=n).customData.operationType,i,"argument-error"),_i(null===(r=a.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,i,"argument-error"),Ca._fromError(i,a)))}else if(s){var a=Fc(t);const c=t;a&&(c.credential=a,c.tenantId=s.tenantId||void 0,c.email=s.email||void 0,c.phoneNumber=s.phoneNumber||void 0)}}function Fc(e){var t=(e instanceof P?e.customData:e)["_tokenResponse"];if(!t)return null;if(!(e instanceof P)&&"temporaryProof"in t&&"phoneNumber"in t)return ao.credentialFromResult(e);const n=t.providerId;if(!n||n===ni.PASSWORD)return null;let r;switch(n){case ni.GOOGLE:r=Vs;break;case ni.FACEBOOK:r=Us;break;case ni.GITHUB:r=qs;break;case ni.TWITTER:r=zs;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:c}=t;return s||a||i||o?o?n.startsWith("saml.")?Bs._create(n,o):Rs._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:i,accessToken:s}):new Fs(n).credential({idToken:i,accessToken:s,rawNonce:c}):null}return e instanceof P?r.credentialFromError(e):r.credentialFromResult(e)}function Uc(t,e){return e.catch(e=>{throw e instanceof P&&Lc(t,e),e}).then(e=>{var t=e.operationType,n=e.user;return{operationType:t,credential:Fc(e),additionalUserInfo:Ta(e),user:Bc.getOrCreate(n)}})}async function Vc(t,e){const n=await e;return{verificationId:n.verificationId,confirm:e=>Uc(t,n.confirm(e))}}class qc{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return Uc(Mc(this.auth),this.resolver.resolveSignIn(e))}}class Bc{constructor(e){var t;this._delegate=e,this.multiFactor=(t=oe(e),Sa.has(t)||Sa.set(t,ka._fromUser(t)),Sa.get(t))}static getOrCreate(e){return Bc.USER_MAP.has(e)||Bc.USER_MAP.set(e,new Bc(e)),Bc.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return Uc(this.auth,na(this._delegate,e))}async linkWithPhoneNumber(e,t){return Vc(this.auth,async function(e,t,n){const r=oe(e);await Xs(!1,r,"phone");var i=await so(r.auth,t,oe(n));return new io(i,e=>na(r,e))}(this._delegate,e,t))}async linkWithPopup(e){return Uc(this.auth,async function(e,t,n){var r=oe(e);mi(r.auth,t,Ms);var i=oo(r.auth,n);const s=new go(r.auth,"linkViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,Oc))}async linkWithRedirect(e){return await Pc(ds(this.auth)),Co(this._delegate,e,Oc)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Uc(this.auth,ra(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Vc(this.auth,async function(e,t,n){const r=oe(e);var i=await so(r.auth,t,oe(n));return new io(i,e=>ra(r,e))}(this._delegate,e,t))}reauthenticateWithPopup(e){return Uc(this.auth,async function(e,t,n){var r=oe(e);mi(r.auth,t,Ms);var i=oo(r.auth,n);const s=new go(r.auth,"reauthViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,Oc))}async reauthenticateWithRedirect(e){return await Pc(ds(this.auth)),Eo(this._delegate,e,Oc)}sendEmailVerification(e){return pa(this._delegate,e)}async unlink(e){return await Ys(this._delegate,e),this}updateEmail(e){return ma(oe(this._delegate),e,null)}updatePassword(e){return ma(oe(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){await Js(oe(e),t)}(this._delegate,e)}updateProfile(e){return ga(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return fa(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}Bc.USER_MAP=new WeakMap;const jc=_i;class zc{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();var n=e.options["apiKey"];jc(n,"invalid-api-key",{appName:e.name}),jc(n,"invalid-api-key",{appName:e.name});var r="undefined"!=typeof window?Oc:void 0;this._delegate=t.initialize({options:{persistence:function(e,t){const n=function(e,t){const n=Dc();if(!n)return[];var r=Yi(Rc,e,t);switch(n.getItem(r)){case Ac.NONE:return[Qi];case Ac.LOCAL:return[Ha,xa];case Ac.SESSION:return[xa];default:return[]}}(e,t);"undefined"==typeof self||n.includes(Ha)||n.push(Ha);if("undefined"!=typeof window)for(const r of[Pa,xa])n.includes(r)||n.push(r);n.includes(Qi)||n.push(Qi);return n}(n,e.name),popupRedirectResolver:r}}),this._delegate._updateErrorMap(ci),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?Bc.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){_s(this._delegate,e,t)}applyActionCode(e){return ua(this._delegate,e)}checkActionCode(e){return ha(this._delegate,e)}confirmPasswordReset(e,t){return async function(t,e,n){await Is(oe(t),{oobCode:e,newPassword:n}).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&la(t),e})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Uc(this._delegate,async function(t,e,n){var r;const i=ds(t),s={returnSecureToken:!0,email:e,password:n,clientType:"CLIENT_TYPE_WEB"};let a;a=null!==(r=i._getRecaptchaConfig())&&void 0!==r&&r.emailPasswordEnabled?(o=await vs(i,s,"signUpPassword"),$s(i,o)):$s(i,s).catch(async e=>{if("auth/missing-recaptcha-token"!==e.code)throw e;console.log("Sign-up is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-up flow.");var t=await vs(i,s,"signUpPassword");return $s(i,t)});var o=await a.catch(e=>{throw"auth/password-does-not-meet-requirements"===e.code&&la(t),e}),o=await Ks._fromIdTokenResponse(i,"signIn",o);return await i._updateCurrentUser(o.user),o}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return da(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=xs.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){jc(kc(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=Oc,await ds(e)._initializationPromise,await ko(e,t,!1));return n?Uc(this._delegate,Promise.resolve(n)):{credential:null,user:null}}addFrameworkForLogging(e){ds(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,n){var{next:r,error:i,complete:s}=$c(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=$c(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return async function(e,t,n){var r;const i=ds(e),s={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};function a(e,t){_i(t.handleCodeInApp,i,"argument-error"),t&&ca(i,e,t)}null!==(r=i._getRecaptchaConfig())&&void 0!==r&&r.emailPasswordEnabled?(a(r=await vs(i,s,"getOobCode",!0),n),await Ss(i,r)):(a(s,n),await Ss(i,s).catch(async e=>{if("auth/missing-recaptcha-token"!==e.code)return Promise.reject(e);console.log("Email link sign-in is protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the sign-in flow.");var t=await vs(i,s,"getOobCode",!0);a(t,n),await Ss(i,t)}))}(this._delegate,e,t)}sendPasswordResetEmail(e,t){return async function(e,t,n){var r;const i=ds(e),s={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};null!==(r=i._getRecaptchaConfig())&&void 0!==r&&r.emailPasswordEnabled?(r=await vs(i,s,"getOobCode",!0),n&&ca(i,r,n),await ks(i,r)):(n&&ca(i,s,n),await ks(i,s).catch(async e=>{if("auth/missing-recaptcha-token"!==e.code)return Promise.reject(e);console.log("Password resets are protected by reCAPTCHA for this project. Automatically triggering the reCAPTCHA flow and restarting the password reset flow.");var t=await vs(i,s,"getOobCode",!0);n&&ca(i,t,n),await ks(i,t)}))}(this._delegate,e,t||void 0)}async setPersistence(e){var t,n;t=this._delegate,n=e,Nc(Object.values(Ac).includes(n),t,"invalid-persistence-type"),C()?Nc(n!==Ac.SESSION,t,"unsupported-persistence-type"):T()?Nc(n===Ac.NONE,t,"unsupported-persistence-type"):Cc()?Nc(n===Ac.NONE||n===Ac.LOCAL&&A(),t,"unsupported-persistence-type"):Nc(n===Ac.NONE||Ec(),t,"unsupported-persistence-type");let r;switch(e){case Ac.SESSION:r=xa;break;case Ac.LOCAL:var i=await Wi(Ha)._isAvailable();r=i?Ha:Pa;break;case Ac.NONE:r=Qi;break;default:return pi("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(r)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Uc(this._delegate,async function(e){const t=ds(e);if(await t._initializationPromise,null!==(n=t.currentUser)&&void 0!==n&&n.isAnonymous)return new Ks({user:t.currentUser,providerId:null,operationType:"signIn"});var n=await $s(t,{returnSecureToken:!0}),n=await Ks._fromIdTokenResponse(t,"signIn",n,!0);return await t._updateCurrentUser(n.user),n}(this._delegate))}signInWithCredential(e){return Uc(this._delegate,ta(this._delegate,e))}signInWithCustomToken(e){return Uc(this._delegate,ia(this._delegate,e))}signInWithEmailAndPassword(e,t){return Uc(this._delegate,(n=this._delegate,e=e,t=t,ta(oe(n),Os.credential(e,t)).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&la(n),e})));var n}signInWithEmailLink(e,t){return Uc(this._delegate,async function(e,t,n){var r=oe(e),i=Os.credentialWithLink(t,n||bi());return _i(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),ta(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Vc(this._delegate,async function(e,t,n){const r=ds(e);var i=await so(r,t,oe(n));return new io(i,e=>ta(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return jc(kc(),this._delegate,"operation-not-supported-in-this-environment"),Uc(this._delegate,async function(e,t,n){var r=ds(e);mi(e,t,Ms);var i=oo(r,n);const s=new go(r,"signInViaPopup",t,i);return s.executeNotNull()}(this._delegate,e,Oc))}async signInWithRedirect(e){return jc(kc(),this._delegate,"operation-not-supported-in-this-environment"),await Pc(this._delegate),To(this._delegate,e,Oc)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await ha(oe(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function $c(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&Bc.getOrCreate(e)),error:t,complete:n}}zc.Persistence=Ac;class Kc{constructor(){this.providerId="phone",this._delegate=new ao(Mc(bt.auth()))}static credential(e,t){return ao.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Kc.PHONE_SIGN_IN_METHOD=ao.PHONE_SIGN_IN_METHOD,Kc.PROVIDER_ID=ao.PROVIDER_ID;const Gc=_i;class Wc{constructor(e,t,n=bt.app()){var r;Gc(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new ro(n.auth(),e,t),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(wc=bt).INTERNAL.registerComponent(new ce("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new zc(t,n)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:ri.EMAIL_SIGNIN,PASSWORD_RESET:ri.PASSWORD_RESET,RECOVER_EMAIL:ri.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:ri.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:ri.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:ri.VERIFY_EMAIL}},EmailAuthProvider:Os,FacebookAuthProvider:Us,GithubAuthProvider:qs,GoogleAuthProvider:Vs,OAuthProvider:Fs,SAMLAuthProvider:js,PhoneAuthProvider:Kc,PhoneMultiFactorGenerator:tc,RecaptchaVerifier:Wc,TwitterAuthProvider:zs,Auth:zc,AuthCredential:bs,Error:P}).setInstantiationMode("LAZY").setMultipleInstances(!1)),wc.registerVersion("@firebase/auth-compat","0.4.6");const Hc="@firebase/database";let Qc="";function Yc(e){Qc=e}class Jc{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),M(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:O(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Xc{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return F(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}var Zc,el,tl,nl,rl,il,sl=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new Jc(t)}}catch(e){}return new Xc};function al(e){var t=function(t){const n=[];let r=0;for(let a=0;a<t.length;a++){let e=t.charCodeAt(a);var i,s;55296<=e&&e<=56319&&(i=e-55296,a++,f(a<t.length,"Surrogate pair missing trail surrogate."),s=t.charCodeAt(a)-56320,e=65536+(i<<10)+s),e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(e<65536?n[r++]=e>>12|224:(n[r++]=e>>18|240,n[r++]=e>>12&63|128),n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}(e);const n=new G;return n.update(t),t=n.digest(),r.encodeByteArray(t)}const ol=sl("localStorage"),cl=sl("sessionStorage"),ll=new ve("@firebase/database"),ul=function(){let e=1;return function(){return e++}}(),hl=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=hl.apply(null,n):t+="object"==typeof n?M(n):n,t+=" "}return t};let dl=null,pl=!0;function fl(t){return function(...e){bl(t,...e)}}function gl(...e){var t="FIREBASE INTERNAL ERROR: "+hl(...e);ll.error(t)}function ml(e,t){return e===t?0:e<t?-1:1}function vl(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+M(t))}function _l(e){if("object"!=typeof e||null===e)return M(e);const t=[];for(const r in e)t.push(r);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=M(t[i]),n+=":",n+=_l(e[t[i]]);return n+="}",n}function yl(e,t){var n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}const wl=function(e,t){f(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(ll.logLevel=m.VERBOSE,dl=ll.log.bind(ll),t&&cl.set("logging_enabled",!0)):"function"==typeof e?dl=e:(dl=null,cl.remove("logging_enabled"))},bl=function(...e){var t;!0===pl&&(pl=!1,null===dl&&!0===cl.get("logging_enabled")&&wl(!0)),dl&&(t=hl.apply(null,e),dl(t))},Il=function(...e){var t=`FIREBASE FATAL ERROR: ${hl(...e)}`;throw ll.error(t),new Error(t)},Tl=function(...e){var t="FIREBASE WARNING: "+hl(...e);ll.warn(t)},El=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Tl("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Cl=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},kl="[MIN_NAME]",Sl="[MAX_NAME]",Al=function(e,t){if(e===t)return 0;if(e===kl||t===Sl)return-1;if(t===kl||e===Sl)return 1;var n=Pl(e),r=Pl(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1};function Nl(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Rl(e){f(!Cl(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));const a=[];for(s=52;s;--s)a.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)a.push(n%2?1:0),n=Math.floor(n/2);a.push(t?1:0),a.reverse();const o=a.join("");let c="";for(s=0;s<64;s+=8){let e=parseInt(o.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),c+=e}return c.toLowerCase()}function Pl(e){if(xl.test(e)){var t=Number(e);if(t>=Ol&&t<=Ml)return t}return null}function Dl(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n}const xl=new RegExp("^-?(0*)\\d{1,10}$"),Ol=-2147483648,Ml=2147483647,Ll=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw Tl("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Fl{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(n){return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){var e;null!==(e=this.appCheckProvider)&&void 0!==e&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){Tl(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Ul{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(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(bl("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}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/.',Tl(e)}}class Vl{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Vl.OWNER="owner";const ql=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Bl="websocket",jl="long_polling";class zl{constructor(e,t,n,r,i=!1,s="",a=!1,o=!1){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=o,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ol.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()&&ol.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function $l(e,t,n){f("string"==typeof t,"typeof type must == string"),f("object"==typeof n,"typeof params must == object");let r;if(t===Bl)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==jl)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);const i=[];return Nl(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class Kl{constructor(){this.counters_={}}incrementCounter(e,t=1){F(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return c(void 0,this.counters_)}}const Gl={},Wl={};function Hl(e){var t=e.toString();return Gl[t]||(Gl[t]=new Kl),Gl[t]}class Ql{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];){const n=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let e=0;e<n.length;++e)n[e]&&Ll(()=>{this.onMessage_(n[e])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class Yl{constructor(e,t,n,r,i,s,a){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=fl(e),this.stats_=Hl(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),$l(t,jl,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Ql(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),function(t){if("complete"===document.readyState)t();else{let e=!1;const n=function(){document.body?e||(e=!0,t()):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))}}(()=>{if(!this.isClosed_){this.scriptTagHolder=new Jl((...e)=>{var[t,n,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const t={start:"t"};t.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(t.cb=this.scriptTagHolder.uniqueCallbackIdentifier),t.v="5",this.transportSessionId&&(t.s=this.transportSessionId),this.lastSessionId&&(t.ls=this.lastSessionId),this.applicationId&&(t.p=this.applicationId),this.appCheckToken&&(t.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&ql.test(location.hostname)&&(t.r="f");var e=this.urlFn(t);this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{})}})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Yl.forceAllow_=!0}static forceDisallow(){Yl.forceDisallow_=!0}static isAvailable(){return!!Yl.forceAllow_||!(Yl.forceDisallow_||"undefined"==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){var t=M(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var t=i(t),n=yl(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const 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){var t=M(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class Jl{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=ul(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=Jl.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){bl("frame writing exception"),e.stack&&bl(e.stack),bl(e)}}}static createIFrame_(){const t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||bl("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}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)));const 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<(0<this.pendingSegs.length?2:1)){this.currentSerial++;const i={};i.id=this.myID,i.pw=this.myPW,i.ser=this.currentSerial;var n=this.urlFn(i);let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{bl("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}catch(e){}},Math.floor(1))}}let Xl=null;"undefined"!=typeof MozWebSocket?Xl=MozWebSocket:"undefined"!=typeof WebSocket&&(Xl=WebSocket);class Zl{constructor(e,t,n,r,i,s,a){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=fl(this.connId),this.stats_=Hl(t),this.connURL=Zl.connectionURL_(t,s,a,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){const s={v:"5"};return"undefined"!=typeof location&&location.hostname&&ql.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s.ac=r),i&&(s.p=i),$l(e,Bl,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ol.set("previous_websocket_failure",!0);try{S(),this.mySock=new Xl(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},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.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){Zl.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return"undefined"==typeof navigator||!navigator.userAgent||(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4&&(e=!0),!e&&null!==Xl&&!Zl.forceDisallow_}static previouslyFailed(){return ol.isInMemoryStorage||!0===ol.get("previous_websocket_failure")}markConnectionHealthy(){ol.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=O(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(f(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=M(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var n=yl(t,16384);1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}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)}}}Zl.responsesRequiredToBeHealthy=2,Zl.healthyTimeout=3e4;class eu{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[Yl,Zl]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){var t=Zl&&Zl.isAvailable();let n=t&&!Zl.previouslyFailed();if(e.webSocketOnly&&(t||Tl("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[Zl];else{const r=this.transports_=[];for(const i of eu.ALL_TRANSPORTS)i&&i.isAvailable()&&r.push(i);eu.globalTransportInitialized_=!0}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}eu.globalTransportInitialized_=!1;class tu{constructor(e,t,n,r,i,s,a,o,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=a,this.onDisconnect_=o,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=fl("c:"+this.id+":"),this.transportManager_=new eu(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),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));var r=e.healthyTimeout||0;0<r&&(this.healthyTimeout_=Dl(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?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(r)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):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){var t;"t"in e&&("a"===(t=e.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){var t=vl("t",e),n=vl("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}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:"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){var t=vl("t",e),n=vl("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){var t=vl("t",e);if("d"in e){var n=e.d;if("h"===t){const r=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(r.h=this.repoInfo_.host),this.onHandshake_(r)}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?gl("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):gl("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&Tl("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var 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;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),Dl(()=>{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):Dl(()=>{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_(){var 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()&&(ol.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 nu{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class ru{constructor(e){this.allowedEvents_=e,this.listeners_={},f(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){const r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){f(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class iu extends ru{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||I()||(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 iu}getInitialEvent(e){return f("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class su{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function au(){return new su("")}function ou(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function cu(e){return e.pieces_.length-e.pieceNum_}function lu(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new su(e.pieces_,t)}function uu(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function hu(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function du(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new su(t,0)}function pu(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof su)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new su(n,0)}function fu(e){return e.pieceNum_>=e.pieces_.length}function gu(e,t){var n=ou(e),r=ou(t);if(null===n)return t;if(n===r)return gu(lu(e),lu(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function mu(e,t){var n=hu(e,0),r=hu(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Al(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function vu(e,t){if(cu(e)!==cu(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function _u(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(cu(e)>cu(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class yu{constructor(e,t){this.errorPrefix_=t,this.parts_=hu(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=te(this.parts_[n]);wu(this)}}function wu(e){if(768<e.byteLength_)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(32<e.parts_.length)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+bu(e))}function bu(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class Iu extends ru{constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}static getInstance(){return new Iu}getInitialEvent(e){return f("visible"===e,"Unknown event type: "+e),[this.visible_]}}class Tu extends nu{constructor(e,t,n,r,i,s,a,o){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=a,this.authOverride_=o,this.id=Tu.nextPersistentConnectionId_++,this.log_=fl("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,o&&!S())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Iu.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&iu.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(M(i)),f(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const n=new y;var t={p:e._path.toString(),q:e._queryObject};this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?n.resolve(t):n.reject(t)}}),this.outstandingGetCount_++;t=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(t),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),f(!this.listens.get(s).has(i),"listen() called twice for same path/queryId.");var a={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(s).set(i,a),this.connected_&&this.sendListen_(a)}sendGet_(t){const n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(r){const i=r.query,s=i._path.toString(),a=i._queryIdentifier;this.log_("Listen on "+s+" for "+a);const e={p:s};r.tag&&(e.q=i._queryObject,e.t=r.tag),e.h=r.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s;Tu.warnOnListenWarnings_(t,i),(this.listens.get(s)&&this.listens.get(s).get(a))===r&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(s,a),r.onComplete&&r.onComplete(n,t))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&F(e,"w")){const i=U(e,"w");var n,r;Array.isArray(i)&&~i.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),Tl("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+`${r} 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){var t;(e&&40===e.length||(e=e,"object"==typeof(t=L(e).claims)&&!0===t.admin))&&(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_){const r=this.authToken_;var e=function(e){const t=L(e),n=t.claims;return!!n&&"object"==typeof n&&n.hasOwnProperty("iat")}(r)?"auth":"gauth";const t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}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,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const s={p:t,d:n};void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++;var a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+t)}sendPut_(t){const n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;const r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+M(e));var t=e.r;const 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;"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):gl("Unrecognized action received from server: "+M(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){f(!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_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=(new Date).getTime()-this.lastConnectionAttemptTime_,e=Math.max(0,this.reconnectDelay_-e),e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),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;var e=this.onDataMessage_.bind(this),r=this.onReady_.bind(this);const u=this.onRealtimeDisconnect_.bind(this);var i=this.id+":"+Tu.nextConnectionId_++,s=this.lastSessionId;let t=!1,n=null;var a=function(){n?n.close():(t=!0,u())};this.realtime_={close:a,sendRequest:function(e){f(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}};var o=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{var[c,l]=await Promise.all([this.authTokenProvider_.getToken(o),this.appCheckTokenProvider_.getToken(o)]);t?bl("getToken() completed but was canceled"):(bl("getToken() completed. Creating connection."),this.authToken_=c&&c.accessToken,this.appCheckToken_=l&&l.token,n=new tu(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,r,u,e=>{Tl(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&Tl(e),a())}}}interrupt(e){bl("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){bl("Resuming connection for reason: "+e),delete this.interruptReasons_[e],V(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const 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=>_l(e)).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n=new su(e).toString();let r;if(this.listens.has(n)){const i=this.listens.get(n);r=i.get(t),i.delete(t),0===i.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){bl("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){bl("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const t of this.listens.values())for(const n of t.values())this.sendListen_(n);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){const e={};e["sdk.js."+Qc.replace(/\./g,"-")]=1,I()?e["framework.cordova"]=1:C()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=iu.getInstance().currentlyOnline();return V(this.interruptReasons_)&&e}}Tu.nextPersistentConnectionId_=0,Tu.nextConnectionId_=0;class Eu{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new Eu(e,t)}}class Cu{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new Eu(kl,e),r=new Eu(kl,t);return 0!==this.compare(n,r)}minPost(){return Eu.MIN}}let ku;class Su extends Cu{static get __EMPTY_NODE(){return ku}static set __EMPTY_NODE(e){ku=e}compare(e,t){return Al(e.name,t.name)}isDefinedOn(e){throw u("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return Eu.MIN}maxPost(){return new Eu(Sl,ku)}makePost(e,t){return f("string"==typeof e,"KeyIndex indexValue must always be a string."),new Eu(e,ku)}toString(){return".key"}}const Au=new Su;class Nu{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){if(0===this.nodeStack_.length)return null;var e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class Ru{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:Ru.RED,this.left=null!=r?r:Du.EMPTY_NODE,this.right=null!=i?i:Du.EMPTY_NODE}copy(e,t,n,r,i){return new Ru(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}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 r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return Du.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),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)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 Du.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){var e=this.copy(null,null,Ru.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,Ru.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var 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_(){var e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}Ru.RED=!0,Ru.BLACK=!1;class Pu{copy(e,t,n,r,i){return this}insert(e,t,n){return new Ru(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}}class Du{constructor(e,t=Du.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Du(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,Ru.BLACK,null,null))}remove(e){return new Du(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Ru.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new Nu(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Nu(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Nu(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Nu(this.root_,null,this.comparator_,!0,e)}}function xu(e,t){return Al(e.name,t.name)}function Ou(e,t){return Al(e,t)}Du.EMPTY_NODE=new Pu;let Mu;function Lu(e){return"number"==typeof e?"number:"+Rl(e):"string:"+e}function Fu(e){var t;e.isLeafNode()?(t=e.val(),f("string"==typeof t||"number"==typeof t||"object"==typeof t&&F(t,".sv"),"Priority must be a string or number.")):f(e===Mu||e.isEmpty(),"priority of unexpected type."),f(e===Mu||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let Uu;class Vu{constructor(e,t=Vu.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,f(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Fu(this.priorityNode_)}static set __childrenNodeConstructor(e){Uu=e}static get __childrenNodeConstructor(){return Uu}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Vu(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Vu.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return fu(e)?this:".priority"===ou(e)?this.priorityNode_:Vu.__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:Vu.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=ou(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(f(".priority"!==n||1===cu(e),".priority must be the last token in a path"),this.updateImmediateChild(n,Vu.__childrenNodeConstructor.EMPTY_NODE.updateChild(lu(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:"+Lu(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"==t?Rl(this.value_):this.value_,this.lazyHash_=al(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Vu.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Vu.__childrenNodeConstructor?-1:(f(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=Vu.VALUE_TYPE_ORDER.indexOf(t),i=Vu.VALUE_TYPE_ORDER.indexOf(n);return f(0<=r,"Unknown leaf type: "+t),f(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&(this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_))}}Vu.VALUE_TYPE_ORDER=["object","boolean","number","string"];let qu,Bu;const ju=new class extends Cu{compare(e,t){const n=e.node.getPriority();var r=t.node.getPriority(),r=n.compareTo(r);return 0===r?Al(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return Eu.MIN}maxPost(){return new Eu(Sl,new Vu("[PRIORITY-POST]",Bu))}makePost(e,t){var n=qu(e);return new Eu(t,new Vu("[PRIORITY-POST]",n))}toString(){return".priority"}},zu=Math.log(2);class $u{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/zu,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=e+1&r}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function Ku(c,e,l,t){c.sort(e);const u=function(e,t){var n=t-e;let r,i;if(0==n)return null;if(1==n)return r=c[e],i=l?l(r):r,new Ru(i,r.node,Ru.BLACK,null,null);var s=parseInt(n/2,10)+e,a=u(e,s),n=u(s+1,t);return r=c[s],i=l?l(r):r,new Ru(i,r.node,Ru.BLACK,a,n)};var n=function(e){let s=null,a=null,o=c.length;function t(e,t){var n=o-e,r=o;o-=e;var i=u(1+n,r),r=c[n],n=l?l(r):r;!function(e){if(s){s.left=e;s=e}else{a=e;s=e}}(new Ru(n,r.node,t,null,i))}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,Ru.BLACK):(t(r,Ru.BLACK),t(r,Ru.RED))}return a}(new $u(c.length));return new Du(t||e,n)}let Gu;const Wu={};class Hu{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return f((Wu,ju),"ChildrenNode.ts has not been loaded"),Gu=Gu||new Hu({".priority":Wu},{".priority":ju}),Gu}get(e){var t=U(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof Du?t:null}hasIndex(e){return F(this.indexSet_,e.toString())}addIndex(e,t){f(e!==Au,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(Eu.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let a;a=r?Ku(n,e.getCompare()):Wu;var o=e.toString();const c=Object.assign({},this.indexSet_);c[o]=e;const l=Object.assign({},this.indexes_);return l[o]=a,new Hu(l,c)}addToIndexes(a,o){var e=q(this.indexes_,(t,e)=>{const n=U(this.indexSet_,e);if(f(n,"Missing index implementation for "+e),t===Wu){if(n.isDefinedOn(a.node)){const i=[],s=o.getIterator(Eu.Wrap);let e=s.getNext();for(;e;)e.name!==a.name&&i.push(e),e=s.getNext();return i.push(a),Ku(i,n.getCompare())}return Wu}{var r=o.get(a.name);let e=t;return r&&(e=e.remove(new Eu(a.name,r))),e.insert(a,a.node)}});return new Hu(e,this.indexSet_)}removeFromIndexes(n,r){var e=q(this.indexes_,e=>{if(e===Wu)return e;var t=r.get(n.name);return t?e.remove(new Eu(n.name,t)):e});return new Hu(e,this.indexSet_)}}let Qu;class Yu{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Fu(this.priorityNode_),this.children_.isEmpty()&&f(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return Qu=Qu||new Yu(new Du(Ou),null,Hu.Default)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Qu}updatePriority(e){return this.children_.isEmpty()?this:new Yu(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?Qu:t}getChild(e){var t=ou(e);return null===t?this:this.getImmediateChild(t).getChild(lu(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(f(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new Eu(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?Qu:this.priorityNode_;return new Yu(e,i,t)}}updateChild(e,t){var n=ou(e);if(null===n)return t;f(".priority"!==ou(e)||1===cu(e),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(lu(e),t);return this.updateImmediateChild(n,r)}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;const r={};let i=0,s=0,a=!0;if(this.forEachChild(ju,(e,t)=>{r[e]=t.val(n),i++,a&&Yu.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):a=!1}),!n&&a&&s<2*i){const e=[];for(const t in r)e[t]=r[t];return e}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+Lu(this.getPriority().val())+":"),this.forEachChild(ju,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":al(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new Eu(e,t));return i?i.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.minKey();return n&&n.name}return this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new Eu(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.maxKey();return n&&n.name}return this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new Eu(t,this.children_.get(t)):null}forEachChild(e,t){const 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(t,n){const e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{const r=this.children_.getIteratorFrom(t.name,Eu.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{const r=this.children_.getReverseIteratorFrom(t.name,Eu.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===Xu?-1:0}withIndex(e){if(e===Au||this.indexMap_.hasIndex(e))return this;var t=this.indexMap_.addIndex(e,this.children_);return new Yu(this.children_,this.priorityNode_,t)}isIndexed(e){return e===Au||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{const r=this.getIterator(ju),i=n.getIterator(ju);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}return!1}}resolveIndex_(e){return e===Au?null:this.indexMap_.get(e.toString())}}Yu.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class Ju extends Yu{constructor(){super(new Du(Ou),Yu.EMPTY_NODE,Hu.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return Yu.EMPTY_NODE}isEmpty(){return!1}}const Xu=new Ju;Object.defineProperties(Eu,{MIN:{value:new Eu(kl,Yu.EMPTY_NODE)},MAX:{value:new Eu(Sl,Xu)}}),Su.__EMPTY_NODE=Yu.EMPTY_NODE,Vu.__childrenNodeConstructor=Yu,Zc=Xu,Mu=Zc,el=Xu,Bu=el;const Zu=!0;function eh(i,e=null){if(null===i)return Yu.EMPTY_NODE;if("object"==typeof i&&".priority"in i&&(e=i[".priority"]),f(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(i="object"==typeof i&&".value"in i&&null!==i[".value"]?i[".value"]:i)||".sv"in i){var t=i;return new Vu(t,eh(e))}if(i instanceof Array||!Zu){let r=Yu.EMPTY_NODE;return Nl(i,(e,t)=>{if(F(i,e)&&"."!==e.substring(0,1)){const n=eh(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(eh(e))}{const s=[];let r=!1;if(Nl(i,(e,t)=>{if("."!==e.substring(0,1)){const n=eh(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new Eu(e,n)))}}),0===s.length)return Yu.EMPTY_NODE;var n=Ku(s,xu,e=>e.name,Ou);if(r){t=Ku(s,ju.getCompare());return new Yu(n,eh(e),new Hu({".priority":t},{".priority":ju}))}return new Yu(n,eh(e),Hu.Default)}}qu=eh;class th extends Cu{constructor(e){super(),this.indexPath_=e,f(!fu(e)&&".priority"!==ou(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){const n=this.extractChild(e.node);var r=this.extractChild(t.node),r=n.compareTo(r);return 0===r?Al(e.name,t.name):r}makePost(e,t){var n=eh(e),n=Yu.EMPTY_NODE.updateChild(this.indexPath_,n);return new Eu(t,n)}maxPost(){var e=Yu.EMPTY_NODE.updateChild(this.indexPath_,Xu);return new Eu(Sl,e)}toString(){return hu(this.indexPath_,0).join("/")}}const nh=new class extends Cu{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?Al(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return Eu.MIN}maxPost(){return Eu.MAX}makePost(e,t){var n=eh(e);return new Eu(t,n)}toString(){return".value"}};function rh(e){return{type:"value",snapshotNode:e}}function ih(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function sh(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function ah(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class oh{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){f(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(r).equals(n.getChild(r))&&a.isEmpty()===n.isEmpty()?e:(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(sh(t,a)):f(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?s.trackChildChange(ih(t,n)):s.trackChildChange(ah(t,n,a))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(ju,(e,t)=>{n.hasChild(e)||i.trackChildChange(sh(e,t))}),n.isLeafNode()||n.forEachChild(ju,(e,t)=>{if(r.hasChild(e)){const n=r.getImmediateChild(e);n.equals(t)||i.trackChildChange(ah(e,t,n))}else i.trackChildChange(ih(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?Yu.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class ch{constructor(e){this.indexedFilter_=new oh(e.getIndex()),this.index_=e.getIndex(),this.startPost_=ch.getStartPost_(e),this.endPost_=ch.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){var t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,s){return this.matches(new Eu(t,n))||(n=Yu.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?Yu.EMPTY_NODE:t).withIndex(this.index_);r=r.updatePriority(Yu.EMPTY_NODE);const i=this;return t.forEachChild(ju,(e,t)=>{i.matches(new Eu(e,t))||(r=r.updateImmediateChild(e,Yu.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){var t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){var t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class lh{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=>{var t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{var t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new ch(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new Eu(t,n))||(n=Yu.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,n,t){let r;if(n.isLeafNode()||n.isEmpty())r=Yu.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<n.numChildren()&&n.isIndexed(this.index_)){r=Yu.EMPTY_NODE.withIndex(this.index_);let e;e=this.reverse_?n.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):n.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let t=0;for(;e.hasNext()&&t<this.limit_;){var i=e.getNext();if(this.withinDirectionalStart(i)){if(!this.withinDirectionalEnd(i))break;r=r.updateImmediateChild(i.name,i.node),t++}}}else{r=n.withIndex(this.index_),r=r.updatePriority(Yu.EMPTY_NODE);let e;e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_);let t=0;for(;e.hasNext();){var s=e.getNext();t<this.limit_&&this.withinDirectionalStart(s)&&this.withinDirectionalEnd(s)?t++:r=r.updateImmediateChild(s.name,Yu.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){const d=this.index_.getCompare();s=(e,t)=>d(t,e)}else s=this.index_.getCompare();const a=e;f(a.numChildren()===this.limit_,"");var o=new Eu(t,n),c=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),l=this.rangedFilter_.matches(o);if(a.hasChild(t)){var u=a.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,c,this.reverse_);for(;null!=e&&(e.name===t||a.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var h=null==e?1:s(e,o);if(l&&!n.isEmpty()&&0<=h)return null!=i&&i.trackChildChange(ah(t,n,u)),a.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(sh(t,u));const p=a.updateImmediateChild(t,Yu.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(ih(e.name,e.node)),p.updateImmediateChild(e.name,e.node)):p}}return!n.isEmpty()&&l&&0<=s(c,o)?(null!=i&&(i.trackChildChange(sh(c.name,c.node)),i.trackChildChange(ih(t,n))),a.updateImmediateChild(t,n).updateImmediateChild(c.name,Yu.EMPTY_NODE)):e}}class uh{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_=ju}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return f(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return f(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:kl}hasEnd(){return this.endSet_}getIndexEndValue(){return f(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return f(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Sl}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return f(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_===ju}copy(){const e=new uh;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 hh(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function dh(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function ph(e,t){const n=e.copy();return n.index_=t,n}function fh(e){const t={};if(e.isDefault())return t;let n;var r;return n=e.index_===ju?"$priority":e.index_===nh?"$value":e.index_===Au?"$key":(f(e.index_ instanceof th,"Unrecognized index type!"),e.index_.toString()),t.orderBy=M(n),e.startSet_&&(r=e.startAfterSet_?"startAfter":"startAt",t[r]=M(e.indexStartValue_),e.startNameSet_&&(t[r]+=","+M(e.indexStartName_))),e.endSet_&&(r=e.endBeforeSet_?"endBefore":"endAt",t[r]=M(e.indexEndValue_),e.endNameSet_&&(t[r]+=","+M(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function gh(t){const n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_),n.sin=!t.startAfterSet_),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_),n.ein=!t.endBeforeSet_),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==ju&&(n.i=t.index_.toString()),n}class mh extends nu{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=fl("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(f(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,r,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const a=mh.getListenId_(e,r),o={};this.listens_[a]=o;var n=fh(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),U(this.listens_,a)===o){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=mh.getListenId_(e,t);delete this.listens_[n]}get(e){var t=fh(e._queryParams);const r=e._path.toString(),i=new y;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},a){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);const n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+z(s);this.log_("Sending REST request for "+n);const r=new XMLHttpRequest;r.onreadystatechange=()=>{if(a&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=O(r.responseText)}catch(e){Tl("Failed to parse JSON response for "+n+": "+r.responseText)}a(null,e)}else 401!==r.status&&404!==r.status&&Tl("Got unsuccessful REST response for "+n+" Status: "+r.status),a(r.status);a=null}},r.open("GET",n,!0),r.send()})}}class vh{constructor(){this.rootNode_=Yu.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function _h(){return{value:null,children:new Map}}function yh(e,t,n){var r;fu(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=ou(t),e.children.has(r)||e.children.set(r,_h()),yh(e.children.get(r),t=lu(t),n))}function wh(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{wh(t,new su(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class bh{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();const n=Object.assign({},e);return this.last_&&Nl(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class Ih{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new bh(e);var n=1e4+2e4*Math.random();Dl(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();const n={};let r=!1;Nl(e,(e,t)=>{0<t&&F(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),Dl(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function Th(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Eh(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function Ch(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(GS=tl=tl||{})[GS.OVERWRITE=0]="OVERWRITE",GS[GS.MERGE=1]="MERGE",GS[GS.ACK_USER_WRITE=2]="ACK_USER_WRITE",GS[GS.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class kh{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=tl.ACK_USER_WRITE,this.source=Th()}operationForChild(e){if(fu(this.path)){if(null!=this.affectedTree.value)return f(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var t=this.affectedTree.subtree(new su(e));return new kh(au(),t,this.revert)}return f(ou(this.path)===e,"operationForChild called for unrelated child."),new kh(lu(this.path),this.affectedTree,this.revert)}}class Sh{constructor(e,t){this.source=e,this.path=t,this.type=tl.LISTEN_COMPLETE}operationForChild(e){return fu(this.path)?new Sh(this.source,au()):new Sh(this.source,lu(this.path))}}class Ah{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=tl.OVERWRITE}operationForChild(e){return fu(this.path)?new Ah(this.source,au(),this.snap.getImmediateChild(e)):new Ah(this.source,lu(this.path),this.snap)}}class Nh{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=tl.MERGE}operationForChild(e){if(fu(this.path)){const t=this.children.subtree(new su(e));return t.isEmpty()?null:t.value?new Ah(this.source,au(),t.value):new Nh(this.source,au(),t)}return f(ou(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Nh(this.source,lu(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Rh{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(fu(e))return this.isFullyInitialized()&&!this.filtered_;var t=ou(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Ph{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function Dh(n,e,t,r){var i=[];const s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),xh(n,i,"child_removed",e,r,t),xh(n,i,"child_added",e,r,t),xh(n,i,"child_moved",s,r,t),xh(n,i,"child_changed",e,r,t),xh(n,i,"value",e,r,t),i}function xh(s,a,t,e,o,c){const n=e.filter(e=>e.type===t);n.sort((e,t)=>function(e,t,n){if(null==t.childName||null==n.childName)throw u("Should only compare child_ events.");var r=new Eu(t.childName,t.snapshotNode),i=new Eu(n.childName,n.snapshotNode);return e.index_.compare(r,i)}(s,e,t)),n.forEach(t=>{const n=(e=s,i=c,"value"===(r=t).type||"child_removed"===r.type||(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_)),r);var e,r,i;o.forEach(e=>{e.respondsTo(t.type)&&a.push(e.createEvent(n,s.query_))})})}function Oh(e,t){return{eventCache:e,serverCache:t}}function Mh(e,t,n,r){return Oh(new Rh(t,n,r),e.serverCache)}function Lh(e,t,n,r){return Oh(e.eventCache,new Rh(t,n,r))}function Fh(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function Uh(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Vh;class qh{constructor(e,t=(Vh=Vh||new Du(ml),Vh)){this.value=e,this.children=t}static fromObject(e){let n=new qh(null);return Nl(e,(e,t)=>{n=n.set(new su(e),t)}),n}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:au(),value:this.value};if(fu(e))return null;{var n=ou(e);const i=this.children.get(n);if(null===i)return null;var r=i.findRootMostMatchingPathAndValue(lu(e),t);return null==r?null:{path:pu(new su(n),r.path),value:r.value}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(fu(e))return this;{var t=ou(e);const n=this.children.get(t);return null!==n?n.subtree(lu(e)):new qh(null)}}set(e,t){if(fu(e))return new qh(t,this.children);{var n=ou(e);const i=this.children.get(n)||new qh(null);var r=i.set(lu(e),t),r=this.children.insert(n,r);return new qh(this.value,r)}}remove(t){if(fu(t))return this.children.isEmpty()?new qh(null):new qh(null,this.children);{var n=ou(t);const r=this.children.get(n);if(r){const i=r.remove(lu(t));let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&e.isEmpty()?new qh(null):new qh(this.value,e)}return this}}get(e){if(fu(e))return this.value;{var t=ou(e);const n=this.children.get(t);return n?n.get(lu(e)):null}}setTree(t,n){if(fu(t))return n;{var r=ou(t);const i=this.children.get(r)||new qh(null),s=i.setTree(lu(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new qh(this.value,e)}}fold(e){return this.fold_(au(),e)}fold_(n,r){const i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(pu(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,au(),t)}findOnPath_(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(fu(e))return null;{r=ou(e);const i=this.children.get(r);return i?i.findOnPath_(lu(e),pu(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,au(),t)}foreachOnPath_(e,t,n){if(fu(e))return this;{this.value&&n(t,this.value);var r=ou(e);const i=this.children.get(r);return i?i.foreachOnPath_(lu(e),pu(t,r),n):new qh(null)}}foreach(e){this.foreach_(au(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(pu(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class Bh{constructor(e){this.writeTree_=e}static empty(){return new Bh(new qh(null))}}function jh(t,n,r){if(fu(n))return new Bh(new qh(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=gu(s,n);return e=e.updateChild(i,r),new Bh(t.writeTree_.set(s,e))}s=new qh(r),s=t.writeTree_.setTree(n,s);return new Bh(s)}function zh(e,n,t){let r=e;return Nl(t,(e,t)=>{r=jh(r,pu(n,e),t)}),r}function $h(e,t){if(fu(t))return Bh.empty();var n=e.writeTree_.setTree(t,new qh(null));return new Bh(n)}function Kh(e,t){return null!=Gh(e,t)}function Gh(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(gu(n.path,t)):null}function Wh(e){const n=[],t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(ju,(e,t)=>{n.push(new Eu(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new Eu(e,t.value))}),n}function Hh(e,t){if(fu(t))return e;var n=Gh(e,t);return null!=n?new Bh(new qh(n)):new Bh(e.writeTree_.subtree(t))}function Qh(e){return e.writeTree_.isEmpty()}function Yh(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(f(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(pu(i,e),t,s)}),s=!s.getChild(i).isEmpty()&&null!==n?s.updateChild(pu(i,".priority"),n):s}}}(au(),e.writeTree_,t)}function Jh(e,t){return ld(t,e)}function Xh(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);f(0<=r,"removeWrite called with nonexistent writeId.");const i=t.allWrites[r];t.allWrites.splice(r,1);let s=i.visible,a=!1,o=t.allWrites.length-1;for(;s&&0<=o;){var c=t.allWrites[o];c.visible&&(o>=r&&function(e,t){{if(e.snap)return _u(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&_u(pu(e.path,n),t))return!0;return!1}}(c,i.path)?s=!1:_u(i.path,c.path)&&(a=!0)),o--}return!!s&&(a?((e=t).visibleWrites=ed(e.allWrites,Zh,au()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=$h(t.visibleWrites,i.path):Nl(i.children,e=>{t.visibleWrites=$h(t.visibleWrites,pu(i.path,e))}),!0)}function Zh(e){return e.visible}function ed(e,t,n){let r=Bh.empty();for(let s=0;s<e.length;++s){const a=e[s];if(t(a)){var i=a.path;let e;if(a.snap)_u(n,i)?(e=gu(n,i),r=jh(r,e,a.snap)):_u(i,n)&&(e=gu(i,n),r=jh(r,au(),a.snap.getChild(e)));else{if(!a.children)throw u("WriteRecord should have .snap or .children");if(_u(n,i))e=gu(n,i),r=zh(r,e,a.children);else if(_u(i,n))if(e=gu(i,n),fu(e))r=zh(r,au(),a.children);else{const o=U(a.children,ou(e));o&&(i=o.getChild(lu(e)),r=jh(r,au(),i))}}}}return r}function td(e,t,n,r,i){if(r||i){var s=Hh(e.visibleWrites,t);if(!i&&Qh(s))return n;if(i||null!=n||Kh(s,au()))return Yh(ed(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(_u(e.path,t)||_u(t,e.path))},t),n||Yu.EMPTY_NODE);return null}s=Gh(e.visibleWrites,t);if(null!=s)return s;s=Hh(e.visibleWrites,t);return Qh(s)?n:null!=n||Kh(s,au())?Yh(s,n||Yu.EMPTY_NODE):null}function nd(e,t,n,r){return td(e.writeTree,e.treePath,t,n,r)}function rd(e,t){return function(e,t,n){let r=Yu.EMPTY_NODE;const i=Gh(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(ju,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const s=Hh(e.visibleWrites,t);return n.forEachChild(ju,(e,t)=>{var n=Yh(Hh(s,new su(e)),t);r=r.updateImmediateChild(e,n)}),Wh(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return Wh(Hh(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function id(e,t,n,r){return function(e,t,n,r,i){f(r||i,"Either existingEventSnap or existingServerSnap must exist");var s=pu(t,n);return Kh(e.visibleWrites,s)?null:Qh(s=Hh(e.visibleWrites,s))?i.getChild(n):Yh(s,i.getChild(n))}(e.writeTree,e.treePath,t,n,r)}function sd(e,t){return n=e.writeTree,t=pu(e.treePath,t),Gh(n.visibleWrites,t);var n}function ad(e,t,n,r,i,s){return function(e,t,n,r,i,s,a){let o;var c=Hh(e.visibleWrites,t),l=Gh(c,au());if(null!=l)o=l;else{if(null==n)return[];o=Yh(c,n)}if(o=o.withIndex(a),o.isEmpty()||o.isLeafNode())return[];{const u=[],h=a.getCompare(),d=s?o.getReverseIteratorFrom(r,a):o.getIteratorFrom(r,a);let e=d.getNext();for(;e&&u.length<i;)0!==h(e,r)&&u.push(e),e=d.getNext();return u}}(e.writeTree,e.treePath,t,n,r,i,s)}function od(e,t,n){return r=e.writeTree,e=e.treePath,n=n,i=pu(e,t=t),null!=(s=Gh(r.visibleWrites,i))?s:n.isCompleteForChild(t)?Yh(Hh(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function cd(e,t){return ld(pu(e.treePath,t),e.writeTree)}function ld(e,t){return{treePath:e,writeTree:t}}class ud{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName;f("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),f(".priority"!==n,"Only non-priority child changes can be tracked.");var r=this.changeMap.get(n);if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,ah(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,sh(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,ih(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw u("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,ah(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const hd=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class dd{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.optCompleteServerCache_?new Rh(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return od(this.writes_,e,n)}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:Uh(this.viewCache_),r=ad(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function pd(e,t,n,r,i){const s=new ud;let a,o;if(n.type===tl.OVERWRITE){var c=n;a=c.source.fromUser?md(e,t,c.path,c.snap,r,i,s):(f(c.source.fromServer,"Unknown source."),o=c.source.tagged||t.serverCache.isFiltered()&&!fu(c.path),gd(e,t,c.path,c.snap,r,i,o,s))}else if(n.type===tl.MERGE){c=n;a=c.source.fromUser?function(r,i,s,e,a,o,c){let l=i;return e.foreach((e,t)=>{var n=pu(s,e);vd(i,ou(n))&&(l=md(r,l,n,t,a,o,c))}),e.foreach((e,t)=>{var n=pu(s,e);vd(i,ou(n))||(l=md(r,l,n,t,a,o,c))}),l}(e,t,c.path,c.children,r,i,s):(f(c.source.fromServer,"Unknown source."),o=c.source.tagged||t.serverCache.isFiltered(),yd(e,t,c.path,c.children,r,i,o,s))}else if(n.type===tl.ACK_USER_WRITE){var l=n;a=l.revert?function(n,r,i,s,e,a){let o;{if(null!=sd(s,i))return r;{var c=new dd(s,r,e);const u=r.eventCache.getNode();let t;if(fu(i)||".priority"===ou(i)){let e;e=r.serverCache.isFullyInitialized()?nd(s,Uh(r)):(l=r.serverCache.getNode(),f(l instanceof Yu,"serverChildren would be complete if leaf node"),rd(s,l)),e=e,t=n.filter.updateFullNode(u,e,a)}else{var l=ou(i);let e=od(s,l,r.serverCache);null==e&&r.serverCache.isCompleteForChild(l)&&(e=u.getImmediateChild(l)),t=null!=e?n.filter.updateChild(u,l,e,lu(i),c,a):r.eventCache.getNode().hasChild(l)?n.filter.updateChild(u,l,Yu.EMPTY_NODE,lu(i),c,a):u,t.isEmpty()&&r.serverCache.isFullyInitialized()&&(o=nd(s,Uh(r)),o.isLeafNode()&&(t=n.filter.updateFullNode(t,o,a)))}return o=r.serverCache.isFullyInitialized()||null!=sd(s,au()),Mh(r,t,o,n.filter.filtersNodes())}}}(e,t,l.path,r,i,s):function(e,t,i,n,s,a,o){if(null!=sd(s,i))return t;const c=t.serverCache.isFiltered(),l=t.serverCache;{if(null!=n.value){if(fu(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return gd(e,t,i,l.getNode().getChild(i),s,a,c,o);if(fu(i)){let n=new qh(null);return l.getNode().forEachChild(Au,(e,t)=>{n=n.set(new su(e),t)}),yd(e,t,i,n,s,a,c,o)}return t}{let r=new qh(null);return n.foreach((e,t)=>{var n=pu(i,e);l.isCompleteForPath(n)&&(r=r.set(e,l.getNode().getChild(n)))}),yd(e,t,i,r,s,a,c,o)}}}(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==tl.LISTEN_COMPLETE)throw u("Unknown operation type: "+n.type);a=function(e,t,n,r,i){const s=t.serverCache,a=Lh(t,s.getNode(),s.isFullyInitialized()||fu(n),s.isFiltered());return fd(e,a,n,r,hd,i)}(e,t,n.path,r,s)}l=s.getChanges();return function(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty();const s=Fh(e);(0<n.length||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(rh(Fh(t)))}}(t,a,l),{viewCache:a,changes:l}}function fd(r,i,s,a,o,c){const l=i.eventCache;if(null!=sd(a,s))return i;{let t,n;if(fu(s)){var e;f(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=rd(a,(e=Uh(i))instanceof Yu?e:Yu.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=nd(a,Uh(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=ou(s);if(".priority"===u){f(1===cu(s),"Can't have a priority with additional path components");var h=l.getNode();n=i.serverCache.getNode();var d=id(a,s,h,n);t=null!=d?r.filter.updatePriority(h,d):l.getNode()}else{h=lu(s);let e;e=l.isCompleteForChild(u)?(n=i.serverCache.getNode(),null!=(d=id(a,s,l.getNode(),n))?l.getNode().getImmediateChild(u).updateChild(h,d):l.getNode().getImmediateChild(u)):od(a,u,i.serverCache),t=null!=e?r.filter.updateChild(l.getNode(),u,e,h,o,c):l.getNode()}}return Mh(i,t,l.isFullyInitialized()||fu(s),r.filter.filtersNodes())}}function gd(e,t,n,r,i,s,a,o){const c=t.serverCache;let l;const u=a?e.filter:e.filter.getIndexedFilter();if(fu(n))l=u.updateFullNode(c.getNode(),r,null);else if(u.filtersNodes()&&!c.isFiltered()){var h=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),h,null)}else{var d=ou(n);if(!c.isCompleteForPath(n)&&1<cu(n))return t;var p=lu(n);const f=c.getNode().getImmediateChild(d);h=f.updateChild(p,r);l=".priority"===d?u.updatePriority(c.getNode(),h):u.updateChild(c.getNode(),d,h,p,hd,null)}p=Lh(t,l,c.isFullyInitialized()||fu(n),u.filtersNodes());return fd(e,p,n,i,new dd(i,p,s),o)}function md(t,n,r,i,e,s,a){const o=n.eventCache;let c,l;const u=new dd(e,n,s);if(fu(r))l=t.filter.updateFullNode(n.eventCache.getNode(),i,a),c=Mh(n,l,!0,t.filter.filtersNodes());else{var h=ou(r);if(".priority"===h)l=t.filter.updatePriority(n.eventCache.getNode(),i),c=Mh(n,l,o.isFullyInitialized(),o.isFiltered());else{var d=lu(r);const p=o.getNode().getImmediateChild(h);let e;if(fu(d))e=i;else{const f=u.getCompleteChild(h);e=null!=f?".priority"===uu(d)&&f.getChild(du(d)).isEmpty()?f:f.updateChild(d,i):Yu.EMPTY_NODE}c=p.equals(e)?n:Mh(n,t.filter.updateChild(o.getNode(),h,e,d,u,a),o.isFullyInitialized(),t.filter.filtersNodes())}}return c}function vd(e,t){return e.eventCache.isCompleteForChild(t)}function _d(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function yd(r,i,e,t,s,a,o,c){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let l=i,n;n=fu(e)?t:new qh(null).setTree(e,t);const u=i.serverCache.getNode();return n.children.inorderTraversal((e,t)=>{var n;u.hasChild(e)&&(n=_d(0,i.serverCache.getNode().getImmediateChild(e),t),l=gd(r,l,new su(e),n,s,a,o,c))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&null===t.value;u.hasChild(e)||n||(n=_d(0,i.serverCache.getNode().getImmediateChild(e),t),l=gd(r,l,new su(e),n,s,a,o,c))}),l}class wd{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new oh(n.getIndex()),i=(e=n).loadsAllData()?new oh(e.getIndex()):new(e.hasLimit()?lh:ch)(e);this.processor_={filter:i};const s=t.serverCache,a=t.eventCache;var o=r.updateFullNode(Yu.EMPTY_NODE,s.getNode(),null),c=i.updateFullNode(Yu.EMPTY_NODE,a.getNode(),null),o=new Rh(o,s.isFullyInitialized(),r.filtersNodes()),c=new Rh(c,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=Oh(c,o),this.eventGenerator_=new Ph(this.query_)}get query(){return this.query_}}function bd(e){return 0===e.eventRegistrations_.length}function Id(n,r,i){const s=[];if(i){f(null==r,"A cancel should cancel all event registrations.");const a=n.query._path;n.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(i,a);t&&s.push(t)})}if(r){let e=[];for(let t=0;t<n.eventRegistrations_.length;++t){const o=n.eventRegistrations_[t];if(o.matches(r)){if(r.hasAnyCallback()){e=e.concat(n.eventRegistrations_.slice(t+1));break}}else e.push(o)}n.eventRegistrations_=e}else n.eventRegistrations_=[];return s}function Td(e,t,n,r){t.type===tl.MERGE&&null!==t.source.queryId&&(f(Uh(e.viewCache_),"We should always have a full cache before handling merges"),f(Fh(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=pd(e.processor_,i,t,n,r);return n=e.processor_,r=s.viewCache,f(r.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),f(r.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed"),f(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,Ed(e,s.changes,s.viewCache.eventCache.getNode(),null)}function Ed(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return Dh(e.eventGenerator_,t,n,i)}let Cd;class kd{constructor(){this.views=new Map}}function Sd(t,n,r,i){var e=n.source.queryId;if(null!==e){e=t.views.get(e);return f(null!=e,"SyncTree gave us an op for an invalid query."),Td(e,n,r,i)}{let e=[];for(const s of t.views.values())e=e.concat(Td(s,n,r,i));return e}}function Ad(e,n,r,i,s){var a=n._queryIdentifier,a=e.views.get(a);if(a)return a;{let e=nd(r,s?i:null),t=!1;t=!!e||(e=i instanceof Yu?rd(r,i):Yu.EMPTY_NODE,!1);a=Oh(new Rh(e,t,!1),new Rh(i,s,!1));return new wd(n,a)}}function Nd(e,t,n,r,i,s){var a=Ad(e,t,r,i,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,a),a.eventRegistrations_.push(n),function(e,t){const n=e.viewCache_.eventCache,r=[];if(!n.getNode().isLeafNode()){const i=n.getNode();i.forEachChild(ju,(e,t)=>{r.push(ih(e,t))})}return n.isFullyInitialized()&&r.push(rh(n.getNode())),Ed(e,r,n.getNode(),t)}(a,n)}function Rd(e,t,n,r){var i=t._queryIdentifier;const s=[];let a=[];var o=Md(e);if("default"===i)for(var[c,l]of e.views.entries())a=a.concat(Id(l,n,r)),bd(l)&&(e.views.delete(c),l.query._queryParams.loadsAllData()||s.push(l.query));else{const u=e.views.get(i);u&&(a=a.concat(Id(u,n,r)),bd(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return o&&!Md(e)&&s.push((f(Cd,"Reference.ts has not been loaded"),new Cd(t._repo,t._path))),{removed:s,events:a}}function Pd(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function Dd(e,t){let n=null;for(const r of e.views.values())n=n||function(e,t){const n=Uh(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!fu(t)&&!n.getImmediateChild(ou(t)).isEmpty())?n.getChild(t):null}(r,t);return n}function xd(e,t){const n=t._queryParams;if(n.loadsAllData())return Ld(e);var r=t._queryIdentifier;return e.views.get(r)}function Od(e,t){return null!=xd(e,t)}function Md(e){return null!=Ld(e)}function Ld(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Fd;let Ud=1;class Vd{constructor(e){this.listenProvider_=e,this.syncPointTree_=new qh(null),this.pendingWriteTree_={visibleWrites:Bh.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function qd(e,t,n,r,i){var s,a,o,c;return s=e.pendingWriteTree_,a=t,o=n,c=r,r=i,f(c>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:a,snap:o,writeId:c,visible:r=void 0===r?!0:r}),r&&(s.visibleWrites=jh(s.visibleWrites,a,o)),s.lastWriteId=c,i?Qd(e,new Ah(Th(),t,n)):[]}function Bd(e,t,n,r){var i,s,a;i=e.pendingWriteTree_,s=t,a=n,r=r,f(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:a,writeId:r,visible:!0}),i.visibleWrites=zh(i.visibleWrites,s,a),i.lastWriteId=r;var o=qh.fromObject(n);return Qd(e,new Nh(Th(),t,o))}function jd(e,t,n=!1){var r=function(e,t){for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null}(e.pendingWriteTree_,t);if(Xh(e.pendingWriteTree_,t)){let t=new qh(null);return null!=r.snap?t=t.set(au(),!0):Nl(r.children,e=>{t=t.set(new su(e),!0)}),Qd(e,new kh(r.path,t,n))}return[]}function zd(e,t,n){return Qd(e,new Ah(Eh(),t,n))}function $d(n,e,t,r,i=!1){var s=e._path,a=n.syncPointTree_.get(s);let o=[];if(a&&("default"===e._queryIdentifier||Od(a,e))){var c=Rd(a,e,t,r);0===a.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(s));const d=c.removed;if(o=c.events,!i){a=-1!==d.findIndex(e=>e._queryParams.loadsAllData()),c=n.syncPointTree_.findOnPath(s,(e,t)=>Md(t));if(a&&!c){const p=n.syncPointTree_.subtree(s);if(!p.isEmpty()){var l=p.fold((e,t,r)=>{if(t&&Md(t))return[Ld(t)];{let n=[];return t&&(n=Pd(t)),Nl(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<l.length;++e){var u=l[e],h=u.query,u=Jd(n,u);n.listenProvider_.startListening(rp(h),Xd(n,h),u.hashFn,u.onComplete)}}}!c&&0<d.length&&!r&&(a?n.listenProvider_.stopListening(rp(e),null):d.forEach(e=>{var t=n.queryToTagMap.get(Zd(e));n.listenProvider_.stopListening(rp(e),t)}))}!function(e,t){for(let i=0;i<t.length;++i){const s=t[i];var n,r;s._queryParams.loadsAllData()||(n=Zd(s),r=e.queryToTagMap.get(n),e.queryToTagMap.delete(n),e.tagToQueryMap.delete(r))}}(n,d)}return o}function Kd(e,t,n,r){var i=ep(e,r);if(null==i)return[];var s=tp(i),a=s.path,i=s.queryId,s=gu(a,t);return np(e,a,new Ah(Ch(i),s,n))}function Gd(e,t,n,r=!1){const i=t._path;let s=null,a=!1;e.syncPointTree_.foreachOnPath(i,(e,t)=>{var n=gu(e,i);s=s||Dd(t,n),a=a||Md(t)});let o=e.syncPointTree_.get(i);o?(a=a||Md(o),s=s||Dd(o,au())):(o=new kd,e.syncPointTree_=e.syncPointTree_.set(i,o));let c;if(null!=s)c=!0;else{c=!1,s=Yu.EMPTY_NODE;const p=e.syncPointTree_.subtree(i);p.foreachChild((e,t)=>{var n=Dd(t,au());n&&(s=s.updateImmediateChild(e,n))})}var l,u=Od(o,t);u||t._queryParams.loadsAllData()||(h=Zd(t),f(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),l=Ud++,e.queryToTagMap.set(h,l),e.tagToQueryMap.set(l,h));var h=Jh(e.pendingWriteTree_,i);let d=Nd(o,t,n,h,s,c);return u||a||r||(u=xd(o,t),d=d.concat(function(t,e,n){const r=e._path,i=Xd(t,e),s=Jd(t,n),a=t.listenProvider_.startListening(rp(e),i,s.hashFn,s.onComplete),o=t.syncPointTree_.subtree(r);if(i)f(!Md(o.value),"If we're adding a query, it shouldn't be shadowed");else{var c=o.fold((e,t,r)=>{if(!fu(e)&&t&&Md(t))return[Ld(t).query];{let n=[];return t&&(n=n.concat(Pd(t).map(e=>e.query))),Nl(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e];t.listenProvider_.stopListening(rp(l),Xd(t,l))}}return a}(e,t,u))),d}function Wd(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=Dd(t,gu(e,r));if(n)return n});return td(n,r,i,t,!0)}function Hd(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=gu(e,r);i=i||Dd(t,n)});let n=e.syncPointTree_.get(r);n?i=i||Dd(n,au()):(n=new kd,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i;const a=s?new Rh(i,!0,!1):null;var o=Jh(e.pendingWriteTree_,t._path);return Fh(Ad(n,t,o,s?a.getNode():Yu.EMPTY_NODE,s).viewCache_)}function Qd(e,t){return function t(n,r,i,s){{if(fu(n.path))return Yd(n,r,i,s);{const a=r.get(au());null==i&&null!=a&&(i=Dd(a,au()));let e=[];const o=ou(n.path),c=n.operationForChild(o),l=r.children.get(o);if(l&&c){const u=i?i.getImmediateChild(o):null,h=cd(s,o);e=e.concat(t(c,l,u,h))}return a&&(e=e.concat(Sd(a,n,s,i))),e}}}(t,e.syncPointTree_,null,Jh(e.pendingWriteTree_,au()))}function Yd(s,e,a,o){var t=e.get(au());null==a&&null!=t&&(a=Dd(t,au()));let c=[];return e.children.inorderTraversal((e,t)=>{var n=a?a.getImmediateChild(e):null,r=cd(o,e),i=s.operationForChild(e);i&&(c=c.concat(Yd(i,t,n,r)))}),t&&(c=c.concat(Sd(t,s,o,a))),c}function Jd(i,t){const s=t.query,a=Xd(i,s);return{hashFn:()=>{const e=t.viewCache_.serverCache.getNode()||Yu.EMPTY_NODE;return e.hash()},onComplete:e=>{if("ok"===e)return a?function(e,t,n){if(s=ep(e,n)){var r=tp(s),i=r.path,s=r.queryId,r=gu(i,t);return np(e,i,new Sh(Ch(s),r))}return[]}(i,s._path,a):(t=i,n=s._path,Qd(t,new Sh(Eh(),n)));var t,n,r=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(e,s);return $d(i,s,null,r)}}}function Xd(e,t){var n=Zd(t);return e.queryToTagMap.get(n)}function Zd(e){return e._path.toString()+"$"+e._queryIdentifier}function ep(e,t){return e.tagToQueryMap.get(t)}function tp(e){var t=e.indexOf("$");return f(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new su(e.substr(0,t))}}function np(e,t,n){var r=e.syncPointTree_.get(t);return f(r,"Missing sync point for query tag that we're tracking"),Sd(r,n,Jh(e.pendingWriteTree_,t),null)}function rp(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(f(Fd,"Reference.ts has not been loaded"),new Fd(e._repo,e._path)):e}class ip{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new ip(t)}node(){return this.node_}}class sp{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=pu(this.path_,e);return new sp(this.syncTree_,t)}node(){return Wd(this.syncTree_,this.path_)}}function ap(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e}function op(e,t,n){return e&&"object"==typeof e?(f(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?cp(e[".sv"],t,n):"object"==typeof e[".sv"]?lp(e[".sv"],t):void f(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const cp=function(e,t,n){if("timestamp"===e)return n.timestamp;f(!1,"Unexpected server value: "+e)},lp=function(e,t,n){e.hasOwnProperty("increment")||f(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment;"number"!=typeof r&&f(!1,"Unexpected increment value: "+r);const i=t.node();if(f(null!==i&&void 0!==i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const s=i;var a=s.getValue();return"number"!=typeof a?r:a+r},up=function(e,t,n,r){return dp(t,new sp(n,e),r)},hp=function(e,t,n){return dp(e,new ip(t),n)};function dp(e,r,i){var t=e.getPriority().val(),n=op(t,r.getImmediateChild(".priority"),i);let s;if(e.isLeafNode()){const a=e;t=op(a.getValue(),r,i);return t!==a.getValue()||n!==a.getPriority().val()?new Vu(t,eh(n)):e}{const o=e;return s=o,n!==o.getPriority().val()&&(s=s.updatePriority(new Vu(n))),o.forEachChild(ju,(e,t)=>{var n=dp(t,r.getImmediateChild(e),i);n!==t&&(s=s.updateImmediateChild(e,n))}),s}}class pp{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function fp(e,t){let n=t instanceof su?t:new su(t),r=e,i=ou(n);for(;null!==i;){var s=U(r.node.children,i)||{children:{},childCount:0};r=new pp(i,r,s),n=lu(n),i=ou(n)}return r}function gp(e){return e.node.value}function mp(e,t){e.node.value=t,wp(e)}function vp(e){return 0<e.node.childCount}function _p(n,r){Nl(n.node.children,(e,t)=>{r(new pp(e,n,t))})}function yp(e){return new su(null===e.parent?e.name:yp(e.parent)+"/"+e.name)}function wp(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=function(e){return void 0===gp(e)&&!vp(e)}(e=e),i=F(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,wp(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,wp(t)))}function bp(e,t,n,r){r&&void 0===t||Op(J(e,"value"),t,n)}function Ip(e,t,r,n){if(!n||void 0!==t){const i=J(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const s=[];Nl(t,(e,t)=>{const n=new su(e);if(Op(i,t,pu(r,n)),".priority"===uu(n)&&!xp(t))throw new Error(i+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(n)}),function(t,n){let r,i;for(r=0;r<n.length;r++){i=n[r];var s=hu(i);for(let e=0;e<s.length;e++)if((".priority"!==s[e]||e!==s.length-1)&&!Rp(s[e]))throw new Error(t+"contains an invalid key ("+s[e]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}n.sort(mu);let e=null;for(r=0;r<n.length;r++){if(i=n[r],null!==e&&_u(e,i))throw new Error(t+"contains a path "+e.toString()+" that is ancestor of another path "+i.toString());e=i}}(i,s)}}function Tp(e,t,n){if(!n||void 0!==t){if(Cl(t))throw new Error(J(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!xp(t))throw new Error(J(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function Ep(e,t,n,r){if(!(r&&void 0===n||Rp(n)))throw new Error(J(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function Cp(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),Mp(e,t,n,r)}function kp(e,t){if(".info"===ou(t))throw new Error(e+" failed = Can't modify data under /.info/")}const Sp=/[\[\].#$\/\u0000-\u001F\u007F]/,Ap=/[\[\].#$\u0000-\u001F\u007F]/,Np=10485760,Rp=function(e){return"string"==typeof e&&0!==e.length&&!Sp.test(e)},Pp=function(e){return"string"==typeof e&&0!==e.length&&!Ap.test(e)},Dp=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),Pp(e)},xp=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!Cl(e)||e&&"object"==typeof e&&F(e,".sv")},Op=function(a,e,t){const o=t instanceof su?new yu(t,a):t;if(void 0===e)throw new Error(a+"contains undefined "+bu(o));if("function"==typeof e)throw new Error(a+"contains a function "+bu(o)+" with contents = "+e.toString());if(Cl(e))throw new Error(a+"contains "+e.toString()+" "+bu(o));if("string"==typeof e&&e.length>Np/3&&te(e)>Np)throw new Error(a+"contains a string greater than "+Np+" utf8 bytes "+bu(o)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(Nl(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!Rp(e)))throw new Error(a+" contains an invalid key ("+e+") "+bu(o)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=o,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=te(e),wu(n),Op(a,t,o),t=o,r=t.parts_.pop(),t.byteLength_-=te(r),0<t.parts_.length&&--t.byteLength_}),i&&s)throw new Error(a+' contains ".value" child '+bu(o)+" in addition to actual children.")}},Mp=function(e,t,n,r){if(!(r&&void 0===n||Pp(n)))throw new Error(J(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Lp=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!Rp(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!Dp(n))throw new Error(J(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class Fp{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Up(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i];var r=s.getPath();null===n||vu(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function Vp(e,t,n){Up(e,n),Bp(e,e=>vu(e,t))}function qp(e,t,n){Up(e,n),Bp(e,e=>_u(e,t)||_u(t,e))}function Bp(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){var r=e.eventLists_[i];r&&(t(r.path)?(function(e){for(let n=0;n<e.events.length;n++){const r=e.events[n];var t;null!==r&&(e.events[n]=null,t=r.getEventRunner(),dl&&bl("event: "+r.toString()),Ll(t))}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}const jp="repo_interrupt",zp=25;class $p{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Fp,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=_h(),this.transactionQueueTree_=new pp,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function Kp(a,e,t){if(a.stats_=Hl(a.repoInfo_),a.forceRestClient_||function(){const e="object"==typeof window&&window.navigator&&window.navigator.userAgent||"";return 0<=e.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)}())a.server_=new mh(a.repoInfo_,(e,t,n,r)=>{Hp(a,e,t,n,r)},a.authTokenProvider_,a.appCheckProvider_),setTimeout(()=>Qp(a,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{M(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}a.persistentConnection_=new Tu(a.repoInfo_,e,(e,t,n,r)=>{Hp(a,e,t,n,r)},e=>{Qp(a,e)},e=>{var n;n=a,Nl(e,(e,t)=>{Yp(n,e,t)})},a.authTokenProvider_,a.appCheckProvider_,t),a.server_=a.persistentConnection_}var n;a.authTokenProvider_.addTokenChangeListener(e=>{a.server_.refreshAuthToken(e)}),a.appCheckProvider_.addTokenChangeListener(e=>{a.server_.refreshAppCheckToken(e.token)}),a.statsReporter_=(e=a.repoInfo_,t=()=>new Ih(a.stats_,a.server_),n=e.toString(),Wl[n]||(Wl[n]=t()),Wl[n]),a.infoData_=new vh,a.infoSyncTree_=new Vd({startListening:(e,t,n,r)=>{let i=[];const s=a.infoData_.getNode(e._path);return s.isEmpty()||(i=zd(a.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),Yp(a,"connected",!1),a.serverSyncTree_=new Vd({startListening:(r,e,t,i)=>(a.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);qp(a.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{a.server_.unlisten(e,t)}})}function Gp(e){const t=e.infoData_.getNode(new su(".info/serverTimeOffset"));var n=t.val()||0;return(new Date).getTime()+n}function Wp(e){return ap({timestamp:Gp(e)})}function Hp(e,t,n,r,i){e.dataUpdateCount++;var s,a,o=new su(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let c=[];c=i?r?(s=q(n,e=>eh(e)),function(e,t,n,r){if(o=ep(e,r)){var i=tp(o),s=i.path,a=i.queryId,o=gu(s,t),i=qh.fromObject(n);return np(e,s,new Nh(Ch(a),o,i))}return[]}(e.serverSyncTree_,o,s,i)):(s=eh(n),Kd(e.serverSyncTree_,o,s,i)):r?(a=q(n,e=>eh(e)),t=e.serverSyncTree_,i=o,r=a,a=qh.fromObject(r),Qd(t,new Nh(Eh(),i,a))):(a=eh(n),zd(e.serverSyncTree_,o,a));let l=o;0<c.length&&(l=cf(e,o)),qp(e.eventQueue_,l,c)}function Qp(e,t){Yp(e,"connected",t),!1===t&&function(r){rf(r,"onDisconnectEvents");const i=Wp(r),s=_h();wh(r.onDisconnect_,au(),(e,t)=>{var n=up(e,t,r.serverSyncTree_,i);yh(s,e,n)});let a=[];wh(s,au(),(e,t)=>{a=a.concat(zd(r.serverSyncTree_,e,t));var n=df(r,e);cf(r,n)}),r.onDisconnect_=_h(),qp(r.eventQueue_,au(),a)}(e)}function Yp(e,t,n){var r=new su("/.info/"+t),i=eh(n);e.infoData_.updateSnapshot(r,i);i=zd(e.infoSyncTree_,r,i);qp(e.eventQueue_,r,i)}function Jp(e){return e.nextWriteId_++}function Xp(r,i,e,t,s){rf(r,"set",{path:i.toString(),value:e,priority:t});var n=Wp(r);const a=eh(e,t);var o=Wd(r.serverSyncTree_,i),n=hp(a,o,n);const c=Jp(r);n=qd(r.serverSyncTree_,i,n,c,!0);Up(r.eventQueue_,n),r.server_.put(i.toString(),a.val(!0),(e,t)=>{var n="ok"===e;n||Tl("set at "+i+" failed: "+e);n=jd(r.serverSyncTree_,c,!n);qp(r.eventQueue_,i,n),sf(0,s,e,t)});n=df(r,i);cf(r,n),qp(r.eventQueue_,n,[])}function Zp(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(fu(t))return n.value=null,n.children.clear(),!0;if(null!==n.value){if(n.value.isLeafNode())return!1;{const i=n.value;return n.value=null,i.forEachChild(ju,(e,t)=>{yh(n,new su(e),t)}),e(n,t)}}if(0<n.children.size){var r=ou(t);return t=lu(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size}return!0}(n.onDisconnect_,r),sf(0,i,e,t)})}function ef(n,r,e,i){const s=eh(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&yh(n.onDisconnect_,r,s),sf(0,i,e,t)})}function tf(e,t,n){let r;r=".info"===ou(t._path)?$d(e.infoSyncTree_,t,n):$d(e.serverSyncTree_,t,n),Vp(e.eventQueue_,t._path,r)}function nf(e){e.persistentConnection_&&e.persistentConnection_.interrupt(jp)}function rf(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),bl(n,...t)}function sf(e,r,i,s){r&&Ll(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);const n=new Error(e);n.code=t,r(n)}})}function af(e,t,n){return Wd(e.serverSyncTree_,t,n)||Yu.EMPTY_NODE}function of(t,e=t.transactionQueueTree_){if(e||hf(t,e),gp(e)){const n=uf(t,e);f(0<n.length,"Sending zero length transaction queue"),n.every(e=>0===e.status)&&function(i,s,a){const e=a.map(e=>e.currentWriteId),t=af(i,s,e);let n=t;var r=t.hash();for(let u=0;u<a.length;u++){const h=a[u];f(0===h.status,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;var o=gu(s,h.path);n=n.updateChild(o,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{rf(i,"transaction put response",{path:l.toString(),status:t});let n=[];if("ok"===t){const r=[];for(let e=0;e<a.length;e++)a[e].status=2,n=n.concat(jd(i.serverSyncTree_,a[e].currentWriteId)),a[e].onComplete&&r.push(()=>a[e].onComplete(null,!0,a[e].currentOutputSnapshotResolved)),a[e].unwatcher();hf(i,fp(i.transactionQueueTree_,s)),of(i,i.transactionQueueTree_),qp(i.eventQueue_,s,n);for(let t=0;t<r.length;t++)Ll(r[t])}else{if("datastale"===t)for(let e=0;e<a.length;e++)3===a[e].status?a[e].status=4:a[e].status=0;else{Tl("transaction at "+l.toString()+" failed: "+t);for(let e=0;e<a.length;e++)a[e].status=4,a[e].abortReason=t}cf(i,s)}},r)}(t,yp(e),n)}else vp(e)&&_p(e,e=>{of(t,e)})}function cf(e,t){var n=lf(e,t),r=yp(n);return function(i,s,a){if(0!==s.length){const l=[];let n=[];const t=s.filter(e=>0===e.status),u=t.map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){const h=s[r];var o=gu(a,h.path);let e=!1,t;if(f(null!==o,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(jd(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=zp)e=!0,t="maxretry",n=n.concat(jd(i.serverSyncTree_,h.currentWriteId,!0));else{const d=af(i,h.path,u);h.currentInputSnapshot=d;var c=s[r].update(d.val());if(void 0!==c){Op("transaction failed: Data returned ",c,h.path);let e=eh(c);"object"==typeof c&&null!=c&&F(c,".priority")||(e=e.updatePriority(d.getPriority()));o=h.currentWriteId,c=Wp(i),c=hp(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=Jp(i),u.splice(u.indexOf(o),1),n=n.concat(qd(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally)),n=n.concat(jd(i.serverSyncTree_,o,!0))}else e=!0,t="nodata",n=n.concat(jd(i.serverSyncTree_,h.currentWriteId,!0))}qp(i.eventQueue_,a,n),n=[],e&&(s[r].status=2,function(e){setTimeout(e,Math.floor(0))}(s[r].unwatcher),s[r].onComplete&&("nodata"===t?l.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):l.push(()=>s[r].onComplete(new Error(t),!1,null))))}hf(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)Ll(l[e]);of(i,i.transactionQueueTree_)}}(e,uf(e,n),r),r}function lf(e,t){let n,r=e.transactionQueueTree_;for(n=ou(t);null!==n&&void 0===gp(r);)r=fp(r,n),t=lu(t),n=ou(t);return r}function uf(e,t){const n=[];return function t(n,e,r){const i=gp(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);_p(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function hf(t,n){const r=gp(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,mp(n,0<r.length?r:void 0)}_p(n,e=>{hf(t,e)})}function df(t,e){var n=yp(lf(t,e)),r=fp(t.transactionQueueTree_,e);return function(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return;r=r.parent}}(r,e=>{pf(t,e)}),pf(t,r),function t(e,n,r,i){r&&!i&&n(e),_p(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{pf(t,e)}),n}function pf(i,s){const a=gp(s);if(a){const o=[];let e=[],t=-1;for(let n=0;n<a.length;n++)3===a[n].status||(1===a[n].status?(f(t===n-1,"All SENT items should be at beginning of queue."),t=n,a[n].status=3,a[n].abortReason="set"):(f(0===a[n].status,"Unexpected transaction status in abort"),a[n].unwatcher(),e=e.concat(jd(i.serverSyncTree_,a[n].currentWriteId,!0)),a[n].onComplete&&o.push(a[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?mp(s,void 0):a.length=t+1,qp(i.eventQueue_,yp(s),e);for(let r=0;r<o.length;r++)Ll(o[r])}}const ff=function(e,t){var n=gf(e),r=n.namespace;"firebase.com"===n.domain&&Il(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||Il("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||El();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new zl(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new su(n.pathString)}},gf=function(r){let i="",s="",a="",o="",c="",l=!0,u="https",h=443;if("string"==typeof r){let e=r.indexOf("//");0<=e&&(u=r.substring(0,e-1),r=r.substring(e+2));let t=r.indexOf("/");-1===t&&(t=r.length);let n=r.indexOf("?");-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(o=function(e){let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t}(r.substring(t,n)));var d,p=function(e){const t={};for(const r of(e="?"===e.charAt(0)?e.substring(1):e).split("&")){var n;0!==r.length&&(2===(n=r.split("=")).length?t[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):Tl(`Invalid query segment '${r}' in query '${e}'`))}return t}(r.substring(Math.min(r.length,n)));e=i.indexOf(":"),0<=e?(l="https"===u||"wss"===u,h=parseInt(i.substring(e+1),10)):e=i.length;const f=i.slice(0,e);"localhost"===f.toLowerCase()?s="localhost":f.split(".").length<=2?s=f:(d=i.indexOf("."),a=i.substring(0,d).toLowerCase(),s=i.substring(d+1),c=a),"ns"in p&&(c=p.ns)}return{host:i,port:h,domain:s,subdomain:a,secure:l,scheme:u,pathString:o,namespace:c}},mf="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",vf=function(){let s=0;const a=[];return function(e){var t=e===s;s=e;let n;const r=new Array(8);for(n=7;0<=n;n--)r[n]=mf.charAt(e%64),e=Math.floor(e/64);f(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===a[n];n--)a[n]=0;a[n]++}else for(n=0;n<12;n++)a[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=mf.charAt(a[n]);return f(20===i.length,"nextPushId: Length should be 20."),i}}();class _f{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+M(this.snapshot.exportVal())}}class yf{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 wf{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return f(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 bf{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new y;return Zp(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){kp("OnDisconnect.remove",this._path);const e=new y;return ef(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){kp("OnDisconnect.set",this._path),bp("OnDisconnect.set",e,this._path,!1);const t=new y;return ef(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){kp("OnDisconnect.setWithPriority",this._path),bp("OnDisconnect.setWithPriority",e,this._path,!1),Tp("OnDisconnect.setWithPriority",t,!1);const n=new y;return function(n,r,e,t,i){const s=eh(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&yh(n.onDisconnect_,r,s),sf(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){kp("OnDisconnect.update",this._path),Ip("OnDisconnect.update",e,this._path,!1);const t=new y;return function(r,i,n,s){if(V(n))return bl("onDisconnect().update() called with empty data. Don't do anything."),sf(0,s,"ok",void 0);r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&Nl(n,(e,t)=>{var n=eh(t);yh(r.onDisconnect_,pu(i,e),n)}),sf(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class If{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return fu(this._path)?null:uu(this._path)}get ref(){return new kf(this._repo,this._path)}get _queryIdentifier(){var e=gh(this._queryParams),e=_l(e);return"{}"===e?"default":e}get _queryObject(){return gh(this._queryParams)}isEqual(e){if(!((e=oe(e))instanceof If))return!1;var t=this._repo===e._repo,n=vu(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}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 Tf(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function Ef(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===Au){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="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()!==kl)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==Sl)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===ju){if(null!=t&&!xp(t)||null!=n&&!xp(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(f(e.getIndex()instanceof th||e.getIndex()===nh,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function Cf(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class kf extends If{constructor(e,t){super(e,t,new uh,!1)}get parent(){var e=du(this._path);return null===e?null:new kf(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class Sf{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){var t=new su(e),n=Rf(this.ref,e);return new Sf(this._node.getChild(t),n,ju)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){if(this._node.isLeafNode())return!1;const e=this._node;return!!e.forEachChild(this._index,(e,t)=>n(new Sf(t,Rf(this.ref,e),ju)))}hasChild(e){var t=new su(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 Af(e,t){return(e=oe(e))._checkNotDeleted("ref"),void 0!==t?Rf(e._root,t):e._root}function Nf(e,t){(e=oe(e))._checkNotDeleted("refFromURL");const n=ff(t,e._repo.repoInfo_.nodeAdmin);Lp("refFromURL",n);var r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||Il("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),Af(e,n.path.toString())}function Rf(e,t){return(null===ou((e=oe(e))._path)?Cp:Mp)("child","path",t,!1),new kf(e._repo,pu(e._path,t))}function Pf(e,t){e=oe(e),kp("set",e._path),bp("set",t,e._path,!1);const n=new y;return Xp(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Df(e,t){Ip("update",t,e._path,!1);const n=new y;return function(i,s,e,a){rf(i,"update",{path:s.toString(),value:e});let n=!0;const r=Wp(i),o={};if(Nl(e,(e,t)=>{n=!1,o[e]=up(pu(s,e),eh(t),i.serverSyncTree_,r)}),n)bl("update() called with empty data. Don't do anything."),sf(0,a,"ok",void 0);else{const c=Jp(i);var t=Bd(i.serverSyncTree_,s,o,c);Up(i.eventQueue_,t),i.server_.merge(s.toString(),e,(e,t)=>{var n="ok"===e;n||Tl("update at "+s+" failed: "+e);var r=jd(i.serverSyncTree_,c,!n),n=0<r.length?cf(i,s):s;qp(i.eventQueue_,n,r),sf(0,a,e,t)}),Nl(e,e=>{var t=df(i,pu(s,e));cf(i,t)}),qp(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function xf(t){t=oe(t);var i,s,a,e=new wf(()=>{}),e=new Of(e);return i=t._repo,s=t,a=e,(null!=(e=Hd(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,n=eh(e).withIndex(s._queryParams.getIndex());Gd(i.serverSyncTree_,s,a,!0);let r;return r=s._queryParams.loadsAllData()?zd(i.serverSyncTree_,s._path,n):(t=Xd(i.serverSyncTree_,s),Kd(i.serverSyncTree_,s._path,n,t)),qp(i.eventQueue_,s._path,r),$d(i.serverSyncTree_,s,a,null,!0),n},e=>(rf(i,"get for query "+M(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new Sf(e,new kf(t._repo,t._path),t._queryParams.getIndex()))}class Of{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new _f("value",this,new Sf(e.snapshotNode,new kf(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 yf(this,e,t):null}matches(e){return e instanceof Of&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Mf{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 yf(this,e,t):null}createEvent(e,t){f(null!=e.childName,"Child events should have a childName.");var n=Rf(new kf(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new _f(e.type,this,new Sf(e.snapshotNode,n,r),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 Mf&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function Lf(n,e,t,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){const c=t;var a=(e,t)=>{tf(n._repo,n,o),c(e,t)};a.userCallback=t.userCallback,a.context=t.context,t=a}a=new wf(t,s||void 0);const o="value"===e?new Of(a):new Mf(e,a);return function(e,t,n){let r;r=".info"===ou(t._path)?Gd(e.infoSyncTree_,t,n):Gd(e.serverSyncTree_,t,n),Vp(e.eventQueue_,t._path,r)}(n._repo,n,o),()=>tf(n._repo,n,o)}function Ff(e,t,n,r){return Lf(e,"value",t,n,r)}function Uf(e,t,n,r){return Lf(e,"child_added",t,n,r)}function Vf(e,t,n,r){return Lf(e,"child_changed",t,n,r)}function qf(e,t,n,r){return Lf(e,"child_moved",t,n,r)}function Bf(e,t,n,r){return Lf(e,"child_removed",t,n,r)}function jf(e,t,n){let r=null;var i=n?new wf(n):null;"value"===t?r=new Of(i):t&&(r=new Mf(t,i)),tf(e._repo,e,r)}class zf{}class $f extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){bp("endAt",this._value,e._path,!0);var t=dh(e._queryParams,this._value,this._key);if(Cf(t),Ef(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new If(e._repo,e._path,t,e._orderByCalled)}}class Kf extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){bp("endBefore",this._value,e._path,!1);var t=function(e,t,n){let r;return r=e.index_===Au||n?dh(e,t,n):dh(e,t,kl),r.endBeforeSet_=!0,r}(e._queryParams,this._value,this._key);if(Cf(t),Ef(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new If(e._repo,e._path,t,e._orderByCalled)}}class Gf extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){bp("startAt",this._value,e._path,!0);var t=hh(e._queryParams,this._value,this._key);if(Cf(t),Ef(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new If(e._repo,e._path,t,e._orderByCalled)}}class Wf extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){bp("startAfter",this._value,e._path,!1);var t=function(e,t,n){let r;return r=e.index_===Au||n?hh(e,t,n):hh(e,t,Sl),r.startAfterSet_=!0,r}(e._queryParams,this._value,this._key);if(Cf(t),Ef(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new If(e._repo,e._path,t,e._orderByCalled)}}class Hf extends zf{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new If(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}class Qf extends zf{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new If(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}class Yf extends zf{constructor(e){super(),this._path=e}_apply(e){Tf(e,"orderByChild");var t=new su(this._path);if(fu(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new th(t),t=ph(e._queryParams,t);return Ef(t),new If(e._repo,e._path,t,!0)}}class Jf extends zf{_apply(e){Tf(e,"orderByKey");var t=ph(e._queryParams,Au);return Ef(t),new If(e._repo,e._path,t,!0)}}class Xf extends zf{_apply(e){Tf(e,"orderByPriority");var t=ph(e._queryParams,ju);return Ef(t),new If(e._repo,e._path,t,!0)}}class Zf extends zf{_apply(e){Tf(e,"orderByValue");var t=ph(e._queryParams,nh);return Ef(t),new If(e._repo,e._path,t,!0)}}class eg extends zf{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(bp("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new $f(this._value,this._key)._apply(new Gf(this._value,this._key)._apply(e))}}function tg(e,...t){let n=oe(e);for(const r of t)n=r._apply(n);return n}nl=kf,f(!Cd,"__referenceConstructor has already been defined"),Cd=nl,rl=kf,f(!Fd,"__referenceConstructor has already been defined"),Fd=rl;const ng="FIREBASE_DATABASE_EMULATOR_HOST",rg={};let ig=!1;function sg(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||Il("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),bl("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let a=ff(s,i),o=a.repoInfo,c,l=void 0;"undefined"!=typeof process&&process.env&&(l=process.env[ng]),l?(c=!0,s=`http://${l}?ns=${o.namespace}`,a=ff(s,i),o=a.repoInfo):c=!a.repoInfo.secure;var u=i&&c?new Vl(Vl.OWNER):new Ul(e.name,e.options,t);Lp("Invalid Firebase Database URL",a),fu(a.path)||Il("Database URL must point to the root of a Firebase Database (not including a child path).");u=function(e,t,n,r){let i=rg[t.name];i||(i={},rg[t.name]=i);var s=i[e.toURLString()];s&&Il("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new $p(e,ig,n,r),i[e.toURLString()]=s}(o,e,u,new Fl(e.name,n));return new ag(u,e)}class ag{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(Kp(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new kf(this._repo,au())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=rg[t];n&&n[e.key]===e||Il(`Database ${t}(${e.repoInfo_}) has already been deleted.`),nf(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&Il("Cannot call "+e+" on a deleted database.")}}function og(){eu.IS_TRANSPORT_INITIALIZED&&Tl("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function cg(){og(),Yl.forceDisallow()}function lg(){og(),Zl.forceDisallow(),Yl.forceAllow()}function ug(e,t,n,r={}){(e=oe(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&Il("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let a=void 0;s.repoInfo_.nodeAdmin?(r.mockUserToken&&Il('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),a=new Vl(Vl.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:w(r.mockUserToken,e.app.options.projectId),a=new Vl(i)),r=s,e=t,t=n,n=a,r.repoInfo_=new zl(`${e}:${t}`,!1,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams,!0),n&&(r.authTokenProvider_=n)}function hg(e){(e=oe(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(jp)}function dg(e,t){wl(e,t)}const pg={".sv":"timestamp"};class fg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function gg(i,e,t){if(i=oe(i),kp("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=null===(r=null==t?void 0:t.applyLocally)||void 0===r||r;const s=new y;var r=Ff(i,()=>{});return function(t,n,e,r,i,s){rf(t,"transaction on "+n);const a={path:n,update:e,onComplete:r,status:null,order:ul(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},o=af(t,n,void 0);a.currentInputSnapshot=o;var c=a.update(o.val());if(void 0===c)a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete&&a.onComplete(null,!1,a.currentInputSnapshot);else{Op("transaction failed: Data returned ",c,a.path),a.status=0;var l=fp(t.transactionQueueTree_,n);const u=gp(l)||[];u.push(a),mp(l,u);let e;if("object"==typeof c&&null!==c&&F(c,".priority"))e=U(c,".priority"),f(xp(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=Wd(t.serverSyncTree_,n)||Yu.EMPTY_NODE;e=h.getPriority().val()}l=Wp(t),c=eh(c,e),l=hp(c,o,l);a.currentOutputSnapshotRaw=c,a.currentOutputSnapshotResolved=l,a.currentWriteId=Jp(t);l=qd(t.serverSyncTree_,n,l,a.currentWriteId,a.applyLocally);qp(t.eventQueue_,n,l),of(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new Sf(n,new kf(i._repo,i._path),ju),s.resolve(new fg(t,r)))},r,n),s.promise}Tu.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},Tu.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},Yc(Je),We(new ce("database",(e,{instanceIdentifier:t})=>{return sg(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),tt(Hc,"1.0.1",il),tt(Hc,"1.0.1","esm2017");function mg(e){var t="FIREBASE WARNING: "+e;vg.warn(t)}const vg=new ve("@firebase/database-compat");class _g{constructor(e){this._delegate=e}cancel(t){Y("OnDisconnect.cancel",0,1,arguments.length),X("OnDisconnect.cancel","onComplete",t,!0);const e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){Y("OnDisconnect.remove",0,1,arguments.length),X("OnDisconnect.remove","onComplete",t,!0);const e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){Y("OnDisconnect.set",1,2,arguments.length),X("OnDisconnect.set","onComplete",t,!0);const n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){Y("OnDisconnect.setWithPriority",2,3,arguments.length),X("OnDisconnect.setWithPriority","onComplete",n,!0);const r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(Y("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,mg("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}X("OnDisconnect.update","onComplete",n,!0);const e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class yg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return Y("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class wg{constructor(e,t){this._database=e,this._delegate=t}val(){return Y("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return Y("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return Y("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return Y("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return Y("DataSnapshot.child",0,1,arguments.length),e=String(e),Mp("DataSnapshot.child","path",e,!1),new wg(this._database,this._delegate.child(e))}hasChild(e){return Y("DataSnapshot.hasChild",1,1,arguments.length),Mp("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return Y("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return Y("DataSnapshot.forEach",1,1,arguments.length),X("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new wg(this._database,e)))}hasChildren(){return Y("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return Y("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return Y("DataSnapshot.ref",0,0,arguments.length),new Ig(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class bg{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){var i;Y("Query.on",2,4,arguments.length),X("Query.on","callback",n,!1);const s=bg.getCancelAndContextArgs_("Query.on",t,r);var a=(e,t)=>{n.call(s.context,new wg(this.database,e),t)};a.userCallback=n,a.context=s.context;var o=null===(i=s.cancel)||void 0===i?void 0:i.bind(s.context);switch(e){case"value":return Ff(this._delegate,a,o),n;case"child_added":return Uf(this._delegate,a,o),n;case"child_removed":return Bf(this._delegate,a,o),n;case"child_changed":return Vf(this._delegate,a,o),n;case"child_moved":return qf(this._delegate,a,o),n;default:throw new Error(J("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){var r;Y("Query.off",0,3,arguments.length),function(e,t,n){if(!n||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(J(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}("Query.off",e,!0),X("Query.off","callback",t,!0),Z("Query.off","context",n,!0),t?((r=()=>{}).userCallback=t,r.context=n,jf(this._delegate,e,r)):jf(this._delegate,e)}get(){return xf(this._delegate).then(e=>new wg(this.database,e))}once(e,r,t,n){Y("Query.once",1,4,arguments.length),X("Query.once","callback",r,!0);const i=bg.getCancelAndContextArgs_("Query.once",t,n),s=new y;var a=(e,t)=>{var n=new wg(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)};a.userCallback=r,a.context=i.context;var o=e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)};switch(e){case"value":Ff(this._delegate,a,o,{onlyOnce:!0});break;case"child_added":Uf(this._delegate,a,o,{onlyOnce:!0});break;case"child_removed":Bf(this._delegate,a,o,{onlyOnce:!0});break;case"child_changed":Vf(this._delegate,a,o,{onlyOnce:!0});break;case"child_moved":qf(this._delegate,a,o,{onlyOnce:!0});break;default:throw new Error(J("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return Y("Query.limitToFirst",1,1,arguments.length),new bg(this.database,tg(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new Hf(e)}(e)))}limitToLast(e){return Y("Query.limitToLast",1,1,arguments.length),new bg(this.database,tg(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Qf(e)}(e)))}orderByChild(e){return Y("Query.orderByChild",1,1,arguments.length),new bg(this.database,tg(this._delegate,function(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return Mp("orderByChild","path",e,!1),new Yf(e)}(e)))}orderByKey(){return Y("Query.orderByKey",0,0,arguments.length),new bg(this.database,tg(this._delegate,new Jf))}orderByPriority(){return Y("Query.orderByPriority",0,0,arguments.length),new bg(this.database,tg(this._delegate,new Xf))}orderByValue(){return Y("Query.orderByValue",0,0,arguments.length),new bg(this.database,tg(this._delegate,new Zf))}startAt(e=null,t){return Y("Query.startAt",0,2,arguments.length),new bg(this.database,tg(this._delegate,([e=null,t]=[e,t],Ep("startAt","key",t,!0),new Gf(e,t))))}startAfter(e=null,t){return Y("Query.startAfter",0,2,arguments.length),new bg(this.database,tg(this._delegate,(e=e,t=t,Ep("startAfter","key",t,!0),new Wf(e,t))))}endAt(e=null,t){return Y("Query.endAt",0,2,arguments.length),new bg(this.database,tg(this._delegate,(e=e,t=t,Ep("endAt","key",t,!0),new $f(e,t))))}endBefore(e=null,t){return Y("Query.endBefore",0,2,arguments.length),new bg(this.database,tg(this._delegate,(e=e,t=t,Ep("endBefore","key",t,!0),new Kf(e,t))))}equalTo(e,t){return Y("Query.equalTo",1,2,arguments.length),new bg(this.database,tg(this._delegate,(e=e,t=t,Ep("equalTo","key",t,!0),new eg(e,t))))}toString(){return Y("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return Y("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(Y("Query.isEqual",1,1,arguments.length),e instanceof bg)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){const r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,X(e,"cancel",r.cancel,!0),r.context=n,Z(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(J(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new Ig(this.database,new kf(this._delegate._repo,this._delegate._path))}}class Ig extends bg{constructor(e,t){super(e,new If(t._repo,t._path,new uh,!1)),this.database=e,this._delegate=t}getKey(){return Y("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return Y("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new Ig(this.database,Rf(this._delegate,e))}getParent(){Y("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new Ig(this.database,e):null}getRoot(){return Y("Reference.root",0,0,arguments.length),new Ig(this.database,this._delegate.root)}set(e,t){Y("Reference.set",1,2,arguments.length),X("Reference.set","onComplete",t,!0);const n=Pf(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(Y("Reference.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,mg("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}kp("Reference.update",this._delegate._path),X("Reference.update","onComplete",n,!0);const e=Df(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){Y("Reference.setWithPriority",2,3,arguments.length),X("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(kp("setWithPriority",e._path),bp("setWithPriority",t,e._path,!1),Tp("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new y;return Xp(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise}(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){Y("Reference.remove",0,1,arguments.length),X("Reference.remove","onComplete",t,!0);const e=(n=this._delegate,kp("remove",n._path),Pf(n,null));var n;return t&&e.then(()=>t(null),e=>t(e)),e}transaction(e,t,n){Y("Reference.transaction",1,3,arguments.length),X("Reference.transaction","transactionUpdate",e,!1),X("Reference.transaction","onComplete",t,!0),function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(J(e,t)+"must be a boolean.")}("Reference.transaction","applyLocally",n,!0);const r=gg(this._delegate,e,{applyLocally:n}).then(e=>new yg(e.committed,new wg(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){Y("Reference.setPriority",1,2,arguments.length),X("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=oe(e),kp("setPriority",e._path),Tp("setPriority",t,!1);const n=new y;return Xp(e._repo,pu(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}push(e,t){Y("Reference.push",0,2,arguments.length),X("Reference.push","onComplete",t,!0);const n=function(e,t){e=oe(e),kp("push",e._path),bp("push",t,e._path,!0);var n=Gp(e._repo),n=vf(n);const r=Rf(e,n),i=Rf(e,n);let s;return s=null!=t?Pf(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r}(this._delegate,e),r=n.then(e=>new Ig(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new Ig(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return kp("Reference.onDisconnect",this._delegate._path),new _g(new bf(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class Tg{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:cg,forceLongPolling:lg}}useEmulator(e,t,n={}){ug(this._delegate,e,t,n)}ref(e){if(Y("database.ref",0,1,arguments.length),e instanceof Ig){var t=Nf(this._delegate,e.toString());return new Ig(this,t)}t=Af(this._delegate,e);return new Ig(this,t)}refFromURL(e){Y("database.refFromURL",1,1,arguments.length);var t=Nf(this._delegate,e);return new Ig(this,t)}goOffline(){var e;Y("database.goOffline",0,0,arguments.length),(e=oe(e=this._delegate))._checkNotDeleted("goOffline"),nf(e._repo)}goOnline(){return Y("database.goOnline",0,0,arguments.length),hg(this._delegate)}}Tg.ServerValue={TIMESTAMP:pg,increment:e=>({".sv":{increment:e}})};var Eg,Cg=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:i,namespace:s,nodeAdmin:a=!1}){Yc(n);var o=new he("database-standalone");const c=new ue("auth-internal",o);c.setComponent(new ce("auth-internal",()=>r,"PRIVATE"));let l=void 0;return i&&(l=new ue("app-check-internal",o),l.setComponent(new ce("app-check-internal",()=>i,"PRIVATE"))),{instance:new Tg(sg(e,c,l,t,a),e),namespace:s}}});const kg=Tg.ServerValue;(Eg=bt).INTERNAL.registerComponent(new ce("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new Tg(r,n)},"PUBLIC").setServiceProps({Reference:Ig,Query:bg,Database:Tg,DataSnapshot:wg,enableLogging:dg,INTERNAL:Cg,ServerValue:kg}).setMultipleInstances(!0)),Eg.registerVersion("@firebase/database-compat","1.0.1");var yt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Sg={},Ag=yt||self;function Ng(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function Rg(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Pg="closure_uid_"+(1e9*Math.random()>>>0),Dg=0;function xg(e,t,n){return e.call.apply(e.bind,arguments)}function Og(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function Mg(e,t,n){return(Mg=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?xg:Og).apply(null,arguments)}function Lg(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function Fg(e,s){function t(){}t.prototype=s.prototype,e.$=s.prototype,e.prototype=new t,(e.prototype.constructor=e).ac=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function Ug(){this.s=this.s,this.o=this.o}Ug.prototype.s=!1,Ug.prototype.sa=function(){var e;!this.s&&(this.s=!0,this.N(),0)&&(e=this,Object.prototype.hasOwnProperty.call(e,Pg)&&e[Pg]||(e[Pg]=++Dg))},Ug.prototype.N=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const Vg=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1};function qg(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function Bg(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(Ng(n)){var r=t.length||0,i=n.length||0;t.length=r+i;for(let e=0;e<i;e++)t[r+e]=n[e]}else t.push(n)}}function jg(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}jg.prototype.h=function(){this.defaultPrevented=!0};var zg=function(){if(!Ag.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{Ag.addEventListener("test",()=>{},t),Ag.removeEventListener("test",()=>{},t)}catch(e){}return e}();function $g(e){return/^[\s\xa0]*$/.test(e)}function Kg(){var e=Ag.navigator;return(e=e&&e.userAgent)?e:""}function Gg(e){return-1!=Kg().indexOf(e)}function Wg(e){return Wg[" "](e),e}Wg[" "]=function(){};var Hg,Qg=Gg("Opera"),Yg=Gg("Trident")||Gg("MSIE"),Jg=Gg("Edge"),Xg=Jg||Yg,Zg=Gg("Gecko")&&!(-1!=Kg().toLowerCase().indexOf("webkit")&&!Gg("Edge"))&&!(Gg("Trident")||Gg("MSIE"))&&!Gg("Edge"),em=-1!=Kg().toLowerCase().indexOf("webkit")&&!Gg("Edge");function tm(){var e=Ag.document;return e?e.documentMode:void 0}e:{var nm="",rm=(rm=Kg(),Zg?/rv:([^\);]+)(\)|;)/.exec(rm):Jg?/Edge\/([\d\.]+)/.exec(rm):Yg?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(rm):em?/WebKit\/(\S+)/.exec(rm):Qg?/(?:Version)[ \/]?(\S+)/.exec(rm):void 0);if(rm&&(nm=rm?rm[1]:""),Yg){rm=tm();if(null!=rm&&rm>parseFloat(nm)){Hg=String(rm);break e}}Hg=nm}var im=Ag.document&&Yg&&(tm()||parseInt(Hg,10))||void 0;function sm(e,t){if(jg.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(Zg){e:{try{Wg(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:am[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&sm.$.h.call(this)}}Fg(sm,jg);var am={2:"touch",3:"pen",4:"mouse"};sm.prototype.h=function(){sm.$.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var om="closure_listenable_"+(1e6*Math.random()|0),cm=0;function lm(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.la=i,this.key=++cm,this.fa=this.ia=!1}function um(e){e.fa=!0,e.listener=null,e.proxy=null,e.src=null,e.la=null}function hm(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function dm(e){const t={};for(const n in e)t[n]=e[n];return t}const pm="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function fm(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<pm.length;e++)n=pm[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function gm(e){this.src=e,this.g={},this.h=0}function mm(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=Vg(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(um(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function vm(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.fa&&s.listener==t&&s.capture==!!n&&s.la==r)return i}return-1}gm.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=vm(e,t,r,i);return-1<a?(t=e[a],n||(t.ia=!1)):((t=new lm(t,this.src,s,!!r,i)).ia=n,e.push(t)),t};var _m="closure_lm_"+(1e6*Math.random()|0),ym={};function wm(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);return null}r=Sm(r);return t&&t[om]?t.P(n,r,Rg(i)?!!i.capture:!!i,s):bm(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)wm(e,t[s],n,r,i);return null}return n=Sm(n),e&&e[om]?e.O(t,n,Rg(r)?!!r.capture:!!r,i):bm(e,t,n,!1,r,i)}function bm(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=Rg(i)?!!i.capture:!!i,o=Cm(e);if(o||(e[_m]=o=new gm(e)),(n=o.add(t,n,r,a,s)).proxy)return n;if(r=function(){const n=Em;return function e(t){return n.call(e.src,e.listener,t)}}(),(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!zg?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(Tm(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function Im(e){var t,n,r;"number"!=typeof e&&e&&!e.fa&&((t=e.src)&&t[om]?mm(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(Tm(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=Cm(t))?(mm(n,e),0==n.h&&(n.src=null,t[_m]=null)):um(e)))}function Tm(e){return e in ym?ym[e]:ym[e]="on"+e}function Em(e,t){var n,r;return e=!!e.fa||(t=new sm(t,this),n=e.listener,r=e.la||e.src,e.ia&&Im(e),n.call(r,t))}function Cm(e){return(e=e[_m])instanceof gm?e:null}var km="__closure_events_fn_"+(1e9*Math.random()>>>0);function Sm(t){return"function"==typeof t?t:(t[km]||(t[km]=function(e){return t.handleEvent(e)}),t[km])}function Am(){Ug.call(this),this.i=new gm(this),(this.S=this).J=null}function Nm(e,t){var n,r=e.J;if(r)for(n=[];r;r=r.J)n.push(r);if(e=e.S,r=t.type||t,"string"==typeof t?t=new jg(t,e):t instanceof jg?t.target=t.target||e:(a=t,fm(t=new jg(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=Rm(s,r,!0,t)&&a;if(a=Rm(s=t.g=e,r,!0,t)&&a,a=Rm(s,r,!1,t)&&a,n)for(i=0;i<n.length;i++)a=Rm(s=t.g=n[i],r,!1,t)&&a}function Rm(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var a,o,c=t[s];c&&!c.fa&&c.capture==n&&(a=c.listener,o=c.la||c.src,c.ia&&mm(e.i,c),i=!1!==a.call(o,r)&&i)}return i&&!r.defaultPrevented}Fg(Am,Ug),Am.prototype[om]=!0,Am.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var a=0;a<n.length;a++)e(t,n[a],r,i,s);else i=Rg(i)?!!i.capture:!!i,r=Sm(r),t&&t[om]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=vm(a=t.g[n],r,i,s))&&(um(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&Cm(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?vm(n,r,i,s):t)?n[t]:null)&&Im(r))}(this,e,t,n,r)},Am.prototype.N=function(){if(Am.$.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)um(n[r]);delete t.g[e],t.h--}}this.J=null},Am.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},Am.prototype.P=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var Pm=Ag.JSON.stringify;var Dm=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new xm,e=>e.reset());class xm{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}let Om,Mm=!1,Lm=new class{constructor(){this.h=this.g=null}add(e,t){const n=Dm.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},Fm=()=>{const e=Ag.Promise.resolve(void 0);Om=()=>{e.then(Um)}};var Um=()=>{for(var e;e=function(){var e=Lm;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){Ag.setTimeout(()=>{throw e},0)}(e)}var t=Dm;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}Mm=!1};function Vm(e,t){Am.call(this),this.h=e||1,this.g=t||Ag,this.j=Mg(this.qb,this),this.l=Date.now()}function qm(e){e.ga=!1,e.T&&(e.g.clearTimeout(e.T),e.T=null)}function Bm(e,t,n){if("function"==typeof e)n&&(e=Mg(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Mg(e.handleEvent,e)}return 2147483647<Number(t)?-1:Ag.setTimeout(e,t||0)}Fg(Vm,Am),(It=Vm.prototype).ga=!1,It.T=null,It.qb=function(){var e;this.ga&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.T=this.g.setTimeout(this.j,this.h-e):(this.T&&(this.g.clearTimeout(this.T),this.T=null),Nm(this,"tick"),this.ga&&(qm(this),this.start())))},It.start=function(){this.ga=!0,this.T||(this.T=this.g.setTimeout(this.j,this.h),this.l=Date.now())},It.N=function(){Vm.$.N.call(this),qm(this),delete this.g};class jm extends Ug{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=Bm(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}N(){super.N(),this.g&&(Ag.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function zm(e){Ug.call(this),this.h=e,this.g={}}Fg(zm,Ug);var $m=[];function Km(e,t,n,r){Array.isArray(n)||(n&&($m[0]=n.toString()),n=$m);for(var i=0;i<n.length;i++){var s=wm(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function Gm(e){hm(e.g,function(e,t){this.g.hasOwnProperty(t)&&Im(e)},e),e.g={}}function Wm(){this.g=!0}function Hm(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var a=1;a<i.length;a++)i[a]=""}}}return Pm(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}zm.prototype.N=function(){zm.$.N.call(this),Gm(this)},zm.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},Wm.prototype.Ea=function(){this.g=!1},Wm.prototype.info=function(){};var Qm={},Ym=null;function Jm(){return Ym=Ym||new Am}function Xm(e){jg.call(this,Qm.Ta,e)}function Zm(){var e=Jm();Nm(e,new Xm(e))}function ev(e,t){jg.call(this,Qm.STAT_EVENT,e),this.stat=t}function tv(e){var t=Jm();Nm(t,new ev(t,e))}function nv(e,t){jg.call(this,Qm.Ua,e),this.size=t}function rv(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return Ag.setTimeout(function(){e()},t)}Qm.Ta="serverreachability",Fg(Xm,jg),Qm.STAT_EVENT="statevent",Fg(ev,jg),Qm.Ua="timingevent",Fg(nv,jg);Tt={NO_ERROR:0,rb:1,Eb:2,Db:3,yb:4,Cb:5,Fb:6,Qa:7,TIMEOUT:8,Ib:9},sl={wb:"complete",Sb:"success",Ra:"error",Qa:"abort",Kb:"ready",Lb:"readystatechange",TIMEOUT:"timeout",Gb:"incrementaldata",Jb:"progress",zb:"downloadprogress",$b:"uploadprogress"};function iv(){}function sv(e){return e.h||(e.h=e.i())}function av(){}iv.prototype.h=null;yt={OPEN:"a",vb:"b",Ra:"c",Hb:"d"};function ov(){jg.call(this,"d")}function cv(){jg.call(this,"c")}function lv(){}function uv(e,t,n,r){this.l=e,this.j=t,this.m=n,this.W=r||1,this.U=new zm(this),this.P=pv,this.V=new Vm(e=Xg?125:void 0),this.I=null,this.i=!1,this.s=this.A=this.v=this.L=this.G=this.Y=this.B=null,this.F=[],this.g=null,this.C=0,this.o=this.u=null,this.ca=-1,this.J=!1,this.O=0,this.M=null,this.ba=this.K=this.aa=this.S=!1,this.h=new hv}function hv(){this.i=null,this.g="",this.h=!1}Fg(ov,jg),Fg(cv,jg),Fg(lv,iv),lv.prototype.g=function(){return new XMLHttpRequest},lv.prototype.i=function(){return{}};var dv=new lv,pv=45e3,fv={},gv={};function mv(e,t,n){e.L=1,e.v=Ov(Nv(t)),e.s=n,e.S=!0,vv(e,null)}function vv(e,t){e.G=Date.now(),wv(e),e.A=Nv(e.v);var a,o,c,l,u,h,n=e.A,r=e.W;Array.isArray(r)||(r=[String(r)]),Wv(n.i,"t",r),e.C=0,n=e.l.J,e.h=new hv,e.g=G_(e.l,n?t:null,!e.s),0<e.O&&(e.M=new jm(Mg(e.Pa,e,e.g),e.O)),Km(e.U,e.g,"readystatechange",e.nb),t=e.I?dm(e.I):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ha(e.A,e.u,e.s,t)):(e.u="GET",e.g.ha(e.A,e.u,null,t)),Zm(),a=e.j,o=e.u,c=e.A,l=e.m,u=e.W,h=e.s,a.info(function(){if(a.g)if(h)for(var e="",t=h.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=h;return"XMLHTTP REQ ("+l+") [attempt "+u+"]: "+o+"\n"+c+"\n"+e})}function _v(e){return e.g&&("GET"==e.u&&2!=e.L&&e.l.Ha)}function yv(e,t,n){let r=!0,i;for(;!e.J&&e.C<n.length;){if(i=(a=n,c=o=void 0,o=(s=e).C,-1==(c=a.indexOf("\n",o))?gv:(o=Number(a.substring(o,c)),isNaN(o)?fv:(c+=1)+o>a.length?gv:(a=a.slice(c,c+o),s.C=c+o,a))),i==gv){4==t&&(e.o=4,tv(14),r=!1),Hm(e.j,e.m,null,"[Incomplete Response]");break}if(i==fv){e.o=4,tv(15),Hm(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}Hm(e.j,e.m,i,null),Cv(e,i)}var s,a,o,c;_v(e)&&i!=gv&&i!=fv&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,tv(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.ba&&(e.ba=!0,(t=e.l).g==e&&t.ca&&!t.M&&(t.l.info("Great, no buffering proxy detected. Bytes received: "+n.length),U_(t),t.M=!0,tv(11))):(Hm(e.j,e.m,n,"[Invalid Chunked Response]"),Ev(e),Tv(e))}function wv(e){e.Y=Date.now()+e.P,bv(e,e.P)}function bv(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=rv(Mg(e.lb,e),t)}function Iv(e){e.B&&(Ag.clearTimeout(e.B),e.B=null)}function Tv(e){0==e.l.H||e.J||B_(e.l,e)}function Ev(e){Iv(e);var t=e.M;t&&"function"==typeof t.sa&&t.sa(),e.M=null,qm(e.V),Gm(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.sa())}function Cv(e,t){try{var n=e.l;if(0!=n.H&&(n.g==e||Zv(n.i,e)))if(!e.K&&Zv(n.i,e)&&3==n.H){try{var r=n.Ja.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.G+3e3<e.G))break e;q_(n),R_(n)}F_(n),tv(18)}}else n.Fa=i[1],0<n.Fa-n.V&&i[2]<37500&&n.G&&0==n.A&&!n.v&&(n.v=rv(Mg(n.ib,n),6e3));if(Xv(n.i)<=1&&n.oa){try{n.oa()}catch(e){}n.oa=void 0}}else z_(n,11)}else if(!e.K&&n.g!=e||q_(n),!$g(t))for(i=n.Ja.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.V=s[0],s=s[1],2==n.H)if("c"==s[0]){n.K=s[1],n.pa=s[2];var a=s[3];null!=a&&(n.ra=a,n.l.info("VER="+n.ra));var o=s[4];null!=o&&(n.Ga=o,n.l.info("SVER="+n.Ga));var c,l,u=s[5];null!=u&&"number"==typeof u&&0<u&&(r=1.5*u,n.L=r,n.l.info("backChannelRequestTimeoutMs_="+r)),r=n;const f=e.g;if(f){const g=f.g?f.g.getResponseHeader("X-Client-Wire-Protocol"):null;g&&((c=r.i).g||-1==g.indexOf("spdy")&&-1==g.indexOf("quic")&&-1==g.indexOf("h2")||(c.j=c.l,c.g=new Set,c.h&&(e_(c,c.h),c.h=null))),!r.F||(l=f.g?f.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.Da=l,xv(r.I,r.F,l))}n.H=3,n.h&&n.h.Ba(),n.ca&&(n.S=Date.now()-e.G,n.l.info("Handshake RTT: "+n.S+"ms"));var h,d,p=e;(r=n).wa=K_(r,r.J?r.pa:null,r.Y),p.K?(t_(r.i,p),h=p,(d=r.L)&&h.setTimeout(d),h.B&&(Iv(h),wv(h)),r.g=p):L_(r),0<n.j.length&&D_(n)}else"stop"!=s[0]&&"close"!=s[0]||z_(n,7);else 3==n.H&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?z_(n,7):N_(n):"noop"!=s[0]&&n.h&&n.h.Aa(s),n.A=0)}Zm()}catch(e){}}function kv(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(Ng(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.ta&&"function"==typeof e.ta)return e.ta();if(!e.Z||"function"!=typeof e.Z){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(Ng(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.Z&&"function"==typeof e.Z)return e.Z();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(Ng(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}(It=uv.prototype).setTimeout=function(e){this.P=e},It.nb=function(e){e=e.target;const t=this.M;t&&3==T_(e)?t.l():this.Pa(e)},It.Pa=function(e){try{if(e==this.g)e:{var t=T_(this.g),n=this.g.Ia();this.g.da();if(!(t<3)&&(3!=t||Xg||this.g&&(this.h.h||this.g.ja()||E_(this.g)))){this.J||4!=t||7==n||Zm(),Iv(this);var r=this.g.da();this.ca=r;t:if(_v(this)){var i=E_(this.g);e="";var s=i.length,a=4==T_(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){Ev(this),Tv(this);var o="";break t}this.h.i=new Ag.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:a&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.ja();if(this.i=200==r,h=this.j,d=this.u,p=this.A,f=this.m,g=this.W,m=t,v=r,h.info(function(){return"XMLHTTP RESP ("+f+") [ attempt "+g+"]: "+d+"\n"+p+"\n"+m+" "+v}),this.i){if(this.aa&&!this.K){t:{if(this.g){var c,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!$g(c)){var u=c;break t}}u=null}if(!(r=u)){this.i=!1,this.o=3,tv(12),Ev(this),Tv(this);break e}Hm(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Cv(this,r)}this.S?(yv(this,t,o),Xg&&this.i&&3==t&&(Km(this.U,this.V,"tick",this.mb),this.V.start())):(Hm(this.j,this.m,o,null),Cv(this,o)),4==t&&Ev(this),this.i&&!this.J&&(4==t?B_(this.l,this):(this.i=!1,wv(this)))}else(function(e){const t={};e=(e.g&&2<=T_(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let i=0;i<e.length;i++)if(!$g(e[i])){var n=function(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}(e[i]),r=n[0];if("string"==typeof(n=n[1])){n=n.trim();const s=t[r]||[];t[r]=s,s.push(n)}}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,function(e){return e.join(", ")})})(this.g),400==r&&0<o.indexOf("Unknown SID")?(this.o=3,tv(12)):(this.o=0,tv(13)),Ev(this),Tv(this)}}}catch(e){}var h,d,p,f,g,m,v},It.mb=function(){var e,t;this.g&&(e=T_(this.g),t=this.g.ja(),this.C<t.length&&(Iv(this),yv(this,e,t),this.i&&4!=e&&wv(this)))},It.cancel=function(){this.J=!0,Ev(this)},It.lb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.Y?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(Zm(),tv(17)),Ev(this),this.o=2,Tv(this)):bv(this,this.Y-n)};var Sv=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Av(e){var t,n;this.g=this.s=this.j="",this.m=null,this.o=this.l="",this.h=!1,e instanceof Av?(this.h=e.h,Rv(this,e.j),this.s=e.s,this.g=e.g,Pv(this,e.m),this.l=e.l,t=e.i,(n=new zv).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),Dv(this,n),this.o=e.o):e&&(t=String(e).match(Sv))?(this.h=!1,Rv(this,t[1]||"",!0),this.s=Mv(t[2]||""),this.g=Mv(t[3]||"",!0),Pv(this,t[4]),this.l=Mv(t[5]||"",!0),Dv(this,t[6]||"",!0),this.o=Mv(t[7]||"")):(this.h=!1,this.i=new zv(null,this.h))}function Nv(e){return new Av(e)}function Rv(e,t,n){e.j=n?Mv(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function Pv(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.m=t}else e.m=null}function Dv(e,t,n){var r,i;t instanceof zv?(e.i=t,r=e.i,(i=e.h)&&!r.j&&($v(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(Kv(this,t),Wv(this,n,e))},r)),r.j=i):(n||(t=Lv(t,Bv)),e.i=new zv(t,e.h))}function xv(e,t,n){e.i.set(t,n)}function Ov(e){return xv(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function Mv(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function Lv(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,Fv),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function Fv(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Av.prototype.toString=function(){var e=[],t=this.j;t&&e.push(Lv(t,Uv,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(Lv(t,Uv,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(Lv(n,"/"==n.charAt(0)?qv:Vv,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.o)&&e.push("#",Lv(n,jv)),e.join("")};var Uv=/[#\/\?@]/g,Vv=/[#\?:]/g,qv=/[#\?]/g,Bv=/[#\?@]/g,jv=/#/g;function zv(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function $v(n){n.g||(n.g=new Map,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function Kv(e,t){$v(e),t=Hv(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Gv(e,t){return $v(e),t=Hv(e,t),e.g.has(t)}function Wv(e,t,n){Kv(e,t),0<n.length&&(e.i=null,e.g.set(Hv(e,t),qg(n)),e.h+=n.length)}function Hv(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(It=zv.prototype).add=function(e,t){$v(this),this.i=null,e=Hv(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},It.forEach=function(n,r){$v(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},It.ta=function(){$v(this);const t=Array.from(this.g.values()),n=Array.from(this.g.keys()),r=[];for(let s=0;s<n.length;s++){var i=t[s];for(let e=0;e<i.length;e++)r.push(n[s])}return r},It.Z=function(t){$v(this);let n=[];if("string"==typeof t)Gv(this,t)&&(n=n.concat(this.g.get(Hv(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},It.set=function(e,t){return $v(this),this.i=null,Gv(this,e=Hv(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},It.get=function(e,t){return e&&0<(e=this.Z(e)).length?String(e[0]):t},It.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),s=this.Z(r),r=0;r<s.length;r++){var a=i;""!==s[r]&&(a+="="+encodeURIComponent(String(s[r]))),e.push(a)}return this.i=e.join("&")};var Qv=class{constructor(e,t){this.g=e,this.map=t}};function Yv(e){this.l=e||10,e=Ag.PerformanceNavigationTiming?0<(e=Ag.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(Ag.g&&Ag.g.Ka&&Ag.g.Ka()&&Ag.g.Ka().ec),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Jv(e){return e.h||e.g&&e.g.size>=e.j}function Xv(e){return e.h?1:e.g?e.g.size:0}function Zv(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function e_(e,t){e.g?e.g.add(t):e.h=t}function t_(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function n_(t){if(null!=t.h)return t.i.concat(t.h.F);if(null==t.g||0===t.g.size)return qg(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.F);return e}}Yv.prototype.cancel=function(){if(this.i=n_(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}};var r_,i_=class{stringify(e){return Ag.JSON.stringify(e,void 0)}parse(e){return Ag.JSON.parse(e,void 0)}};function s_(){this.g=new i_}function a_(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function o_(e){this.l=e.fc||null,this.j=e.ob||!1}function c_(e,t){Am.call(this),this.F=e,this.u=t,this.m=void 0,this.readyState=l_,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}Fg(o_,iv),o_.prototype.g=function(){return new c_(this.l,this.j)},o_.prototype.i=(r_={},function(){return r_}),Fg(c_,Am);var l_=0;function u_(e){e.j.read().then(e.Xa.bind(e)).catch(e.ka.bind(e))}function h_(e){e.readyState=4,e.l=null,e.j=null,e.A=null,d_(e)}function d_(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(It=c_.prototype).open=function(e,t){if(this.readyState!=l_)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,d_(this)},It.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.F||Ag).fetch(new Request(this.B,t)).then(this.$a.bind(this),this.ka.bind(this))},It.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,h_(this)),this.readyState=l_},It.$a=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,d_(this)),this.g&&(this.readyState=3,d_(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ya.bind(this),this.ka.bind(this));else if(void 0!==Ag.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;u_(this)}else e.text().then(this.Za.bind(this),this.ka.bind(this))},It.Xa=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?h_:d_)(this),3==this.readyState&&u_(this))},It.Za=function(e){this.g&&(this.response=this.responseText=e,h_(this))},It.Ya=function(e){this.g&&(this.response=e,h_(this))},It.ka=function(){this.g&&h_(this)},It.setRequestHeader=function(e,t){this.v.append(e,t)},It.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},It.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(c_.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var p_=Ag.JSON.parse;function f_(e){Am.call(this),this.headers=new Map,this.u=e||null,this.h=!1,this.C=this.g=null,this.I="",this.m=0,this.j="",this.l=this.G=this.v=this.F=!1,this.B=0,this.A=null,this.K=g_,this.L=this.M=!1}Fg(f_,Am);var g_="",m_=/^https?$/i,v_=["POST","PUT"];function __(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,y_(e),b_(e)}function y_(e){e.F||(e.F=!0,Nm(e,"complete"),Nm(e,"error"))}function w_(e){if(e.h&&void 0!==Sg&&(!e.C[1]||4!=T_(e)||2!=e.da()))if(e.v&&4==T_(e))Bm(e.La,0,e);else if(Nm(e,"readystatechange"),4==T_(e)){e.h=!1;try{var t,n,r,i=e.da();e:switch(i){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var s=!0;break e;default:s=!1}if((t=s)||((n=0===i)&&(!(r=String(e.I).match(Sv)[1]||null)&&Ag.self&&Ag.self.location&&(r=Ag.self.location.protocol.slice(0,-1)),n=!m_.test(r?r.toLowerCase():"")),t=n),t)Nm(e,"complete"),Nm(e,"success");else{e.m=6;try{var a=2<T_(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.da()+"]",y_(e)}}finally{b_(e)}}}function b_(e,t){if(e.g){I_(e);const n=e.g,r=e.C[0]?()=>{}:null;e.g=null,e.C=null,t||Nm(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function I_(e){e.g&&e.L&&(e.g.ontimeout=null),e.A&&(Ag.clearTimeout(e.A),e.A=null)}function T_(e){return e.g?e.g.readyState:0}function E_(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.K){case g_:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function C_(e){let n="";return hm(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function k_(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=C_(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):xv(e,t,n))}function S_(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function A_(e){this.Ga=0,this.j=[],this.l=new Wm,this.pa=this.wa=this.I=this.Y=this.g=this.Da=this.F=this.na=this.o=this.U=this.s=null,this.fb=this.W=0,this.cb=S_("failFast",!1,e),this.G=this.v=this.u=this.m=this.h=null,this.aa=!0,this.Fa=this.V=-1,this.ba=this.A=this.C=0,this.ab=S_("baseRetryDelayMs",5e3,e),this.hb=S_("retryDelaySeedMs",1e4,e),this.eb=S_("forwardChannelMaxRetries",2,e),this.xa=S_("forwardChannelRequestTimeoutMs",2e4,e),this.va=e&&e.xmlHttpFactory||void 0,this.Ha=e&&e.dc||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.i=new Yv(e&&e.concurrentRequestLimit),this.Ja=new s_,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.bb=e&&e.bc||!1,e&&e.Ea&&this.l.Ea(),e&&e.forceLongPolling&&(this.aa=!1),this.ca=!this.P&&this.aa&&e&&e.detectBufferingProxy||!1,this.qa=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.qa=e.longPollingTimeout),this.oa=void 0,this.S=0,this.M=!1,this.ma=this.B=null}function N_(e){if(P_(e),3==e.H){var t=e.W++,n=Nv(e.I);if(xv(n,"SID",e.K),xv(n,"RID",t),xv(n,"TYPE","terminate"),O_(e,n),(t=new uv(e,e.l,t)).L=2,t.v=Ov(Nv(n)),n=!1,Ag.navigator&&Ag.navigator.sendBeacon)try{n=Ag.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&Ag.Image&&((new Image).src=t.v,n=!0),n||(t.g=G_(t.l,null),t.g.ha(t.v)),t.G=Date.now(),wv(t)}$_(e)}function R_(e){e.g&&(U_(e),e.g.cancel(),e.g=null)}function P_(e){R_(e),e.u&&(Ag.clearTimeout(e.u),e.u=null),q_(e),e.i.cancel(),e.m&&("number"==typeof e.m&&Ag.clearTimeout(e.m),e.m=null)}function D_(e){var t;Jv(e.i)||e.m||(e.m=!0,t=e.Na,Om||Fm(),Mm||(Om(),Mm=!0),Lm.add(t,e),e.C=0)}function x_(e,t){var n=t?t.m:e.W++,r=Nv(e.I);xv(r,"SID",e.K),xv(r,"RID",n),xv(r,"AID",e.V),O_(e,r),e.o&&e.s&&k_(r,e.o,e.s),n=new uv(e,e.l,n,e.C+1),null===e.o&&(n.I=e.s),t&&(e.j=t.F.concat(e.j)),t=M_(e,n,1e3),n.setTimeout(Math.round(.5*e.xa)+Math.round(.5*e.xa*Math.random())),e_(e.i,n),mv(n,r,t)}function O_(e,n){e.na&&hm(e.na,function(e,t){xv(n,t,e)}),e.h&&kv({},function(e,t){xv(n,t,e)})}function M_(e,t,r){r=Math.min(e.j.length,r);var i=e.h?Mg(e.h.Va,e.h,e):null;e:{var s=e.j;let n=-1;for(;;){const c=["count="+r];-1==n?0<r?(n=s[0].g,c.push("ofs="+n)):n=0:c.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var a=s[t].g,o=s[t].map;if((a-=n)<0)n=Math.max(0,s[t].g-100),e=!1;else try{!function(e,r,t){const i=t||"";try{kv(e,function(e,t){let n=e;Rg(e)&&(n=Pm(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(o,c,"req"+a+"_")}catch(e){i&&i(o)}}if(e){i=c.join("&");break e}}}return e=e.j.splice(0,r),t.F=e,i}function L_(e){var t;e.g||e.u||(e.ba=1,t=e.Ma,Om||Fm(),Mm||(Om(),Mm=!0),Lm.add(t,e),e.A=0)}function F_(e){return!(e.g||e.u||3<=e.A)&&(e.ba++,e.u=rv(Mg(e.Ma,e),j_(e,e.A)),e.A++,1)}function U_(e){null!=e.B&&(Ag.clearTimeout(e.B),e.B=null)}function V_(e){e.g=new uv(e,e.l,"rpc",e.ba),null===e.o&&(e.g.I=e.s),e.g.O=0;var t=Nv(e.wa);xv(t,"RID","rpc"),xv(t,"SID",e.K),xv(t,"AID",e.V),xv(t,"CI",e.G?"0":"1"),!e.G&&e.qa&&xv(t,"TO",e.qa),xv(t,"TYPE","xmlhttp"),O_(e,t),e.o&&e.s&&k_(t,e.o,e.s),e.L&&e.g.setTimeout(e.L);var n=e.g;e=e.pa,n.L=1,n.v=Ov(Nv(t)),n.s=null,n.S=!0,vv(n,e)}function q_(e){null!=e.v&&(Ag.clearTimeout(e.v),e.v=null)}function B_(e,t){var n,r,i,s=null;if(e.g==t){q_(e),U_(e),e.g=null;var a=2}else{if(!Zv(e.i,t))return;s=t.F,t_(e.i,t),a=1}if(0!=e.H)if(t.i)1==a?(s=t.s?t.s.length:0,t=Date.now()-t.G,n=e.C,Nm(a=Jm(),new nv(a,s)),D_(e)):L_(e);else if(3==(n=t.o)||0==n&&0<t.ca||(1!=a||(i=t,Xv((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.j=i.F.concat(r.j),0):1==r.H||2==r.H||r.C>=(r.cb?0:r.eb)||(r.m=rv(Mg(r.Na,r,i),j_(r,r.C)),r.C++,0))))&&(2!=a||!F_(e)))switch(s&&0<s.length&&(t=e.i,t.i=t.i.concat(s)),n){case 1:z_(e,5);break;case 4:z_(e,10);break;case 3:z_(e,6);break;default:z_(e,2)}}function j_(e,t){let n=e.ab+Math.floor(Math.random()*e.hb);return e.isActive()||(n*=2),n*t}function z_(e,t){var n,r;e.l.info("Error code "+t),2==t?(n=null,e.h&&(n=null),r=Mg(e.pb,e),n||(n=new Av("//www.google.com/images/cleardot.gif"),Ag.location&&"http"==Ag.location.protocol||Rv(n,"https"),Ov(n)),function(e,t){var n=new Wm;if(Ag.Image){const r=new Image;r.onload=Lg(a_,n,r,"TestLoadImage: loaded",!0,t),r.onerror=Lg(a_,n,r,"TestLoadImage: error",!1,t),r.onabort=Lg(a_,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=Lg(a_,n,r,"TestLoadImage: timeout",!1,t),Ag.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):tv(2),e.H=0,e.h&&e.h.za(t),$_(e),P_(e)}function $_(e){var t;e.H=0,e.ma=[],e.h&&(0==(t=n_(e.i)).length&&0==e.j.length||(Bg(e.ma,t),Bg(e.ma,e.j),e.i.i.length=0,qg(e.j),e.j.length=0),e.h.ya())}function K_(e,t,n){var r,i,s=n instanceof Av?Nv(n):new Av(n);return""!=s.g?(t&&(s.g=t+"."+s.g),Pv(s,s.m)):(s=(r=Ag.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new Av(null),s&&Rv(i,s),t&&(i.g=t),r&&Pv(i,r),n&&(i.l=n),s=i),n=e.F,t=e.Da,n&&t&&xv(s,n,t),xv(s,"VER",e.ra),O_(e,s),s}function G_(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ha&&!e.va?new f_(new o_({ob:!0})):new f_(e.va)).Oa(e.J),t}function W_(){}function H_(){if(Yg&&!(10<=Number(im)))throw Error("Environmental error: no available transport.")}function Q_(e,t){Am.call(this),this.g=new A_(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.Ca&&(e?e["X-WebChannel-Client-Profile"]=t.Ca:e={"X-WebChannel-Client-Profile":t.Ca}),this.g.U=e,(e=t&&t.cc)&&!$g(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!$g(t)&&(this.g.F=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new X_(this)}function Y_(e){ov.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function J_(){cv.call(this),this.status=1}function X_(e){this.g=e}function Z_(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.m=Array(this.blockSize),this.i=this.h=0,this.reset()}function ey(e,t,n){n=n||0;var r=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;i<16;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1];var i=e.g[2],s=e.g[3],a=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+((a=t+(s^n&(i^s))+r[0]+3614090360&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((s=(t=n+((a=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((i=s+((a=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295;e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function ty(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}(It=f_.prototype).Oa=function(e){this.M=e},It.ha=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.I+"; newUri="+e);t=t?t.toUpperCase():"GET",this.I=e,this.j="",this.m=0,this.F=!1,this.h=!0,this.g=(this.u||dv).g(),this.C=this.u?sv(this.u):sv(dv),this.g.onreadystatechange=Mg(this.La,this);try{this.G=!0,this.g.open(t,String(e),!0),this.G=!1}catch(e){return void __(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const c of r.keys())n.set(c,r.get(c))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),i=Ag.FormData&&e instanceof Ag.FormData,0<=Vg(v_,t)&&!r&&!i&&n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(var[s,a]of n)this.g.setRequestHeader(s,a);this.K&&(this.g.responseType=this.K),"withCredentials"in this.g&&this.g.withCredentials!==this.M&&(this.g.withCredentials=this.M);try{I_(this),0<this.B&&((this.L=(o=this.g,Yg&&"number"==typeof o.timeout&&void 0!==o.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=Mg(this.ua,this)):this.A=Bm(this.ua,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){__(this,e)}var o},It.ua=function(){void 0!==Sg&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,Nm(this,"timeout"),this.abort(8))},It.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,Nm(this,"complete"),Nm(this,"abort"),b_(this))},It.N=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),b_(this,!0)),f_.$.N.call(this)},It.La=function(){this.s||(this.G||this.v||this.l?w_(this):this.kb())},It.kb=function(){w_(this)},It.isActive=function(){return!!this.g},It.da=function(){try{return 2<T_(this)?this.g.status:-1}catch(e){return-1}},It.ja=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},It.Wa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),p_(t)}},It.Ia=function(){return this.m},It.Sa=function(){return"string"==typeof this.j?this.j:String(this.j)},(It=A_.prototype).ra=8,It.H=1,It.Na=function(t){if(this.m)if(this.m=null,1==this.H){if(!t){this.W=Math.floor(1e5*Math.random()),t=this.W++;const s=new uv(this,this.l,t);let e=this.s;if(this.U&&(e?(e=dm(e),fm(e,this.U)):e=this.U),null!==this.o||this.O||(s.I=e,e=null),this.P)e:{for(var n=0,r=0;r<this.j.length;r++){var i=this.j[r];if("__data__"in i.map&&"string"==typeof(i=i.map.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.j.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=M_(this,s,n),xv(r=Nv(this.I),"RID",t),xv(r,"CVER",22),this.F&&xv(r,"X-HTTP-Session-Id",this.F),O_(this,r),e&&(this.O?n="headers="+encodeURIComponent(String(C_(e)))+"&"+n:this.o&&k_(r,this.o,e)),e_(this.i,s),this.bb&&xv(r,"TYPE","init"),this.P?(xv(r,"$req",n),xv(r,"SID","null"),s.aa=!0,mv(s,r,null)):mv(s,r,n),this.H=2}}else 3==this.H&&(t?x_(this,t):0==this.j.length||Jv(this.i)||x_(this))},It.Ma=function(){var e;this.u=null,V_(this),this.ca&&!(this.M||null==this.g||this.S<=0)&&(e=2*this.S,this.l.info("BP detection timer enabled: "+e),this.B=rv(Mg(this.jb,this),e))},It.jb=function(){this.B&&(this.B=null,this.l.info("BP detection timeout reached."),this.l.info("Buffering proxy detected and switch to long-polling!"),this.G=!1,this.M=!0,tv(10),R_(this),V_(this))},It.ib=function(){null!=this.v&&(this.v=null,R_(this),F_(this),tv(19))},It.pb=function(e){e?(this.l.info("Successfully pinged google.com"),tv(2)):(this.l.info("Failed to ping google.com"),tv(1))},It.isActive=function(){return!!this.h&&this.h.isActive(this)},(It=W_.prototype).Ba=function(){},It.Aa=function(){},It.za=function(){},It.ya=function(){},It.isActive=function(){return!0},It.Va=function(){},H_.prototype.g=function(e,t){return new Q_(e,t)},Fg(Q_,Am),Q_.prototype.m=function(){this.g.h=this.j,this.A&&(this.g.J=!0);var e=this.g,t=this.l,n=this.h||void 0;tv(0),e.Y=t,e.na=n||{},e.G=e.aa,e.I=K_(e,null,e.Y),D_(e)},Q_.prototype.close=function(){N_(this.g)},Q_.prototype.u=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.v&&((t={}).__data__=Pm(e),e=t),n.j.push(new Qv(n.fb++,e)),3==n.H&&D_(n)},Q_.prototype.N=function(){this.g.h=null,delete this.j,N_(this.g),delete this.g,Q_.$.N.call(this)},Fg(Y_,ov),Fg(J_,cv),Fg(X_,W_),X_.prototype.Ba=function(){Nm(this.g,"a")},X_.prototype.Aa=function(e){Nm(this.g,new Y_(e))},X_.prototype.za=function(e){Nm(this.g,new J_)},X_.prototype.ya=function(){Nm(this.g,"b")},Fg(Z_,function(){this.blockSize=-1}),Z_.prototype.reset=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.i=this.h=0},Z_.prototype.j=function(e,t){for(var n=(t=void 0===t?e.length:t)-this.blockSize,r=this.m,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)ey(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){ey(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){ey(this,r),i=0;break}}this.h=i,this.i+=t},Z_.prototype.l=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;for(var n=8*this.i,t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.j(e),e=Array(16),t=n=0;t<4;++t)for(var r=0;r<32;r+=8)e[n++]=this.g[t]>>>r&255;return e};var ny={};function ry(e){return-128<=e&&e<128?(t=e,n=function(e){return new ty([0|e],e<0?-1:0)},r=ny,Object.prototype.hasOwnProperty.call(r,t)?r[t]:r[t]=n(t)):new ty([0|e],e<0?-1:0);var t,n,r}function iy(e){if(isNaN(e)||!isFinite(e))return ay;if(e<0)return hy(iy(-e));for(var t=[],n=1,r=0;n<=e;r++)t[r]=e/n|0,n*=sy;return new ty(t,0)}var sy=4294967296,ay=ry(0),oy=ry(1),cy=ry(16777216);function ly(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function uy(e){return-1==e.h}function hy(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new ty(n,~e.h).add(oy)}function dy(e,t){return e.add(hy(t))}function py(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function fy(e,t){this.g=e,this.h=t}function gy(e,t){if(ly(t))throw Error("division by zero");if(ly(e))return new fy(ay,ay);if(uy(e))return t=gy(hy(e),t),new fy(hy(t.g),hy(t.h));if(uy(t))return t=gy(e,hy(t)),new fy(hy(t.g),t.h);if(30<e.g.length){if(uy(e)||uy(t))throw Error("slowDivide_ only works with positive integers.");for(var n=oy,r=t;r.X(e)<=0;)n=my(n),r=my(r);for(var i=vy(n,1),s=vy(r,1),r=vy(r,2),n=vy(n,2);!ly(r);){var a=s.add(r);a.X(e)<=0&&(i=i.add(n),s=a),r=vy(r,1),n=vy(n,1)}return t=dy(e,i.R(t)),new fy(i,t)}for(i=ay;0<=e.X(t);){for(n=Math.max(1,Math.floor(e.ea()/t.ea())),r=(r=Math.ceil(Math.log(n)/Math.LN2))<=48?1:Math.pow(2,r-48),a=(s=iy(n)).R(t);uy(a)||0<a.X(e);)a=(s=iy(n-=r)).R(t);ly(s)&&(s=oy),i=i.add(s),e=dy(e,a)}return new fy(i,e)}function my(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.D(r)<<1|e.D(r-1)>>>31;return new ty(n,e.h)}function vy(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],s=0;s<r;s++)i[s]=0<t?e.D(s+n)>>>t|e.D(s+n+1)<<32-t:e.D(s+n);return new ty(i,e.h)}(It=ty.prototype).ea=function(){if(uy(this))return-hy(this).ea();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.D(n);e+=(0<=r?r:sy+r)*t,t*=sy}return e},It.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(ly(this))return"0";if(uy(this))return"-"+hy(this).toString(e);for(var t=iy(Math.pow(e,6)),n=this,r="";;){var i=gy(n,t).g,s=((0<(n=dy(n,i.R(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(ly(n=i))return s+r;for(;s.length<6;)s="0"+s;r=s+r}},It.D=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},It.X=function(e){return uy(e=dy(this,e))?-1:ly(e)?0:1},It.abs=function(){return uy(this)?hy(this):this},It.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var s=r+(65535&this.D(i))+(65535&e.D(i)),a=(s>>>16)+(this.D(i)>>>16)+(e.D(i)>>>16),r=a>>>16;s&=65535,a&=65535,n[i]=a<<16|s}return new ty(n,-2147483648&n[n.length-1]?-1:0)},It.R=function(e){if(ly(this)||ly(e))return ay;if(uy(this))return uy(e)?hy(this).R(hy(e)):hy(hy(this).R(e));if(uy(e))return hy(this.R(hy(e)));if(this.X(cy)<0&&e.X(cy)<0)return iy(this.ea()*e.ea());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.D(r)>>>16,a=65535&this.D(r),o=e.D(i)>>>16,c=65535&e.D(i);n[2*r+2*i]+=a*c,py(n,2*r+2*i),n[2*r+2*i+1]+=s*c,py(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,py(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,py(n,2*r+2*i+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new ty(n,0)},It.gb=function(e){return gy(this,e).h},It.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)&e.D(r);return new ty(n,this.h&e.h)},It.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)|e.D(r);return new ty(n,this.h|e.h)},It.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.D(r)^e.D(r);return new ty(n,this.h^e.h)},H_.prototype.createWebChannel=H_.prototype.g,Q_.prototype.send=Q_.prototype.u,Q_.prototype.open=Q_.prototype.m,Tt.NO_ERROR=0,Tt.TIMEOUT=8,Tt.HTTP_ERROR=6,sl.COMPLETE="complete",(av.EventType=yt).OPEN="a",yt.CLOSE="b",yt.ERROR="c",yt.MESSAGE="d",Am.prototype.listen=Am.prototype.O,f_.prototype.listenOnce=f_.prototype.P,f_.prototype.getLastError=f_.prototype.Sa,f_.prototype.getLastErrorCode=f_.prototype.Ia,f_.prototype.getStatus=f_.prototype.da,f_.prototype.getResponseJson=f_.prototype.Wa,f_.prototype.getResponseText=f_.prototype.ja,f_.prototype.send=f_.prototype.ha,f_.prototype.setWithCredentials=f_.prototype.Oa,Z_.prototype.digest=Z_.prototype.l,Z_.prototype.update=Z_.prototype.j,ty.prototype.multiply=ty.prototype.R,ty.prototype.modulo=ty.prototype.gb,ty.prototype.compare=ty.prototype.X,ty.prototype.toNumber=ty.prototype.ea,ty.prototype.getBits=ty.prototype.D,ty.fromNumber=iy,ty.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if((n=n||10)<2||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return hy(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=iy(Math.pow(n,8)),i=ay,s=0;s<t.length;s+=8)var a=Math.min(8,t.length-s),o=parseInt(t.substring(s,s+a),n),i=a<8?(a=iy(Math.pow(n,a)),i.R(a).add(iy(o))):(i=i.R(r)).add(iy(o));return i};var _y,yy=Jm,wy=Tt,by=sl,Iy=Qm,Ty=10,Ey=11,Cy=av,ky=f_,Sy=Z_,Ay=ty;const Ny="@firebase/firestore";class Ry{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}Ry.UNAUTHENTICATED=new Ry(null),Ry.GOOGLE_CREDENTIALS=new Ry("google-credentials-uid"),Ry.FIRST_PARTY=new Ry("first-party-uid"),Ry.MOCK_USER=new Ry("mock-user");let Py="10.3.1";const Dy=new ve("@firebase/firestore");function xy(){return Dy.logLevel}function Oy(e,...t){var n;Dy.logLevel<=m.DEBUG&&(n=t.map(Fy),Dy.debug(`Firestore (${Py}): ${e}`,...n))}function My(e,...t){var n;Dy.logLevel<=m.ERROR&&(n=t.map(Fy),Dy.error(`Firestore (${Py}): ${e}`,...n))}function Ly(e,...t){var n;Dy.logLevel<=m.WARN&&(n=t.map(Fy),Dy.warn(`Firestore (${Py}): ${e}`,...n))}function Fy(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function Uy(e="Unexpected state"){var t=`FIRESTORE (${Py}) INTERNAL ASSERTION FAILED: `+e;throw My(t),new Error(t)}function Vy(e){e||Uy()}const qy={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class By extends P{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class jy{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class zy{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class $y{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(Ry.UNAUTHENTICATED))}shutdown(){}}class Ky{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class Gy{constructor(e){this.t=e,this.currentUser=Ry.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new jy;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new jy,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{Oy("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),a()};this.t.onInit(e=>o(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?o(e):(Oy("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new jy))},0),a()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(Oy("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(Vy("string"==typeof e.accessToken),new zy(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return Vy(null===e||"string"==typeof e),new Ry(e)}}class Wy{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=Ry.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);var e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}}class Hy{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Wy(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(Ry.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Qy{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class Yy{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(t,n){const r=e=>{null!=e.error&&Oy("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);var t=e.token!==this.R;return this.R=e.token,Oy("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{Oy("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):Oy("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(Vy("string"==typeof e.token),this.R=e.token,new Qy(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class Jy{static V(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function Xy(e,t){return e<t?-1:t<e?1:0}function Zy(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function ew(e){return e+"\0"}class tw{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new By(qy.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new By(qy.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new By(qy.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new By(qy.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return tw.fromMillis(Date.now())}static fromDate(e){return tw.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new tw(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Xy(this.nanoseconds,e.nanoseconds):Xy(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class nw{constructor(e){this.timestamp=e}static fromTimestamp(e){return new nw(e)}static min(){return new nw(new tw(0,0))}static max(){return new nw(new tw(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}class rw{constructor(e,t,n){void 0===t?t=0:t>e.length&&Uy(),void 0===n?n=e.length-t:n>e.length-t&&Uy(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===rw.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof rw?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class iw extends rw{construct(e,t,n){return new iw(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new By(qy.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new iw(t)}static emptyPath(){return new iw([])}}const sw=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class aw extends rw{construct(e,t,n){return new aw(e,t,n)}static isValidIdentifier(e){return sw.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!aw.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new aw(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new By(qy.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new By(qy.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new By(qy.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new By(qy.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new aw(t)}static emptyPath(){return new aw([])}}class ow{constructor(e){this.path=e}static fromPath(e){return new ow(iw.fromString(e))}static fromName(e){return new ow(iw.fromString(e).popFirst(5))}static empty(){return new ow(iw.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===iw.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return iw.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ow(new iw(e.slice()))}}class cw{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function lw(e){return e.fields.find(e=>2===e.kind)}function uw(e){return e.fields.filter(e=>2!==e.kind)}cw.UNKNOWN_ID=-1;class hw{constructor(e,t){this.fieldPath=e,this.kind=t}}class dw{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new dw(0,gw.min())}}function pw(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=nw.fromTimestamp(1e9===r?new tw(n+1,0):new tw(n,r));return new gw(r,ow.empty(),t)}function fw(e){return new gw(e.readTime,e.key,-1)}class gw{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new gw(nw.min(),ow.empty(),-1)}static max(){return new gw(nw.max(),ow.empty(),-1)}}function mw(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=ow.comparator(e.documentKey,t.documentKey),0!==n?n:Xy(e.largestBatchId,t.largestBatchId))}const vw="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class _w{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function yw(e){if(e.code!==qy.FAILED_PRECONDITION||e.message!==vw)throw e;Oy("LocalStore","Unexpectedly lost primary lease")}class ww{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,i){return this.callbackAttached&&Uy(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new ww((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof ww?t:ww.resolve(t)}catch(e){return ww.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):ww.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):ww.reject(t)}static resolve(n){return new ww((e,t)=>{e(n)})}static reject(n){return new ww((e,t)=>{t(n)})}static waitFor(e){return new ww((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=ww.resolve(!1);for(const n of e)t=t.next(e=>e?ww.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}static mapArray(o,c){return new ww((t,n)=>{const r=o.length,i=new Array(r);let s=0;for(let e=0;e<r;e++){const a=e;c(o[a]).next(e=>{i[a]=e,++s,s===r&&t(i)},e=>n(e))}})}static doWhile(r,i){return new ww((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class bw{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.m=new jy,this.transaction.oncomplete=()=>{this.m.resolve()},this.transaction.onabort=()=>{e.error?this.m.reject(new Ew(n,e.error)):this.m.resolve()},this.transaction.onerror=e=>{var t=Nw(e.target.error);this.m.reject(new Ew(n,t))}}static open(e,t,n,r){try{return new bw(t,e.transaction(r,n))}catch(e){throw new Ew(t,e)}}get g(){return this.m.promise}abort(e){e&&this.m.reject(e),this.aborted||(Oy("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}p(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new kw(t)}}class Iw{constructor(e,t,n){this.name=e,this.version=t,this.S=n,12.2===Iw.D(b())&&My("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return Oy("SimpleDb","Removing database:",e),Sw(window.indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!A())return!1;if(Iw.v())return!0;const e=b(),t=Iw.D(e),n=0<t&&t<10,r=Iw.F(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static v(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.M)}static O(e,t){return e.store(t)}static D(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static F(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async N(s){return this.db||(Oy("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new Ew(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new By(qy.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new By(qy.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new Ew(s,t))},i.onupgradeneeded=e=>{Oy("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.S.B(t,i.transaction,e.oldVersion,this.version).next(()=>{Oy("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.L&&(this.db.onversionchange=e=>this.L(e)),this.db}k(t){this.L=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.N(e);const t=bw.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.p(),e)).catch(e=>(t.abort(e),ww.reject(e))).toPromise();return s.catch(()=>{}),await t.g,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(Oy("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}class Tw{constructor(e){this.q=e,this.K=!1,this.$=null}get isDone(){return this.K}get U(){return this.$}set cursor(e){this.q=e}done(){this.K=!0}W(e){this.$=e}delete(){return Sw(this.q.delete())}}class Ew extends By{constructor(e,t){super(qy.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function Cw(e){return"IndexedDbTransactionError"===e.name}class kw{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(Oy("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(Oy("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),Sw(n)}add(e){return Oy("SimpleDb","ADD",this.store.name,e,e),Sw(this.store.add(e))}get(t){return Sw(this.store.get(t)).next(e=>(Oy("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return Oy("SimpleDb","DELETE",this.store.name,e),Sw(this.store.delete(e))}count(){return Oy("SimpleDb","COUNT",this.store.name),Sw(this.store.count())}G(e,n){var t=this.options(e,n);if(t.index||"function"!=typeof this.store.getAll){const e=this.cursor(t),n=[];return this.j(e,(e,t)=>{n.push(t)}).next(()=>n)}{const e=this.store.getAll(t.range);return new ww((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}}H(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new ww((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}J(e,t){Oy("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Y=!1;var r=this.cursor(n);return this.j(r,(e,t,n)=>n.delete())}Z(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.j(r,t)}X(i){const e=this.cursor({});return new ww((n,r)=>{e.onerror=e=>{var t=Nw(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}j(e,s){const a=[];return new ww((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new Tw(t),r=s(t.primaryKey,t.value,n);if(r instanceof ww){const e=r.catch(e=>(n.done(),ww.reject(e)));a.push(e)}n.isDone?i():null===n.U?t.continue():t.continue(n.U)}else i()}}).next(()=>ww.waitFor(a))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.Y?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function Sw(e){return new ww((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=Nw(e.target.error);r(t)}})}let Aw=!1;function Nw(e){const t=Iw.D(b());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new By("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return Aw||(Aw=!0,setTimeout(()=>{throw e},0)),e}}return e}class Rw{constructor(e,t){this.asyncQueue=e,this.ee=t,this.task=null}start(){this.te(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}te(e){Oy("IndexBackiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{Oy("IndexBackiller",`Documents written: ${await this.ee.ne()}`)}catch(e){Cw(e)?Oy("IndexBackiller","Ignoring IndexedDB error during index backfill: ",e):await yw(e)}await this.te(6e4)})}}class Pw{constructor(e,t){this.localStore=e,this.persistence=t}async ne(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.re(e,t))}re(e,t){const n=new Set;let r=t,i=!0;return ww.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(Oy("IndexBackiller",`Processing collection: ${t}`),this.ie(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}ie(r,i,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(r,i).next(n=>this.localStore.localDocuments.getNextDocuments(r,i,n,e).next(e=>{const t=e.changes;return this.localStore.indexManager.updateIndexEntries(r,t).next(()=>this.se(n,e)).next(e=>(Oy("IndexBackiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}se(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=fw(t);0<mw(n,r)&&(r=n)}),new gw(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class Dw{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.oe(e),this._e=e=>t.writeSequenceNumber(e))}oe(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this._e&&this._e(e),e}}function xw(e){return null==e}function Ow(e){return 0===e&&1/e==-1/0}function Mw(e){return"number"==typeof e&&Number.isInteger(e)&&!Ow(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function Lw(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=Fw(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return Fw(t)}function Fw(e){return e+""}function Uw(t){const n=t.length;if(Vy(2<=n),2===n)return Vy(""===t.charAt(0)&&""===t.charAt(1)),iw.emptyPath();const __PRIVATE_lastReasonableEscapeIndex=n-2,r=[];let i="";for(let a=0;a<n;){const n=t.indexOf("",a);switch((n<0||n>__PRIVATE_lastReasonableEscapeIndex)&&Uy(),t.charAt(n+1)){case"":var s=t.substring(a,n);let e;0===i.length?e=s:(i+=s,e=i,i=""),r.push(e);break;case"":i+=t.substring(a,n),i+="\0";break;case"":i+=t.substring(a,n+1);break;default:Uy()}a=n+2}return new iw(r)}Dw.ae=-1;const Vw=["userId","batchId"];function qw(e,t){return[e,Lw(t)]}function Bw(e,t,n){return[e,Lw(t),n]}const jw={},zw=["prefixPath","collectionGroup","readTime","documentId"],$w=["prefixPath","collectionGroup","documentId"],Kw=["collectionGroup","readTime","prefixPath","documentId"],Gw=["canonicalId","targetId"],Ww=["targetId","path"],Hw=["path","targetId"],Qw=["collectionId","parent"],Yw=["indexId","uid"],Jw=["uid","sequenceNumber"],Xw=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Zw=["indexId","uid","orderedDocumentKey"],eb=["userId","collectionPath","documentId"],tb=["userId","collectionPath","largestBatchId"],nb=["userId","collectionGroup","largestBatchId"],rb=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],ib=[...rb,"documentOverlays"],sb=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],ab=sb,ob=[...ab,"indexConfiguration","indexState","indexEntries"];class cb extends _w{constructor(e,t){super(),this.ue=e,this.currentSequenceNumber=t}}function lb(e,t){var n=e;return Iw.O(n.ue,t)}function ub(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function hb(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function db(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class pb{constructor(e,t){this.comparator=e,this.root=t||gb.EMPTY}insert(e,t){return new pb(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,gb.BLACK,null,null))}remove(e){return new pb(this.comparator,this.root.remove(e,this.comparator).copy(null,null,gb.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new fb(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new fb(this.root,e,this.comparator,!1)}getReverseIterator(){return new fb(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new fb(this.root,e,this.comparator,!0)}}class fb{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class gb{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:gb.RED,this.left=null!=r?r:gb.EMPTY,this.right=null!=i?i:gb.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new gb(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return gb.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return gb.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,gb.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,gb.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var 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(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw Uy();if(this.right.isRed())throw Uy();var e=this.left.check();if(e!==this.right.check())throw Uy();return e+(this.isRed()?0:1)}}gb.EMPTY=null,gb.RED=!0,gb.BLACK=!1,gb.EMPTY=new class{constructor(){this.size=0}get key(){throw Uy()}get value(){throw Uy()}get color(){throw Uy()}get left(){throw Uy()}get right(){throw Uy()}copy(e,t,n,r,i){return this}insert(e,t,n){return new gb(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class mb{constructor(e){this.comparator=e,this.data=new pb(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new vb(this.data.getIterator())}getIteratorFrom(e){return new vb(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof mb))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new mb(this.comparator);return t.data=e,t}}class vb{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function _b(e){return e.hasNext()?e.getNext():void 0}class yb{constructor(e){(this.fields=e).sort(aw.comparator)}static empty(){return new yb([])}unionWith(e){let t=new mb(aw.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new yb(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Zy(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class wb extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class bb{constructor(e){this.binaryString=e}static fromBase64String(e){var t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new wb("Invalid base64 string: "+e):e}}(e);return new bb(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new bb(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Xy(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}bb.EMPTY_BYTE_STRING=new bb("");const Ib=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function Tb(t){if(Vy(!!t),"string"!=typeof t)return{seconds:Eb(t.seconds),nanos:Eb(t.nanos)};{let e=0;var n=Ib.exec(t);Vy(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function Eb(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function Cb(e){return"string"==typeof e?bb.fromBase64String(e):bb.fromUint8Array(e)}function kb(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function Sb(e){var t=e.mapValue.fields.__previous_value__;return kb(t)?Sb(t):t}function Ab(e){var t=Tb(e.mapValue.fields.__local_write_time__.timestampValue);return new tw(t.seconds,t.nanos)}class Nb{constructor(e,t,n,r,i,s,a,o,c){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=c}}class Rb{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new Rb("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof Rb&&e.projectId===this.projectId&&e.database===this.database}}const Pb={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},Db={nullValue:"NULL_VALUE"};function xb(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?kb(e)?4:Gb(e)?9007199254740991:10:Uy()}function Ob(e,t){if(e===t)return!0;var n,r,i=xb(e);if(i!==xb(t))return!1;switch(i){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return Ab(e).isEqual(Ab(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;var n=Tb(e.timestampValue),r=Tb(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return r=t,Cb(e.bytesValue).isEqual(Cb(r.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return n=t,Eb((r=e).geoPointValue.latitude)===Eb(n.geoPointValue.latitude)&&Eb(r.geoPointValue.longitude)===Eb(n.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return Eb(e.integerValue)===Eb(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=Eb(e.doubleValue),r=Eb(t.doubleValue);return n===r?Ow(n)===Ow(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return Zy(e.arrayValue.values||[],t.arrayValue.values||[],Ob);case 10:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(ub(n)!==ub(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Ob(n[e],r[e])))return!1;return!0}(e,t);default:return Uy()}}function Mb(e,t){return void 0!==(e.values||[]).find(e=>Ob(e,t))}function Lb(e,t){if(e===t)return 0;var n,r,i,s,a=xb(e),o=xb(t);if(a!==o)return Xy(a,o);switch(a){case 0:case 9007199254740991:return 0;case 1:return Xy(e.booleanValue,t.booleanValue);case 2:return r=t,i=Eb((n=e).integerValue||n.doubleValue),s=Eb(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return Fb(e.timestampValue,t.timestampValue);case 4:return Fb(Ab(e),Ab(t));case 5:return Xy(e.stringValue,t.stringValue);case 6:return function(e,t){const n=Cb(e),r=Cb(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=Xy(n[i],r[i]);if(0!==t)return t}return Xy(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=Xy(Eb(n.latitude),Eb(r.latitude)))?s:Xy(Eb(n.longitude),Eb(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=Lb(n[i],r[i]);if(t)return t}return Xy(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){if(e===Pb.mapValue&&t===Pb.mapValue)return 0;if(e===Pb.mapValue)return 1;if(t===Pb.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let o=0;o<r.length&&o<s.length;++o){const t=Xy(r[o],s[o]);if(0!==t)return t;var a=Lb(n[r[o]],i[s[o]]);if(0!==a)return a}return Xy(r.length,s.length)}(e.mapValue,t.mapValue);default:throw Uy()}}function Fb(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Xy(e,t);var n=Tb(e),r=Tb(t),i=Xy(n.seconds,r.seconds);return 0!==i?i:Xy(n.nanos,r.nanos)}function Ub(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=Tb(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return Cb(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return ow.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):Uy()}(e)}function Vb(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function qb(e){return!!e&&"integerValue"in e}function Bb(e){return!!e&&"arrayValue"in e}function jb(e){return e&&"nullValue"in e}function zb(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function $b(e){return e&&"mapValue"in e}function Kb(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){const n={mapValue:{fields:{}}};return hb(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=Kb(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=Kb(t.arrayValue.values[e]);return r}return Object.assign({},t)}function Gb(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}function Wb(e,t){var n=Lb(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function Hb(e,t){var n=Lb(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Qb{constructor(e){this.value=e}static empty(){return new Qb({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!$b(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Kb(t)}setAll(e){let n=aw.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=Kb(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());$b(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Ob(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];$b(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){hb(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new Qb(Kb(this.value))}}class Yb{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new Yb(e,0,nw.min(),nw.min(),nw.min(),Qb.empty(),0)}static newFoundDocument(e,t,n,r){return new Yb(e,1,t,nw.min(),n,r,0)}static newNoDocument(e,t){return new Yb(e,2,t,nw.min(),nw.min(),Qb.empty(),0)}static newUnknownDocument(e,t){return new Yb(e,3,t,nw.min(),nw.min(),Qb.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(nw.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Qb.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Qb.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=nw.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof Yb&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new Yb(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Jb{constructor(e,t){this.position=e,this.inclusive=t}}function Xb(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],a=e.position[i];if(r=s.field.isKeyField()?ow.comparator(ow.fromName(a.referenceValue),n.key):Lb(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function Zb(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Ob(e.position[n],t.position[n]))return!1;return!0}class eI{constructor(e,t="asc"){this.field=e,this.dir=t}}class tI{}class nI extends tI{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new uI(e,t,n):"array-contains"===t?new fI(e,n):"in"===t?new gI(e,n):"not-in"===t?new mI(e,n):"array-contains-any"===t?new vI(e,n):new nI(e,t,n)}static createKeyFieldInFilter(e,t,n){return new("in"===t?hI:dI)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Lb(t,this.value)):null!==t&&xb(this.value)===xb(t)&&this.matchesComparison(Lb(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return Uy()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}getFirstInequalityField(){return this.isInequality()?this.field:null}}class rI extends tI{constructor(e,t){super(),this.filters=e,this.op=t,this.ce=null}static create(e,t){return new rI(e,t)}matches(t){return iI(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ce||(this.ce=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ce}getFilters(){return Object.assign([],this.filters)}getFirstInequalityField(){var e=this.le(e=>e.isInequality());return null!==e?e.field:null}le(e){for(const t of this.getFlattenedFilters())if(e(t))return t;return null}}function iI(e){return"and"===e.op}function sI(e){return"or"===e.op}function aI(e){return oI(e)&&iI(e)}function oI(e){for(const t of e.filters)if(t instanceof rI)return!1;return!0}function cI(e,t){var n=e.filters.concat(t);return rI.create(n,e.op)}function lI(e){return e instanceof nI?`${(t=e).field.canonicalString()} ${t.op} ${Ub(t.value)}`:e instanceof rI?(e=e).op.toString()+" {"+e.getFilters().map(lI).join(" ,")+"}":"Filter";var t}class uI extends nI{constructor(e,t,n){super(e,t,n),this.key=ow.fromName(n.referenceValue)}matches(e){var t=ow.comparator(e.key,this.key);return this.matchesComparison(t)}}class hI extends nI{constructor(e,t){super(e,"in",t),this.keys=pI(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class dI extends nI{constructor(e,t){super(e,"not-in",t),this.keys=pI(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function pI(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>ow.fromName(e.referenceValue))}class fI extends nI{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return Bb(t)&&Mb(t.arrayValue,this.value)}}class gI extends nI{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&Mb(this.value.arrayValue,t)}}class mI extends nI{constructor(e,t){super(e,"not-in",t)}matches(e){if(Mb(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!Mb(this.value.arrayValue,t)}}class vI extends nI{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Bb(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>Mb(this.value.arrayValue,e))}}class _I{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.he=null}}function yI(e,t=null,n=[],r=[],i=null,s=null,a=null){return new _I(e,t,n,r,i,s,a)}function wI(e){const t=e;if(null===t.he){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function t(e){if(e instanceof nI)return e.field.canonicalString()+e.op.toString()+Ub(e.value);if(aI(e))return e.filters.map(e=>t(e)).join(",");var n=e.filters.map(e=>t(e)).join(",");return`${e.op}(${n})`}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),xw(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>Ub(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>Ub(e)).join(",")),t.he=e}return t.he}function bI(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++)if(n=e.orderBy[i],r=t.orderBy[i],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r;if(e.filters.length!==t.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!function r(e,t){return e instanceof nI?(n=e,(s=t)instanceof nI&&n.op===s.op&&n.field.isEqual(s.field)&&Ob(n.value,s.value)):e instanceof rI?(i=t)instanceof rI&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce((e,t,n)=>e&&r(t,i.filters[n]),!0):void Uy();var i,n,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Zb(e.startAt,t.startAt)&&Zb(e.endAt,t.endAt)}function II(e){return ow.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function TI(e,t){return e.filters.filter(e=>e instanceof nI&&e.field.isEqual(t))}function EI(t,n,r){let i=Db,s=!0;for(const r of TI(t,n)){let e=Db,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?Db:"booleanValue"in a?{booleanValue:!1}:"integerValue"in a||"doubleValue"in a?{doubleValue:NaN}:"timestampValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in a?{stringValue:""}:"bytesValue"in a?{bytesValue:""}:"referenceValue"in a?Vb(Rb.empty(),ow.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?{mapValue:{}}:Uy();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=Db}Wb({value:i,inclusive:s},{value:e,inclusive:t})<0&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];Wb({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function CI(t,n,r){let i=Pb,s=!0;for(const r of TI(t,n)){let e=Pb,t=!0;switch(r.op){case">=":case">":e="nullValue"in(a=r.value)?{booleanValue:!1}:"booleanValue"in a?{doubleValue:NaN}:"integerValue"in a||"doubleValue"in a?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in a?{stringValue:""}:"stringValue"in a?{bytesValue:""}:"bytesValue"in a?Vb(Rb.empty(),ow.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?{mapValue:{}}:"mapValue"in a?Pb:Uy(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=Pb}0<Hb({value:i,inclusive:s},{value:e,inclusive:t})&&(i=e,s=t)}var a;if(null!==r)for(let e=0;e<t.orderBy.length;++e)if(t.orderBy[e].field.isEqual(n)){const t=r.position[e];0<Hb({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class kI{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Pe=null,this.Ie=null,this.de=null,this.startAt,this.endAt}}function SI(e,t,n,r,i,s,a,o){return new kI(e,t,n,r,i,s,a,o)}function AI(e){return new kI(e)}function NI(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function RI(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function PI(e){for(const t of e.filters){const e=t.getFirstInequalityField();if(null!==e)return e}return null}function DI(e){return null!==e.collectionGroup}function xI(t){const n=t;if(null===n.Pe){n.Pe=[];const t=PI(n),e=RI(n);if(null!==t&&null===e)t.isKeyField()||n.Pe.push(new eI(t)),n.Pe.push(new eI(aw.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.Pe.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.Pe.push(new eI(aw.keyField(),t))}}}return n.Pe}function OI(e){const t=e;return t.Ie||(t.Ie=function(e,t){if("F"===e.limitType)return yI(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{var t="desc"===e.dir?"asc":"desc";return new eI(e.field,t)});var n=e.endAt?new Jb(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new Jb(e.startAt.position,e.startAt.inclusive):null;return yI(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(t,xI(e))),t.Ie}function MI(e,t){t.getFirstInequalityField(),PI(e);var n=e.filters.concat([t]);return new kI(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function LI(e,t,n){return new kI(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function FI(e,t){return bI(OI(e),OI(t))&&e.limitType===t.limitType}function UI(e){return`${wI(OI(e))}|lt:${e.limitType}`}function VI(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>lI(e)).join(", ")}]`),xw(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>Ub(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>Ub(e)).join(",")),`Target(${t})`}(OI(e))}; limitType=${e.limitType})`}function qI(e,t){return t.isFoundDocument()&&(i=e,a=(s=t).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):ow.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e,t){for(const n of xI(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return;return 1}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return;return 1}(e,t)&&(i=t,(!(t=e).startAt||(n=t.startAt,e=xI(t),r=Xb(n,e,i),n.inclusive?r<=0:r<0))&&(!t.endAt||(n=t.endAt,t=xI(t),r=Xb(n,t,i),n.inclusive?0<=r:0<r)));var n,r,i,s,a}function BI(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function jI(i){return(e,t)=>{let n=!1;for(const r of xI(i)){const i=function(e,t,n){var r=e.field.isKeyField()?ow.comparator(t.key,n.key):function(e,t,n){var r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?Lb(r,i):Uy()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return Uy()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}class zI{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let i=0;i<r.length;i++)if(this.equalsFn(r[i][0],e))return void(r[i]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(r){hb(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return db(this.inner)}size(){return this.innerSize}}const $I=new pb(ow.comparator);const KI=new pb(ow.comparator);function GI(...e){let t=KI;for(const n of e)t=t.insert(n.key,n);return t}function WI(e){let n=KI;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function HI(){return new zI(e=>e.toString(),(e,t)=>e.isEqual(t))}const QI=new pb(ow.comparator),YI=new mb(ow.comparator);function JI(...e){let t=YI;for(const n of e)t=t.add(n);return t}const XI=new mb(Xy);function ZI(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:Ow(t)?"-0":t}}function eT(e){return{integerValue:""+e}}function tT(e,t){return Mw(t)?eT(t):ZI(e,t)}class nT{constructor(){this._=void 0}}function rT(e,t){return e instanceof lT?qb(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class iT extends nT{}class sT extends nT{constructor(e){super(),this.elements=e}}function aT(e,t){const n=hT(t);for(const t of e.elements)n.some(e=>Ob(e,t))||n.push(t);return{arrayValue:{values:n}}}class oT extends nT{constructor(e){super(),this.elements=e}}function cT(e,t){let n=hT(t);for(const t of e.elements)n=n.filter(e=>!Ob(e,t));return{arrayValue:{values:n}}}class lT extends nT{constructor(e,t){super(),this.serializer=e,this.Te=t}}function uT(e){return Eb(e.integerValue||e.doubleValue)}function hT(e){return Bb(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class dT{constructor(e,t){this.field=e,this.transform=t}}class pT{constructor(e,t){this.version=e,this.transformResults=t}}class fT{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new fT}static exists(e){return new fT(void 0,e)}static updateTime(e){return new fT(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function gT(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class mT{}function vT(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new kT(e.key,fT.none()):new bT(e.key,e.data,fT.none());{const i=e.data,s=Qb.empty();let t=new mb(aw.comparator);for(var r of n.fields)if(!t.has(r)){let e=i.field(r);null===e&&1<r.length&&(r=r.popLast(),e=i.field(r)),null===e?s.delete(r):s.set(r,e),t=t.add(r)}return new IT(e.key,s,new yb(t.toArray()),fT.none())}}function _T(e,t,n){e instanceof bT?function(e,t,n){const r=e.value.clone(),i=ET(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof IT?function(e,t,n){if(!gT(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=ET(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(TT(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function yT(e,t,n,r){return e instanceof bT?function(e,t,n,r){if(!gT(e.precondition,t))return n;const i=e.value.clone(),s=CT(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof IT?function(e,t,n,r){if(!gT(e.precondition,t))return n;const i=CT(e.fieldTransforms,r,t),s=t.data;return s.setAll(TT(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):(t=t,n=n,gT(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function wT(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&Zy(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof sT&&t instanceof sT||e instanceof oT&&t instanceof oT?Zy(e.elements,t.elements,Ob):e instanceof lT&&t instanceof lT?Ob(e.Te,t.Te):e instanceof iT&&t instanceof iT)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}class bT extends mT{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class IT extends mT{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function TT(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function ET(e,t,n){const r=new Map;Vy(e.length===n.length);for(let u=0;u<n.length;u++){var i=e[u],s=i.transform,a=t.data.field(i.field);r.set(i.field,(o=s,c=a,l=n[u],o instanceof sT?aT(o,c):o instanceof oT?cT(o,c):l))}var o,c,l;return r}function CT(e,t,n){const r=new Map;for(const l of e){const e=l.transform,u=n.data.field(l.field);r.set(l.field,(i=e,s=u,a=t,c=o=void 0,i instanceof iT?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return(t=t&&kb(t)?Sb(t):t)&&(n.fields.__previous_value__=t),{mapValue:n}}(a,s):i instanceof sT?aT(i,s):i instanceof oT?cT(i,s):(o=rT(i=i,s),c=uT(o)+uT(i.Te),qb(o)&&qb(i.Te)?eT(c):ZI(i.serializer,c))))}var i,s,a,o,c;return r}class kT extends mT{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class ST extends mT{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class AT{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&_T(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=yT(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=yT(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,a){const o=HI();return this.mutations.forEach(e=>{const t=s.get(e.key),n=t.overlayedDocument;let r=this.applyToLocalView(n,t.mutatedFields);r=a.has(e.key)?null:r;var i=vT(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(nw.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),JI())}isEqual(e){return this.batchId===e.batchId&&Zy(this.mutations,e.mutations,(e,t)=>wT(e,t))&&Zy(this.baseMutations,e.baseMutations,(e,t)=>wT(e,t))}}class NT{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){Vy(e.mutations.length===n.length);let r=QI;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new NT(e,t,n,r)}}class RT{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class PT{constructor(e,t){this.count=e,this.unchangedNames=t}}function DT(e){switch(e){default:return Uy();case qy.CANCELLED:case qy.UNKNOWN:case qy.DEADLINE_EXCEEDED:case qy.RESOURCE_EXHAUSTED:case qy.INTERNAL:case qy.UNAVAILABLE:case qy.UNAUTHENTICATED:return!1;case qy.INVALID_ARGUMENT:case qy.NOT_FOUND:case qy.ALREADY_EXISTS:case qy.PERMISSION_DENIED:case qy.FAILED_PRECONDITION:case qy.ABORTED:case qy.OUT_OF_RANGE:case qy.UNIMPLEMENTED:case qy.DATA_LOSS:return!0}}function xT(e){if(void 0===e)return My("GRPC error has no .code"),qy.UNKNOWN;switch(e){case _y.OK:return qy.OK;case _y.CANCELLED:return qy.CANCELLED;case _y.UNKNOWN:return qy.UNKNOWN;case _y.DEADLINE_EXCEEDED:return qy.DEADLINE_EXCEEDED;case _y.RESOURCE_EXHAUSTED:return qy.RESOURCE_EXHAUSTED;case _y.INTERNAL:return qy.INTERNAL;case _y.UNAVAILABLE:return qy.UNAVAILABLE;case _y.UNAUTHENTICATED:return qy.UNAUTHENTICATED;case _y.INVALID_ARGUMENT:return qy.INVALID_ARGUMENT;case _y.NOT_FOUND:return qy.NOT_FOUND;case _y.ALREADY_EXISTS:return qy.ALREADY_EXISTS;case _y.PERMISSION_DENIED:return qy.PERMISSION_DENIED;case _y.FAILED_PRECONDITION:return qy.FAILED_PRECONDITION;case _y.ABORTED:return qy.ABORTED;case _y.OUT_OF_RANGE:return qy.OUT_OF_RANGE;case _y.UNIMPLEMENTED:return qy.UNIMPLEMENTED;case _y.DATA_LOSS:return qy.DATA_LOSS;default:return Uy()}}function OT(){return new TextEncoder}(Tt=_y=_y||{})[Tt.OK=0]="OK",Tt[Tt.CANCELLED=1]="CANCELLED",Tt[Tt.UNKNOWN=2]="UNKNOWN",Tt[Tt.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Tt[Tt.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Tt[Tt.NOT_FOUND=5]="NOT_FOUND",Tt[Tt.ALREADY_EXISTS=6]="ALREADY_EXISTS",Tt[Tt.PERMISSION_DENIED=7]="PERMISSION_DENIED",Tt[Tt.UNAUTHENTICATED=16]="UNAUTHENTICATED",Tt[Tt.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Tt[Tt.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Tt[Tt.ABORTED=10]="ABORTED",Tt[Tt.OUT_OF_RANGE=11]="OUT_OF_RANGE",Tt[Tt.UNIMPLEMENTED=12]="UNIMPLEMENTED",Tt[Tt.INTERNAL=13]="INTERNAL",Tt[Tt.UNAVAILABLE=14]="UNAVAILABLE",Tt[Tt.DATA_LOSS=15]="DATA_LOSS";const MT=new Ay([4294967295,4294967295],0);function LT(e){const t=OT().encode(e),n=new Sy;return n.update(t),new Uint8Array(n.digest())}function FT(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new Ay([n,r],0),new Ay([i,s],0)]}class UT{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||8<=t)throw new VT(`Invalid padding: ${t}`);if(n<0)throw new VT(`Invalid hash count: ${n}`);if(0<e.length&&0===this.hashCount)throw new VT(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new VT(`Invalid padding when bitmap length is 0: ${t}`);this.Ae=8*e.length-t,this.Re=Ay.fromNumber(this.Ae)}Ve(e,t,n){let r=e.add(t.multiply(Ay.fromNumber(n)));return 1===r.compare(MT)&&(r=new Ay([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Re).toNumber()}me(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ae)return!1;const t=LT(e),[n,r]=FT(t);for(let i=0;i<this.hashCount;i++){const t=this.Ve(n,r,i);if(!this.me(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new UT(i,r,t);return n.forEach(e=>s.insert(e)),s}insert(t){if(0!==this.Ae){const n=LT(t),[r,i]=FT(n);for(let e=0;e<this.hashCount;e++){const n=this.Ve(r,i,e);this.fe(n)}}}fe(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class VT extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class qT{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,BT.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new qT(nw.min(),r,new pb(Xy),$I,JI())}}class BT{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new BT(n,t,JI(),JI(),JI())}}class jT{constructor(e,t,n,r){this.ge=e,this.removedTargetIds=t,this.key=n,this.pe=r}}class zT{constructor(e,t){this.targetId=e,this.ye=t}}class $T{constructor(e,t,n=bb.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class KT{constructor(){this.we=0,this.Se=HT(),this.be=bb.EMPTY_BYTE_STRING,this.De=!1,this.Ce=!0}get current(){return this.De}get resumeToken(){return this.be}get ve(){return 0!==this.we}get Fe(){return this.Ce}Me(e){0<e.approximateByteSize()&&(this.Ce=!0,this.be=e)}xe(){let n=JI(),r=JI(),i=JI();return this.Se.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:Uy()}}),new BT(this.be,this.De,n,r,i)}Oe(){this.Ce=!1,this.Se=HT()}Ne(e,t){this.Ce=!0,this.Se=this.Se.insert(e,t)}Be(e){this.Ce=!0,this.Se=this.Se.remove(e)}Le(){this.we+=1}ke(){--this.we}qe(){this.Ce=!0,this.De=!0}}class GT{constructor(e){this.Qe=e,this.Ke=new Map,this.$e=$I,this.Ue=WT(),this.We=new pb(Xy)}Ge(e){for(const t of e.ge)e.pe&&e.pe.isFoundDocument()?this.ze(t,e.pe):this.je(t,e.key,e.pe);for(const n of e.removedTargetIds)this.je(n,e.key,e.pe)}He(n){this.forEachTarget(n,e=>{const t=this.Je(e);switch(n.state){case 0:this.Ye(e)&&t.Me(n.resumeToken);break;case 1:t.ke(),t.ve||t.Oe(),t.Me(n.resumeToken);break;case 2:t.ke(),t.ve||this.removeTarget(e);break;case 3:this.Ye(e)&&(t.qe(),t.Me(n.resumeToken));break;case 4:this.Ye(e)&&(this.Ze(e),t.Me(n.resumeToken));break;default:Uy()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Ke.forEach((e,t)=>{this.Ye(t)&&n(t)})}Xe(e){const t=e.targetId,n=e.ye.count,r=this.et(t);if(r){var i=r.target;if(II(i))if(0===n){const e=new ow(i.path);this.je(t,e,Yb.newNoDocument(e,nw.min()))}else Vy(1===n);else{const r=this.tt(t);if(r!==n){const n=this.nt(e),s=n?this.rt(n,e,r):1;if(0!==s){this.Ze(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.We=this.We.insert(t,e)}}}}}nt(e){var t=e.ye.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:n="",padding:r=0},hashCount:t=0}=t;let i,s;try{i=Cb(n).toUint8Array()}catch(e){if(e instanceof wb)return Ly("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{s=new UT(i,r,t)}catch(e){return Ly(e instanceof VT?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ae?null:s}rt(e,t,n){return t.ye.count===n-this.ot(e,t.targetId)?0:2}ot(n,r){const e=this.Qe.getRemoteKeysForTarget(r);let i=0;return e.forEach(e=>{var t=this.Qe.st(),t=`projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`;n.mightContain(t)||(this.je(r,e,null),i++)}),i}_t(r){const i=new Map;this.Ke.forEach((e,t)=>{var n=this.et(t);if(n){if(e.current&&II(n.target)){const i=new ow(n.target.path);null!==this.$e.get(i)||this.ut(t,i)||this.je(t,i,Yb.newNoDocument(i,r))}e.Fe&&(i.set(t,e.xe()),e.Oe())}});let s=JI();this.Ue.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.et(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.$e.forEach((e,t)=>t.setReadTime(r));var e=new qT(r,i,this.We,this.$e,s);return this.$e=$I,this.Ue=WT(),this.We=new pb(Xy),e}ze(e,t){var n;this.Ye(e)&&(n=this.ut(e,t.key)?2:0,this.Je(e).Ne(t.key,n),this.$e=this.$e.insert(t.key,t),this.Ue=this.Ue.insert(t.key,this.ct(t.key).add(e)))}je(e,t,n){if(this.Ye(e)){const r=this.Je(e);this.ut(e,t)?r.Ne(t,1):r.Be(t),this.Ue=this.Ue.insert(t,this.ct(t).delete(e)),n&&(this.$e=this.$e.insert(t,n))}}removeTarget(e){this.Ke.delete(e)}tt(e){var t=this.Je(e).xe();return this.Qe.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Le(e){this.Je(e).Le()}Je(e){let t=this.Ke.get(e);return t||(t=new KT,this.Ke.set(e,t)),t}ct(e){let t=this.Ue.get(e);return t||(t=new mb(Xy),this.Ue=this.Ue.insert(e,t)),t}Ye(e){var t=null!==this.et(e);return t||Oy("WatchChangeAggregator","Detected inactive target",e),t}et(e){var t=this.Ke.get(e);return t&&t.ve?null:this.Qe.lt(e)}Ze(t){this.Ke.set(t,new KT),this.Qe.getRemoteKeysForTarget(t).forEach(e=>{this.je(t,e,null)})}ut(e,t){return this.Qe.getRemoteKeysForTarget(e).has(t)}}function WT(){return new pb(ow.comparator)}function HT(){return new pb(ow.comparator)}const QT={asc:"ASCENDING",desc:"DESCENDING"},YT={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},JT={and:"AND",or:"OR"};class XT{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function ZT(e,t){return e.useProto3Json||xw(t)?t:{value:t}}function e0(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function t0(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function n0(e){return Vy(!!e),nw.fromTimestamp((t=Tb(e),new tw(t.seconds,t.nanos)));var t}function r0(e,t){return e=e,new iw(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function i0(e){var t=iw.fromString(e);return Vy(I0(t)),t}function s0(e,t){return r0(e.databaseId,t.path)}function a0(e,t){const n=i0(t);if(n.get(1)!==e.databaseId.projectId)throw new By(qy.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new By(qy.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new ow(u0(n))}function o0(e,t){return r0(e.databaseId,t)}function c0(e){var t=i0(e);return 4===t.length?iw.emptyPath():u0(t)}function l0(e){return new iw(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function u0(e){return Vy(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function h0(e,t,n){return{name:s0(e,t),fields:n.value.mapValue.fields}}function d0(e,t,n){const r=a0(e,t.name),i=n0(t.updateTime),s=t.createTime?n0(t.createTime):nw.min(),a=new Qb({mapValue:{fields:t.fields}}),o=Yb.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function p0(e,t){let n;if(t instanceof bT)n={update:h0(e,t.key,t.value)};else if(t instanceof kT)n={delete:s0(e,t.key)};else if(t instanceof IT)n={update:h0(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof ST))return Uy();n={verify:s0(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof iT)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof sT)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof oT)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof lT)return{fieldPath:e.field.canonicalString(),increment:t.Te};throw Uy()}(e))),t.precondition.isNone||(n.currentDocument=(r=e,void 0!==(e=t.precondition).updateTime?{updateTime:(t=e.updateTime,e0(r,t.toTimestamp()))}:void 0!==e.exists?{exists:e.exists}:Uy())),n;var r}function f0(t,e){const n=e.currentDocument?void 0!==(i=e.currentDocument).updateTime?fT.updateTime(n0(i.updateTime)):void 0!==i.exists?fT.exists(i.exists):fT.none():fT.none(),r=e.updateTransforms?e.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)Vy("REQUEST_TIME"===t.setToServerValue),n=new iT;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new sT(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new oT(e)}else"increment"in t?n=new lT(e,t.increment):Uy();var r=aw.fromServerFormat(t.fieldPath);return new dT(r,n)}(t,e)):[];var i;if(e.update){e.update.name;var s=a0(t,e.update.name),a=new Qb({mapValue:{fields:e.update.fields}});if(e.updateMask){const t=function(e){const t=e.fieldPaths||[];return new yb(t.map(e=>aw.fromServerFormat(e)))}(e.updateMask);return new IT(s,a,t,n,r)}return new bT(s,a,n,r)}if(e.delete){const r=a0(t,e.delete);return new kT(r,n)}if(e.verify){const r=a0(t,e.verify);return new ST(r,n)}return Uy()}function g0(e,t){return{documents:[o0(e,t.path)]}}function m0(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=o0(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=o0(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length)return function n(e){return e instanceof nI?function(e){if("=="===e.op){if(zb(e.value))return{unaryFilter:{field:w0(e.field),op:"IS_NAN"}};if(jb(e.value))return{unaryFilter:{field:w0(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(zb(e.value))return{unaryFilter:{field:w0(e.field),op:"IS_NOT_NAN"}};if(jb(e.value))return{unaryFilter:{field:w0(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:w0(e.field),op:_0(e.op),value:e.value}}}(e):e instanceof rI?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:y0(e.op),filters:t}}}(e):Uy()}(rI.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:w0(e.field),direction:(e=e.dir,QT[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);i=ZT(e,t.limit);return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt={before:(e=t.startAt).inclusive,values:e.position}),t.endAt&&(n.structuredQuery.endAt={before:!(t=t.endAt).inclusive,values:t.position}),n}function v0(e){let t=c0(e.parent);var n,r,i,s=e.structuredQuery,a=s.from?s.from.length:0;let o=null;if(0<a){Vy(1===a);const p=s.from[0];p.allDescendants?o=p.collectionId:t=t.child(p.collectionId)}let c=[];s.where&&(c=function(e){const t=function t(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=b0(e.unaryFilter.field);return nI.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=b0(e.unaryFilter.field);return nI.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=b0(e.unaryFilter.field);return nI.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=b0(e.unaryFilter.field);return nI.create(i,"!=",{nullValue:"NULL_VALUE"});default:return Uy()}}(e):void 0!==e.fieldFilter?function(e){return nI.create(b0(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return Uy()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return rI.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return Uy()}}(e.compositeFilter.op))}(e):Uy()}(e);return t instanceof rI&&aI(t)?t.getFilters():[t]}(s.where));let l=[];s.orderBy&&(l=s.orderBy.map(e=>function(e){return new eI(b0(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)));let u=null;s.limit&&(u=(e=s.limit,xw(n="object"==typeof e?e.value:e)?null:n));let h=null;s.startAt&&(h=(r=s.startAt,i=!!r.before,n=r.values||[],new Jb(n,i)));let d=null;return s.endAt&&(d=(r=s.endAt,i=!r.before,s=r.values||[],new Jb(s,i))),SI(t,o,l,c,u,"F",h,d)}function _0(e){return YT[e]}function y0(e){return JT[e]}function w0(e){return{fieldPath:e.canonicalString()}}function b0(e){return aw.fromServerFormat(e.fieldPath)}function I0(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class T0{constructor(e,t,n,r,i=nw.min(),s=nw.min(),a=bb.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new T0(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new T0(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new T0(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new T0(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class E0{constructor(e){this.ht=e}}function C0(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:k0(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:s0(i=e.ht,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:e0(i,e.version.toTimestamp()),createTime:e0(i,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:S0(t.version)};else{if(!t.isUnknownDocument())return Uy();r.unknownDocument={path:n.path.toArray(),version:S0(t.version)}}var i;return r}function k0(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function S0(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function A0(e){var t=new tw(e.seconds,e.nanoseconds);return nw.fromTimestamp(t)}function N0(t,e){const n=(e.baseMutations||[]).map(e=>f0(t.ht,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>f0(t.ht,e)),i=tw.fromMillis(e.localWriteTimeMs);return new AT(e.batchId,i,n,r)}function R0(e){var t,n=A0(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?A0(e.lastLimboFreeSnapshotVersion):nw.min(),i=void 0!==e.query.documents?(Vy(1===(t=e.query).documents.length),OI(AI(c0(t.documents[0])))):OI(v0(e.query));return new T0(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,bb.fromBase64String(e.resumeToken))}function P0(e,t){var n=S0(t.snapshotVersion),r=S0(t.lastLimboFreeSnapshotVersion),i=(II(t.target)?g0:m0)(e.ht,t.target),s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:wI(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function D0(e){var t=v0({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?LI(t,t.limit,"L"):t}function x0(e,t){return new RT(t.largestBatchId,f0(e.ht,t.overlayMutation))}function O0(e,t){var n=t.path.lastSegment();return[e,Lw(t.path.popLast()),n]}function M0(e,t,n,r){return{indexId:e,uid:t.uid||"",sequenceNumber:n,readTime:S0(r.readTime),documentKey:Lw(r.documentKey.path),largestBatchId:r.largestBatchId}}class L0{getBundleMetadata(e,t){return F0(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:A0(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return F0(e).put({bundleId:(t=t).id,createTime:S0(n0(t.createTime)),version:t.version})}getNamedQuery(e,t){return U0(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:D0(e.bundledQuery),readTime:A0(e.readTime)}})}saveNamedQuery(e,t){return U0(e).put({name:(t=t).name,readTime:S0(n0(t.readTime)),bundledQuery:t.bundledQuery})}}function F0(e){return lb(e,"bundles")}function U0(e){return lb(e,"namedQueries")}class V0{constructor(e,t){this.serializer=e,this.userId=t}static Pt(e,t){var n=t.uid||"";return new V0(e,n)}getOverlay(e,t){return q0(e).get(O0(this.userId,t)).next(e=>e?x0(this.serializer,e):null)}getOverlays(e,t){const n=HI();return ww.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(r,i,e){const s=[];return e.forEach((e,t)=>{var n=new RT(i,t);s.push(this.It(r,n))}),ww.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(Lw(e.getCollectionPath())));const i=[];return t.forEach(e=>{var t=IDBKeyRange.bound([this.userId,e,r],[this.userId,e,r+1],!1,!0);i.push(q0(n).J("collectionPathOverlayIndex",t))}),ww.waitFor(i)}getOverlaysForCollection(e,t,n){const r=HI(),i=Lw(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return q0(e).G("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=x0(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=HI();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return q0(e).Z({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=x0(this.serializer,t);s.size()<i||r.largestBatchId===a?(s.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>s)}It(e,t){return q0(e).put(function(e,t,n){var[,r,i]=O0(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:p0(e.ht,n.mutation)}}(this.serializer,this.userId,t))}}function q0(e){return lb(e,"documentOverlays")}class B0{constructor(){}dt(e,t){this.Tt(e,t),t.Et()}Tt(e,t){var n,r;"nullValue"in e?this.At(t,5):"booleanValue"in e?(this.At(t,10),t.Rt(e.booleanValue?1:0)):"integerValue"in e?(this.At(t,15),t.Rt(Eb(e.integerValue))):"doubleValue"in e?(n=Eb(e.doubleValue),isNaN(n)?this.At(t,13):(this.At(t,15),Ow(n)?t.Rt(0):t.Rt(n))):"timestampValue"in e?(r=e.timestampValue,this.At(t,20),"string"==typeof r?t.Vt(r):(t.Vt(`${r.seconds||""}`),t.Rt(r.nanos||0))):"stringValue"in e?(this.ft(e.stringValue,t),this.gt(t)):"bytesValue"in e?(this.At(t,30),t.yt(Cb(e.bytesValue)),this.gt(t)):"referenceValue"in e?this.wt(e.referenceValue,t):"geoPointValue"in e?(r=e.geoPointValue,this.At(t,45),t.Rt(r.latitude||0),t.Rt(r.longitude||0)):"mapValue"in e?Gb(e)?this.At(t,Number.MAX_SAFE_INTEGER):(this.St(e.mapValue,t),this.gt(t)):"arrayValue"in e?(this.bt(e.arrayValue,t),this.gt(t)):Uy()}ft(e,t){this.At(t,25),this.Dt(e,t)}Dt(e,t){t.Vt(e)}St(e,t){var n=e.fields||{};this.At(t,55);for(const e of Object.keys(n))this.ft(e,t),this.Tt(n[e],t)}bt(e,t){var n=e.values||[];this.At(t,50);for(const e of n)this.Tt(e,t)}wt(e,t){this.At(t,37),ow.fromName(e).path.forEach(e=>{this.At(t,60),this.Dt(e,t)})}At(e,t){e.Rt(t)}gt(e){e.Rt(2)}}function j0(e){var t=64-function(e){let t=0;for(let r=0;r<8;++r){var n=function(e){if(0===e)return 8;let t=0;return e>>4==0&&(t+=4,e<<=4),e>>6==0&&(t+=2,e<<=2),e>>7==0&&(t+=1),t}(255&e[r]);if(t+=n,8!==n)break}return t}(e);return Math.ceil(t/8)}B0.Ct=new B0;class z0{constructor(){this.buffer=new Uint8Array(1024),this.position=0}vt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ft(n.value),n=t.next();this.Mt()}xt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Ot(n.value),n=t.next();this.Nt()}Bt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ft(e);else if(e<2048)this.Ft(960|e>>>6),this.Ft(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ft(480|e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e);else{const e=t.codePointAt(0);this.Ft(240|e>>>18),this.Ft(128|63&e>>>12),this.Ft(128|63&e>>>6),this.Ft(128|63&e)}}this.Mt()}Lt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Ot(e);else if(e<2048)this.Ot(960|e>>>6),this.Ot(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Ot(480|e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e);else{const e=t.codePointAt(0);this.Ot(240|e>>>18),this.Ot(128|63&e>>>12),this.Ot(128|63&e>>>6),this.Ot(128|63&e)}}this.Nt()}kt(e){var t=this.qt(e),n=j0(t);this.Qt(1+n),this.buffer[this.position++]=255&n;for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=255&t[r]}Kt(e){var t=this.qt(e),n=j0(t);this.Qt(1+n),this.buffer[this.position++]=~(255&n);for(let r=t.length-n;r<t.length;++r)this.buffer[this.position++]=~(255&t[r])}$t(){this.Ut(255),this.Ut(255)}Wt(){this.Gt(255),this.Gt(255)}reset(){this.position=0}seed(e){this.Qt(e.length),this.buffer.set(e,this.position),this.position+=e.length}zt(){return this.buffer.slice(0,this.position)}qt(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=0!=(128&t[0]);t[0]^=n?255:128;for(let r=1;r<t.length;++r)t[r]^=n?255:0;return t}Ft(e){var t=255&e;0==t?(this.Ut(0),this.Ut(255)):255==t?(this.Ut(255),this.Ut(0)):this.Ut(t)}Ot(e){var t=255&e;0==t?(this.Gt(0),this.Gt(255)):255==t?(this.Gt(255),this.Gt(0)):this.Gt(e)}Mt(){this.Ut(0),this.Ut(1)}Nt(){this.Gt(0),this.Gt(1)}Ut(e){this.Qt(1),this.buffer[this.position++]=e}Gt(e){this.Qt(1),this.buffer[this.position++]=~e}Qt(e){var t=e+this.position;if(!(t<=this.buffer.length)){let e=2*this.buffer.length;e<t&&(e=t);const n=new Uint8Array(e);n.set(this.buffer),this.buffer=n}}}class $0{constructor(e){this.jt=e}yt(e){this.jt.vt(e)}Vt(e){this.jt.Bt(e)}Rt(e){this.jt.kt(e)}Et(){this.jt.$t()}}class K0{constructor(e){this.jt=e}yt(e){this.jt.xt(e)}Vt(e){this.jt.Lt(e)}Rt(e){this.jt.Kt(e)}Et(){this.jt.Wt()}}class G0{constructor(){this.jt=new z0,this.Ht=new $0(this.jt),this.Jt=new K0(this.jt)}seed(e){this.jt.seed(e)}Yt(e){return 0===e?this.Ht:this.Jt}zt(){return this.jt.zt()}reset(){this.jt.reset()}}class W0{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}Zt(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new W0(this.indexId,this.documentKey,this.arrayValue,n)}}function H0(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=Q0(e.arrayValue,t.arrayValue),0!==n?n:(n=Q0(e.directionalValue,t.directionalValue),0!==n?n:ow.comparator(e.documentKey,t.documentKey)))}function Q0(e,t){for(let r=0;r<e.length&&r<t.length;++r){var n=e[r]-t[r];if(0!=n)return n}return e.length-t.length}class Y0{constructor(e){this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.Xt=e.orderBy,this.en=[];for(const t of e.filters){const e=t;e.isInequality()?this.tn=e:this.en.push(e)}}nn(e){Vy(e.collectionGroup===this.collectionId);var t=lw(e);if(void 0!==t&&!this.rn(t))return!1;const n=uw(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.rn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(void 0!==this.tn){if(!r.has(this.tn.field.canonicalString())){const e=n[i];if(!this.sn(this.tn,e)||!this.on(this.Xt[s++],e))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.Xt.length||!this.on(this.Xt[s++],e))return!1}return!0}_n(){let e=new mb(aw.comparator);const t=[];for(const n of this.en)n.field.isKeyField()||("array-contains"===n.op||"array-contains-any"===n.op?t.push(new hw(n.field,2)):e.has(n.field)||(e=e.add(n.field),t.push(new hw(n.field,0))));for(const r of this.Xt)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),t.push(new hw(r.field,"asc"===r.dir?0:1)));return new cw(cw.UNKNOWN_ID,this.collectionId,t,dw.empty())}rn(e){for(const t of this.en)if(this.sn(t,e))return!0;return!1}sn(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;var n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind==n}on(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function J0(e){if(0===e.getFilters().length)return[];const t=function t(e){if(Vy(e instanceof nI||e instanceof rI),e instanceof nI)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=rI.create(n,e.op);return r=rE(r),eE(r)?r:(Vy(r instanceof rI),Vy(iI(r)),Vy(1<r.filters.length),r.filters.reduce((e,t)=>tE(e,t)))}(function t(n){var e;if(Vy(n instanceof nI||n instanceof rI),n instanceof nI){if(n instanceof gI){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>nI.create(n.field,"==",e)))||[];return rI.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return rI.create(r,n.op)}(e));return Vy(eE(t)),X0(t)||Z0(t)?[t]:t.getFilters()}function X0(e){return e instanceof nI}function Z0(e){return e instanceof rI&&aI(e)}function eE(e){return X0(e)||Z0(e)||function(e){if(e instanceof rI&&sI(e)){for(const t of e.getFilters())if(!X0(t)&&!Z0(t))return!1;return!0}return!1}(e)}function tE(e,t){var n,r;return Vy(e instanceof nI||e instanceof rI),Vy(t instanceof nI||t instanceof rI),rE(e instanceof nI?t instanceof nI?(n=e,r=t,rI.create([n,r],"and")):nE(e,t):t instanceof nI?nE(t,e):function(e,t){if(Vy(0<e.filters.length&&0<t.filters.length),iI(e)&&iI(t))return cI(e,t.getFilters());const n=sI(e)?e:t,r=sI(e)?t:e,i=n.filters.map(e=>tE(e,r));return rI.create(i,"or")}(e,t))}function nE(t,e){if(iI(e))return cI(e,t.getFilters());var n=e.filters.map(e=>tE(t,e));return rI.create(n,"or")}function rE(t){if(Vy(t instanceof nI||t instanceof rI),t instanceof nI)return t;const e=t.getFilters();if(1===e.length)return rE(e[0]);if(oI(t))return t;const n=e.map(e=>rE(e)),r=[];return n.forEach(e=>{e instanceof nI?r.push(e):e instanceof rI&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:rI.create(r,t.op)}class iE{constructor(){this.an=new sE}addToCollectionParentIndex(e,t){return this.an.add(t),ww.resolve()}getCollectionParents(e,t){return ww.resolve(this.an.getEntries(t))}addFieldIndex(e,t){return ww.resolve()}deleteFieldIndex(e,t){return ww.resolve()}deleteAllFieldIndexes(e){return ww.resolve()}createTargetIndexes(e,t){return ww.resolve()}getDocumentsMatchingTarget(e,t){return ww.resolve(null)}getIndexType(e,t){return ww.resolve(0)}getFieldIndexes(e,t){return ww.resolve([])}getNextCollectionGroupToUpdate(e){return ww.resolve(null)}getMinOffset(e,t){return ww.resolve(gw.min())}getMinOffsetFromCollectionGroup(e,t){return ww.resolve(gw.min())}updateCollectionGroup(e,t,n){return ww.resolve()}updateIndexEntries(e,t){return ww.resolve()}}class sE{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new mb(iw.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new mb(iw.comparator)).toArray()}}const aE=new Uint8Array(0);class oE{constructor(e,t){this.user=e,this.databaseId=t,this.un=new sE,this.cn=new zI(e=>wI(e),(e,t)=>bI(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.un.has(t))return ww.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.un.add(t)});r={collectionId:n,parent:Lw(r)};return cE(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[ew(n),""],!1,!0);return cE(e).G(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(Uw(t.parent))}return r})}addFieldIndex(e,t){const n=uE(e),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;const i=n.add(r);if(t.indexState){const n=hE(e);return i.next(e=>{n.put(M0(e,this.user,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=uE(e),r=hE(e),i=lE(e);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){const t=uE(e),n=lE(e),r=hE(e);return t.J().next(()=>n.J()).next(()=>r.J())}createTargetIndexes(n,e){return ww.forEach(this.ln(e),t=>this.getIndexType(n,t).next(e=>{if(0===e||1===e){const e=new Y0(t);return this.addFieldIndex(n,e._n())}}))}getDocumentsMatchingTarget(e,u){const h=lE(e);let d=!0;const n=new Map;return ww.forEach(this.ln(u),t=>this.hn(e,t).next(e=>{d=d&&!!e,n.set(t,e)})).next(()=>{if(d){let l=JI();const d=[];return ww.forEach(n,(e,t)=>{var n;Oy("IndexedDbIndexManager",`Using index ${n=e,`id=${n.indexId}|cg=${n.collectionGroup}|f=${n.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${wI(u)}`);var r=function(e,t){var n=lw(t);if(void 0===n)return null;for(const t of TI(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(t,e),i=function(e,t){const n=new Map;for(const r of uw(t))for(const t of TI(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(t,e),s=function(e,t){const n=[];let r=!0;for(const i of uw(t)){const t=(0===i.kind?EI:CI)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new Jb(n,r)}(t,e),a=function(e,t){const n=[];let r=!0;for(const i of uw(t)){const t=(0===i.kind?CI:EI)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new Jb(n,r)}(t,e),o=this.Pn(e,t,s),c=this.Pn(e,t,a),i=this.In(e,t,i),i=this.dn(e.indexId,r,o,s.inclusive,c,a.inclusive,i);return ww.forEach(i,e=>h.H(e,u.limit).next(e=>{e.forEach(e=>{var t=ow.fromSegments(e.documentKey);l.has(t)||(l=l.add(t),d.push(t))})}))}).next(()=>d)}return ww.resolve(null)})}ln(t){let e=this.cn.get(t);return e||(e=0===t.filters.length?[t]:J0(rI.create(t.filters,"and")).map(e=>yI(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.cn.set(t,e),e)}dn(t,e,n,r,i,s,a){const o=(null!=e?e.length:1)*Math.max(n.length,i.length),c=o/(null!=e?e.length:1),l=[];for(let u=0;u<o;++u){const o=e?this.Tn(e[u/c]):aE,h=this.En(t,o,n[u%c],r),d=this.An(t,o,i[u%c],s),p=a.map(e=>this.En(t,o,e,!0));l.push(...this.createRange(h,d,p))}return l}En(e,t,n,r){const i=new W0(e,ow.empty(),t,n);return r?i:i.Zt()}An(e,t,n,r){const i=new W0(e,ow.empty(),t,n);return r?i.Zt():i}hn(e,t){const r=new Y0(t),n=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,n).next(e=>{let t=null;for(const n of e)r.nn(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.ln(t);return ww.forEach(r,t=>this.hn(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new mb(aw.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})).next(()=>function(e){return null!==e.limit}(t)&&1<r.length&&2===n?1:n)}Rn(e,t){const n=new G0;for(const i of uw(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.Yt(i.kind);B0.Ct.dt(e,r)}return n.zt()}Tn(e){const t=new G0;return B0.Ct.dt(e,t.Yt(0)),t.zt()}Vn(e,t){const n=new G0;return B0.Ct.dt(Vb(this.databaseId,t),n.Yt(0===(r=uw(e)).length?0:r[r.length-1].kind)),n.zt();var r}In(e,t,n){if(null===n)return[];let r=[];r.push(new G0);let i=0;for(const s of uw(e)){const e=n[i++];for(const n of r)if(this.mn(t,s.fieldPath)&&Bb(e))r=this.fn(r,s,e);else{const t=n.Yt(s.kind);B0.Ct.dt(e,t)}}return this.gn(r)}Pn(e,t,n){return this.In(e,t,n.position)}gn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].zt();return t}fn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new G0;r.seed(n.zt()),B0.Ct.dt(e,r.Yt(t.kind)),i.push(r)}return i}mn(e,t){return!!e.filters.find(e=>e instanceof nI&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=uE(e),r=hE(e);return(t?n.G("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.G()).next(e=>{const s=[];return ww.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new dw(e.sequenceNumber,new gw(A0(e.readTime),new ow(Uw(e.documentKey)),e.largestBatchId)):dw.empty(),r=t.fields.map(([e,t])=>new hw(aw.fromServerFormat(e),t)),new cw(t.indexId,t.collectionGroup,r,n)))})).next(()=>s)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{var n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!=n?n:Xy(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=uE(e),s=hE(e);return this.pn(e).next(t=>i.G("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>ww.forEach(e,e=>s.put(M0(e.indexId,this.user,t,r)))))}updateIndexEntries(i,e){const n=new Map;return ww.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?ww.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),ww.forEach(e,n=>this.yn(i,t,n).next(e=>{var t=this.wn(r,n);return e.isEqual(t)?ww.resolve():this.Sn(i,r,n,e,t)}))))})}bn(e,t,n,r){return lE(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.Vn(n,t.key),documentKey:t.key.path.toArray()})}Dn(e,t,n,r){return lE(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.Vn(n,t.key),t.key.path.toArray()])}yn(e,n,r){const t=lE(e);let i=new mb(H0);return t.Z({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.Vn(r,n)])},(e,t)=>{i=i.add(new W0(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}wn(e,t){let n=new mb(H0);var r=this.Rn(t,e);if(null==r)return n;const i=lw(t);if(null!=i){var s=e.data.field(i.fieldPath);if(Bb(s))for(const i of s.arrayValue.values||[])n=n.add(new W0(t.indexId,e.key,this.Tn(i),r))}else n=n.add(new W0(t.indexId,e.key,aE,r));return n}Sn(t,n,r,e,i){Oy("IndexedDbIndexManager","Updating index entries for document '%s'",n.key);const s=[];return function(e,t,n,r,i){var s=e.getIterator(),a=t.getIterator();let o=_b(s),c=_b(a);for(;o||c;){let e=!1,t=!1;if(o&&c){const r=n(o,c);r<0?t=!0:0<r&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(c),c=_b(a)):t?(i(o),o=_b(s)):(o=_b(s),c=_b(a))}}(e,i,H0,e=>{s.push(this.bn(t,n,r,e))},e=>{s.push(this.Dn(t,n,r,e))}),ww.waitFor(s)}pn(e){let r=1;return hE(e).Z({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,t,n)=>{n.done(),r=t.sequenceNumber+1}).next(()=>r)}createRange(e,t,n){n=n.sort((e,t)=>H0(e,t)).filter((e,t,n)=>!t||0!==H0(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=H0(i,e),s=H0(i,t);if(0===n)r[0]=e.Zt();else if(0<n&&s<0)r.push(i),r.push(i.Zt());else if(0<s)break}r.push(t);const i=[];for(let a=0;a<r.length;a+=2){if(this.Cn(r[a],r[a+1]))return[];const t=[r[a].indexId,this.uid,r[a].arrayValue,r[a].directionalValue,aE,[]],n=[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,aE,[]];i.push(IDBKeyRange.bound(t,n))}return i}Cn(e,t){return 0<H0(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(dE)}getMinOffset(t,e){return ww.mapArray(this.ln(e),e=>this.hn(t,e).next(e=>e||Uy())).next(dE)}}function cE(e){return lb(e,"collectionParents")}function lE(e){return lb(e,"indexEntries")}function uE(e){return lb(e,"indexConfiguration")}function hE(e){return lb(e,"indexState")}function dE(e){Vy(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let i=1;i<e.length;i++){var r=e[i].indexState.offset;mw(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new gw(t.readTime,t.documentKey,n)}const pE={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class fE{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new fE(e,fE.DEFAULT_COLLECTION_PERCENTILE,fE.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function gE(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId);let o=0;const c=r.Z({range:a},(e,t,n)=>(o++,n.delete()));s.push(c.next(()=>{Vy(1===o)}));const l=[];for(const e of n.mutations){const r=Bw(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return ww.waitFor(s).next(()=>l)}function mE(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw Uy();t=e.noDocument}return JSON.stringify(t).length}fE.DEFAULT_COLLECTION_PERCENTILE=10,fE.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,fE.DEFAULT=new fE(41943040,fE.DEFAULT_COLLECTION_PERCENTILE,fE.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),fE.DISABLED=new fE(-1,0,0);class vE{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.vn={}}static Pt(e,t,n,r){Vy(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new vE(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return yE(e).Z({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,p){const f=wE(u),g=yE(u);return g.add({}).next(e=>{Vy("number"==typeof e);const t=new AT(e,h,d,p),n=(i=this.serializer,s=this.userId,a=t,o=a.baseMutations.map(e=>p0(i.ht,e)),c=a.mutations.map(e=>p0(i.ht,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:c}),r=[];var i,s,a,o,c;let l=new mb((e,t)=>Xy(e.canonicalString(),t.canonicalString()));for(const u of p){const h=Bw(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(f.put(h,jw))}return l.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.vn[e]=t.keys()}),ww.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return yE(e).get(t).next(e=>e?(Vy(e.userId===this.userId),N0(this.serializer,e)):null)}Fn(e,n){return this.vn[n]?ww.resolve(this.vn[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.vn[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return yE(e).Z({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(Vy(t.batchId>=r),i=N0(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return yE(e).Z({index:"userMutationsIndex",range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return yE(e).G("userMutationsIndex",t).next(e=>e.map(e=>N0(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=qw(this.userId,o.path),t=IDBKeyRange.lowerBound(e),c=[];return wE(a).Z({range:t},(e,t,n)=>{var[r,i,s]=e,i=Uw(i);if(r===this.userId&&o.path.isEqual(i))return yE(a).get(s).next(e=>{if(!e)throw Uy();Vy(e.userId===this.userId),c.push(N0(this.serializer,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new mb(Xy);const n=[];return e.forEach(a=>{var e=qw(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=wE(t).Z({range:e},(e,t,n)=>{var[r,i,s]=e,i=Uw(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),ww.waitFor(n).next(()=>this.Mn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=qw(this.userId,a),r=IDBKeyRange.lowerBound(n);let c=new mb(Xy);return wE(e).Z({range:r},(e,t,n)=>{var[r,i,s]=e,i=Uw(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(c=c.add(s)):n.done()}).next(()=>this.Mn(e,c))}Mn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(yE(t).get(e).next(e=>{if(null===e)throw Uy();Vy(e.userId===this.userId),n.push(N0(this.serializer,e))}))}),ww.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return gE(t.ue,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.xn(n.batchId)}),ww.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}xn(e){delete this.vn[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return ww.resolve();const t=IDBKeyRange.lowerBound([this.userId]),r=[];return wE(n).Z({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=Uw(e[1]);r.push(t)}else n.done()}).next(()=>{Vy(0===r.length)})})}containsKey(e,t){return _E(e,this.userId,t)}On(e){return bE(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function _E(e,s,t){const n=qw(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return wE(e).Z({range:r,Y:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function yE(e){return lb(e,"mutations")}function wE(e){return lb(e,"documentMutations")}function bE(e){return lb(e,"mutationQueues")}class IE{constructor(e){this.Nn=e}next(){return this.Nn+=2,this.Nn}static Bn(){return new IE(0)}static Ln(){return new IE(-1)}}class TE{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(n){return this.kn(n).next(e=>{const t=new IE(e.highestTargetId);return e.highestTargetId=t.next(),this.qn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.kn(e).next(e=>nw.fromTimestamp(new tw(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.kn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.kn(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.qn(t,e)))}addTargetData(t,n){return this.Qn(t,n).next(()=>this.kn(t).next(e=>(e.targetCount+=1,this.Kn(n,e),this.qn(t,e))))}updateTargetData(e,t){return this.Qn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>EE(t).delete(e.targetId)).next(()=>this.kn(t)).next(e=>(Vy(0<e.targetCount),--e.targetCount,this.qn(t,e)))}removeTargets(r,i,s){let a=0;const o=[];return EE(r).Z((e,t)=>{var n=R0(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>ww.waitFor(o)).next(()=>a)}forEachTarget(e,r){return EE(e).Z((e,t)=>{var n=R0(t);r(n)})}kn(e){return CE(e).get("targetGlobalKey").next(e=>(Vy(null!==e),e))}qn(e,t){return CE(e).put("targetGlobalKey",t)}Qn(e,t){return EE(e).put(P0(this.serializer,t))}Kn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.kn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=wI(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return EE(e).Z({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=R0(t);bI(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=kE(n);return e.forEach(e=>{var t=Lw(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),ww.waitFor(i)}removeMatchingKeys(n,e,r){const i=kE(n);return ww.forEach(e,e=>{var t=Lw(e.path);return ww.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=kE(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=kE(e);let i=JI();return r.Z({range:n,Y:!0},(e,t,n)=>{var r=Uw(e[1]),r=new ow(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=Lw(t.path),n=IDBKeyRange.bound([n],[ew(n)],!1,!0);let r=0;return kE(e).Z({index:"documentTargetsIndex",Y:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}lt(e,t){return EE(e).get(t).next(e=>e?R0(e):null)}}function EE(e){return lb(e,"targets")}function CE(e){return lb(e,"targetGlobal")}function kE(e){return lb(e,"targetDocuments")}function SE([e,t],[n,r]){var i=Xy(e,n);return 0===i?Xy(t,r):i}class AE{constructor(e){this.$n=e,this.buffer=new mb(SE),this.Un=0}Wn(){return++this.Un}Gn(e){var t=[e,this.Wn()];if(this.buffer.size<this.$n)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();SE(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class NE{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.zn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.jn(6e4)}stop(){this.zn&&(this.zn.cancel(),this.zn=null)}get started(){return null!==this.zn}jn(e){Oy("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.zn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.zn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){Cw(e)?Oy("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await yw(e)}await this.jn(3e5)})}}class RE{constructor(e,t){this.Hn=e,this.params=t}calculateTargetCount(e,t){return this.Hn.Jn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return ww.resolve(Dw.ae);const n=new AE(t);return this.Hn.forEachTarget(e,e=>n.Gn(e.sequenceNumber)).next(()=>this.Hn.Yn(e,e=>n.Gn(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.Hn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Hn.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(Oy("LruGarbageCollector","Garbage collection skipped; disabled"),ww.resolve(pE)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(Oy("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),pE):this.Zn(t,n))}getCacheSize(e){return this.Hn.getCacheSize(e)}Zn(t,n){let r,i,s,a,o,c,l;const u=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(Oy("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,a=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(r=e,o=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,c=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(l=Date.now(),xy()<=m.DEBUG&&Oy("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-u}ms\n\tDetermined least recently used ${i} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(c-o)+"ms\n"+`\tRemoved ${e} documents in `+(l-c)+"ms\n"+`Total Duration: ${l-u}ms`),ww.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class PE{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new RE(e,t))}Jn(e){const n=this.Xn(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Xn(e){let t=0;return this.Yn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Yn(e,n){return this.er(e,(e,t)=>n(t))}addReference(e,t,n){return DE(e,n)}removeReference(e,t,n){return DE(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return DE(e,t)}tr(t,n){let r=!1;return bE(t).X(e=>_E(t,e,n).next(e=>(e&&(r=!0),ww.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.er(n,(t,e)=>{if(e<=r){const r=this.tr(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,nw.min()),kE(n).delete(function(e){return[0,Lw(e.path)]}(t))))});s.push(r)}}).next(()=>ww.waitFor(s)).next(()=>i.apply(n)).next(()=>a)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return DE(e,t)}er(e,r){const t=kE(e);let i,s=Dw.ae;return t.Z({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==Dw.ae&&r(new ow(Uw(i)),s),s=n,i=t):s=Dw.ae}).next(()=>{s!==Dw.ae&&r(new ow(Uw(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function DE(e,t){return kE(e).put((e=e.currentSequenceNumber,{targetId:0,path:Lw(t.path),sequenceNumber:e}))}class xE{constructor(){this.changes=new zI(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Yb.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?ww.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class OE{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return UE(e).put(n)}removeEntry(e,t,n){return UE(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],k0(t),n[n.length-1]]}(t,n))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.nr(t,e)))}getEntry(e,n){let r=Yb.newInvalidDocument(n);return UE(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(VE(n))},(e,t)=>{r=this.rr(n,t)}).next(()=>r)}ir(e,n){let r={size:0,document:Yb.newInvalidDocument(n)};return UE(e).Z({index:"documentKeyIndex",range:IDBKeyRange.only(VE(n))},(e,t)=>{r={document:this.rr(n,t),size:mE(t)}}).next(()=>r)}getEntries(e,t){let r=$I;return this.sr(e,t,(e,t)=>{var n=this.rr(e,t);r=r.insert(e,n)}).next(()=>r)}_r(e,t){let r=$I,i=new pb(ow.comparator);return this.sr(e,t,(e,t)=>{var n=this.rr(e,t);r=r.insert(e,n),i=i.insert(e,mE(t))}).next(()=>({documents:r,ar:i}))}sr(e,t,i){if(t.isEmpty())return ww.resolve();let n=new mb(BE);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(VE(n.first()),VE(n.last())),s=n.getIterator();let a=s.getNext();return UE(e).Z({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=ow.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&BE(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.W(VE(a)):n.done()}).next(()=>{for(;a;)i(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,n,t,r,i){const s=n.path,a=[s.popLast().toArray(),s.lastSegment(),k0(t.readTime),t.documentKey.path.isEmpty()?"":t.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return UE(e).G(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let t=$I;for(const i of e){const e=this.rr(ow.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(qI(n,e)||r.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,i){let s=$I;var r=qE(t,n),a=qE(t,gw.max());return UE(e).Z({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.rr(ow.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(r.key,r),s.size===i&&n.done()}).next(()=>s)}newChangeBuffer(e){return new LE(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return FE(e).get("remoteDocumentGlobalKey").next(e=>(Vy(!!e),e))}nr(e,t){return FE(e).put("remoteDocumentGlobalKey",t)}rr(e,t){if(t){const e=function(e,t){let n;if(t.document)n=d0(e.ht,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=ow.fromSegments(t.noDocument.path),i=A0(t.noDocument.readTime);n=Yb.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return Uy();{const e=ow.fromSegments(t.unknownDocument.path),s=A0(t.unknownDocument.version);n=Yb.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new tw(t[0],t[1]),nw.fromTimestamp(r))),n;var r}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(nw.min()))return e}return Yb.newInvalidDocument(e)}}function ME(e){return new OE(e)}class LE extends xE{constructor(e,t){super(),this.ur=e,this.trackRemovals=t,this.cr=new zI(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,c=new mb((e,t)=>Xy(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.cr.get(e);if(a.push(this.ur.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=C0(this.ur.serializer,t);c=c.add(e.path.popLast());var i=mE(r);o+=i-n.size,a.push(this.ur.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=C0(this.ur.serializer,t.convertToNoDocument(nw.min()));a.push(this.ur.addEntry(s,e,o))}}),c.forEach(e=>{a.push(this.ur.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.ur.updateMetadata(s,o)),ww.waitFor(a)}getFromCache(e,t){return this.ur.ir(e,t).next(e=>(this.cr.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.ur._r(e,t).next(({documents:n,ar:e})=>(e.forEach((e,t)=>{this.cr.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function FE(e){return lb(e,"remoteDocumentGlobal")}function UE(e){return lb(e,"remoteDocumentsV14")}function VE(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function qE(e,t){const n=t.documentKey.path.toArray();return[e,k0(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function BE(e,t){var n=e.path.toArray(),r=t.path.toArray();let i=0;for(let s=0;s<n.length-2&&s<r.length-2;++s)if(i=Xy(n[s],r[s]),i)return i;return i=Xy(n.length,r.length),i||(i=Xy(n[n.length-2],r[r.length-2]),i||Xy(n[n.length-1],r[r.length-1]))}class jE{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class zE{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(t,n){let r=null;return this.documentOverlayCache.getOverlay(t,n).next(e=>(r=e,this.remoteDocumentCache.getEntry(t,n))).next(e=>(null!==r&&yT(r.mutation,e,yb.empty(),tw.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,JI()).next(()=>e))}getLocalViewOfDocuments(e,t,n=JI()){const r=HI();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=GI();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=HI();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,JI()))}populateOverlays(e,n,t){const r=[];return t.forEach(e=>{n.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,t)=>{n.set(e,t)})})}computeViews(e,t,r,i){let s=$I;const a=HI(),o=HI();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof IT)?s=s.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),yT(n.mutation,t,n.mutation.getFieldMask(),tw.now())):a.set(t.key,yb.empty())}),this.recalculateAndSaveOverlays(e,s).next(e=>(e.forEach((e,t)=>a.set(e,t)),t.forEach((e,t)=>{var n;return o.set(e,new jE(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=HI();let c=new pb((e,t)=>e-t),l=JI();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(s,a).next(e=>{for(const r of e)r.keys().forEach(e=>{var t,n=a.get(e);null!==n&&(t=o.get(e)||yb.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(c.get(r.batchId)||JI()).add(e),c=c.insert(r.batchId,t))})}).next(()=>{const e=[],t=c.getReverseIterator();for(;t.hasNext();){const c=t.getNext(),n=c.key,r=c.value,i=HI();r.forEach(e=>{var t;l.has(e)||(null!==(t=vT(a.get(e),o.get(e)))&&i.set(e,t),l=l.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return ww.waitFor(e)}).next(()=>o)}recalculateAndSaveOverlaysForDocumentKeys(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.recalculateAndSaveOverlays(t,e))}getDocumentsMatchingQuery(e,t,n,r){return i=t,ow.isDocumentKey(i.path)&&null===i.collectionGroup&&0===i.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):DI(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r);var i}getNextDocuments(s,t,a,o){return this.remoteDocumentCache.getAllFromCollectionGroup(s,t,a,o).next(n=>{const e=0<o-n.size?this.documentOverlayCache.getOverlaysForCollectionGroup(s,t,a.largestBatchId,o-n.size):ww.resolve(HI());let r=-1,i=n;return e.next(e=>ww.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?ww.resolve():this.remoteDocumentCache.getEntry(s,t).next(e=>{i=i.insert(t,e)}))).next(()=>this.populateOverlays(s,e,n)).next(()=>this.computeViews(s,i,e,JI())).next(e=>({batchId:r,changes:WI(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new ow(t)).next(e=>{let t=GI();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s,a){const o=i.collectionGroup;let c=GI();return this.indexManager.getCollectionParents(r,o).next(e=>ww.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new kI(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.getDocumentsMatchingCollectionQuery(r,n,s,a).next(e=>{e.forEach((e,t)=>{c=c.insert(e,t)})})}).next(()=>c))}getDocumentsMatchingCollectionQuery(t,s,n,r){let a;return this.documentOverlayCache.getOverlaysForCollection(t,s.path,n.largestBatchId).next(e=>(a=e,this.remoteDocumentCache.getDocumentsMatchingQuery(t,s,n,a,r))).next(r=>{a.forEach((e,t)=>{var n=t.getKey();null===r.get(n)&&(r=r.insert(n,Yb.newInvalidDocument(n)))});let i=GI();return r.forEach((e,t)=>{var n=a.get(e);void 0!==n&&yT(n.mutation,t,yb.empty(),tw.now()),qI(s,t)&&(i=i.insert(e,t))}),i})}}class $E{constructor(e){this.serializer=e,this.lr=new Map,this.hr=new Map}getBundleMetadata(e,t){return ww.resolve(this.lr.get(t))}saveBundleMetadata(e,t){return this.lr.set(t.id,{id:t.id,version:t.version,createTime:n0(t.createTime)}),ww.resolve()}getNamedQuery(e,t){return ww.resolve(this.hr.get(t))}saveNamedQuery(e,t){return this.hr.set(t.name,{name:(t=t).name,query:D0(t.bundledQuery),readTime:n0(t.readTime)}),ww.resolve()}}class KE{constructor(){this.overlays=new pb(ow.comparator),this.Pr=new Map}getOverlay(e,t){return ww.resolve(this.overlays.get(t))}getOverlays(e,t){const n=HI();return ww.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(n,r,e){return e.forEach((e,t)=>{this.It(n,r,t)}),ww.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.Pr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.Pr.delete(n)),ww.resolve()}getOverlaysForCollection(e,t,n){const r=HI(),i=t.length+1,s=new ow(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){const e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return ww.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new pb((e,t)=>e-t);const s=this.overlays.getIterator();for(;s.hasNext();){const t=s.getNext().value;if(t.getKey().getCollectionGroup()===e&&t.largestBatchId>n){let e=i.get(t.largestBatchId);null===e&&(e=HI(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=HI(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return ww.resolve(a)}It(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.Pr.get(r.largestBatchId).delete(n.key);this.Pr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new RT(t,n));let i=this.Pr.get(t);void 0===i&&(i=JI(),this.Pr.set(t,i)),this.Pr.set(t,i.add(n.key))}}class GE{constructor(){this.Ir=new mb(WE.dr),this.Tr=new mb(WE.Er)}isEmpty(){return this.Ir.isEmpty()}addReference(e,t){var n=new WE(e,t);this.Ir=this.Ir.add(n),this.Tr=this.Tr.add(n)}Ar(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Rr(new WE(e,t))}Vr(e,t){e.forEach(e=>this.removeReference(e,t))}mr(e){const t=new ow(new iw([])),n=new WE(t,e),r=new WE(t,e+1),i=[];return this.Tr.forEachInRange([n,r],e=>{this.Rr(e),i.push(e.key)}),i}gr(){this.Ir.forEach(e=>this.Rr(e))}Rr(e){this.Ir=this.Ir.delete(e),this.Tr=this.Tr.delete(e)}pr(e){var t=new ow(new iw([])),n=new WE(t,e),t=new WE(t,e+1);let r=JI();return this.Tr.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new WE(e,0),t=this.Ir.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class WE{constructor(e,t){this.key=e,this.yr=t}static dr(e,t){return ow.comparator(e.key,t.key)||Xy(e.yr,t.yr)}static Er(e,t){return Xy(e.yr,t.yr)||ow.comparator(e.key,t.key)}}class HE{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.wr=1,this.Sr=new mb(WE.dr)}checkEmpty(e){return ww.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.wr;this.wr++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new AT(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.Sr=this.Sr.add(new WE(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return ww.resolve(s)}lookupMutationBatch(e,t){return ww.resolve(this.br(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.Dr(t+1),n=n<0?0:n;return ww.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return ww.resolve(0===this.mutationQueue.length?-1:this.wr-1)}getAllMutationBatches(e){return ww.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new WE(t,0),r=new WE(t,Number.POSITIVE_INFINITY),i=[];return this.Sr.forEachInRange([n,r],e=>{var t=this.br(e.yr);i.push(t)}),ww.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new mb(Xy);return t.forEach(e=>{var t=new WE(e,0),n=new WE(e,Number.POSITIVE_INFINITY);this.Sr.forEachInRange([t,n],e=>{r=r.add(e.yr)})}),ww.resolve(this.Cr(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;ow.isDocumentKey(i)||(i=i.child(""));var s=new WE(new ow(i),0);let a=new mb(Xy);return this.Sr.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.yr)),!0)},s),ww.resolve(this.Cr(a))}Cr(e){const n=[];return e.forEach(e=>{var t=this.br(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){Vy(0===this.vr(r.batchId,"removed")),this.mutationQueue.shift();let i=this.Sr;return ww.forEach(r.mutations,e=>{var t=new WE(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.Sr=i})}xn(e){}containsKey(e,t){var n=new WE(t,0),n=this.Sr.firstAfterOrEqual(n);return ww.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,ww.resolve()}vr(e,t){return this.Dr(e)}Dr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}br(e){var t=this.Dr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class QE{constructor(e){this.Fr=e,this.docs=new pb(ow.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Fr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return ww.resolve(n?n.document.mutableCopy():Yb.newInvalidDocument(t))}getEntries(e,t){let n=$I;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Yb.newInvalidDocument(e))}),ww.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=$I;const s=t.path,a=new ow(s.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||mw(fw(a),n)<=0||(r.has(a.key)||qI(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return ww.resolve(i)}getAllFromCollectionGroup(e,t,n,r){Uy()}Mr(e,t){return ww.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new YE(this)}getSize(e){return ww.resolve(this.size)}}class YE extends xE{constructor(e){super(),this.ur=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.ur.addEntry(n,t)):this.ur.removeEntry(e)}),ww.waitFor(r)}getFromCache(e,t){return this.ur.getEntry(e,t)}getAllFromCache(e,t){return this.ur.getEntries(e,t)}}class JE{constructor(e){this.persistence=e,this.Or=new zI(e=>wI(e),bI),this.lastRemoteSnapshotVersion=nw.min(),this.highestTargetId=0,this.Nr=0,this.Br=new GE,this.targetCount=0,this.Lr=IE.Bn()}forEachTarget(e,n){return this.Or.forEach((e,t)=>n(t)),ww.resolve()}getLastRemoteSnapshotVersion(e){return ww.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return ww.resolve(this.Nr)}allocateTargetId(e){return this.highestTargetId=this.Lr.next(),ww.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Nr&&(this.Nr=t),ww.resolve()}Qn(e){this.Or.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Lr=new IE(t),this.highestTargetId=t),e.sequenceNumber>this.Nr&&(this.Nr=e.sequenceNumber)}addTargetData(e,t){return this.Qn(t),this.targetCount+=1,ww.resolve()}updateTargetData(e,t){return this.Qn(t),ww.resolve()}removeTargetData(e,t){return this.Or.delete(t.target),this.Br.mr(t.targetId),--this.targetCount,ww.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Or.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Or.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),ww.waitFor(a).next(()=>s)}getTargetCount(e){return ww.resolve(this.targetCount)}getTargetData(e,t){var n=this.Or.get(t)||null;return ww.resolve(n)}addMatchingKeys(e,t,n){return this.Br.Ar(t,n),ww.resolve()}removeMatchingKeys(t,e,n){this.Br.Vr(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),ww.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Br.mr(t),ww.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Br.pr(t);return ww.resolve(n)}containsKey(e,t){return ww.resolve(this.Br.containsKey(t))}}class XE{constructor(e,t){this.kr={},this.overlays={},this.qr=new Dw(0),this.Qr=!1,this.Qr=!0,this.referenceDelegate=e(this),this.Kr=new JE(this),this.indexManager=new iE,this.remoteDocumentCache=(e=e=>this.referenceDelegate.$r(e),new QE(e)),this.serializer=new E0(t),this.Ur=new $E(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Qr=!1,Promise.resolve()}get started(){return this.Qr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new KE,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.kr[e.toKey()];return n||(n=new HE(t,this.referenceDelegate),this.kr[e.toKey()]=n),n}getTargetCache(){return this.Kr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ur}runTransaction(e,t,n){Oy("MemoryPersistence","Starting transaction:",e);const r=new ZE(this.qr.next());return this.referenceDelegate.Wr(),n(r).next(e=>this.referenceDelegate.Gr(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}zr(t,n){return ww.or(Object.values(this.kr).map(e=>()=>e.containsKey(t,n)))}}class ZE extends _w{constructor(e){super(),this.currentSequenceNumber=e}}class eC{constructor(e){this.persistence=e,this.jr=new GE,this.Hr=null}static Jr(e){return new eC(e)}get Yr(){if(this.Hr)return this.Hr;throw Uy()}addReference(e,t,n){return this.jr.addReference(n,t),this.Yr.delete(n.toString()),ww.resolve()}removeReference(e,t,n){return this.jr.removeReference(n,t),this.Yr.add(n.toString()),ww.resolve()}markPotentiallyOrphaned(e,t){return this.Yr.add(t.toString()),ww.resolve()}removeTarget(e,t){this.jr.mr(t.targetId).forEach(e=>this.Yr.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Yr.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Wr(){this.Hr=new Set}Gr(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return ww.forEach(this.Yr,e=>{const t=ow.fromPath(e);return this.Zr(n,t).next(e=>{e||r.removeEntry(t,nw.min())})}).next(()=>(this.Hr=null,r.apply(n)))}updateLimboDocument(e,t){return this.Zr(e,t).next(e=>{e?this.Yr.delete(t.toString()):this.Yr.add(t.toString())})}$r(e){return 0}Zr(e,t){return ww.or([()=>ww.resolve(this.jr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.zr(e,t)])}}class tC{constructor(e){this.serializer=e}B(t,e,n,r){const i=new bw("createOrUpgrade",e);var s;n<1&&1<=r&&(t.createObjectStore("owner"),(s=t).createObjectStore("mutationQueues",{keyPath:"userId"}),s.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Vw,{unique:!0}),s.createObjectStore("documentMutations"),nC(t),t.createObjectStore("remoteDocuments"));let a=ww.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),nC(t)),a=a.next(()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:nw.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i))),n<4&&4<=r&&(0!==n&&(a=a.next(()=>function(r,i){return i.store("mutations").G().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Vw,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return ww.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.ei(i))),n<6&&6<=r&&(a=a.next(()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(t),this.ti(i)))),n<7&&7<=r&&(a=a.next(()=>this.ni(i))),n<8&&8<=r&&(a=a.next(()=>this.ri(t,i))),n<9&&9<=r&&(a=a.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&10<=r&&(a=a.next(()=>this.ii(i))),n<11&&11<=r&&(a=a.next(()=>{t.createObjectStore("bundles",{keyPath:"bundleId"}),t.createObjectStore("namedQueries",{keyPath:"name"})})),n<12&&12<=r&&(a=a.next(()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:eb});t.createIndex("collectionPathOverlayIndex",tb,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",nb,{unique:!1})}(t)})),n<13&&13<=r&&(a=a.next(()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:zw});t.createIndex("documentKeyIndex",$w),t.createIndex("collectionGroupIndex",Kw)}(t)).next(()=>this.si(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.oi(t,i))),n<15&&15<=r&&(a=a.next(()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Yw}).createIndex("sequenceNumberIndex",Jw,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Xw}).createIndex("documentKeyIndex",Zw,{unique:!1})}(t))),a}ti(t){let n=0;return t.store("remoteDocuments").Z((e,t)=>{n+=mE(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}ei(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.G().next(e=>ww.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.G("userMutationsIndex",e).next(e=>ww.forEach(e,e=>{Vy(e.userId===n.userId);var t=N0(this.serializer,e);return gE(r,n.userId,t).next(()=>{})}))}))}ni(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.Z((e,t)=>{const n=new iw(e),r=[0,Lw(n)];s.push(a.get(r).next(e=>e?ww.resolve():(e=>a.put({targetId:0,path:Lw(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>ww.waitFor(s))})}ri(e,t){e.createObjectStore("collectionParents",{keyPath:Qw});const n=t.store("collectionParents"),r=new sE,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Lw(r)})}};return t.store("remoteDocuments").Z({Y:!0},(e,t)=>{const n=new iw(e);return i(n.popLast())}).next(()=>t.store("documentMutations").Z({Y:!0},([,e],t)=>{const n=Uw(e);return i(n.popLast())}))}ii(e){const r=e.store("targets");return r.Z((e,t)=>{var n=R0(t),n=P0(this.serializer,n);return r.put(n)})}si(e,a){const t=a.store("remoteDocuments"),o=[];return t.Z((e,t)=>{const n=a.store("remoteDocumentsV14"),r=((s=t).document?new ow(iw.fromString(s.document.name).popFirst(5)):s.noDocument?ow.fromSegments(s.noDocument.path):s.unknownDocument?ow.fromSegments(s.unknownDocument.path):Uy()).path.toArray(),i={prefixPath:r.slice(0,r.length-2),collectionGroup:r[r.length-2],documentId:r[r.length-1],readTime:t.readTime||[0,0],unknownDocument:t.unknownDocument,noDocument:t.noDocument,document:t.document,hasCommittedMutations:!!t.hasCommittedMutations};var s;o.push(n.put(i))}).next(()=>ww.waitFor(o))}oi(e,s){const t=s.store("mutations"),a=ME(this.serializer),o=new XE(eC.Jr,this.serializer.ht);return t.G().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:JI();N0(this.serializer,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),ww.forEach(r,(e,t)=>{var n=new Ry(t),r=V0.Pt(this.serializer,n),i=o.getIndexManager(n),n=vE.Pt(n,this.serializer,i,o.referenceDelegate);return new zE(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new cb(s,Dw.ae),e).next()})})}}function nC(e){e.createObjectStore("targetDocuments",{keyPath:Ww}).createIndex("documentTargetsIndex",Hw,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Gw,{unique:!0}),e.createObjectStore("targetGlobal")}const rC="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class iC{constructor(e,t,n,r,i,s,a,o,c,l,u=15){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this._i=i,this.window=s,this.document=a,this.ai=c,this.ui=l,this.ci=u,this.qr=null,this.Qr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.li=null,this.inForeground=!1,this.hi=null,this.Pi=null,this.Ii=Number.NEGATIVE_INFINITY,this.di=e=>Promise.resolve(),!iC.C())throw new By(qy.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new PE(this,r),this.Ti=t+"main",this.serializer=new E0(o),this.Ei=new Iw(this.Ti,this.ci,new tC(this.serializer)),this.Kr=new TE(this.referenceDelegate,this.serializer),this.remoteDocumentCache=ME(this.serializer),this.Ur=new L0,this.window&&this.window.localStorage?this.Ai=this.window.localStorage:(this.Ai=null,!1===l&&My("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.Ri().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new By(qy.FAILED_PRECONDITION,rC);return this.Vi(),this.mi(),this.fi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Kr.getHighestSequenceNumber(e))}).then(e=>{this.qr=new Dw(e,this.ai)}).then(()=>{this.Qr=!0}).catch(e=>(this.Ei&&this.Ei.close(),Promise.reject(e)))}gi(t){return this.di=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ei.k(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this._i.enqueueAndForget(async()=>{this.started&&await this.Ri()}))}Ri(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>aC(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.pi(t).next(e=>{e||(this.isPrimary=!1,this._i.enqueueRetryable(()=>this.di(!1)))})}).next(()=>this.yi(t)).next(e=>this.isPrimary&&!e?this.wi(t).next(()=>!1):!!e&&this.Si(t).next(()=>!0))).catch(e=>{if(Cw(e))return Oy("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return Oy("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this._i.enqueueRetryable(()=>this.di(e)),this.isPrimary=e})}pi(e){return sC(e).get("owner").next(e=>ww.resolve(this.bi(e)))}Di(e){return aC(e).delete(this.clientId)}async Ci(){if(this.isPrimary&&!this.vi(this.Ii,18e5)){this.Ii=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=lb(e,"clientMetadata");return r.G().next(e=>{const t=this.Fi(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return ww.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.Ai)for(const t of e)this.Ai.removeItem(this.Mi(t.clientId))}}fi(){this.Pi=this._i.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Ri().then(()=>this.Ci()).then(()=>this.fi()))}bi(e){return!!e&&e.ownerId===this.clientId}yi(t){return this.ui?ww.resolve(!0):sC(t).get("owner").next(e=>{if(null!==e&&this.vi(e.leaseTimestampMs,5e3)&&!this.xi(e.ownerId)){if(this.bi(e)&&this.networkEnabled)return!0;if(!this.bi(e)){if(!e.allowTabSynchronization)throw new By(qy.FAILED_PRECONDITION,rC);return!1}}return!(!this.networkEnabled||!this.inForeground)||aC(t).G().next(e=>void 0===this.Fi(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&Oy("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Qr=!1,this.Oi(),this.Pi&&(this.Pi.cancel(),this.Pi=null),this.Ni(),this.Bi(),await this.Ei.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new cb(e,Dw.ae);return this.wi(t).next(()=>this.Di(t))}),this.Ei.close(),this.Li()}Fi(e,t){return e.filter(e=>this.vi(e.updateTimeMs,t)&&!this.xi(e.clientId))}ki(){return this.runTransaction("getActiveClients","readonly",e=>aC(e).G().next(e=>this.Fi(e,18e5).map(e=>e.clientId)))}get started(){return this.Qr}getMutationQueue(e,t){return vE.Pt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Kr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new oE(e,this.serializer.ht.databaseId)}getDocumentOverlayCache(e){return V0.Pt(this.serializer,e)}getBundleCache(){return this.Ur}runTransaction(t,n,r){Oy("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",s=15===(e=this.ci)?ob:14===e?ab:13===e?sb:12===e?ib:11===e?rb:void Uy();let a;return this.Ei.runTransaction(t,i,s,e=>(a=new cb(e,this.qr?this.qr.next():Dw.ae),"readwrite-primary"===n?this.pi(a).next(e=>!!e||this.yi(a)).next(e=>{if(!e)throw My(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this._i.enqueueRetryable(()=>this.di(!1)),new By(qy.FAILED_PRECONDITION,vw);return r(a)}).next(e=>this.Si(a).next(()=>e)):this.qi(a).next(()=>r(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}qi(e){return sC(e).get("owner").next(e=>{if(null!==e&&this.vi(e.leaseTimestampMs,5e3)&&!this.xi(e.ownerId)&&!this.bi(e)&&!(this.ui||this.allowTabSynchronization&&e.allowTabSynchronization))throw new By(qy.FAILED_PRECONDITION,rC)})}Si(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return sC(e).put("owner",t)}static C(){return Iw.C()}wi(e){const t=sC(e);return t.get("owner").next(e=>this.bi(e)?(Oy("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):ww.resolve())}vi(e,t){var n=Date.now();return!(e<n-t||n<e&&(My(`Detected an update time that is in the future: ${e} > ${n}`),1))}Vi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.hi=()=>{this._i.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Ri()))},this.document.addEventListener("visibilitychange",this.hi),this.inForeground="visible"===this.document.visibilityState)}Ni(){this.hi&&(this.document.removeEventListener("visibilitychange",this.hi),this.hi=null)}mi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.li=()=>{this.Oi();var e=/(?:Version|Mobile)\/1[456]/;T()||!navigator.userAgent.includes("Safari")||navigator.userAgent.includes("Chrome")||!navigator.appVersion.match(e)&&!navigator.userAgent.match(e)||this._i.enterRestrictedMode(!0),this._i.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.li))}Bi(){this.li&&(this.window.removeEventListener("pagehide",this.li),this.li=null)}xi(e){var t;try{var n=null!==(null===(t=this.Ai)||void 0===t?void 0:t.getItem(this.Mi(e)));return Oy("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return My("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Oi(){if(this.Ai)try{this.Ai.setItem(this.Mi(this.clientId),String(Date.now()))}catch(e){My("Failed to set zombie client id.",e)}}Li(){if(this.Ai)try{this.Ai.removeItem(this.Mi(this.clientId))}catch(e){}}Mi(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function sC(e){return lb(e,"owner")}function aC(e){return lb(e,"clientMetadata")}function oC(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class cC{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Qi=n,this.Ki=r}static $i(e,t){let n=JI(),r=JI();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new cC(e,t.fromCache,n,r)}}class lC{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class uC{constructor(){this.Ui=!1,this.Wi=!1,this.Gi=100,this.zi=2}initialize(e,t){this.ji=e,this.indexManager=t,this.Ui=!0}getDocumentsMatchingQuery(n,r,e,t){const i={result:null};return this.Hi(n,r).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.Ji(n,r,t,e).next(e=>{i.result=e})}).next(()=>{if(!i.result){const t=new lC;return this.Yi(n,r,t).next(e=>{if(i.result=e,this.Wi)return this.Zi(n,r,t,e.size)})}}).next(()=>i.result)}Zi(e,t,n,r){return n.documentReadCount<this.Gi?(xy()<=m.DEBUG&&Oy("QueryEngine","SDK will not create cache indexes for query:",VI(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Gi,"documents"),ww.resolve()):(xy()<=m.DEBUG&&Oy("QueryEngine","Query:",VI(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.zi*r?(xy()<=m.DEBUG&&Oy("QueryEngine","The SDK decides to create cache indexes for query:",VI(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,OI(t))):ww.resolve())}Hi(i,s){if(NI(s))return ww.resolve(null);let t=OI(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=LI(s,null,"F"),t=OI(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=JI(...e);return this.ji.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.Xi(s,n);return this.es(s,t,r,e.readTime)?this.Hi(i,LI(s,null,"F")):this.ts(i,t,s,e)}))})))}Ji(n,r,i,s){return NI(r)||s.isEqual(nw.min())?ww.resolve(null):this.ji.getDocuments(n,i).next(e=>{var t=this.Xi(r,e);return this.es(r,t,i,s)?ww.resolve(null):(xy()<=m.DEBUG&&Oy("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),VI(r)),this.ts(n,t,r,pw(s,-1)).next(e=>e))})}Xi(n,e){let r=new mb(jI(n));return e.forEach((e,t)=>{qI(n,t)&&(r=r.add(t))}),r}es(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}Yi(e,t,n){return xy()<=m.DEBUG&&Oy("QueryEngine","Using full collection scan to execute query:",VI(t)),this.ji.getDocumentsMatchingQuery(e,t,gw.min(),n)}ts(e,n,t,r){return this.ji.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class hC{constructor(e,t,n,r){this.persistence=e,this.ns=t,this.serializer=r,this.rs=new pb(Xy),this.ss=new zI(e=>wI(e),bI),this.os=new Map,this._s=e.getRemoteDocumentCache(),this.Kr=e.getTargetCache(),this.Ur=e.getBundleCache(),this.us(n)}us(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new zE(this._s,this.mutationQueue,this.documentOverlayCache,this.indexManager),this._s.setIndexManager(this.indexManager),this.ns.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.rs))}}function dC(e,t,n,r){return new hC(e,t,n,r)}async function pC(e,t){const a=e;return a.persistence.runTransaction("Handle user change","readonly",i=>{let s;return a.mutationQueue.getAllMutationBatches(i).next(e=>(s=e,a.us(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=JI();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return a.localDocuments.getDocuments(i,r).next(e=>({cs:e,removedBatchIds:t,addedBatchIds:n}))})})}function fC(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Kr.getLastRemoteSnapshotVersion(e))}function gC(e,l){const u=e,h=l.snapshotVersion;let d=u.rs;return u.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=u._s.newChangeBuffer({trackRemovals:!0});d=u.rs;const c=[];l.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){c.push(u.Kr.removeMatchingKeys(o,t.removedDocuments,n).next(()=>u.Kr.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;null!==l.targetMismatches.get(n)?e=e.withResumeToken(bb.EMPTY_BYTE_STRING,nw.min()).withLastLimboFreeSnapshotVersion(nw.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,h)),d=d.insert(n,e),i=r,s=e,a=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<a.addedDocuments.size+a.modifiedDocuments.size+a.removedDocuments.size)||c.push(u.Kr.updateTargetData(o,e))}});let t=$I,n=JI();if(l.documentUpdates.forEach(e=>{l.resolvedLimboDocuments.has(e)&&c.push(u.persistence.referenceDelegate.updateLimboDocument(o,e))}),c.push(mC(o,e,l.documentUpdates).next(e=>{t=e.ls,n=e.hs})),!h.isEqual(nw.min())){const l=u.Kr.getLastRemoteSnapshotVersion(o).next(e=>u.Kr.setTargetsMetadata(o,o.currentSequenceNumber,h));c.push(l)}return ww.waitFor(c).next(()=>e.apply(o)).next(()=>u.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(u.rs=d,e))}function mC(e,s,t){let n=JI(),a=JI();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=$I;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(nw.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):Oy("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{ls:i,hs:a}})}function vC(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Kr.getTargetData(t,r).next(e=>e?(n=e,ww.resolve(n)):i.Kr.allocateTargetId(t).next(e=>(n=new T0(r,e,"TargetPurposeListen",t.currentSequenceNumber),i.Kr.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.rs.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.rs=i.rs.insert(e.targetId,e),i.ss.set(r,e.targetId)),e})}async function _C(e,t,n){const r=e,i=r.rs.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!Cw(e))throw e;Oy("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.rs=r.rs.remove(t),r.ss.delete(i.target)}function yC(e,n,r){const i=e;let s=nw.min(),a=JI();return i.persistence.runTransaction("Execute query","readwrite",t=>function(e,t,n){const r=e,i=r.ss.get(n);return void 0!==i?ww.resolve(r.rs.get(i)):r.Kr.getTargetData(t,n)}(i,t,OI(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Kr.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.ns.getDocumentsMatchingQuery(t,n,r?s:nw.min(),r?a:JI())).next(e=>(IC(i,BI(n),e),{documents:e,Ps:a})))}function wC(e,t){const n=e,r=n.Kr,i=n.rs.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.lt(e,t).next(e=>e?e.target:null))}function bC(e,t){const n=e,r=n.os.get(t)||nw.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n._s.getAllFromCollectionGroup(e,t,pw(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(IC(n,t,e),e))}function IC(e,t,n){let r=e.os.get(t)||nw.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.os.set(t,r)}function TC(e,t){return`firestore_clients_${e}_${t}`}function EC(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function CC(e,t){return`firestore_targets_${e}_${t}`}class kC{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Es(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new By(r.error.code,r.error.message))),s?new kC(e,t,r.state,i):(My("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}As(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class SC{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Es(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new By(n.error.code,n.error.message))),i?new SC(e,n.state,r):(My("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}As(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class AC{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Es(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=XI;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=Mw(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new AC(e,i):(My("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class NC{constructor(e,t){this.clientId=e,this.onlineState=t}static Es(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new NC(t.clientId,t.onlineState):(My("SharedClientState",`Failed to parse online state: ${e}`),null)}}class RC{constructor(){this.activeTargetIds=XI}Rs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Vs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}As(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class PC{constructor(e,t,n,r,i){this.window=e,this._i=t,this.persistenceKey=n,this.fs=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.gs=this.ps.bind(this),this.ys=new pb(Xy),this.started=!1,this.ws=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Ss=TC(this.persistenceKey,this.fs),this.bs=`firestore_sequence_number_${this.persistenceKey}`,this.ys=this.ys.insert(this.fs,new RC),this.Ds=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Cs=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.vs=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.Fs=`firestore_online_state_${this.persistenceKey}`,this.Ms=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.gs)}static C(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.ki();for(const n of e)if(n!==this.fs){const e=this.getItem(TC(this.persistenceKey,n));var t;!e||(t=AC.Es(n,e))&&(this.ys=this.ys.insert(t.clientId,t))}this.xs();const n=this.storage.getItem(this.Fs);if(n){const e=this.Os(n);e&&this.Ns(e)}for(const e of this.ws)this.ps(e);this.ws=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.bs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Bs(this.ys)}isActiveQueryTarget(n){let r=!1;return this.ys.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.Ls(e,"pending")}updateMutationState(e,t,n){this.Ls(e,t,n),this.ks(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(CC(this.persistenceKey,e)))||(n=SC.Es(e,n))&&(t=n.state)),this.qs.Rs(e),this.xs(),t}removeLocalQueryTarget(e){this.qs.Vs(e),this.xs()}isLocalQueryTarget(e){return this.qs.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(CC(this.persistenceKey,e))}updateQueryState(e,t,n){this.Qs(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.ks(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Ks(e)}notifyBundleLoaded(e){this.$s(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.gs),this.removeItem(this.Ss),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return Oy("SharedClientState","READ",e,t),t}setItem(e,t){Oy("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){Oy("SharedClientState","REMOVE",e),this.storage.removeItem(e)}ps(e){const i=e;i.storageArea===this.storage&&(Oy("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.Ss?this._i.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.Ds.test(i.key)){if(null==i.newValue){var e=this.Us(i.key);return this.Ws(e,null)}e=this.Gs(i.key,i.newValue);if(e)return this.Ws(e.clientId,e)}else if(this.Cs.test(i.key)){if(null!==i.newValue){var t=this.zs(i.key,i.newValue);if(t)return this.js(t)}}else if(this.vs.test(i.key)){if(null!==i.newValue){t=this.Hs(i.key,i.newValue);if(t)return this.Js(t)}}else if(i.key===this.Fs){if(null!==i.newValue){var n=this.Os(i.newValue);if(n)return this.Ns(n)}}else if(i.key===this.bs){n=function(e){let t=Dw.ae;if(null!=e)try{var n=JSON.parse(e);Vy("number"==typeof n),t=n}catch(e){My("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==Dw.ae&&this.sequenceNumberHandler(n)}else if(i.key===this.Ms){const r=this.Ys(i.newValue);await Promise.all(r.map(e=>this.syncEngine.Zs(e)))}}else this.ws.push(i)}):My("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get qs(){return this.ys.get(this.fs)}xs(){this.setItem(this.Ss,this.qs.As())}Ls(e,t,n){const r=new kC(this.currentUser,e,t,n),i=EC(this.persistenceKey,this.currentUser,e);this.setItem(i,r.As())}ks(e){var t=EC(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Ks(e){var t={clientId:this.fs,onlineState:e};this.storage.setItem(this.Fs,JSON.stringify(t))}Qs(e,t,n){const r=CC(this.persistenceKey,e),i=new SC(e,t,n);this.setItem(r,i.As())}$s(e){var t=JSON.stringify(Array.from(e));this.setItem(this.Ms,t)}Us(e){var t=this.Ds.exec(e);return t?t[1]:null}Gs(e,t){var n=this.Us(e);return AC.Es(n,t)}zs(e,t){var n=this.Cs.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return kC.Es(new Ry(n),r,t)}Hs(e,t){var n=this.vs.exec(e),n=Number(n[1]);return SC.Es(n,t)}Os(e){return NC.Es(e)}Ys(e){return JSON.parse(e)}async js(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Xs(e.batchId,e.state,e.error);Oy("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Js(e){return this.syncEngine.eo(e.targetId,e.state,e.error)}Ws(e,t){const n=t?this.ys.insert(e,t):this.ys.remove(e),r=this.Bs(this.ys),i=this.Bs(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.no(s,a).then(()=>{this.ys=n})}Ns(e){this.ys.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Bs(e){let n=XI;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class DC{constructor(){this.ro=new RC,this.io={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.ro.Rs(e),this.io[e]||"not-current"}updateQueryState(e,t,n){this.io[e]=t}removeLocalQueryTarget(e){this.ro.Vs(e)}isLocalQueryTarget(e){return this.ro.activeTargetIds.has(e)}clearQueryState(e){delete this.io[e]}getAllActiveQueryTargets(){return this.ro.activeTargetIds}isActiveQueryTarget(e){return this.ro.activeTargetIds.has(e)}start(){return this.ro=new RC,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class xC{so(e){}shutdown(){}}class OC{constructor(){this.oo=()=>this._o(),this.ao=()=>this.uo(),this.co=[],this.lo()}so(e){this.co.push(e)}shutdown(){window.removeEventListener("online",this.oo),window.removeEventListener("offline",this.ao)}lo(){window.addEventListener("online",this.oo),window.addEventListener("offline",this.ao)}_o(){Oy("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.co)e(0)}uo(){Oy("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.co)e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let MC=null;function LC(){return null===MC?MC=268435456+Math.round(2147483648*Math.random()):MC++,"0x"+MC.toString(16)}const FC={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class UC{constructor(e){this.ho=e.ho,this.Po=e.Po}Io(e){this.To=e}Eo(e){this.Ao=e}onMessage(e){this.Ro=e}close(){this.Po()}send(e){this.ho(e)}Vo(){this.To()}mo(e){this.Ao(e)}fo(e){this.Ro(e)}}const VC="WebChannelConnection";class qC extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.po=t+"://"+e.host,this.yo=`projects/${n}/databases/${r}`,this.wo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}get So(){return!1}bo(t,e,n,r,i){const s=LC(),a=this.Do(t,e);Oy("RestConnection",`Sending RPC '${t}' ${s}:`,a,n);var o={"google-cloud-resource-prefix":this.yo,"x-goog-request-params":this.wo};return this.Co(o,r,i),this.vo(t,a,o,n).then(e=>(Oy("RestConnection",`Received RPC '${t}' ${s}: `,e),e),e=>{throw Ly("RestConnection",`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",n),e})}Fo(e,t,n,r,i,s){return this.bo(e,t,n,r,i)}Co(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+Py,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}Do(e,t){var n=FC[e];return`${this.po}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}vo(c,t,n,r){const l=LC();return new Promise((s,a)=>{const o=new ky;o.setWithCredentials(!0),o.listenOnce(by.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case wy.NO_ERROR:var e=o.getResponseJson();Oy(VC,`XHR for RPC '${c}' ${l} received:`,JSON.stringify(e)),s(e);break;case wy.TIMEOUT:Oy(VC,`RPC '${c}' ${l} timed out`),a(new By(qy.DEADLINE_EXCEEDED,"Request time out"));break;case wy.HTTP_ERROR:var t=o.getStatus();if(Oy(VC,`RPC '${c}' ${l} failed with status:`,t,"response text:",o.getResponseText()),0<t){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);var n=null==e?void 0:e.error;if(n&&n.status&&n.message){const c=(r=n.status,i=r.toLowerCase().replace(/_/g,"-"),0<=Object.values(qy).indexOf(i)?i:qy.UNKNOWN);a(new By(c,n.message))}else a(new By(qy.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new By(qy.UNAVAILABLE,"Connection failed."));break;default:Uy()}}finally{Oy(VC,`RPC '${c}' ${l} completed.`)}var r,i});var e=JSON.stringify(r);Oy(VC,`RPC '${c}' ${l} sending request:`,r),o.send(t,"POST",e,n,15)})}Mo(i,e,t){const s=LC(),n=[this.po,"/","google.firestore.v1.Firestore","/",i,"/channel"],r=new H_,a=yy(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},c=this.longPollingOptions.timeoutSeconds;void 0!==c&&(o.longPollingTimeout=Math.round(1e3*c)),this.useFetchStreams&&(o.useFetchStreams=!0),this.Co(o.initMessageHeaders,e,t),o.encodeInitMessageHeaders=!0;var l=n.join("");Oy(VC,`Creating RPC '${i}' stream ${s}: ${l}`,o);const u=r.createWebChannel(l,o);let h=!1,d=!1;const p=new UC({ho:e=>{d?Oy(VC,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(h||(Oy(VC,`Opening RPC '${i}' stream ${s} transport.`),u.open(),h=!0),Oy(VC,`RPC '${i}' stream ${s} sending:`,e),u.send(e))},Po:()=>u.close()}),f=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return f(u,Cy.EventType.OPEN,()=>{d||Oy(VC,`RPC '${i}' stream ${s} transport opened.`)}),f(u,Cy.EventType.CLOSE,()=>{d||(d=!0,Oy(VC,`RPC '${i}' stream ${s} transport closed`),p.mo())}),f(u,Cy.EventType.ERROR,e=>{d||(d=!0,Ly(VC,`RPC '${i}' stream ${s} transport errored:`,e),p.mo(new By(qy.UNAVAILABLE,"The operation could not be completed")))}),f(u,Cy.EventType.MESSAGE,n=>{if(!d){var e=n.data[0];Vy(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){Oy(VC,`RPC '${i}' stream ${s} received error:`,r);const n=r.status;let e=function(e){var t=_y[e];if(void 0!==t)return xT(t)}(n),t=r.message;void 0===e&&(e=qy.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),d=!0,p.mo(new By(e,t)),u.close()}else Oy(VC,`RPC '${i}' stream ${s} received:`,e),p.fo(e)}}),f(a,Iy.STAT_EVENT,e=>{e.stat===Ty?Oy(VC,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===Ey&&Oy(VC,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{p.Vo()},0),p}}function BC(){return"undefined"!=typeof window?window:null}function jC(){return"undefined"!=typeof document?document:null}function zC(e){return new XT(e,!0)}class $C{constructor(e,t,n=1e3,r=1.5,i=6e4){this._i=e,this.timerId=t,this.xo=n,this.Oo=r,this.No=i,this.Bo=0,this.Lo=null,this.ko=Date.now(),this.reset()}reset(){this.Bo=0}qo(){this.Bo=this.No}Qo(e){this.cancel();var t=Math.floor(this.Bo+this.Ko()),n=Math.max(0,Date.now()-this.ko),r=Math.max(0,t-n);0<r&&Oy("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Bo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Lo=this._i.enqueueAfterDelay(this.timerId,r,()=>(this.ko=Date.now(),e())),this.Bo*=this.Oo,this.Bo<this.xo&&(this.Bo=this.xo),this.Bo>this.No&&(this.Bo=this.No)}$o(){null!==this.Lo&&(this.Lo.skipDelay(),this.Lo=null)}cancel(){null!==this.Lo&&(this.Lo.cancel(),this.Lo=null)}Ko(){return(Math.random()-.5)*this.Bo}}class KC{constructor(e,t,n,r,i,s,a,o){this._i=e,this.Uo=n,this.Wo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Go=0,this.zo=null,this.jo=null,this.stream=null,this.Ho=new $C(e,t)}Jo(){return 1===this.state||5===this.state||this.Yo()}Yo(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.Zo()}async stop(){this.Jo()&&await this.close(0)}Xo(){this.state=0,this.Ho.reset()}e_(){this.Yo()&&null===this.zo&&(this.zo=this._i.enqueueAfterDelay(this.Uo,6e4,()=>this.t_()))}n_(e){this.r_(),this.stream.send(e)}async t_(){if(this.Yo())return this.close(0)}r_(){this.zo&&(this.zo.cancel(),this.zo=null)}i_(){this.jo&&(this.jo.cancel(),this.jo=null)}async close(e,t){this.r_(),this.i_(),this.Ho.cancel(),this.Go++,4!==e?this.Ho.reset():t&&t.code===qy.RESOURCE_EXHAUSTED?(My(t.toString()),My("Using maximum backoff delay to prevent overloading the backend."),this.Ho.qo()):t&&t.code===qy.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.s_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Eo(t)}s_(){}auth(){this.state=1;const e=this.o_(this.Go),n=this.Go;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Go===n&&this.__(e,t)},t=>{e(()=>{var e=new By(qy.UNKNOWN,"Fetching auth token failed: "+t.message);return this.a_(e)})})}__(e,t){const n=this.o_(this.Go);this.stream=this.u_(e,t),this.stream.Io(()=>{n(()=>(this.state=2,this.jo=this._i.enqueueAfterDelay(this.Wo,1e4,()=>(this.Yo()&&(this.state=3),Promise.resolve())),this.listener.Io()))}),this.stream.Eo(e=>{n(()=>this.a_(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}Zo(){this.state=5,this.Ho.Qo(async()=>{this.state=0,this.start()})}a_(e){return Oy("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}o_(t){return e=>{this._i.enqueueAndForget(()=>this.Go===t?e():(Oy("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class GC extends KC{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}u_(e,t){return this.connection.Mo("Listen",e,t)}onMessage(e){this.Ho.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(p=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===p?1:"REMOVE"===p?2:"CURRENT"===p?3:"RESET"===p?4:Uy(),i=t.targetChange.targetIds||[],s=(p=t.targetChange.resumeToken,e.useProto3Json?(Vy(void 0===p||"string"==typeof p),bb.fromBase64String(p||"")):(Vy(void 0===p||p instanceof Uint8Array),bb.fromUint8Array(p||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(p=a).code?qy.UNKNOWN:xT(p.code),new By(o,p.message||""));n=new $T(r,i,s,o||null)}else if("documentChange"in t){t.documentChange;var c=t.documentChange;c.document,c.document.name,c.document.updateTime;var s=a0(e,c.document.name),o=n0(c.document.updateTime),l=c.document.createTime?n0(c.document.createTime):nw.min(),u=new Qb({mapValue:{fields:c.document.fields}}),l=Yb.newFoundDocument(s,o,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new jT(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=a0(e,u.document),l=u.readTime?n0(u.readTime):nw.min(),l=Yb.newNoDocument(c,l),u=u.removedTargetIds||[];n=new jT([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=a0(e,h.document),h=h.removedTargetIds||[];n=new jT([],h,d,null)}else{if(!("filter"in t))return Uy();{t.filter;const e=t.filter;e.targetId;var{count:h=0,unchangedNames:d}=e,h=new PT(h,d),d=e.targetId;n=new zT(d,h)}}var o,p;return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return nw.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?n0(t.readTime):nw.min()}(e);return this.listener.c_(t,n)}l_(e){const t={};t.database=l0(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=II(r)?{documents:g0(e,r)}:{query:m0(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()){n.resumeToken=t0(e,t.resumeToken);const r=ZT(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(0<t.snapshotVersion.compareTo(nw.min())){n.readTime=e0(e,t.snapshotVersion.toTimestamp());const r=ZT(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);var n,n=(this.serializer,e,null==(n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return Uy()}}(e.purpose))?null:{"goog-listen-tags":n});n&&(t.labels=n),this.n_(t)}h_(e){const t={};t.database=l0(this.serializer),t.removeTarget=e,this.n_(t)}}class WC extends KC{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i,this.P_=!1}get I_(){return this.P_}start(){this.P_=!1,this.lastStreamToken=void 0,super.start()}s_(){this.P_&&this.d_([])}u_(e,t){return this.connection.Mo("Write",e,t)}onMessage(e){if(Vy(!!e.streamToken),this.lastStreamToken=e.streamToken,this.P_){this.Ho.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(Vy(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?n0(e.updateTime):n0(t);return n.isEqual(nw.min())&&(n=n0(t)),new pT(n,e.transformResults||[])}(e,i))):[]),n=n0(e.commitTime);return this.listener.T_(n,t)}var r,i;return Vy(!e.writeResults||0===e.writeResults.length),this.P_=!0,this.listener.E_()}A_(){const e={};e.database=l0(this.serializer),this.n_(e)}d_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>p0(this.serializer,e))};this.n_(t)}}class HC extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.R_=!1}V_(){if(this.R_)throw new By(qy.FAILED_PRECONDITION,"The client has already been terminated.")}bo(n,r,i){return this.V_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.bo(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===qy.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new By(qy.UNKNOWN,e.toString())})}Fo(n,r,i,s){return this.V_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.Fo(n,r,i,e,t,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===qy.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new By(qy.UNKNOWN,e.toString())})}terminate(){this.R_=!0}}class QC{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.f_=0,this.g_=null,this.p_=!0}y_(){0===this.f_&&(this.w_("Unknown"),this.g_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.g_=null,this.S_("Backend didn't respond within 10 seconds."),this.w_("Offline"),Promise.resolve())))}b_(e){"Online"===this.state?this.w_("Unknown"):(this.f_++,1<=this.f_&&(this.D_(),this.S_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.w_("Offline")))}set(e){this.D_(),this.f_=0,"Online"===e&&(this.p_=!1),this.w_(e)}w_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}S_(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.p_?(My(t),this.p_=!1):Oy("OnlineStateTracker",t)}D_(){null!==this.g_&&(this.g_.cancel(),this.g_=null)}}class YC{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.C_=[],this.v_=new Map,this.F_=new Set,this.M_=[],this.x_=i,this.x_.so(e=>{n.enqueueAndForget(async()=>{sk(this)&&(Oy("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.F_.add(4),await XC(t),t.O_.set("Unknown"),t.F_.delete(4),await JC(t)}(this))})}),this.O_=new QC(n,r)}}async function JC(e){if(sk(e))for(const t of e.M_)await t(!0)}async function XC(e){for(const t of e.M_)await t(!1)}function ZC(e,t){const n=e;n.v_.has(t.targetId)||(n.v_.set(t.targetId,t),ik(n)?rk(n):gk(n).Yo()&&tk(n,t))}function ek(e,t){const n=e,r=gk(n);n.v_.delete(t),r.Yo()&&nk(n,t),0===n.v_.size&&(r.Yo()?r.e_():sk(n)&&n.O_.set("Unknown"))}function tk(e,t){var n;e.N_.Le(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(nw.min()))&&(n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(n)),gk(e).l_(t)}function nk(e,t){e.N_.Le(t),gk(e).h_(t)}function rk(t){t.N_=new GT({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),lt:e=>t.v_.get(e)||null,st:()=>t.datastore.serializer.databaseId}),gk(t).start(),t.O_.y_()}function ik(e){return sk(e)&&!gk(e).Jo()&&0<e.v_.size}function sk(e){return 0===e.F_.size}function ak(e){e.N_=void 0}async function ok(e,t,n){if(!Cw(t))throw t;e.F_.add(1),await XC(e),e.O_.set("Offline"),n=n||(()=>fC(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{Oy("RemoteStore","Retrying IndexedDB access"),await n(),e.F_.delete(1),await JC(e)})}function ck(t,n){return n().catch(e=>ok(t,e,n))}async function lk(e){const t=e,n=mk(t);let r=0<t.C_.length?t.C_[t.C_.length-1].batchId:-1;for(;sk(i=t)&&i.C_.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.C_.length&&n.e_();break}r=e.batchId,function(e,t){e.C_.push(t);const n=mk(e);n.Yo()&&n.I_&&n.d_(t.mutations)}(t,e)}catch(e){await ok(t,e)}var i;uk(t)&&hk(t)}function uk(e){return sk(e)&&!mk(e).Jo()&&0<e.C_.length}function hk(e){mk(e).start()}async function dk(e,t){t&&mk(e).I_&&await async function(e,t){if(DT(n=t.code)&&n!==qy.ABORTED){const r=e.C_.shift();mk(e).Xo(),await ck(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await lk(e)}var n}(e,t),uk(e)&&hk(e)}async function pk(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),Oy("RemoteStore","RemoteStore received new credentials");var r=sk(n);n.F_.add(3),await XC(n),r&&n.O_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.F_.delete(3),await JC(n)}async function fk(e,t){const n=e;t?(n.F_.delete(2),await JC(n)):(n.F_.add(2),await XC(n),n.O_.set("Unknown"))}function gk(t){return t.B_||(t.B_=function(e,t,n){const r=e;return r.V_(),new GC(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Io:(async function(n){n.v_.forEach((e,t)=>{tk(n,e)})}).bind(null,t),Eo:(async function(e,t){ak(e),ik(e)?(e.O_.b_(t),rk(e)):e.O_.set("Unknown")}).bind(null,t),c_:(async function(e,t,n){if(e.O_.set("Online"),t instanceof $T&&2===t.state&&t.cause)try{await async function(e,t){var n=t.cause;for(const r of t.targetIds)e.v_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.v_.delete(r),e.N_.removeTarget(r))}(e,t)}catch(n){Oy("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await ok(e,n)}else if(t instanceof jT?e.N_.Ge(t):t instanceof zT?e.N_.Xe(t):e.N_.He(t),!n.isEqual(nw.min()))try{const t=await fC(e.localStore);0<=n.compareTo(t)&&await function(i,r){const e=i.N_._t(r);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=i.v_.get(t);n&&i.v_.set(t,n.withResumeToken(e.resumeToken,r))}}),e.targetMismatches.forEach((e,t)=>{const n=i.v_.get(e);var r;n&&(i.v_.set(e,n.withResumeToken(bb.EMPTY_BYTE_STRING,n.snapshotVersion)),nk(i,e),r=new T0(n.target,e,t,n.sequenceNumber),tk(i,r))}),i.remoteSyncer.applyRemoteEvent(e)}(e,n)}catch(t){Oy("RemoteStore","Failed to raise snapshot:",t),await ok(e,t)}}).bind(null,t)}),t.M_.push(async e=>{e?(t.B_.Xo(),ik(t)?rk(t):t.O_.set("Unknown")):(await t.B_.stop(),ak(t))})),t.B_}function mk(t){return t.L_||(t.L_=function(e,t,n){const r=e;return r.V_(),new WC(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Io:(async function(e){mk(e).A_()}).bind(null,t),Eo:dk.bind(null,t),E_:(async function(e){const t=mk(e);for(const n of e.C_)t.d_(n.mutations)}).bind(null,t),T_:(async function(e,t,n){const r=e.C_.shift(),i=NT.from(r,t,n);await ck(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await lk(e)}).bind(null,t)}),t.M_.push(async e=>{e?(t.L_.Xo(),await lk(t)):(await t.L_.stop(),0<t.C_.length&&(Oy("RemoteStore",`Stopping write stream with ${t.C_.length} pending writes`),t.C_=[]))})),t.L_}class vk{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new jy,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,a=new vk(e,t,s,r,i);return a.start(n),a}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new By(qy.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function _k(e,t){if(My("AsyncQueue",`${t}: ${e}`),Cw(e))return new By(qy.UNAVAILABLE,`${t}: ${e}`);throw e}class yk{constructor(n){this.comparator=n?(e,t)=>n(e,t)||ow.comparator(e.key,t.key):(e,t)=>ow.comparator(e.key,t.key),this.keyedMap=GI(),this.sortedSet=new pb(this.comparator)}static emptySet(e){return new yk(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof yk))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n "+t.join(" \n")+"\n)"}copy(e,t){const n=new yk;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class wk{constructor(){this.k_=new pb(ow.comparator)}track(e){var t=e.doc.key,n=this.k_.get(t);!n||0!==e.type&&3===n.type?this.k_=this.k_.insert(t,e):3===e.type&&1!==n.type?this.k_=this.k_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.k_=this.k_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.k_=this.k_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.k_=this.k_.remove(t):1===e.type&&2===n.type?this.k_=this.k_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.k_=this.k_.insert(t,{type:2,doc:e.doc}):Uy()}q_(){const n=[];return this.k_.inorderTraversal((e,t)=>{n.push(t)}),n}}class bk{constructor(e,t,n,r,i,s,a,o,c){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=c}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new bk(e,t,yk.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&FI(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class Ik{constructor(){this.Q_=void 0,this.listeners=[]}}class Tk{constructor(){this.queries=new zI(e=>UI(e),FI),this.onlineState="Unknown",this.K_=new Set}}async function Ek(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new Ik),i)try{s.Q_=await n.onListen(r)}catch(e){const n=_k(e,`Initialization of query '${VI(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.U_(n.onlineState),!s.Q_||t.W_(s.Q_)&&kk(n)}async function Ck(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function kk(e){e.K_.forEach(e=>{e.next()})}class Sk{constructor(e,t,n){this.query=e,this.G_=t,this.z_=!1,this.j_=null,this.onlineState="Unknown",this.options=n||{}}W_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new bk(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.z_?this.H_(e)&&(this.G_.next(e),t=!0):this.J_(e,this.onlineState)&&(this.Y_(e),t=!0),this.j_=e,t}onError(e){this.G_.error(e)}U_(e){this.onlineState=e;let t=!1;return this.j_&&!this.z_&&this.J_(this.j_,e)&&(this.Y_(this.j_),t=!0),t}J_(e,t){return!e.fromCache||(!this.options.Z_||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}H_(e){if(0<e.docChanges.length)return!0;var t=this.j_&&this.j_.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}Y_(e){e=bk.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.z_=!0,this.G_.next(e)}}class Ak{constructor(e,t){this.X_=e,this.byteLength=t}ea(){return"metadata"in this.X_}}class Nk{constructor(e){this.serializer=e}Is(e){return a0(this.serializer,e)}ds(e){return e.metadata.exists?d0(this.serializer,e.document,!1):Yb.newNoDocument(this.Is(e.metadata.name),this.Ts(e.metadata.readTime))}Ts(e){return n0(e)}}class Rk{constructor(e,t,n){this.ta=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=Pk(e)}na(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.X_.namedQuery)this.queries.push(e.X_.namedQuery);else if(e.X_.documentMetadata){this.documents.push({metadata:e.X_.documentMetadata}),e.X_.documentMetadata.exists||++t;const n=iw.fromString(e.X_.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.X_.document&&(this.documents[this.documents.length-1].document=e.X_.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}ra(e){const t=new Map,n=new Nk(this.serializer);for(const i of e)if(i.metadata.queries){const e=n.Is(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||JI()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=JI(),a=$I;for(const e of n){const n=t.Is(e.metadata.name);e.document&&(s=s.add(n));const l=t.ds(e);l.setReadTime(t.Ts(e.metadata.readTime)),a=a.insert(n,l)}const o=i._s.newChangeBuffer({trackRemovals:!0}),c=await vC(i,(r=r,OI(AI(iw.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>mC(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Kr.removeMatchingKeysForTargetId(t,c.targetId).next(()=>i.Kr.addMatchingKeys(t,s,c.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.ls,e.hs)).next(()=>e.ls)))}(this.localStore,new Nk(this.serializer),this.documents,this.ta.id),t=this.ra(this.documents);for(const e of this.queries)await async function(e,n,r=JI()){const i=await vC(e,OI(D0(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=n0(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.Ur.saveNamedQuery(e,n);t=i.withResumeToken(bb.EMPTY_BYTE_STRING,t);return s.rs=s.rs.insert(t.targetId,t),s.Kr.updateTargetData(e,t).next(()=>s.Kr.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Kr.addMatchingKeys(e,r,i.targetId)).next(()=>s.Ur.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,ia:this.collectionGroups,sa:e}}}function Pk(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Dk{constructor(e){this.key=e}}class xk{constructor(e){this.key=e}}class Ok{constructor(e,t){this.query=e,this.oa=t,this._a=null,this.hasCachedResults=!1,this.current=!1,this.aa=JI(),this.mutatedKeys=JI(),this.ua=jI(e),this.ca=new yk(this.ua)}get la(){return this.oa}ha(e,t){const o=t?t.Pa:new wk,c=(t||this).ca;let l=(t||this).mutatedKeys,u=c,h=!1;const d="F"===this.query.limitType&&c.size===this.query.limit?c.last():null,p="L"===this.query.limitType&&c.size===this.query.limit?c.first():null;if(e.inorderTraversal((e,t)=>{const n=c.get(e),r=qI(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let a=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(o.track({type:3,doc:r}),a=!0):this.Ia(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.ua(r,d)||p&&this.ua(r,p)<0)&&(h=!0)):!n&&r?(o.track({type:0,doc:r}),a=!0):n&&!r&&(o.track({type:1,doc:n}),a=!0,(d||p)&&(h=!0)),a&&(l=r?(u=u.add(r),s?l.add(e):l.delete(e)):(u=u.delete(e),l.delete(e)))}),null!==this.query.limit)for(;u.size>this.query.limit;){const e="F"===this.query.limitType?u.last():u.first();u=u.delete(e.key),l=l.delete(e.key),o.track({type:1,doc:e})}return{ca:u,Pa:o,es:h,mutatedKeys:l}}Ia(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.ca;this.ca=e.ca,this.mutatedKeys=e.mutatedKeys;const i=e.Pa.q_();i.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return Uy()}};return n(e)-n(t)}(e.type,t.type)||this.ua(e.doc,t.doc)),this.da(n);var s=t?this.Ta():[],a=0===this.aa.size&&this.current?1:0,o=a!==this._a;return this._a=a,0!==i.length||o?{snapshot:new bk(this.query,e.ca,r,i,e.mutatedKeys,0==a,o,!1,!!n&&0<n.resumeToken.approximateByteSize()),Ea:s}:{Ea:s}}U_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({ca:this.ca,Pa:new wk,mutatedKeys:this.mutatedKeys,es:!1},!1)):{Ea:[]}}Aa(e){return!this.oa.has(e)&&!!this.ca.has(e)&&!this.ca.get(e).hasLocalMutations}da(e){e&&(e.addedDocuments.forEach(e=>this.oa=this.oa.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.oa=this.oa.delete(e)),this.current=e.current)}Ta(){if(!this.current)return[];const t=this.aa;this.aa=JI(),this.ca.forEach(e=>{this.Aa(e.key)&&(this.aa=this.aa.add(e.key))});const n=[];return t.forEach(e=>{this.aa.has(e)||n.push(new xk(e))}),this.aa.forEach(e=>{t.has(e)||n.push(new Dk(e))}),n}Ra(e){this.oa=e.Ps,this.aa=JI();var t=this.ha(e.documents);return this.applyChanges(t,!0)}Va(){return bk.fromInitialDocuments(this.query,this.ca,this.mutatedKeys,0===this._a,this.hasCachedResults)}}class Mk{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Lk{constructor(e){this.key=e,this.ma=!1}}class Fk{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.fa={},this.ga=new zI(e=>UI(e),FI),this.pa=new Map,this.ya=new Set,this.wa=new pb(ow.comparator),this.Sa=new Map,this.ba=new GE,this.Da={},this.Ca=new Map,this.va=IE.Ln(),this.onlineState="Unknown",this.Fa=void 0}get isPrimaryClient(){return!0===this.Fa}}async function Uk(r,e,t,n,i){r.Ma=(e,t,n)=>async function(e,t,n,r){let i=t.view.ha(n);i.es&&(i=await yC(e.localStore,t.query,!1).then(({documents:e})=>t.view.ha(e,i)));var s=r&&r.targetChanges.get(t.targetId),s=t.view.applyChanges(i,e.isPrimaryClient,s);return Wk(e,t.targetId,s.Ea),s.snapshot}(r,e,t,n);const s=await yC(r.localStore,e,!0),a=new Ok(e,s.Ps),o=a.ha(s.documents),c=BT.createSynthesizedTargetChangeForCurrentChange(t,n&&"Offline"!==r.onlineState,i),l=a.applyChanges(o,r.isPrimaryClient,c);Wk(r,t,l.Ea);var u=new Mk(e,t,a);return r.ga.set(e,u),r.pa.has(t)?r.pa.get(t).push(e):r.pa.set(t,[e]),l.snapshot}async function Vk(e,t,n){const r=eS(e);try{const e=await function(e,i){const s=e,a=tw.now(),o=i.reduce((e,t)=>e.add(t.key),JI());let c,l;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=$I,r=JI();return s._s.getEntries(n,o).next(e=>{t=e,t.forEach((e,t)=>{t.isValidDocument()||(r=r.add(e))})}).next(()=>s.localDocuments.getOverlayedDocuments(n,t)).next(e=>{c=e;const t=[];for(const n of i){const i=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=rT(r.transform,e||null);null!=i&&(null===n&&(n=Qb.empty()),n.set(r.field,i))}return n||null}(n,c.get(n.key).overlayedDocument);null!=i&&t.push(new IT(n.key,i,function r(e){const i=[];return hb(e.fields,(e,t)=>{const n=new aw([e]);if($b(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new yb(i)}(i.value.mapValue),fT.exists(!0)))}return s.mutationQueue.addMutationBatch(n,a,t,i)}).next(e=>{var t=(l=e).applyToLocalDocumentSet(c,r);return s.documentOverlayCache.saveOverlays(n,e.batchId,t)})}).then(()=>({batchId:l.batchId,changes:WI(c)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Da[e.currentUser.toKey()];r=r||new pb(Xy),r=r.insert(t,n),e.Da[e.currentUser.toKey()]=r}(r,e.batchId,n),await Qk(r,e.changes),await lk(r.remoteStore)}catch(e){const t=_k(e,"Failed to persist write");n.reject(t)}}async function qk(e,t){const r=e;try{const e=await gC(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Sa.get(t);n&&(Vy(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.ma=!0:0<e.modifiedDocuments.size?Vy(n.ma):0<e.removedDocuments.size&&(Vy(n.ma),n.ma=!1))}),await Qk(r,e,t)}catch(e){await yw(e)}}function Bk(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.ga.forEach((e,t)=>{var n=t.view.U_(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.U_(n)&&(r=!0)}),r&&kk(t)}(t.eventManager,i),r.length&&t.fa.c_(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function jk(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i._s.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=ww.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);Vy(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.mutationQueue.performConsistencyCheck(e)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(e,t,r.batch.batchId)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=JI();for(let n=0;n<e.mutationResults.length;++n)0<e.mutationResults[n].transformResults.length&&(t=t.add(e.batch.mutations[n].key));return t}(r))).next(()=>i.localDocuments.getDocuments(e,t))})}(n.localStore,t);$k(n,r,null),zk(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Qk(n,e)}catch(e){await yw(e)}}function zk(e,t){(e.Ca.get(t)||[]).forEach(e=>{e.resolve()}),e.Ca.delete(t)}function $k(e,t,n){const r=e;let i=r.Da[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Da[r.currentUser.toKey()]=i}}function Kk(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.pa.get(e))t.ga.delete(r),n&&t.fa.xa(r,n);t.pa.delete(e),t.isPrimaryClient&&t.ba.mr(e).forEach(e=>{t.ba.containsKey(e)||Gk(t,e)})}function Gk(e,t){e.ya.delete(t.path.canonicalString());var n=e.wa.get(t);null!==n&&(ek(e.remoteStore,n),e.wa=e.wa.remove(t),e.Sa.delete(n),Hk(e))}function Wk(e,t,n){for(const r of n)r instanceof Dk?(e.ba.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.wa.get(n)||e.ya.has(r)||(Oy("SyncEngine","New document in limbo: "+n),e.ya.add(r),Hk(e))}(e,r)):r instanceof xk?(Oy("SyncEngine","Document no longer in limbo: "+r.key),e.ba.removeReference(r.key,t),e.ba.containsKey(r.key)||Gk(e,r.key)):Uy()}function Hk(e){for(;0<e.ya.size&&e.wa.size<e.maxConcurrentLimboResolutions;){var t=e.ya.values().next().value;e.ya.delete(t);var n=new ow(iw.fromString(t)),t=e.va.next();e.Sa.set(t,new Lk(n)),e.wa=e.wa.insert(n,t),ZC(e.remoteStore,new T0(OI(AI(n.path)),t,"TargetPurposeLimboResolution",Dw.ae))}}async function Qk(e,t,r){const i=e,s=[],a=[],o=[];i.ga.isEmpty()||(i.ga.forEach((e,n)=>{o.push(i.Ma(n,t,r).then(e=>{var t;(e||r)&&i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,null!=e&&e.fromCache?"not-current":"current"),e&&(s.push(e),t=cC.$i(n.targetId,e),a.push(t))}))}),await Promise.all(o),i.fa.c_(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>ww.forEach(t,t=>ww.forEach(t.Qi,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>ww.forEach(t.Ki,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!Cw(e))throw e;Oy("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.rs.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.rs=r.rs.insert(t,i)}}}(i.localStore,a))}async function Yk(r,e){const i=r;if(Zk(i),eS(i),!0===e&&!0!==i.Fa){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await Jk(i,r.toArray());i.Fa=!0,await fk(i.remoteStore,!0);for(const r of e)ZC(i.remoteStore,r)}else if(!1===e&&!1!==i.Fa){const r=[];let n=Promise.resolve();i.pa.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(Kk(i,t),_C(i.localStore,t,!0))),ek(i.remoteStore,t)}),await n,await Jk(i,r),function(e){const n=e;n.Sa.forEach((e,t)=>{ek(n.remoteStore,t)}),n.ba.gr(),n.Sa=new Map,n.wa=new pb(ow.comparator)}(i),i.Fa=!1,await fk(i.remoteStore,!1)}}async function Jk(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.pa.get(t);if(u&&0!==u.length){e=await vC(r.localStore,OI(u[0]));for(const t of u){const n=r.ga.get(t),u=(a=r,o=n,l=c=void 0,l=await yC((c=a).localStore,o.query,!0),l=o.view.Ra(l),c.isPrimaryClient&&Wk(c,o.targetId,l.Ea),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await wC(r.localStore,t);e=await vC(r.localStore,u),await Uk(r,Xk(u),t,!1,e.resumeToken)}i.push(e)}var a,o,c,l;return r.fa.c_(s),i}function Xk(e){return SI(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Zk(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=qk.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Sa.get(t);if(r&&r.ma)return JI().add(r.key);{let e=JI();const r=n.pa.get(t);if(!r)return e;for(const t of r){const r=n.ga.get(t);e=e.unionWith(r.view.la)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.Sa.get(t),s=i&&i.key;if(s){let e=new pb(ow.comparator);e=e.insert(s,Yb.newNoDocument(s,nw.min()));const n=JI().add(s),i=new qT(nw.min(),new Map,new pb(Xy),e,n);await qk(r,i),r.wa=r.wa.remove(s),r.Sa.delete(t),Hk(r)}else await _C(r.localStore,t,!1).then(()=>Kk(r,t,n)).catch(yw)}).bind(null,t),t.fa.c_=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.W_(e)&&(r=!0);i.Q_=e}}r&&kk(n)}).bind(null,t.eventManager),t.fa.xa=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function eS(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=jk.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.mutationQueue.lookupMutationBatch(t,r).next(e=>(Vy(null!==e),n=e.keys(),i.mutationQueue.removeMutationBatch(t,e))).next(()=>i.mutationQueue.performConsistencyCheck(t)).next(()=>i.documentOverlayCache.removeOverlaysForBatchId(t,n,r)).next(()=>i.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t,n)).next(()=>i.localDocuments.getDocuments(t,n))})}(r.localStore,t);$k(r,t,n),zk(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Qk(r,e)}catch(n){await yw(n)}}).bind(null,t),t}class tS{constructor(){this.synchronizeTabs=!1}async initialize(e){this.serializer=zC(e.databaseInfo.databaseId),this.sharedClientState=this.createSharedClientState(e),this.persistence=this.createPersistence(e),await this.persistence.start(),this.localStore=this.createLocalStore(e),this.gcScheduler=this.createGarbageCollectionScheduler(e,this.localStore),this.indexBackfillerScheduler=this.createIndexBackfillerScheduler(e,this.localStore)}createGarbageCollectionScheduler(e,t){return null}createIndexBackfillerScheduler(e,t){return null}createLocalStore(e){return dC(this.persistence,new uC,e.initialUser,this.serializer)}createPersistence(e){return new XE(eC.Jr,this.serializer)}createSharedClientState(e){return new DC}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class nS extends tS{constructor(e,t,n){super(),this.Na=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Na.initialize(this,e),await eS(this.Na.syncEngine),await lk(this.Na.remoteStore),await this.persistence.gi(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}createLocalStore(e){return dC(this.persistence,new uC,e.initialUser,this.serializer)}createGarbageCollectionScheduler(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new NE(n,e.asyncQueue,t)}createIndexBackfillerScheduler(e,t){var n=new Pw(t,this.persistence);return new Rw(e.asyncQueue,n)}createPersistence(e){var t=oC(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?fE.withCacheSize(this.cacheSizeBytes):fE.DEFAULT;return new iC(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,BC(),jC(),this.serializer,this.sharedClientState,!!this.forceOwnership)}createSharedClientState(e){return new DC}}class rS extends nS{constructor(e,t){super(e,t,!1),this.Na=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Na.syncEngine;this.sharedClientState instanceof PC&&(this.sharedClientState.syncEngine={Xs:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.mutationQueue;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Fn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):ww.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await lk(i.remoteStore):"acknowledged"===n||"rejected"===n?($k(i,t,r||null),zk(i,t),i.localStore.mutationQueue.xn(t)):Uy(),await Qk(i,s)):Oy("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),eo:(async function(e,t,n,r){const i=e;if(i.Fa)Oy("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.pa.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await bC(i.localStore,BI(s[0])),r=qT.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,bb.EMPTY_BYTE_STRING);await Qk(i,e,r);break}case"rejected":await _C(i.localStore,t,!0),Kk(i,t,r);break;default:Uy()}}}).bind(null,t),no:(async function(e,t,n){const r=Zk(e);if(r.Fa){for(const e of t)if(r.pa.has(e))Oy("SyncEngine","Adding an already active target "+e);else{const t=await wC(r.localStore,e),n=await vC(r.localStore,t);await Uk(r,Xk(t),n.targetId,!1,n.resumeToken),ZC(r.remoteStore,n)}for(const e of n)r.pa.has(e)&&await _C(r.localStore,e,!1).then(()=>{ek(r.remoteStore,e),Kk(r,e)}).catch(yw)}}).bind(null,t),ki:(function(e){return e.localStore.persistence.ki()}).bind(null,t),Zs:(async function(e,t){const n=e;return bC(n.localStore,t).then(e=>Qk(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.gi(async e=>{await Yk(this.Na.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}createSharedClientState(e){var t=BC();if(!PC.C(t))throw new By(qy.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=oC(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new PC(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class iS{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>Bk(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){Oy("SyncEngine","User change. New user:",t.toKey());const i=await pC(n.localStore,t);n.currentUser=t,e=n,r="'waitForPendingWrites' promise is rejected due to a user change.",e.Ca.forEach(e=>{e.forEach(e=>{e.reject(new By(qy.CANCELLED,r))})}),e.Ca.clear(),n.sharedClientState.handleUserChange(t,i.removedBatchIds,i.addedBatchIds),await Qk(n,i.cs)}var r}).bind(null,this.syncEngine),await fk(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new Tk}createDatastore(e){var t,n,r,i=zC(e.databaseInfo.databaseId),s=(r=e.databaseInfo,new qC(r));return t=e.authCredentials,n=e.appCheckCredentials,r=s,e=i,new HC(t,n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>Bk(this.syncEngine,e,0),e=new(OC.C()?OC:xC),new YC(t,n,r,i,e);var t,n,r,i}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){const o=new Fk(e,t,n,r,i,s);return a&&(o.Fa=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;Oy("RemoteStore","RemoteStore shutting down."),t.F_.add(5),await XC(t),t.x_.shutdown(),t.O_.set("Unknown")}(this.remoteStore)}}function sS(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}class aS{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.Ba(this.observer.next,e)}error(e){this.observer.error?this.Ba(this.observer.error,e):My("Uncaught Error in snapshot listener:",e.toString())}La(){this.muted=!0}Ba(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class oS{constructor(e,t){this.ka=e,this.serializer=t,this.metadata=new jy,this.buffer=new Uint8Array,this.qa=new TextDecoder("utf-8"),this.Qa().then(e=>{e&&e.ea()?this.metadata.resolve(e.X_.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.X_)}`))},e=>this.metadata.reject(e))}close(){return this.ka.cancel()}async getMetadata(){return this.metadata.promise}async Oa(){return await this.getMetadata(),this.Qa()}async Qa(){var e=await this.Ka();if(null===e)return null;var t=this.qa.decode(e),n=Number(t);isNaN(n)&&this.$a(`length string (${t}) is not valid number`);t=await this.Ua(n);return new Ak(JSON.parse(t),e.length+n)}Wa(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async Ka(){for(;this.Wa()<0&&!await this.Ga(););if(0===this.buffer.length)return null;var e=this.Wa();e<0&&this.$a("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async Ua(e){for(;this.buffer.length<e;)await this.Ga()&&this.$a("Reached the end of bundle when more is expected.");var t=this.qa.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}$a(e){throw this.ka.cancel(),new Error(`Invalid bundle format: ${e}`)}async Ga(){var e=await this.ka.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class cS{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new By(qy.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=l0(r.serializer)+"/documents",i={documents:t.map(e=>s0(r.serializer,e))},s=await r.Fo("BatchGetDocuments",n,i,t.length),a=new Map;s.forEach(e=>{const t=(n=r.serializer,"found"in(e=e)?function(e,t){Vy(!!t.found),t.found.name,t.found.updateTime;var n=a0(e,t.found.name),r=n0(t.found.updateTime),i=t.found.createTime?n0(t.found.createTime):nw.min(),s=new Qb({mapValue:{fields:t.found.fields}});return Yb.newFoundDocument(n,r,i,s)}(n,e):"missing"in e?function(e,t){Vy(!!t.missing),Vy(!!t.readTime);var n=a0(e,t.missing),r=n0(t.readTime);return Yb.newNoDocument(n,r)}(n,e):Uy());var n;a.set(t.key.toString(),t)});const o=[];return t.forEach(e=>{var t=a.get(e.toString());Vy(!!t),o.push(t)}),o}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new kT(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=ow.fromPath(t);this.mutations.push(new ST(n,this.precondition(n)))}),await async function(e,t){const n=e,r=l0(n.serializer)+"/documents",i={writes:t.map(e=>p0(n.serializer,e))};await n.bo("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw Uy();t=nw.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new By(qy.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(nw.min())?fT.exists(!1):fT.updateTime(t):fT.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return fT.exists(!0);if(t.isEqual(nw.min()))throw new By(qy.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return fT.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class lS{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.za=n.maxAttempts,this.Ho=new $C(this.asyncQueue,"transaction_retry")}run(){--this.za,this.ja()}ja(){this.Ho.Qo(async()=>{const t=new cS(this.datastore),e=this.Ha(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.Ja(e)}))}).catch(e=>{this.Ja(e)})})}Ha(e){try{var t=this.updateFunction(e);return!xw(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Ja(e){0<this.za&&this.Ya(e)?(--this.za,this.asyncQueue.enqueueAndForget(()=>(this.ja(),Promise.resolve()))):this.deferred.reject(e)}Ya(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!DT(t)}}class uS{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=Ry.UNAUTHENTICATED,this.clientId=Jy.V(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{Oy("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(Oy("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new By(qy.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new jy;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=_k(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function hS(e,t){e.asyncQueue.verifyOperationInProgress(),Oy("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await pC(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function dS(e,n){e.asyncQueue.verifyOperationInProgress();var t=await fS(e);Oy("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>pk(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>pk(n.remoteStore,t)),e._onlineComponents=n}function pS(e){return"FirebaseError"===e.name?e.code===qy.FAILED_PRECONDITION||e.code===qy.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}async function fS(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){Oy("FirestoreClient","Using user provided OfflineComponentProvider");try{await hS(t,t._uninitializedComponentsProvider._offline)}catch(e){var n=e;if(!pS(n))throw n;Ly("Error using user provided cache. Falling back to memory cache: "+n),await hS(t,new tS)}}else Oy("FirestoreClient","Using default OfflineComponentProvider"),await hS(t,new tS);return t._offlineComponents}async function gS(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(Oy("FirestoreClient","Using user provided OnlineComponentProvider"),await dS(e,e._uninitializedComponentsProvider._online)):(Oy("FirestoreClient","Using default OnlineComponentProvider"),await dS(e,new iS))),e._onlineComponents}function mS(e){return fS(e).then(e=>e.persistence)}function vS(e){return fS(e).then(e=>e.localStore)}function _S(e){return gS(e).then(e=>e.remoteStore)}function yS(e){return gS(e).then(e=>e.syncEngine)}async function wS(e){const t=await gS(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=Zk(e);let r,i;const s=n.ga.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.Va();else{const e=await vC(n.localStore,OI(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await Uk(n,t,r,"current"===s,e.resumeToken),n.isPrimaryClient&&ZC(n.remoteStore,e)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.ga.get(t),i=n.pa.get(r.targetId);if(1<i.length)return n.pa.set(r.targetId,i.filter(e=>!FI(e,t))),void n.ga.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await _C(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),ek(n.remoteStore,r.targetId),Kk(n,r.targetId)}).catch(yw)):(Kk(n,r.targetId),await _C(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function bS(e,t,n={}){const r=new jy;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const e=new aS({next:e=>{r.enqueueAndForget(()=>Ck(n,o));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new By(qy.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new By(qy.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):a.resolve(e)},error:e=>a.reject(e)}),o=new Sk(AI(i.path),e,{includeMetadataChanges:!0,Z_:!0});return Ek(n,o)}(await wS(e),e.asyncQueue,t,n,r)),r.promise}function IS(e,t,n={}){const r=new jy;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new aS({next:e=>{n.enqueueAndForget(()=>Ck(t,a)),e.fromCache&&"server"===r.source?i.reject(new By(qy.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(e)},error:e=>i.reject(e)}),a=new Sk(e,s,{includeMetadataChanges:!0,Z_:!0});return Ek(t,a)}(await wS(e),e.asyncQueue,t,n,r)),r.promise}function TS(e,t,n,r){const i=(n=n,t=zC(t),s="string"==typeof n?OT().encode(n):n,n=function(e,t){if(e instanceof Uint8Array)return sS(e,t);if(e instanceof ArrayBuffer)return sS(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new oS(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=n0(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Ur.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);r._updateProgress(Pk(i));const a=new Rk(i,t.localStore,n.serializer);let e=await n.Oa();for(;e;){const t=await a.na(e);t&&r._updateProgress(t),e=await n.Oa()}var s=await a.complete();return await Qk(t,s.sa,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Ur.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.ia)}catch(t){return Ly("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await yS(e),i,r)})}function ES(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const CS=new Map;function kS(e,t,n){if(!n)throw new By(qy.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function SS(e,t,n,r){if(!0===t&&!0===r)throw new By(qy.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function AS(e){if(!ow.isDocumentKey(e))throw new By(qy.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function NS(e){if(ow.isDocumentKey(e))throw new By(qy.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function RS(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":Uy();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function PS(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new By(qy.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=RS(e);throw new By(qy.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function DS(e,t){if(t<=0)throw new By(qy.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class xS{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new By(qy.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new By(qy.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}SS("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=ES(null!==(t=e.experimentalLongPollingOptions)&&void 0!==t?t:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new By(qy.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new By(qy.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(30<e.timeoutSeconds)throw new By(qy.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams;var t,n}}class OS{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new xS({}),this._settingsFrozen=!1}get app(){if(!this._app)throw new By(qy.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new By(qy.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new xS(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new $y;switch(e.type){case"firstParty":return new Hy(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new By(qy.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=CS.get(e);t&&(Oy("ComponentProvider","Removing Datastore"),CS.delete(e),t.terminate())}(this),Promise.resolve()}}class MS{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new MS(this.firestore,e,this._query)}}class LS{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new FS(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new LS(this.firestore,e,this._key)}}class FS extends MS{constructor(e,t,n){super(e,t,AI(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new LS(this.firestore,null,new ow(e))}withConverter(e){return new FS(this.firestore,e,this._path)}}function US(e,t,...n){if(e=oe(e),kS("collection","path",t),e instanceof OS){var r=iw.fromString(t,...n);return NS(r),new FS(e,null,r)}if(!(e instanceof LS||e instanceof FS))throw new By(qy.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(iw.fromString(t,...n));return NS(r),new FS(e.firestore,null,r)}function VS(e,t,...n){if(e=oe(e),kS("doc","path",t=1===arguments.length?Jy.V():t),e instanceof OS){var r=iw.fromString(t,...n);return AS(r),new LS(e,null,new ow(r))}if(!(e instanceof LS||e instanceof FS))throw new By(qy.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(iw.fromString(t,...n));return AS(r),new LS(e.firestore,e instanceof FS?e.converter:null,new ow(r))}function qS(e,t){return e=oe(e),t=oe(t),(e instanceof LS||e instanceof FS)&&(t instanceof LS||t instanceof FS)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function BS(e,t){return e=oe(e),t=oe(t),e instanceof MS&&t instanceof MS&&e.firestore===t.firestore&&FI(e._query,t._query)&&e.converter===t.converter}class jS{constructor(){this.Za=Promise.resolve(),this.Xa=[],this.eu=!1,this.tu=[],this.nu=null,this.ru=!1,this.iu=!1,this.su=[],this.Ho=new $C(this,"async_queue_retry"),this.ou=()=>{var e=jC();e&&Oy("AsyncQueue","Visibility state changed to "+e.visibilityState),this.Ho.$o()};const e=jC();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.ou)}get isShuttingDown(){return this.eu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this._u(),this.au(e)}enterRestrictedMode(e){if(!this.eu){this.eu=!0,this.iu=e||!1;const t=jC();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.ou)}}enqueue(e){if(this._u(),this.eu)return new Promise(()=>{});const t=new jy;return this.au(()=>this.eu&&this.iu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Xa.push(e),this.uu()))}async uu(){if(0!==this.Xa.length){try{await this.Xa[0](),this.Xa.shift(),this.Ho.reset()}catch(e){if(!Cw(e))throw e;Oy("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Xa.length&&this.Ho.Qo(()=>this.uu())}}au(e){var t=this.Za.then(()=>(this.ru=!0,e().catch(e=>{throw this.nu=e,this.ru=!1,My("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.ru=!1,e))));return this.Za=t}enqueueAfterDelay(e,t,n){this._u(),-1<this.su.indexOf(e)&&(t=0);var r=vk.createAndSchedule(this,e,t,n,e=>this.cu(e));return this.tu.push(r),r}_u(){this.nu&&Uy()}verifyOperationInProgress(){}async lu(){for(var e;await(e=this.Za),e!==this.Za;);}hu(e){for(const t of this.tu)if(t.timerId===e)return!0;return!1}Pu(t){return this.lu().then(()=>{this.tu.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.tu)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.lu()})}Iu(e){this.su.push(e)}cu(e){var t=this.tu.indexOf(e);this.tu.splice(t,1)}}function zS(e){return function(e,t){if("object"==typeof e&&null!==e){var n=e;for(const e of t)if(e in n&&"function"==typeof n[e])return 1}}(e,["next","error","complete"])}class $S{constructor(){this._progressObserver={},this._taskCompletionResolver=new jy,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var KS,GS,WS,HS,QS,YS;class JS extends OS{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new jS,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}_terminate(){return this._firestoreClient||ZS(this),this._firestoreClient.terminate()}}function XS(e){return e._firestoreClient||ZS(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function ZS(e){var t,n,r,i,s,a=e._freezeSettings(),o=(n=e._databaseId,r=(null===(o=e._app)||void 0===o?void 0:o.options.appId)||"",i=e._persistenceKey,s=a,new Nb(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,ES(s.experimentalLongPollingOptions),s.useFetchStreams));e._firestoreClient=new uS(e._authCredentials,e._appCheckCredentials,e._queue,o),null!==(o=a.localCache)&&void 0!==o&&o._offlineComponentProvider&&null!==(t=a.localCache)&&void 0!==t&&t._onlineComponentProvider&&(e._firestoreClient._uninitializedComponentsProvider={_offlineKind:a.localCache.kind,_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider})}function eA(e,t,n){const r=new jy;return e.asyncQueue.enqueue(async()=>{try{await hS(e,n),await dS(e,t),r.resolve()}catch(e){const t=e;if(!pS(t))throw t;Ly("Error enabling indexeddb cache. Falling back to memory cache: "+t),r.reject(t)}}).then(()=>r.promise)}function tA(e){return function(e){const t=new jy;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;sk(n.remoteStore)||Oy("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=e;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e))}(n.localStore);if(-1===e)return void t.resolve();const r=n.Ca.get(e)||[];r.push(t),n.Ca.set(e,r)}catch(e){const n=_k(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await yS(e),t)),t.promise}(XS(e=PS(e,JS)))}function nA(e){return(n=XS(e=PS(e,JS))).asyncQueue.enqueue(async()=>{const e=await mS(n),t=await _S(n);return e.setNetworkEnabled(!0),function(e){const t=e;return t.F_.delete(0),JC(t)}(t)});var n}function rA(e){return(n=XS(e=PS(e,JS))).asyncQueue.enqueue(async()=>{const e=await mS(n),t=await _S(n);return e.setNetworkEnabled(!1),async function(e){const t=e;t.F_.add(0),await XC(t),t.O_.set("Offline")}(t)});var n}function iA(t,e){return n=XS(t=PS(t,JS)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Ur.getNamedQuery(e,t))}(await vS(n),r)).then(e=>e?new MS(t,null,e.query):null);var n,r}function sA(e){if(e._initialized||e._terminated)throw new By(qy.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class aA{constructor(e){this._byteString=e}static fromBase64String(e){try{return new aA(bb.fromBase64String(e))}catch(e){throw new By(qy.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new aA(bb.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class oA{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new By(qy.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new aw(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class cA{constructor(e){this._methodName=e}}class lA{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new By(qy.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new By(qy.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return Xy(this._lat,e._lat)||Xy(this._long,e._long)}}const uA=/^__.*__$/;class hA{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new IT(e,this.data,this.fieldMask,t,this.fieldTransforms):new bT(e,this.data,t,this.fieldTransforms)}}class dA{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new IT(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function pA(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw Uy()}}class fA{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.du(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Tu(){return this.settings.Tu}Eu(e){return new fA(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Au(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Eu({path:n,Ru:!1});return r.Vu(e),r}mu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Eu({path:n,Ru:!1});return r.du(),r}fu(e){return this.Eu({path:void 0,Ru:!0})}gu(e){return OA(e,this.settings.methodName,this.settings.pu||!1,this.path,this.settings.yu)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}du(){if(this.path)for(let e=0;e<this.path.length;e++)this.Vu(this.path.get(e))}Vu(e){if(0===e.length)throw this.gu("Document fields must not be empty");if(pA(this.Tu)&&uA.test(e))throw this.gu('Document fields cannot begin and end with "__"')}}class gA{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||zC(e)}wu(e,t,n,r=!1){return new fA({Tu:e,methodName:t,yu:n,path:aw.emptyPath(),Ru:!1,pu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function mA(e){var t=e._freezeSettings(),n=zC(e._databaseId);return new gA(e._databaseId,!!t.ignoreUndefinedProperties,n)}function vA(e,t,n,r,i,s={}){const a=e.wu(s.merge||s.mergeFields?2:0,t,n,i);RA("Data must be an object, but it was:",a,r);var o=AA(r,a);let c,l;if(s.merge)c=new yb(a.fieldMask),l=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=PA(t,r,n);if(!a.contains(i))throw new By(qy.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);MA(e,i)||e.push(i)}c=new yb(e),l=a.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=a.fieldTransforms;return new hA(new Qb(o),c,l)}class _A extends cA{_toFieldTransform(e){if(2!==e.Tu)throw 1===e.Tu?e.gu(`${this._methodName}() can only appear at the top level of your update data`):e.gu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof _A}}function yA(e,t,n){return new fA({Tu:3,yu:t.settings.yu,methodName:e._methodName,Ru:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class wA extends cA{_toFieldTransform(e){return new dT(e.path,new iT)}isEqual(e){return e instanceof wA}}class bA extends cA{constructor(e,t){super(e),this.Su=t}_toFieldTransform(e){const t=yA(this,e,!0),n=this.Su.map(e=>SA(e,t)),r=new sT(n);return new dT(e.path,r)}isEqual(e){return this===e}}class IA extends cA{constructor(e,t){super(e),this.Su=t}_toFieldTransform(e){const t=yA(this,e,!0),n=this.Su.map(e=>SA(e,t)),r=new oT(n);return new dT(e.path,r)}isEqual(e){return this===e}}class TA extends cA{constructor(e,t){super(e),this.bu=t}_toFieldTransform(e){var t=new lT(e.serializer,tT(e.serializer,this.bu));return new dT(e.path,t)}isEqual(e){return this===e}}function EA(e,i,s,t){const a=e.wu(1,i,s);RA("Data must be an object, but it was:",a,t);const o=[],c=Qb.empty();hb(t,(e,t)=>{var n=xA(i,e,s);t=oe(t);var r=a.mu(n);if(t instanceof _A)o.push(n);else{const e=SA(t,r);null!=e&&(o.push(n),c.set(n,e))}});var n=new yb(o);return new dA(c,n,a.fieldTransforms)}function CA(e,t,n,r,i,s){const a=e.wu(1,t,n),o=[PA(t,r,n)],c=[i];if(s.length%2!=0)throw new By(qy.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let p=0;p<s.length;p+=2)o.push(PA(t,s[p])),c.push(s[p+1]);const l=[],u=Qb.empty();for(let f=o.length-1;0<=f;--f)if(!MA(l,o[f])){const t=o[f];var h=oe(h=c[f]);const r=a.mu(t);if(h instanceof _A)l.push(t);else{const e=SA(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new yb(l);return new dA(u,d,a.fieldTransforms)}function kA(e,t,n,r=!1){return SA(n,e.wu(r?4:3,t))}function SA(e,t){if(NA(e=oe(e)))return RA("Unsupported field value:",t,e),AA(e,t);if(e instanceof cA)return function(e,t){if(!pA(t.Tu))throw t.gu(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.gu(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Ru&&4!==t.Tu)throw t.gu("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=SA(i,t.fu(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=oe(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return tT(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=tw.fromDate(e);return{timestampValue:e0(t.serializer,n)}}if(e instanceof tw){n=new tw(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:e0(t.serializer,n)}}if(e instanceof lA)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof aA)return{bytesValue:t0(t.serializer,e._byteString)};if(e instanceof LS){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.gu(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:r0(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.gu(`Unsupported field value: ${RS(e)}`)}(e,t)}function AA(e,r){const i={};return db(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):hb(e,(e,t)=>{var n=SA(t,r.Au(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function NA(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof tw||e instanceof lA||e instanceof aA||e instanceof LS||e instanceof cA)}function RA(e,t,n){if(!NA(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=RS(n);throw"an object"===r?t.gu(e+" a custom object"):t.gu(e+" "+r)}var i}function PA(e,t,n){if((t=oe(t))instanceof oA)return t._internalPath;if("string"==typeof t)return xA(e,t);throw OA("Field path arguments must be of type string or ",e,!1,void 0,n)}const DA=new RegExp("[~\\*/\\[\\]]");function xA(t,n,r){if(0<=n.search(DA))throw OA(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new oA(...n.split("."))._internalPath}catch(e){throw OA(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function OA(e,t,n,r,i){var s=r&&!r.isEmpty(),a=void 0!==i;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let c="";return(s||a)&&(c+=" (found",s&&(c+=` in field ${r}`),a&&(c+=` in document ${i}`),c+=")"),new By(qy.INVALID_ARGUMENT,o+e+c)}function MA(e,t){return e.some(e=>e.isEqual(t))}class LA{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new LS(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new FA(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(UA("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class FA extends LA{data(){return super.data()}}function UA(e,t){return"string"==typeof t?xA(e,t):(t instanceof oA?t:t._delegate)._internalPath}function VA(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new By(qy.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class qA{}class BA extends qA{}function jA(e,t,...n){let r=[];t instanceof qA&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof $A).length,n=e.filter(e=>e instanceof zA).length;if(1<t||0<t&&0<n)throw new By(qy.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r);for(const t of r)e=t._apply(e);return e}class zA extends BA{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new zA(e,t,n)}_apply(e){var t=this._parse(e);return XA(e._query,t),new MS(e.firestore,e.converter,MI(e._query,t))}_parse(e){var t=mA(e.firestore);return function(e,t,n,r,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new By(qy.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){JA(a,s);const t=[];for(const n of a)t.push(YA(r,e,n));o={arrayValue:{values:t}}}else o=YA(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||JA(a,s),o=kA(n,t,a,"in"===s||"not-in"===s);return nI.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}class $A extends qA{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new $A(e,t)}_parse(t){var e=this._queryConstraints.map(e=>e._parse(t)).filter(e=>0<e.getFilters().length);return 1===e.length?e[0]:rI.create(e,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;for(const e of t.getFlattenedFilters())XA(n,e),n=MI(n,e)}(e._query,t),new MS(e.firestore,e.converter,MI(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class KA extends BA{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new KA(e,t)}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new By(qy.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new By(qy.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new eI(t,n);return n=i,null!==RI(e=e)||null!==(r=PI(e))&&ZA(0,r,n.field),i}(e._query,this._field,this._direction);return new MS(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new kI(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class GA extends BA{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new GA(e,t,n)}_apply(e){return new MS(e.firestore,e.converter,LI(e._query,this._limit,this._limitType))}}class WA extends BA{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new WA(e,t,n)}_apply(e){var t,n=QA(e,this.type,this._docOrFields,this._inclusive);return new MS(e.firestore,e.converter,(t=e._query,e=n,new kI(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class HA extends BA{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new HA(e,t,n)}_apply(e){var t,n=QA(e,this.type,this._docOrFields,this._inclusive);return new MS(e.firestore,e.converter,(t=e._query,e=n,new kI(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function QA(e,t,n,r){if(n[0]=oe(n[0]),n[0]instanceof LA)return function(e,t,n,r,i){if(!r)throw new By(qy.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of xI(e))if(n.field.isKeyField())s.push(Vb(t,r.key));else{const e=r.data.field(n.field);if(kb(e))throw new By(qy.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new By(qy.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new Jb(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=mA(e.firestore);return function(e,t,n,r,i,s){const a=e.explicitOrderBy;if(i.length>a.length)throw new By(qy.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const o=[];for(let c=0;c<i.length;c++){const l=i[c];if(a[c].field.isKeyField()){if("string"!=typeof l)throw new By(qy.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!DI(e)&&-1!==l.indexOf("/"))throw new By(qy.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(iw.fromString(l));if(!ow.isDocumentKey(n))throw new By(qy.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new ow(n);o.push(Vb(t,i))}else{const e=kA(n,r,l);o.push(e)}}return new Jb(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function YA(e,t,n){if("string"==typeof(n=oe(n))){if(""===n)throw new By(qy.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!DI(t)&&-1!==n.indexOf("/"))throw new By(qy.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(iw.fromString(n));if(!ow.isDocumentKey(r))throw new By(qy.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Vb(e,new ow(r))}if(n instanceof LS)return Vb(e,n._key);throw new By(qy.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${RS(n)}.`)}function JA(e,t){if(!Array.isArray(e)||0===e.length)throw new By(qy.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function XA(e,t){if(t.isInequality()){const r=PI(e),i=t.field;if(null!==r&&!r.isEqual(i))throw new By(qy.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${i.toString()}'`);var n=RI(e);null!==n&&ZA(0,i,n)}const r=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(0<=t.indexOf(e.op))return e.op;return null}(e.filters,function(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==r)throw r===t.op?new By(qy.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new By(qy.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}function ZA(e,t,n){if(!n.isEqual(t))throw new By(qy.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class eN{convertValue(e,t="none"){switch(xb(e)){case 0:return null;case 1:return e.booleanValue;case 2:return Eb(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(Cb(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw Uy()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,n="none"){const r={};return hb(e,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new lA(Eb(e.latitude),Eb(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=Sb(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(Ab(e));default:return null}}convertTimestamp(e){var t=Tb(e);return new tw(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=iw.fromString(e);Vy(I0(n));const r=new Rb(n.get(1),n.get(3)),i=new ow(n.popFirst(5));return r.isEqual(t)||My(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function tN(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class nN extends eN{constructor(e){super(),this.firestore=e}convertBytes(e){return new aA(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new LS(this.firestore,null,t)}}class rN{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class iN extends LA{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new sN(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(UA("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class sN extends iN{data(e={}){return super.data(e)}}class aN{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new rN(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new sN(this._firestore,this._userDataWriter,e.key,e,new rN(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new By(qy.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let n=0;return s._snapshot.docChanges.map(e=>{var t=new sN(s._firestore,s._userDataWriter,e.doc.key,e.doc,new rN(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);return e.doc,{type:"added",doc:t,oldIndex:-1,newIndex:n++}})}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new sN(s._firestore,s._userDataWriter,e.doc.key,e.doc,new rN(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return Uy()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function oN(e,t){return e instanceof iN&&t instanceof iN?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof aN&&t instanceof aN&&e._firestore===t._firestore&&BS(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class cN extends eN{constructor(e){super(),this.firestore=e}convertBytes(e){return new aA(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new LS(this.firestore,null,t)}}function lN(t){t=PS(t,LS);const n=PS(t.firestore,JS),e=XS(n),r=new cN(n);return function(e,t){const n=new jy;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(e,t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.localDocuments.getDocument(e,t))}(e,t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new By(qy.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){var r=_k(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await vS(e),t,n)),n.promise}(e,t._key).then(e=>new iN(n,r,t._key,e,new rN(null!==e&&e.hasLocalMutations,!0),t.converter))}function uN(t){t=PS(t,MS);const n=PS(t.firestore,JS),e=XS(n),r=new cN(n);return function(e,t){const n=new jy;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await yC(e,t,!0),s=new Ok(t,i.Ps),a=s.ha(i.documents),o=s.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=_k(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await vS(e),t,n)),n.promise}(e,t._query).then(e=>new aN(n,r,t,e))}function hN(e,t,n){e=PS(e,LS);var r=PS(e.firestore,JS),i=tN(e.converter,t,n);return gN(r,[vA(mA(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,fT.none())])}function dN(e,t,n,...r){e=PS(e,LS);var i=PS(e.firestore,JS),s=mA(i);let a;return a="string"==typeof(t=oe(t))||t instanceof oA?CA(s,"updateDoc",e._key,t,n,r):EA(s,"updateDoc",e._key,t),gN(i,[a.toMutation(e._key,fT.exists(!0))])}function pN(t,...n){var e;t=oe(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||zS(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(zS(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let a,o,c;if(t instanceof LS)o=PS(t.firestore,JS),c=AI(t._key.path),a={next:e=>{n[i]&&n[i](mN(o,t,e))},error:n[i+1],complete:n[i+2]};else{const l=PS(t,MS);o=PS(l.firestore,JS),c=l._query;const u=new cN(o);a={next:e=>{n[i]&&n[i](new aN(o,u,l,e))},error:n[i+1],complete:n[i+2]},VA(t._query)}return function(e,t,n,r){const i=new aS(r),s=new Sk(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>Ek(await wS(e),s)),()=>{i.La(),e.asyncQueue.enqueueAndForget(async()=>Ck(await wS(e),s))}}(XS(o),c,s,a)}function fN(e,t){return function(e,t){const n=new aS(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.K_.add(t),t.next()}(await wS(e),n)),()=>{n.La(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.K_.delete(t)}(await wS(e),n))}}(XS(e=PS(e,JS)),zS(t)?t:{next:t})}function gN(e,t){return function(e,t){const n=new jy;return e.asyncQueue.enqueueAndForget(async()=>Vk(await yS(e),t,n)),n.promise}(XS(e),t)}function mN(e,t,n){var r=n.docs.get(t._key),i=new cN(e);return new iN(e,i,t._key,r,new rN(n.hasPendingWrites,n.fromCache),t.converter)}const vN={maxAttempts:5};class _N{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=mA(e)}set(e,t,n){this._verifyNotCommitted();const r=yN(e,this._firestore),i=tN(r.converter,t,n),s=vA(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,fT.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=yN(e,this._firestore);let s;return s="string"==typeof(t=oe(t))||t instanceof oA?CA(this._dataReader,"WriteBatch.update",i._key,t,n,r):EA(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,fT.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=yN(e,this._firestore);return this._mutations=this._mutations.concat(new kT(t._key,fT.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new By(qy.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function yN(e,t){if((e=oe(e)).firestore!==t)throw new By(qy.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class wN extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=mA(e)}get(e){const n=yN(e,this._firestore),r=new nN(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return Uy();const t=e[0];if(t.isFoundDocument())return new LA(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new LA(this._firestore,r,n._key,null,n.converter);throw Uy()})}set(e,t,n){var r=yN(e,this._firestore),i=tN(r.converter,t,n),i=vA(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=yN(e,this._firestore),s="string"==typeof(t=oe(t))||t instanceof oA?CA(this._dataReader,"Transaction.update",i._key,t,n,r):EA(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=yN(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=yN(e,this._firestore),n=new cN(this._firestore);return super.get(e).then(e=>new iN(this._firestore,n,t._key,e._document,new rN(!1,!1),t.converter))}}function bN(t,n,e){t=PS(t,JS);var r=Object.assign(Object.assign({},vN),e);return function(e){if(e.maxAttempts<1)throw new By(qy.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(t,n,r){const i=new jy;return t.asyncQueue.enqueueAndForget(async()=>{var e=await gS(t).then(e=>e.datastore);new lS(t.asyncQueue,e,r,n,i).run()}),i.promise}(XS(t),e=>n(new wN(t,e)),r)}KS=!0,GS=Je,Py=GS,We(new ce("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new JS(new Gy(e.getProvider("auth-internal")),new Yy(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new By(qy.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new Rb(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:KS},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),tt(Ny,"4.1.3",cR),tt(Ny,"4.1.3","esm2017");function IN(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new By("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function TN(){if("undefined"==typeof Uint8Array)throw new By("unimplemented","Uint8Arrays are not available in this environment.")}function EN(){if("undefined"==typeof atob)throw new By("unimplemented","Blobs are unavailable in Firestore in this environment.")}class CN{constructor(e){this._delegate=e}static fromBase64String(e){return EN(),new CN(aA.fromBase64String(e))}static fromUint8Array(e){return TN(),new CN(aA.fromUint8Array(e))}toBase64(){return EN(),this._delegate.toBase64()}toUint8Array(){return TN(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function kN(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class SN{enableIndexedDbPersistence(e,t){return function(e,t){sA(e=PS(e,JS));var n=XS(e);if(n._uninitializedComponentsProvider)throw new By(qy.FAILED_PRECONDITION,"SDK cache is already specified.");Ly("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var r=e._freezeSettings(),i=new iS;return eA(n,i,new nS(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){sA(e=PS(e,JS));var t=XS(e);if(t._uninitializedComponentsProvider)throw new By(qy.FAILED_PRECONDITION,"SDK cache is already specified.");Ly("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");var n=e._freezeSettings(),r=new iS;return eA(t,r,new rS(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new By(qy.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new jy;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!Iw.C())return Promise.resolve();var t=e+"main";await Iw.delete(t)}(oC(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class AN{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof Rb||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||Ly("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){!function(n,e,t,r={}){var i;const s=(n=PS(n,OS))._getSettings(),a=`${e}:${t}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&Ly("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),n._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=Ry.MOCK_USER;else{e=w(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new By(qy.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new Ry(s)}n._authCredentials=new Ky(new zy(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return nA(this._delegate)}disableNetwork(){return rA(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,SS("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return tA(this._delegate)}onSnapshotsInSync(e){return fN(this._delegate,e)}get app(){if(!this._appCompat)throw new By("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new jN(this,US(this._delegate,e))}catch(e){throw ON(e,"collection()","Firestore.collection()")}}doc(e){try{return new xN(this,VS(this._delegate,e))}catch(e){throw ON(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new VN(this,function(e,t){if(e=PS(e,OS),kS("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new By(qy.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new MS(e,null,(t=t,new kI(iw.emptyPath(),t)))}(this._delegate,e))}catch(e){throw ON(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return bN(this._delegate,e=>t(new RN(this,e)))}batch(){return XS(this._delegate),new PN(new _N(this._delegate,e=>gN(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=XS(t=PS(t,JS)),r=new $S,TS(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return iA(this._delegate,e).then(e=>e?new VN(this,e):null)}}class NN extends eN{constructor(e){super(),this.firestore=e}convertBytes(e){return new CN(new aA(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return xN.forKey(t,this.firestore,null)}}class RN{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new NN(e)}get(e){const t=zN(e);return this._delegate.get(t).then(e=>new FN(this._firestore,new iN(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=zN(e);return n?(IN("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=zN(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=zN(e);return this._delegate.delete(t),this}}class PN{constructor(e){this._delegate=e}set(e,t,n){var r=zN(e);return n?(IN("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=zN(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=zN(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class DN{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new sN(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new UN(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=DN.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new DN(e,new NN(e),t),r.set(t,i)),i}}DN.INSTANCES=new WeakMap;class xN{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new NN(e)}static forPath(e,t,n){if(e.length%2!=0)throw new By("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new xN(t,new LS(t._delegate,n,new ow(e)))}static forKey(e,t,n){return new xN(t,new LS(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new jN(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new jN(this.firestore,US(this._delegate,e))}catch(e){throw ON(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=oe(e))instanceof LS&&qS(this._delegate,e)}set(e,t){t=IN("DocumentReference.set",t);try{return t?hN(this._delegate,e,t):hN(this._delegate,e)}catch(e){throw ON(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?dN(this._delegate,e):dN(this._delegate,e,t,...n)}catch(e){throw ON(e,"updateDoc()","DocumentReference.update()")}}delete(){return gN(PS((e=this._delegate).firestore,JS),[new kT(e._key,fT.none())]);var e}onSnapshot(...e){var t=MN(e),n=LN(e,e=>new FN(this.firestore,new iN(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return pN(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?lN:"server"===(null==e?void 0:e.source)?function(t){t=PS(t,LS);const n=PS(t.firestore,JS);return bS(XS(n),t._key,{source:"server"}).then(e=>mN(n,t,e))}:function(t){t=PS(t,LS);const n=PS(t.firestore,JS);return bS(XS(n),t._key).then(e=>mN(n,t,e))})(this._delegate),t.then(e=>new FN(this.firestore,new iN(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new xN(this.firestore,e?this._delegate.withConverter(DN.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function ON(e,t,n){return e.message=e.message.replace(t,n),e}function MN(e){for(const t of e)if("object"==typeof t&&!kN(t))return t;return{}}function LN(e,t){var n;let r;return r=kN(e[0])?e[0]:kN(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class FN{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new xN(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return oN(this._delegate,e._delegate)}}class UN extends FN{data(e){var t=this._delegate.data(e);return void 0!==t||Uy(),t}}class VN{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new NN(e)}where(e,t,n){try{return new VN(this.firestore,jA(this._delegate,(r=n,i=t,s=UA("where",e),zA._create(s,i,r))))}catch(e){throw ON(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new VN(this.firestore,jA(this._delegate,([n,r="asc"]=[e,t],i=r,s=UA("orderBy",n),KA._create(s,i))))}catch(e){throw ON(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new VN(this.firestore,jA(this._delegate,(DS("limit",t=e),GA._create("limit",t,"F"))))}catch(e){throw ON(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new VN(this.firestore,jA(this._delegate,(DS("limitToLast",t=e),GA._create("limitToLast",t,"L"))))}catch(e){throw ON(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new VN(this.firestore,jA(this._delegate,function(...e){return WA._create("startAt",e,!0)}(...e)))}catch(e){throw ON(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new VN(this.firestore,jA(this._delegate,function(...e){return WA._create("startAfter",e,!1)}(...e)))}catch(e){throw ON(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new VN(this.firestore,jA(this._delegate,function(...e){return HA._create("endBefore",e,!1)}(...e)))}catch(e){throw ON(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new VN(this.firestore,jA(this._delegate,function(...e){return HA._create("endAt",e,!0)}(...e)))}catch(e){throw ON(e,"endAt()","Query.endAt()")}}isEqual(e){return BS(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?uN:"server"===(null==e?void 0:e.source)?function(t){t=PS(t,MS);const n=PS(t.firestore,JS),e=XS(n),r=new cN(n);return IS(e,t._query,{source:"server"}).then(e=>new aN(n,r,t,e))}:function(t){t=PS(t,MS);const n=PS(t.firestore,JS),e=XS(n),r=new cN(n);return VA(t._query),IS(e,t._query).then(e=>new aN(n,r,t,e))})(this._delegate),t.then(e=>new BN(this.firestore,new aN(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=MN(e),n=LN(e,e=>new BN(this.firestore,new aN(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return pN(this._delegate,t,n)}withConverter(e){return new VN(this.firestore,e?this._delegate.withConverter(DN.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class qN{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new UN(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class BN{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new VN(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new UN(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new qN(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new UN(this._firestore,e))})}isEqual(e){return oN(this._delegate,e._delegate)}}class jN extends VN{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new xN(this.firestore,e):null}doc(e){try{return void 0===e?new xN(this.firestore,VS(this._delegate)):new xN(this.firestore,VS(this._delegate,e))}catch(e){throw ON(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=PS(e.firestore,JS),r=VS(e),i=tN(e.converter,t);return gN(n,[vA(mA(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,fT.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new xN(this.firestore,e))}isEqual(e){return qS(this._delegate,e._delegate)}withConverter(e){return new jN(this.firestore,e?this._delegate.withConverter(DN.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function zN(e){return PS(e,LS)}const $N={Firestore:AN,GeoPoint:lA,Timestamp:tw,Blob:CN,Transaction:RN,WriteBatch:PN,DocumentReference:xN,DocumentSnapshot:FN,Query:VN,QueryDocumentSnapshot:UN,QuerySnapshot:BN,CollectionReference:jN,FieldPath:class Z1{constructor(...e){this._delegate=new oA(...e)}static documentId(){return new Z1(aw.keyField().canonicalString())}isEqual(e){return(e=oe(e))instanceof oA&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class eO{constructor(e){this._delegate=e}static serverTimestamp(){const e=new wA("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new eO(e)}static delete(){const e=new _A("deleteField");return e._methodName="FieldValue.delete",new eO(e)}static arrayUnion(...e){const t=function(...e){return new bA("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new eO(t)}static arrayRemove(...e){const t=function(...e){return new IA("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new eO(t)}static increment(e){const t=new TA("increment",e);return t._methodName="FieldValue.increment",new eO(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,Dy.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};WS=bt,HS=(e,t)=>new AN(e,t,new SN),WS.INTERNAL.registerComponent(new ce("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return HS(t,n)},"PUBLIC").setServiceProps(Object.assign({},$N))),WS.registerVersion("@firebase/firestore-compat","0.3.17");const KN="type.googleapis.com/google.protobuf.Int64Value",GN="type.googleapis.com/google.protobuf.UInt64Value";function WN(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function HN(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case KN:case GN:var t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t;default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(e=>HN(e)):"function"==typeof e||"object"==typeof e?WN(e,e=>HN(e)):e}const QN="functions",YN={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class JN extends P{constructor(e,t,n){super(`${QN}/${e}`,t||""),this.details=n}}function XN(e,t){let n=function(e){if(200<=e&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),r=n,i=void 0;try{var s=t&&t.error;if(s){const e=s.status;if("string"==typeof e){if(!YN[e])return new JN("internal","internal");n=YN[e],r=e}var a=s.message;"string"==typeof a&&(r=a),i=s.details,void 0!==i&&(i=HN(i))}}catch(e){}return"ok"===n?null:new JN(n,r,i)}class ZN{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then(e=>this.auth=e,()=>{}),this.messaging||t.get().then(e=>this.messaging=e,()=>{}),this.appCheck||n.get().then(e=>this.appCheck=e,()=>{})}async getAuthToken(){if(this.auth)try{var e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return this.messaging.getToken()}catch(e){return}}async getAppCheckToken(e){if(this.appCheck){var t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}const eR="us-central1";class tR{constructor(e,t,n,r,i=eR,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new ZN(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var a=new URL(i);this.customDomain=a.origin,this.region=eR}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){var t=this.app.options.projectId;return null===this.emulatorOrigin?null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`:`${this.emulatorOrigin}/${t}/${this.region}/${e}`}}function nR(i,s,a){return e=>{return t=e,n=a||{},r=(e=i)._url(s),rR(e,r,t,n);var t,n,r}}async function rR(e,t,n,r){var i={data:n=function t(e){if(null==e)return null;if("number"==typeof(e=e instanceof Number?e.valueOf():e)&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>t(e));if("function"==typeof e||"object"==typeof e)return WN(e,e=>t(e));throw new Error("Data cannot be encoded in JSON: "+e)}(n)};const s={};var a=await e.contextProvider.getContext(r.limitedUseAppCheckTokens);a.authToken&&(s.Authorization="Bearer "+a.authToken),a.messagingToken&&(s["Firebase-Instance-ID-Token"]=a.messagingToken),null!==a.appCheckToken&&(s["X-Firebase-AppCheck"]=a.appCheckToken);const o=function(n){let r=null;return{promise:new Promise((e,t)=>{r=setTimeout(()=>{t(new JN("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{r&&clearTimeout(r)}}}(r.timeout||7e4);a=await Promise.race([async function(e,t,n,r){n["Content-Type"]="application/json";let i;try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}}(t,i,s,e.fetchImpl),o.promise,e.cancelAllRequests]);if(o.cancel(),!a)throw new JN("cancelled","Firebase Functions instance was deleted.");i=XN(a.status,a.json);if(i)throw i;if(!a.json)throw new JN("internal","Response is not valid JSON object.");let c=a.json.data;if(void 0===c&&(c=a.json.result),void 0===c)throw new JN("internal","Response is missing data field.");return{data:HN(c)}}const iR="@firebase/functions";function sR(e,t,n){oe(e).emulatorOrigin=`http://${t}:${n}`}function aR(e,t,n){return r=oe(e),i=t,s=n,e=>rR(r,i,e,s||{});var r,i,s}QS=fetch.bind(self),We(new ce(QN,(e,{instanceIdentifier:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new tR(n,r,i,s,t,QS)},"PUBLIC").setMultipleInstances(!0)),tt(iR,"0.10.0",YS),tt(iR,"0.10.0","esm2017");var oR,cR,lR,uR,hR;class dR{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return nR(oe(this._delegate),e,t)}httpsCallableFromURL(e,t){return aR(this._delegate,e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new P("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new P("functions","Port missing in origin provided to useFunctionsEmulator()");return sR(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return sR(this._delegate,e,t)}}const pR="us-central1",fR=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:pR});return new dR(n,r)};oR={Functions:dR},bt.INTERNAL.registerComponent(new ce("functions-compat",fR,"PUBLIC").setServiceProps(oR).setMultipleInstances(!0)),bt.registerVersion("@firebase/functions-compat","0.3.5");const gR="/firebase-messaging-sw.js",mR="/firebase-cloud-messaging-push-scope",vR="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",_R="https://fcmregistrations.googleapis.com/v1",yR="google.c.a.c_id",wR="google.c.a.e";function bR(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(cR=Mx=Mx||{})[cR.DATA_MESSAGE=1]="DATA_MESSAGE",cR[cR.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(sl=lR=lR||{}).PUSH_RECEIVED="push-received",sl.NOTIFICATION_CLICKED="notification-clicked";const IR="fcm_token_details_db",TR="fcm_token_object_Store";async function ER(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(IR))return null}let l=null;const e=await Pe(IR,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(TR)){const o=r.objectStore(TR);var s,a=await o.index("fcmSenderId").get(c);await o.clear(),a&&(2===t?(s=a).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:bR(s.vapidKey)}}):3===t?(s=a,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:bR(s.auth),p256dh:bR(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:bR(s.vapidKey)}}):4===t&&(a=a,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:bR(a.auth),p256dh:bR(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:bR(a.vapidKey)}}))}}});return e.close(),await De(IR),await De("fcm_vapid_details_db"),await De("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(l)?l:null}const CR="firebase-messaging-database",kR=1,SR="firebase-messaging-store";let AR=null;function NR(){return AR=AR||Pe(CR,kR,{upgrade:(e,t)=>{0===t&&e.createObjectStore(SR)}}),AR}async function RR(e){var t=DR(e);const n=await NR();t=await n.transaction(SR).objectStore(SR).get(t);if(t)return t;t=await ER(e.appConfig.senderId);return t?(await PR(e,t),t):void 0}async function PR(e,t){var n=DR(e);const r=await NR(),i=r.transaction(SR,"readwrite");return await i.objectStore(SR).put(t,n),await i.done,t}function DR({appConfig:e}){return e.appId}const xR=new D("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function OR(e,t){var n={method:"DELETE",headers:await LR(e)};try{const s=await fetch(`${MR(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw xR.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw xR.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function MR({projectId:e}){return`${_R}/projects/${e}/registrations`}async function LR({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function FR({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==vR&&(i.web.applicationPubKey=r),i}const UR=6048e5;async function VR(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,a,o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:bR(t.getKey("auth")),p256dh:bR(t.getKey("p256dh"))},c=await RR(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=o.vapidKey===n.vapidKey,i=o.endpoint===n.endpoint,s=o.auth===n.auth,a=o.p256dh===n.p256dh,r&&i&&s&&a)return Date.now()>=c.createTime+UR?async function(t,e){try{var n=await async function(e,t){var n=await LR(e),r=FR(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${MR(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw xR.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw xR.create("token-update-failed",{errorInfo:r})}if(!i.token)throw xR.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await PR(t.firebaseDependencies,r),n}catch(e){throw await qR(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await OR(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return BR(e.firebaseDependencies,o)}return BR(e.firebaseDependencies,o)}async function qR(e){var t=await RR(e.firebaseDependencies);t&&(await OR(e.firebaseDependencies,t.token),await async function(e){var t=DR(e);const n=await NR(),r=n.transaction(SR,"readwrite");await r.objectStore(SR).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function BR(e,t){var n={token:await async function(e,t){var n=await LR(e),r=FR(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(MR(e.appConfig),r);i=await s.json()}catch(e){throw xR.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw xR.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw xR.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await PR(e,n),n.token}function jR(e){var t,n,r,i,s,a={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return r=a,(n=e).notification&&(r.notification={},(t=n.notification.title)&&(r.notification.title=t),(t=n.notification.body)&&(r.notification.body=t),(t=n.notification.image)&&(r.notification.image=t),(t=n.notification.icon)&&(r.notification.icon=t)),n=a,(r=e).data&&(n.data=r.data),r=a,((e=e).fcmOptions||null!==(i=e.notification)&&void 0!==i&&i.click_action)&&(r.fcmOptions={},(s=null!==(i=null===(i=e.fcmOptions)||void 0===i?void 0:i.link)&&void 0!==i?i:null===(s=e.notification)||void 0===s?void 0:s.click_action)&&(r.fcmOptions.link=s),(s=null===(s=e.fcmOptions)||void 0===s?void 0:s.analytics_label)&&(r.fcmOptions.analyticsLabel=s)),a}function zR(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}function $R(e){return xR.create("missing-app-config-values",{valueName:e})}zR("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),zR("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class KR{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw $R("App Configuration Object");if(!e.name)throw $R("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw $R(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}async function GR(e){try{e.swRegistration=await navigator.serviceWorker.register(gR,{scope:mR}),e.swRegistration.update().catch(()=>{})}catch(e){throw xR.create("failed-service-worker-registration",{browserErrorMessage:null==e?void 0:e.message})}}async function WR(e,t){if(!navigator)throw xR.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw xR.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=vR)),await async function(e,t){if(t||e.swRegistration||await GR(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw xR.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),VR(e)}async function HR(e,t,n){var r=function(e){switch(e){case lR.NOTIFICATION_CLICKED:return"notification_open";case lR.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[yR],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}async function QR(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===lR.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(jR(r)):e.onMessageHandler.next(jR(r))),n=r.data,"object"==typeof(t=n)&&t&&yR in t&&"1"===n[wR]&&await HR(e,r.messageType,n))}const YR="@firebase/messaging",JR=e=>{const t=new KR(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>QR(t,e)),t},XR=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>WR(t,e)}};function ZR(e){return async function(e){if(!navigator)throw xR.create("only-available-in-window");return e.swRegistration||await GR(e),qR(e)}(e=oe(e))}function eP(e,t){return function(e,t){if(!navigator)throw xR.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=oe(e),t)}We(new ce("messaging",JR,"PUBLIC")),We(new ce("messaging-internal",XR,"PRIVATE")),tt(YR,"0.12.4"),tt(YR,"0.12.4","esm2017");const tP="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",nP="https://fcmregistrations.googleapis.com/v1",rP="FCM_MSG",iP="google.c.a.c_id",sP=3,aP=1;function oP(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(sl=uR=uR||{})[sl.DATA_MESSAGE=1]="DATA_MESSAGE",sl[sl.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(sl=hR=hR||{}).PUSH_RECEIVED="push-received",sl.NOTIFICATION_CLICKED="notification-clicked";const cP="fcm_token_details_db",lP="fcm_token_object_Store";async function uP(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(cP))return null}let l=null;const e=await Pe(cP,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(lP)){const o=r.objectStore(lP);var s,a=await o.index("fcmSenderId").get(c);await o.clear(),a&&(2===t?(s=a).auth&&s.p256dh&&s.endpoint&&(l={token:s.fcmToken,createTime:null!==(i=s.createTime)&&void 0!==i?i:Date.now(),subscriptionOptions:{auth:s.auth,p256dh:s.p256dh,endpoint:s.endpoint,swScope:s.swScope,vapidKey:"string"==typeof s.vapidKey?s.vapidKey:oP(s.vapidKey)}}):3===t?(s=a,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:oP(s.auth),p256dh:oP(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:oP(s.vapidKey)}}):4===t&&(a=a,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:oP(a.auth),p256dh:oP(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:oP(a.vapidKey)}}))}}});return e.close(),await De(cP),await De("fcm_vapid_details_db"),await De("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(l)?l:null}const hP="firebase-messaging-database",dP=1,pP="firebase-messaging-store";let fP=null;function gP(){return fP=fP||Pe(hP,dP,{upgrade:(e,t)=>{0===t&&e.createObjectStore(pP)}}),fP}async function mP(e){var t=_P(e);const n=await gP();t=await n.transaction(pP).objectStore(pP).get(t);if(t)return t;t=await uP(e.appConfig.senderId);return t?(await vP(e,t),t):void 0}async function vP(e,t){var n=_P(e);const r=await gP(),i=r.transaction(pP,"readwrite");return await i.objectStore(pP).put(t,n),await i.done,t}function _P({appConfig:e}){return e.appId}const yP=new D("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function wP(e,t){var n={method:"DELETE",headers:await IP(e)};try{const s=await fetch(`${bP(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw yP.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw yP.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function bP({projectId:e}){return`${nP}/projects/${e}/registrations`}async function IP({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function TP({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==tP&&(i.web.applicationPubKey=r),i}async function EP(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,a,o={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:oP(t.getKey("auth")),p256dh:oP(t.getKey("p256dh"))},c=await mP(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=o.vapidKey===n.vapidKey,i=o.endpoint===n.endpoint,s=o.auth===n.auth,a=o.p256dh===n.p256dh,r&&i&&s&&a)return Date.now()>=c.createTime+6048e5?async function(t,e){try{var n=await async function(e,t){var n=await IP(e),r=TP(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${bP(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw yP.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw yP.create("token-update-failed",{errorInfo:r})}if(!i.token)throw yP.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await vP(t.firebaseDependencies,r),n}catch(e){throw await CP(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await wP(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return kP(e.firebaseDependencies,o)}return kP(e.firebaseDependencies,o)}async function CP(e){var t=await mP(e.firebaseDependencies);t&&(await wP(e.firebaseDependencies,t.token),await async function(e){var t=_P(e);const n=await gP(),r=n.transaction(pP,"readwrite");await r.objectStore(pP).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function kP(e,t){var n={token:await async function(e,t){var n=await IP(e),r=TP(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(bP(e.appConfig),r);i=await s.json()}catch(e){throw yP.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw yP.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw yP.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await vP(e,n),n.token}async function SP(e,t){var n=function(e,t){var n;const r={};e.from&&(r.project_number=e.from);e.fcmMessageId&&(r.message_id=e.fcmMessageId);r.instance_id=t,e.notification?r.message_type=uR.DISPLAY_NOTIFICATION.toString():r.message_type=uR.DATA_MESSAGE.toString();r.sdk_platform=sP.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=aP.toString(),null!==(n=e.fcmOptions)&&void 0!==n&&n.analytics_label&&(r.analytics_label=null===(n=e.fcmOptions)||void 0===n?void 0:n.analytics_label);return r}(t,await e.firebaseDependencies.installations.getId());!function(e,t){const n={};n.event_time_ms=Math.floor(Date.now()).toString(),n.source_extension_json_proto3=JSON.stringify(t),e.logEvents.push(n)}(e,n)}function AP(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}async function NP(e,t){var n=function({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(n){t.deliveryMetricsExportedToBigQueryEnabled&&await SP(t,n);var r,i,s,a,o=await PP();if(o.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=hR.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(o,n);n.notification&&await function(e){var t=e["actions"],n=Notification["maxActions"];t&&n&&t.length>n&&console.warn(`This browser only supports ${n} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(null!==(n=e.title)&&void 0!==n?n:"",e)}(function(e){const t=Object.assign({},e.notification);return t.data={[rP]:e},t}(n)),t&&t.onBackgroundMessageHandler&&(a={from:(r=n).from,collapseKey:r.collapse_key,messageId:r.fcmMessageId},o=a,(e=r).notification&&(o.notification={},(n=e.notification.title)&&(o.notification.title=n),(n=e.notification.body)&&(o.notification.body=n),(n=e.notification.image)&&(o.notification.image=n),(n=e.notification.icon)&&(o.notification.icon=n)),e=a,(o=r).data&&(e.data=o.data),o=a,((r=r).fcmOptions||null!==(i=r.notification)&&void 0!==i&&i.click_action)&&(o.fcmOptions={},(s=null!==(i=null===(i=r.fcmOptions)||void 0===i?void 0:i.link)&&void 0!==i?i:null===(s=r.notification)||void 0===s?void 0:s.click_action)&&(o.fcmOptions.link=s),(s=null===(s=r.fcmOptions)||void 0===s?void 0:s.analytics_label)&&(o.fcmOptions.analyticsLabel=s)),a=a,"function"==typeof t.onBackgroundMessageHandler?await t.onBackgroundMessageHandler(a):t.onBackgroundMessageHandler.next(a))}}async function RP(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[rP];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var n=function(e){var t;var n=null!==(t=null===(t=e.fcmOptions)||void 0===t?void 0:t.link)&&void 0!==t?t:null===(n=e.notification)||void 0===n?void 0:n.click_action;if(n)return n;return function(e){return"object"==typeof e&&e&&iP in e}(e.data)?self.location.origin:null}(t);if(n){var r,i=new URL(n,self.location.href),s=new URL(self.location.origin);if(i.host===s.host){let e=await async function(e){var t=await PP();for(const r of t){var n=new URL(r.url,self.location.href);if(e.host===n.host)return r}return null}(i);if(e?e=await e.focus():(e=await self.clients.openWindow(n),r=3e3,await new Promise(e=>{setTimeout(e,r)})),e)return t.messageType=hR.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function PP(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function DP(e){return yP.create("missing-app-config-values",{valueName:e})}AP("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),AP("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class xP{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw DP("App Configuration Object");if(!e.name)throw DP("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw DP(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}const OP=e=>{const t=new xP(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(NP(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await mP(t.firebaseDependencies),await CP(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:tP,await EP(t)):await CP(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(RP(e))}),t};function MP(e,t){return function(e,t){if(void 0!==self.document)throw yP.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=oe(e),t)}We(new ce("messaging-sw",OP,"PUBLIC"));var LP,FP,UP,VP;class qP{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return WR(e=oe(e),t)}(this._delegate,e)}async deleteToken(){return ZR(this._delegate)}onMessage(e){return eP(this._delegate,e)}onBackgroundMessage(e){return MP(this._delegate,e)}}const BP=e=>self&&"ServiceWorkerGlobalScope"in self?new qP(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new qP(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),jP={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?A()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&A()&&R()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};bt.INTERNAL.registerComponent(new ce("messaging-compat",BP,"PUBLIC").setServiceProps(jP)),bt.registerVersion("@firebase/messaging-compat","0.2.4");const zP="firebasestorage.googleapis.com",$P="storageBucket";class KP extends P{constructor(e,t,n=0){super(GP(e),`Firebase Storage: ${t} (${GP(e)})`),this.status_=n,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,KP.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return GP(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}function GP(e){return"storage/"+e}function WP(){return new KP(LP.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function HP(){return new KP(LP.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function QP(){return new KP(LP.CANCELED,"User canceled the upload/download.")}function YP(){return new KP(LP.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function JP(e){return new KP(LP.INVALID_ARGUMENT,e)}function XP(){return new KP(LP.APP_DELETED,"The Firebase app was deleted.")}function ZP(e){return new KP(LP.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function eD(e,t){return new KP(LP.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function tD(e){throw new KP(LP.INTERNAL_ERROR,"Internal error: "+e)}(Tt=LP=LP||{}).UNKNOWN="unknown",Tt.OBJECT_NOT_FOUND="object-not-found",Tt.BUCKET_NOT_FOUND="bucket-not-found",Tt.PROJECT_NOT_FOUND="project-not-found",Tt.QUOTA_EXCEEDED="quota-exceeded",Tt.UNAUTHENTICATED="unauthenticated",Tt.UNAUTHORIZED="unauthorized",Tt.UNAUTHORIZED_APP="unauthorized-app",Tt.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",Tt.INVALID_CHECKSUM="invalid-checksum",Tt.CANCELED="canceled",Tt.INVALID_EVENT_NAME="invalid-event-name",Tt.INVALID_URL="invalid-url",Tt.INVALID_DEFAULT_BUCKET="invalid-default-bucket",Tt.NO_DEFAULT_BUCKET="no-default-bucket",Tt.CANNOT_SLICE_BLOB="cannot-slice-blob",Tt.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",Tt.NO_DOWNLOAD_URL="no-download-url",Tt.INVALID_ARGUMENT="invalid-argument",Tt.INVALID_ARGUMENT_COUNT="invalid-argument-count",Tt.APP_DELETED="app-deleted",Tt.INVALID_ROOT_OPERATION="invalid-root-operation",Tt.INVALID_FORMAT="invalid-format",Tt.INTERNAL_ERROR="internal-error",Tt.UNSUPPORTED_ENVIRONMENT="unsupported-environment";class nD{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let n;try{n=nD.makeFromUrl(t,e)}catch(e){return new nD(t,"")}if(""===n.path)return n;throw t=t,new KP(LP.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+t+"'.")}static makeFromUrl(e,t){let n=null;var r="([A-Za-z0-9.\\-_]+)";var i=new RegExp("^gs://"+r+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}var a=t.replace(/[.]/g,"\\."),o=new RegExp(`^https?://${a}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),a=t===zP?"(?:storage.googleapis.com|storage.cloud.google.com)":t,c=[{regex:i,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:o,indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${a}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let h=0;h<c.length;h++){const d=c[h];var l=d.regex.exec(e);if(l){var u=l[d.indices.bucket];let e=l[d.indices.path];e=e||"",n=new nD(u,e),d.postModify(n);break}}if(null==n)throw t=e,new KP(LP.INVALID_URL,"Invalid URL '"+t+"'.");return n}}class rD{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function iD(e){return"string"==typeof e||e instanceof String}function sD(e){return aD()&&e instanceof Blob}function aD(){return"undefined"!=typeof Blob&&!T()}function oD(e,t,n,r){if(r<t)throw JP(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw JP(`Invalid value for '${e}'. Expected ${n} or less.`)}function cD(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function lD(e){const t=encodeURIComponent;let n="?";for(const i in e){var r;e.hasOwnProperty(i)&&(r=t(i)+"="+t(e[i]),n=n+r+"&")}return n=n.slice(0,-1),n}function uD(e,t){var n=500<=e&&e<600,r=-1!==[408,429].indexOf(e),i=-1!==t.indexOf(e);return n||r||i}(Tt=FP=FP||{})[Tt.NO_ERROR=0]="NO_ERROR",Tt[Tt.NETWORK_ERROR=1]="NETWORK_ERROR",Tt[Tt.ABORT=2]="ABORT";class hD{constructor(e,t,n,r,i,s,a,o,c,l,u,h=!0){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=a,this.errorCallback_=o,this.timeout_=c,this.progressCallback_=l,this.connectionFactory_=u,this.retry=h,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()})}start_(){var e=(n,e)=>{if(e)n(!1,new dD(!1,null,!0));else{const r=this.connectionFactory_();this.pendingConnection_=r;const i=e=>{var t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&r.addUploadProgressListener(i),r.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&r.removeUploadProgressListener(i),this.pendingConnection_=null;var e=r.getErrorCode()===FP.NO_ERROR,t=r.getStatus();!e||uD(t,this.additionalRetryCodes_)&&this.retry?(e=r.getErrorCode()===FP.ABORT,n(!1,new dD(!1,null,e))):(t=-1!==this.successCodes_.indexOf(t),n(!0,new dD(t,r)))})}},t=(e,t)=>{const n=this.resolve_,r=this.reject_,i=t.connection;if(t.wasSuccessCode)try{var s=this.callback_(i,i.getResponse());void 0!==s?n(s):n()}catch(e){r(e)}else if(null!==i){const o=WP();o.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,o)):r(o)}else{var a;t.canceled?(a=(this.appDelete_?XP:QP)(),r(a)):(a=HP(),r(a))}};this.canceled_?t(0,new dD(!1,null,!0)):this.backoffId_=function(t,n,e){let r=1,i=null,s=null,a=!1,o=0;function c(){return 2===o}let l=!1;function u(...e){l||(l=!0,n.apply(null,e))}function h(e){i=setTimeout(()=>{i=null,t(p,c())},e)}function d(){s&&clearTimeout(s)}function p(t,...n){if(l)d();else{if(t)return d(),void u.call(null,t,...n);if(c()||a)return d(),void u.call(null,t,...n);r<64&&(r*=2);let e;e=1===o?(o=2,0):1e3*(r+Math.random()),h(e)}}let f=!1;function g(e){f||(f=!0,d(),l||(null!==i?(e||(o=2),clearTimeout(i),h(0)):e||(o=1)))}return h(0),s=setTimeout(()=>{g(a=!0)},e),g}(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}}class dD{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function pD(...t){const n="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==n){const r=new n;for(let e=0;e<t.length;e++)r.append(t[e]);return r.getBlob()}if(aD())return new Blob(t);throw new KP(LP.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function fD(e){if("undefined"==typeof atob)throw new KP(LP.UNSUPPORTED_ENVIRONMENT,"base-64 is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.");return atob(e)}const gD={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class mD{constructor(e,t){this.data=e,this.contentType=t||null}}function vD(e,t){switch(e){case gD.RAW:return new mD(_D(t));case gD.BASE64:case gD.BASE64URL:return new mD(yD(e,t));case gD.DATA_URL:return new mD((n=t,(r=new wD(n)).base64?yD(gD.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw eD(gD.DATA_URL,"Malformed data URL.")}return _D(t)}(r.rest)),(n=t,new wD(n).contentType))}var n,r;throw WP()}function _D(t){const n=[];for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);var r,i;e<=127?n.push(e):e<=2047?n.push(192|e>>6,128|63&e):55296==(64512&e)?s<t.length-1&&56320==(64512&t.charCodeAt(s+1))?(r=e,i=t.charCodeAt(++s),e=65536|(1023&r)<<10|1023&i,n.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):n.push(239,191,189):56320==(64512&e)?n.push(239,191,189):n.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(n)}function yD(t,e){switch(t){case gD.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw eD(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case gD.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw eD(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=fD(e)}catch(e){if(e.message.includes("polyfill"))throw e;throw eD(t,"Invalid character found")}const s=new Uint8Array(i.length);for(let a=0;a<i.length;a++)s[a]=i.charCodeAt(a);return s}class wD{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw eD(gD.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const i=r[1]||null;null!=i&&(this.base64=(t=i,n=";base64",t.length>=n.length&&t.substring(t.length-n.length)===n),this.contentType=this.base64?i.substring(0,i.length-";base64".length):i),this.rest=e.substring(e.indexOf(",")+1)}}class bD{constructor(e,t){let n=0,r="";sD(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(sD(this.data_)){var n=this.data_,n=(i=e,s=t,(r=n).webkitSlice?r.webkitSlice(i,s):r.mozSlice?r.mozSlice(i,s):r.slice?r.slice(i,s):null);return null===n?null:new bD(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new bD(n,!0)}static getBlob(...e){if(aD()){var t=e.map(e=>e instanceof bD?e.data_:e);return new bD(pD.apply(null,t))}{const r=e.map(e=>iD(e)?vD(gD.RAW,e).data:e.data_);let t=0;r.forEach(e=>{t+=e.byteLength});const i=new Uint8Array(t);let n=0;return r.forEach(e=>{for(let t=0;t<e.length;t++)i[n++]=e[t]}),new bD(i,!0)}}uploadData(){return this.data_}}function ID(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function TD(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function ED(e,t){return t}class CD{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||ED}}let kD=null;function SD(){if(kD)return kD;const e=[];e.push(new CD("bucket")),e.push(new CD("generation")),e.push(new CD("metageneration")),e.push(new CD("name","fullPath",!0));const t=new CD("name");t.xform=function(e,t){return!iD(t=t)||t.length<2?t:TD(t)},e.push(t);const n=new CD("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new CD("timeCreated")),e.push(new CD("updated")),e.push(new CD("md5Hash",null,!0)),e.push(new CD("cacheControl",null,!0)),e.push(new CD("contentDisposition",null,!0)),e.push(new CD("contentEncoding",null,!0)),e.push(new CD("contentLanguage",null,!0)),e.push(new CD("contentType",null,!0)),e.push(new CD("metadata","customMetadata",!0)),kD=e,kD}function AD(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new nD(e,t);return r._makeStorageReference(t)}})}function ND(e,t,n){var r=ID(t);return null===r?null:function(e,t,n){const r={type:"file"};var i=n.length;for(let s=0;s<i;s++){const a=n[s];r[a.local]=a.xform(r,t[a.server])}return AD(r,e),r}(e,r,n)}function RD(e,t){const n={};var r=t.length;for(let s=0;s<r;s++){var i=t[s];i.writable&&(n[i.server]=e[i.local])}return JSON.stringify(n)}const PD="prefixes";function DD(e,t,n){var r=ID(n);return null===r?null:function(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n[PD])for(const a of n[PD]){var i=a.replace(/\/$/,""),i=e._makeStorageReference(new nD(t,i));r.prefixes.push(i)}if(n.items)for(const o of n.items){var s=e._makeStorageReference(new nD(t,o.name));r.items.push(s)}return r}(e,t,r)}class xD{constructor(e,t,n,r){this.url=e,this.method=t,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function OD(e){if(!e)throw WP()}function MD(r,i){return function(e,t){var n=ND(r,t,i);return OD(null!==n),n}}function LD(r,i){return function(e,t){var n=DD(r,i,t);return OD(null!==n),n}}function FD(r,i){return function(e,t){var n=ND(r,t,i);return OD(null!==n),function(r,e,i,s){var t=ID(e);if(null===t)return null;if(!iD(t.downloadTokens))return null;const n=t.downloadTokens;if(0===n.length)return null;const a=encodeURIComponent,o=n.split(",");return o.map(e=>{var t=r.bucket,n=r.fullPath;return cD("/b/"+a(t)+"/o/"+a(n),i,s)+lD({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function UD(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new KP(LP.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project."):new KP(LP.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new KP(LP.QUOTA_EXCEEDED,"Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(r=i.path,new KP(LP.UNAUTHORIZED,"User does not have permission to access '"+r+"'.")):t,n.status=e.getStatus(),n.serverResponse=t.serverResponse,n}}function VD(r){const i=UD(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new KP(LP.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function qD(e,t,n){var r=cD(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new xD(r,"GET",MD(e,n),i);return s.errorHandler=VD(t),s}function BD(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=(e=t,(t=null)&&t.contentType||e&&e.type()||"application/octet-stream")),r}function jD(e,t,n,r,i){var s=t.bucketOnlyServerUrl();const a={"X-Goog-Upload-Protocol":"multipart"};var o=function(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();a["Content-Type"]="multipart/related; boundary="+o;var c=BD(t,r,i),l="--"+o+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+RD(c,n)+"\r\n--"+o+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",o="\r\n--"+o+"--";const u=bD.getBlob(l,r,o);if(null===u)throw YP();o={name:c.fullPath},c=cD(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new xD(c,"POST",MD(e,n),s);return h.urlParams=o,h.headers=a,h.body=u.uploadData(),h.errorHandler=UD(t),h}class zD{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function $D(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){OD(!1)}const r=t||["active"];return OD(!!n&&-1!==r.indexOf(n)),n}function KD(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),a=BD(t,r,i),o={name:a.fullPath},c=cD(s,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":a.contentType,"Content-Type":"application/json; charset=utf-8"},s=RD(a,n),a=e.maxUploadRetryTime;const u=new xD(c,"POST",function(e){$D(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){OD(!1)}return OD(iD(t)),t},a);return u.urlParams=o,u.headers=l,u.body=s,u.errorHandler=UD(t),u}function GD(e,t,n,i){var r=e.maxUploadRetryTime;const s=new xD(n,"POST",function(e){var t=$D(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){OD(!1)}n||OD(!1);var r=Number(n);return OD(!isNaN(r)),new zD(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=UD(t),s}function WD(e,a,t,o,n,c,r,i){const l=new zD(0,0);if(r?(l.current=r.current,l.total=r.total):(l.current=0,l.total=o.size()),o.size()!==l.total)throw new KP(LP.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");var s=l.total-l.current;let u=s;0<n&&(u=Math.min(u,n));var h=l.current,d=h+u;let p="";p=0===u?"finalize":s===u?"upload, finalize":"upload";s={"X-Goog-Upload-Command":p,"X-Goog-Upload-Offset":`${l.current}`};const f=o.slice(h,d);if(null===f)throw YP();d=a.maxUploadRetryTime;const g=new xD(t,"POST",function(e,t){var n=$D(e,["active","final"]),r=l.current+u,i=o.size();let s;return s="final"===n?MD(a,c)(e,t):null,new zD(r,i,"final"===n,s)},d);return g.headers=s,g.body=f.uploadData(),g.progressCallback=i||null,g.errorHandler=UD(e),g}const HD={STATE_CHANGED:"state_changed"},QD={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function YD(e){switch(e){case"running":case"pausing":case"canceling":return QD.RUNNING;case"paused":return QD.PAUSED;case"success":return QD.SUCCESS;case"canceled":return QD.CANCELED;default:return QD.ERROR}}class JD{constructor(e,t,n){var r;"function"==typeof e||null!=t||null!=n?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0):(this.next=(r=e).next,this.error=r.error,this.complete=r.complete)}}function XD(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class ZD extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=FP.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=FP.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=FP.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw tD("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const i in r)r.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,r[i].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw tD("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw tD("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw tD("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw tD("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}{initXhr(){this.xhr_.responseType="text"}}function ex(){return new ZD}class tx{constructor(e,t,n=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=n,this._mappings=SD(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(LP.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{var t=this.isExponentialBackoffExpired();if(uD(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=HP()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(LP.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t,this._start()}),this._promise.then(null,()=>{})}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){const t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(n){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":n(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var n=KD(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,ex,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const i=this._uploadUrl;this._resolveToken((e,t)=>{var n=GD(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,ex,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){const i=262144*this._chunkMultiplier,s=new zD(this._transferred,this._blob.size()),a=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=WD(this._ref._location,this._ref.storage,a,this._blob,i,this._mappings,s,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const r=this._ref.storage._makeRequest(n,ex,e,t,!1);this._request=r,r.getPromise().then(e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){2*(262144*this._chunkMultiplier)<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{var n=qD(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,ex,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var n=jD(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,ex,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=QP(),this._state=e,this._notifyObservers();break;case"error":case"success":this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){var e=YD(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const i=new JD(t||void 0,n||void 0,r||void 0);return this._addObserver(i),()=>{this._removeObserver(i)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){var t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();const e=this._observers.slice();e.forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(YD(this._state)){case QD.SUCCESS:XD(this._resolve.bind(null,this.snapshot))();break;case QD.CANCELED:case QD.ERROR:const t=this._reject;XD(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(YD(this._state)){case QD.RUNNING:case QD.PAUSED:e.next&&XD(e.next.bind(e,this.snapshot))();break;case QD.SUCCESS:e.complete&&XD(e.complete.bind(e))();break;case QD.CANCELED:case QD.ERROR:default:e.error&&XD(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class nx{constructor(e,t){this._service=e,t instanceof nD?this._location=t:this._location=nD.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new nx(e,t)}get root(){var e=new nD(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return TD(this._location.path)}get storage(){return this._service}get parent(){var e=function(e){if(0===e.length)return null;var t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;e=new nD(this._location.bucket,e);return new nx(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw ZP(e)}}function rx(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await ix(t,i);n.prefixes.push(...s.prefixes);n.items.push(...s.items);null!=s.nextPageToken&&await e(t,n,s.nextPageToken)}(e,t).then(()=>t)}function ix(e,t){null!=t&&"number"==typeof t.maxResults&&oD("options.maxResults",1,1e3,t.maxResults);var n=t||{},n=function(e,t,n,r,i){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&0<n.length&&(s.delimiter=n),r&&(s.pageToken=r),i&&(s.maxResults=i);var a=cD(t.bucketOnlyServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime;const c=new xD(a,"GET",LD(e,t.bucket),o);return c.urlParams=s,c.errorHandler=UD(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,ex)}function sx(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=cD(t.fullServerUrl(),e.host,e._protocol),s=RD(n,r),a=e.maxOperationRetryTime;const o=new xD(i,"PATCH",MD(e,r),a);return o.headers={"Content-Type":"application/json; charset=utf-8"},o.body=s,o.errorHandler=VD(t),o}(e.storage,e._location,t,SD());return e.storage.makeRequestWithTokens(n,ex)}function ax(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=cD(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new xD(r,"GET",FD(e,n),i);return s.errorHandler=VD(t),s}(e.storage,e._location,SD());return e.storage.makeRequestWithTokens(t,ex).then(e=>{if(null===e)throw new KP(LP.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return e})}function ox(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=cD(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new xD(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=VD(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,ex)}function cx(e,t){var n,r=(n=e._location.path,r=t.split("/").filter(e=>0<e.length).join("/"),0===n.length?r:n+"/"+r),r=new nD(e._location.bucket,r);return new nx(e.storage,r)}function lx(e,t){if(e instanceof dx){var n=e;if(null==n._bucket)throw new KP(LP.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+$P+"' property when initializing the app?");n=new nx(n,n._bucket);return null!=t?lx(n,t):n}return void 0!==t?cx(e,t):e}function ux(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof dx)return n=e,r=t,new nx(n,r);throw JP("To use ref(service, url), the first argument must be a Storage instance.")}return lx(e,t);var n,r}function hx(e,t){var n=null==t?void 0:t[$P];return null==n?null:nD.makeFromBucketSpec(n,e)}class dx{constructor(e,t,n,r,i){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=i,this._bucket=null,this._host=zP,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?nD.makeFromBucketSpec(r,this._host):hx(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=nD.makeFromBucketSpec(this._url,e):this._bucket=hx(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){oD("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){oD("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){var t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new nx(this,e)}_makeRequest(e,t,n,r,i=!0){if(this._deleted)return new rD(XP());{const u=([s,a,o,e,n,r,t=!0]=[e,this._appId,n,r,t,this._firebaseVersion,i],c=lD(s.urlParams),l=s.url+c,c=Object.assign({},s.headers),i=c,(a=a)&&(i["X-Firebase-GMPID"]=a),a=c,null!==(o=o)&&0<o.length&&(a.Authorization="Firebase "+o),r=r,c["X-Firebase-Storage-Version"]="webjs/"+(null!=r?r:"AppManager"),r=c,null!==(e=e)&&(r["X-Firebase-AppCheck"]=e),new hD(l,s.method,c,s.body,s.successCodes,s.additionalRetryCodes,s.handler,s.errorHandler,s.timeout,s.progressCallback,n,t));return this._requests.add(u),u.getPromise().then(()=>this._requests.delete(u),()=>this._requests.delete(u)),u}var s,a,o,c,l}async makeRequestWithTokens(e,t){var[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const px="@firebase/storage";function fx(e,t,n){return e=oe(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new tx(e,new bD(t),n)}function gx(e){return function(e){e._throwIfRoot("getMetadata");var t=qD(e.storage,e._location,SD());return e.storage.makeRequestWithTokens(t,ex)}(e=oe(e))}function mx(e,t){return ux(e=oe(e),t)}function vx(e,t,n,r={}){!function(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";var i=r["mockUserToken"];i&&(e._overrideAuthToken="string"==typeof i?i:w(i,e.app.options.projectId))}(e,t,n,r)}function _x(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new dx(n,r,i,t,Je)}We(new ce("storage",_x,"PUBLIC").setMultipleInstances(!0)),tt(px,"0.11.2",""),tt(px,"0.11.2","esm2017");class yx{constructor(e,t,n){this._delegate=e,this.task=t,this.ref=n}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class wx{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new yx(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new yx(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new yx(e,this,this._ref)):{next:t.next?e=>t.next(new yx(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,n||void 0,r||void 0)}}class bx{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new Ix(e,this._service))}get items(){return this._delegate.items.map(e=>new Ix(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class Ix{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=cx(this._delegate,e);return new Ix(t,this.storage)}get root(){return new Ix(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new Ix(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new wx(fx(this._delegate,e,t),this)}putString(e,t=gD.RAW,n){this._throwIfRoot("putString");var r=vD(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new wx(new tx(this._delegate,new bD(r.data,!0),i),this)}listAll(){return rx(oe(this._delegate)).then(e=>new bx(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,ix(t=oe(t),e).then(e=>new bx(e,this.storage));var t}getMetadata(){return gx(this._delegate)}updateMetadata(e){return sx(oe(this._delegate),e)}getDownloadURL(){return ax(oe(this._delegate))}delete(){return this._throwIfRoot("delete"),ox(oe(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw ZP(e)}}class Tx{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(Ex(e))throw JP("ref() expected a child path but got a URL, use refFromURL instead.");return new Ix(mx(this._delegate,e),this)}refFromURL(e){if(!Ex(e))throw JP("refFromURL() expected a full URL but got a child path, use ref() instead.");try{nD.makeFromUrl(e,this._delegate.host)}catch(e){throw JP("refFromUrl() expected a valid full URL but got an invalid one.")}return new Ix(mx(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){vx(this._delegate,e,t,n)}}function Ex(e){return/^[A-Za-z]+:\/\//.test(e)}function Cx(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new Tx(n,r)}UP=bt,VP={TaskState:QD,TaskEvent:HD,StringFormat:gD,Storage:Tx,Reference:Ix},UP.INTERNAL.registerComponent(new ce("storage-compat",Cx,"PUBLIC").setServiceProps(VP).setMultipleInstances(!0)),UP.registerVersion("@firebase/storage-compat","0.3.2");const kx="@firebase/performance",Sx="0.6.4",Ax=Sx,Nx="FB-PERF-TRACE-MEASURE",Rx="@firebase/performance/config",Px="@firebase/performance/configexpire";var Dx,xx,Ox,Mx="Performance";const Lx=new D("performance",Mx,{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"initializePerformance() has already been called with different options. To avoid this error, call initializePerformance() with the same options as when it was originally called, or call getPerformance() to return the already initialized instance."}),Fx=new ve(Mx);Fx.logLevel=m.INFO;let Ux,Vx;class qx{constructor(e){if(!(this.window=e))throw Lx.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)}getEntriesByType(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]}getEntriesByName(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&R()?!!A()||(Fx.info("IndexedDB is not supported by current browser"),!1):(Fx.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,n){if(this.PerformanceObserver){const t=new this.PerformanceObserver(e=>{for(const t of e.getEntries())n(t)});t.observe({entryTypes:[e]})}}static getInstance(){return void 0===Ux&&(Ux=new qx(Vx)),Ux}}let Bx;function jx(e,t){var n=e.length-t.length;if(n<0||1<n)throw Lx.create("invalid String merger input");const r=[];for(let i=0;i<e.length;i++)r.push(e.charAt(i)),t.length>i&&r.push(t.charAt(i));return r.join("")}let zx;class $x{constructor(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=jx("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=jx("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===zx&&(zx=new $x),zx}}(Tt=Dx=Dx||{})[Tt.UNKNOWN=0]="UNKNOWN",Tt[Tt.VISIBLE=1]="VISIBLE",Tt[Tt.HIDDEN=2]="HIDDEN";const Kx=["firebase_","google_","ga_"],Gx=new RegExp("^[a-zA-Z]\\w*$");function Wx(){switch(qx.getInstance().document.visibilityState){case"visible":return Dx.VISIBLE;case"hidden":return Dx.HIDDEN;default:return Dx.UNKNOWN}}function Hx(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw Lx.create("no app id");return t}const Qx="0.0.1",Yx={loggingEnabled:!0},Jx="FIREBASE_INSTALLATIONS_AUTH";function Xx(e,t){var r,i,n=function(){const e=qx.getInstance().localStorage;if(e){var t=e.getItem(Px);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(Rx);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?(e1(n),Promise.resolve()):(i=t,function(e){const t=e.getToken();return t.then(e=>{}),t}((r=e).installations).then(e=>{var t=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.projectId;if(!t)throw Lx.create("no project id");return t}(r.app),n=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.apiKey;if(!t)throw Lx.create("no api key");return t}(r.app),n=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${t}/namespaces/fireperf:fetch?key=${n}`,{method:"POST",headers:{Authorization:`${Jx} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:Hx(r.app),app_version:Ax,sdk_version:Qx})});return fetch(n).then(e=>{if(e.ok)return e.json();throw Lx.create("RC response not ok")})}).catch(()=>{Fx.info(Zx)}).then(e1).then(e=>function(e){const t=qx.getInstance().localStorage;e&&t&&(t.setItem(Rx,JSON.stringify(e)),t.setItem(Px,String(Date.now()+60*$x.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const Zx="Could not fetch config, will use default configs";function e1(e){if(!e)return e;const t=$x.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=Yx.loggingEnabled,n.fpr_log_source?t.logSource=Number(n.fpr_log_source):Yx.logSource&&(t.logSource=Yx.logSource),n.fpr_log_endpoint_url?t.logEndPointUrl=n.fpr_log_endpoint_url:Yx.logEndPointUrl&&(t.logEndPointUrl=Yx.logEndPointUrl),n.fpr_log_transport_key?t.transportKey=n.fpr_log_transport_key:Yx.transportKey&&(t.transportKey=Yx.transportKey),void 0!==n.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate):void 0!==Yx.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=Yx.networkRequestsSamplingRate),void 0!==n.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate):void 0!==Yx.tracesSamplingRate&&(t.tracesSamplingRate=Yx.tracesSamplingRate),t.logTraceAfterSampling=t1(t.tracesSamplingRate),t.logNetworkAfterSampling=t1(t.networkRequestsSamplingRate),e}function t1(e){return Math.random()<=e}let n1=1,r1;function i1(e){var t;return n1=2,r1=r1||(t=e,function(){const n=qx.getInstance().document;return new Promise(e=>{if(n&&"complete"!==n.readyState){const t=()=>{"complete"===n.readyState&&(n.removeEventListener("readystatechange",t),e())};n.addEventListener("readystatechange",t)}else e()})}().then(()=>function(e){const t=e.getId();return t.then(e=>{Bx=e}),t}(t.installations)).then(e=>Xx(t,e)).then(()=>s1(),()=>s1())),r1}function s1(){n1=3}const a1=1e4,o1=3,c1=1e3;let l1=o1,u1=[],h1=!1;function d1(e){setTimeout(()=>{if(0!==l1)return u1.length?void function(){const e=u1.splice(0,c1),t=e.map(e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)})),n={request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:$x.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=$x.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||Fx.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=a1;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(u1=[...r,...u1],Fx.info("Retry transport request later.")),l1=o1,d1(n)})}(n,e).catch(()=>{u1=[...e,...u1],l1--,Fx.info(`Tries left: ${l1}.`),d1(a1)})}():d1(a1)},e)}function p1(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw Lx.create("invalid cc log");u1=[...u1,e]}({message:t(...e),eventTime:Date.now()})}}let f1;function g1(e,t){f1=f1||p1(_1),f1(e,t)}function m1(e){var t=$x.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&qx.getInstance().requiredApisAvailable()&&(e.isAuto&&Wx()!==Dx.VISIBLE||(3===n1?v1(e):i1(e.performanceController).then(()=>v1(e),()=>v1(e))))}function v1(e){var t;!Bx||(t=$x.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>g1(e,1),0)}function _1(e,t){return 0===t?(n={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},n={application_info:y1(e.performanceController.app),network_request_metric:n},JSON.stringify(n)):function(e){const t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);var n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);n={application_info:y1(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function y1(e){return{google_app_id:Hx(e),app_instance_id:Bx,web_app_info:{sdk_version:Ax,page_url:qx.getInstance().getUrl(),service_worker_status:null!=(t=qx.getInstance().navigator)&&t.serviceWorker?t.serviceWorker.controller?2:3:1,visibility_state:Wx(),effective_connection_type:function(){var e=qx.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}()},application_process_state:0};var t}const w1=["_fp","_fcp","_fid"];class b1{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=qx.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark=`FB-PERF-TRACE-START-${this.randomId}-${this.name}`,this.traceStopMark=`FB-PERF-TRACE-STOP-${this.randomId}-${this.name}`,this.traceMeasure=r||`${Nx}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw Lx.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw Lx.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),m1(this)}record(e,t,n){if(e<=0)throw Lx.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw Lx.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const r of Object.keys(n.metrics))isNaN(Number(n.metrics[r]))||(this.counters[r]=Math.floor(Number(n.metrics[r])));m1(this)}incrementMetric(e,t=1){void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)}putMetric(e,t){if(r=e,i=this.name,0===r.length||100<r.length||!(i&&i.startsWith("_wt_")&&-1<w1.indexOf(r))&&r.startsWith("_"))throw Lx.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=null!=t?t:0,(n=Math.floor(t))<t&&Fx.info(`Metric value should be an Integer, setting the value as : ${n}.`),n)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){var n,r,i=!(0===(n=e).length||40<n.length)&&(!Kx.some(e=>n.startsWith(e))&&!!n.match(Gx)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw Lx.create("invalid attribute name",{attributeName:e});if(!s)throw Lx.create("invalid attribute value",{attributeValue:t})}}getAttribute(e){return this.customAttributes[e]}removeAttribute(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]}getAttributes(){return Object.assign({},this.customAttributes)}setStartTime(e){this.startTimeUs=e}setDuration(e){this.durationUs=e}calculateTraceMetrics(){var e=this.api.getEntriesByName(this.traceMeasure),e=e&&e[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))}static createOobTrace(e,t,n,r){var i=qx.getInstance().getUrl();if(i){const s=new b1(e,"_wt_"+i,!0);i=Math.floor(1e3*qx.getInstance().getTimeOrigin());s.setStartTime(i),t&&t[0]&&(s.setDuration(Math.floor(1e3*t[0].duration)),s.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),s.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),s.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));n&&((i=n.find(e=>"first-paint"===e.name))&&i.startTime&&s.putMetric("_fp",Math.floor(1e3*i.startTime)),(i=n.find(e=>"first-contentful-paint"===e.name))&&i.startTime&&s.putMetric("_fcp",Math.floor(1e3*i.startTime)),r&&s.putMetric("_fid",Math.floor(1e3*r))),m1(s)}}static createUserTimingTrace(e,t){m1(new b1(e,t,!1,t))}}function I1(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=qx.getInstance().getTimeOrigin(),r=Math.floor(1e3*(n.startTime+s)),i=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,s=Math.floor(1e3*(n.responseEnd-n.startTime)),function(e){const t=$x.getInstance();var n,r,i;t.instrumentationEnabled&&(n=e.url,r=t.logEndPointUrl.split("?")[0],i=t.flTransportEndpointUrl.split("?")[0],n!==r&&n!==i&&t.loggingEnabled&&t.logNetworkAfterSampling&&setTimeout(()=>g1(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const T1=5e3;function E1(e){Bx&&(setTimeout(()=>function(n){const e=qx.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{b1.createOobTrace(n,r,i),t=void 0},T1);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),b1.createOobTrace(n,r,i,e))})}else b1.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=qx.getInstance(),n=e.getEntriesByType("resource");for(const r of n)I1(t,r);e.setupObserver("resource",e=>I1(t,e))}(e),0),setTimeout(()=>function(t){const e=qx.getInstance(),n=e.getEntriesByType("measure");for(const r of n)C1(t,r);e.setupObserver("measure",e=>C1(t,e))}(e),0))}function C1(e,t){const n=t.name;n.substring(0,Nx.length)!==Nx&&b1.createUserTimingTrace(e,n)}class k1{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),qx.getInstance().requiredApisAvailable()?N().then(e=>{e&&(h1||(d1(5500),h1=!0),i1(this).then(()=>E1(this),()=>E1(this)),this.initialized=!0)}).catch(e=>{Fx.info(`Environment doesn't support IndexedDB: ${e}`)}):Fx.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){$x.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return $x.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){$x.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return $x.getInstance().dataCollectionEnabled}}const S1="[DEFAULT]";const A1=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==S1)throw Lx.create("FB not default");if("undefined"==typeof window)throw Lx.create("no window");e=window,Vx=e;const i=new k1(n,r);return i._init(t),i};We(new ce("performance",A1,"PUBLIC")),tt(kx,Sx),tt(kx,Sx,"esm2017");class N1{constructor(e,t){this.app=e,this._delegate=t}get instrumentationEnabled(){return this._delegate.instrumentationEnabled}set instrumentationEnabled(e){this._delegate.instrumentationEnabled=e}get dataCollectionEnabled(){return this._delegate.dataCollectionEnabled}set dataCollectionEnabled(e){this._delegate.dataCollectionEnabled=e}trace(e){return t=this._delegate,e=e,t=oe(t),new b1(t,e);var t}}function R1(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new N1(t,n)}(xx=bt).INTERNAL.registerComponent(new ce("performance-compat",R1,"PUBLIC")),xx.registerVersion("@firebase/performance-compat","0.2.4");const P1="@firebase/remote-config";class D1{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const x1=new D("remoteconfig","Remote Config",{"registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out. Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser"});const O1=["1","true","t","yes","y","on"];class M1{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=O1.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}async function L1(e){const t=oe(e);var[n,r]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.eTag!==r)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.eTag)]),!0)}function F1(e){const t=oe(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function U1(t){const n=oe(t),e=new D1;setTimeout(async()=>{e.abort()},n.settings.fetchTimeoutMillis);try{await n._client.fetch({cacheMaxAgeMillis:n.settings.minimumFetchIntervalMillis,signal:e}),await n._storageCache.setLastFetchStatus("success")}catch(e){var r=(i="fetch-throttle",(t=e)instanceof P&&-1!==t.code.indexOf(i)?"throttle":"failure");throw await n._storageCache.setLastFetchStatus(r),e}var i}function V1(n){const e=oe(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=q1(n,t),e),{});var t,r}function q1(e,t){const n=oe(e);n._isInitializationComplete||n._logger.debug(`A value was requested for key "${t}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value.");var r=n._storageCache.getActiveConfig();return r&&void 0!==r[t]?new M1("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new M1("default",String(n.defaultConfig[t])):(n._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new M1("static"))}class B1{constructor(e,t,n,r){this.client=e,this.storage=t,this.storageCache=n,this.logger=r}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;var n=Date.now()-t,r=n<=e;return this.logger.debug("Config fetch cache check."+` Cache age millis: ${n}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${r}.`),r}async fetch(e){var[t,n]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(n&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return n;e.eTag=n&&n.eTag;n=await this.client.fetch(e);const r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===n.status&&r.push(this.storage.setLastSuccessfulFetchResponse(n)),await Promise.all(r),n}}class j1{constructor(e,t,n,r,i,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=r,this.apiKey=i,this.appId=s}async fetch(n){var e,[t,r]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,s={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":n.eTag||"*"},r={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:r,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language},r={method:"POST",headers:s,body:JSON.stringify(r)},i=fetch(i,r),r=new Promise((e,t)=>{n.signal.addEventListener(()=>{const e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let a;try{await Promise.race([i,r]),a=await i}catch(e){let t="fetch-client-network";throw"AbortError"===(null==e?void 0:e.name)&&(t="fetch-timeout"),x1.create(t,{originalErrorMessage:null==e?void 0:e.message})}let o=a.status;i=a.headers.get("ETag")||void 0;let c,l;if(200===a.status){let e;try{e=await a.json()}catch(e){throw x1.create("fetch-client-parse",{originalErrorMessage:null==e?void 0:e.message})}c=e.entries,l=e.state}if("INSTANCE_STATE_UNSPECIFIED"===l?o=500:"NO_CHANGE"===l?o=304:"NO_TEMPLATE"!==l&&"EMPTY_CONFIG"!==l||(c={}),304!==o&&200!==o)throw x1.create("fetch-status",{httpStatus:o});return{status:o,eTag:i,config:c}}}class z1{constructor(e,t){this.client=e,this.storage=t}async fetch(e){var t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:n}){var i,s;i=t.signal,s=e,await new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(x1.create("fetch-throttle",{throttleEndTimeMillis:s}))})});try{var r=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),r}catch(e){if(!function(e){if(e instanceof P&&e.customData){var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}}(e))throw e;r={throttleEndTimeMillis:Date.now()+ae(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class $1{constructor(e,t,n,r,i){this.app=e,this._client=t,this._storageCache=n,this._storage=r,this._logger=i,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function K1(e,t){var n=e.target.error||void 0;return x1.create(t,{originalErrorMessage:n&&(null==n?void 0:n.message)})}const G1="app_namespace_store";class W1{constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n(K1(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(G1,{keyPath:"compositeKey"})}}catch(e){n(x1.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}})}()){this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=r}getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}async get(a){const o=await this.openDbPromise;return new Promise((n,t)=>{const e=o.transaction([G1],"readonly"),r=e.objectStore(G1);var i=this.createCompositeKey(a);try{const s=r.get(i);s.onerror=e=>{t(K1(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(x1.create("storage-get",{originalErrorMessage:null==e?void 0:e.message}))}})}async set(a,o){const c=await this.openDbPromise;return new Promise((e,t)=>{const n=c.transaction([G1],"readwrite"),r=n.objectStore(G1);var i=this.createCompositeKey(a);try{const s=r.put({compositeKey:i,value:o});s.onerror=e=>{t(K1(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(x1.create("storage-set",{originalErrorMessage:null==e?void 0:e.message}))}})}async delete(a){const o=await this.openDbPromise;return new Promise((e,t)=>{const n=o.transaction([G1],"readwrite"),r=n.objectStore(G1);var i=this.createCompositeKey(a);try{const s=r.delete(i);s.onerror=e=>{t(K1(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(x1.create("storage-delete",{originalErrorMessage:null==e?void 0:e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class H1{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),n=this.storage.getActiveConfig(),e=await e;e&&(this.lastFetchStatus=e);t=await t;t&&(this.lastSuccessfulFetchTimestampMillis=t);n=await n;n&&(this.activeConfig=n)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}}async function Q1(){if(!A())return!1;try{return await N()}catch(e){return!1}}We(new ce("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw x1.create("registration-window");if(!A())throw x1.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:a}=n.options;if(!i)throw x1.create("registration-project-id");if(!s)throw x1.create("registration-api-key");if(!a)throw x1.create("registration-app-id");t=t||"firebase";const o=new W1(a,n.name,t),c=new H1(o),l=new ve(P1);l.logLevel=m.ERROR;a=new j1(r,Je,t,i,s,a),a=new z1(a,o),a=new B1(a,o,c,l),a=new $1(n,a,c,o,l);return F1(a),a},"PUBLIC").setMultipleInstances(!0)),tt(P1,"0.4.4"),tt(P1,"0.4.4","esm2017");class Y1{constructor(e,t){this.app=e,this._delegate=t}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(e){this._delegate.defaultConfig=e}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(e){this._delegate.settings=e}activate(){return L1(this._delegate)}ensureInitialized(){return F1(this._delegate)}fetch(){return U1(this._delegate)}fetchAndActivate(){return async function(e){return await U1(e=oe(e)),L1(e)}(this._delegate)}getAll(){return V1(this._delegate)}getBoolean(e){return q1(oe(this._delegate),e).asBoolean()}getNumber(e){return q1(oe(this._delegate),e).asNumber()}getString(e){return q1(oe(this._delegate),e).asString()}getValue(e){return q1(this._delegate,e)}setLogLevel(e){!function(e,t){const n=oe(e);switch(t){case"debug":n._logger.logLevel=m.DEBUG;break;case"silent":n._logger.logLevel=m.SILENT;break;default:n._logger.logLevel=m.ERROR}}(this._delegate,e)}}function J1(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new Y1(n,r)}return(Ox=bt).INTERNAL.registerComponent(new ce("remoteConfig-compat",J1,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:Q1})),Ox.registerVersion("@firebase/remote-config-compat","0.2.4"),console.warn("\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n"),bt.registerVersion("firebase","10.3.1","compat-cdn"),bt});
|
|
10
10
|
//# sourceMappingURL=firebase-compat.js.map
|