Kargi-Sitesi/node_modules/firebase/firebase-compat.js

19 lines
776 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

!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(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}function C(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function S(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function k(){const e=b();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function A(){return!0===t.NODE_ADMIN}function N(){return!T()&&navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function R(){try{return"object"==typeof indexedDB}catch(e){return!1}}function P(){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 D(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class x extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,x.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,O.prototype.create)}}class O{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(L,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new x(i,s,n)}}const L=/\{\$([^}]+)}/g;function M(e){return JSON.parse(e)}function F(e){return JSON.stringify(e)}function U(e){let t={},n={},r={},i="";try{var s=e.split(".");t=M(a(s[0])||""),n=M(a(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function V(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function q(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function j(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function B(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 z(e,t){if(e===t)return!0;const n=Object.keys(e),r=Object.keys(t);for(const a of n){if(!r.includes(a))return!1;var i=e[a],s=t[a];if(K(i)&&K(s)){if(!z(i,s))return!1}else if(i!==s)return!1}for(const o of r)if(!n.includes(o))return!1;return!0}function K(e){return null!==e&&"object"==typeof e}function $(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function W(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 G(e){var t=e.indexOf("?");if(!t)return"";var n=e.indexOf("#",t);return e.substring(t,0<n?n:void 0)}class H{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 Q(e,t){const n=new Y(e,t);return n.subscribe.bind(n)}class Y{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=J),void 0===r.error&&(r.error=J),void 0===r.complete&&(r.complete=J);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 J(){}function X(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 Z(e,t){return`${e} failed: ${t} argument `}function ee(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(Z(e,t)+"must be a valid function.")}function te(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(Z(e,t)+"must be a valid context object.")}function ne(){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 re=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},ie=1e3,se=2,ae=144e5,oe=.5;function ce(e,t=ie,n=se){var r=t*Math.pow(n,e),i=Math.round(oe*r*(Math.random()-.5)*2);return Math.min(ae,r+i)}function le(e){return e&&e._delegate?e._delegate:e}class ue{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 he="[DEFAULT]";class de{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:he})}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=he){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=he){return this.instances.has(e)}getOptions(e=he){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)===he?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=he){return!this.component||this.component.multipleInstances?e:he}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class pe{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 de(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const fe=[];(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 ge={debug:m.DEBUG,verbose:m.VERBOSE,info:m.INFO,warn:m.WARN,error:m.ERROR,silent:m.SILENT},me=m.INFO,ve={[m.DEBUG]:"log",[m.VERBOSE]:"log",[m.INFO]:"info",[m.WARN]:"warn",[m.ERROR]:"error"},_e=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=ve[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class ye{constructor(e){this.name=e,this._logLevel=me,this._logHandler=_e,this._userLogHandler=null,fe.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?ge[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 we=(t,e)=>e.some(e=>t instanceof e);let be,Ie;const Te=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Se=new WeakMap,ke=new WeakMap;let Ae={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return Ee.get(e);if("objectStoreNames"===t)return e.objectStoreNames||Ce.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Pe(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 Ne(r){return r!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Ie=Ie||[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]).includes(r)?function(...e){return r.apply(De(this),e),Pe(Te.get(this))}:function(...e){return Pe(r.apply(De(this),e))}:function(e,...t){var n=r.call(De(this),e,...t);return Ce.set(n,e.sort?e.sort():[e]),Pe(n)}}function Re(e){return"function"==typeof e?Ne(e):(e instanceof IDBTransaction&&(s=e,Ee.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)}),Ee.set(s,t))),we(e,be=be||[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])?new Proxy(e,Ae):e);var s,t}function Pe(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(Pe(s.result)),n()},i=()=>{t(s.error),n()};s.addEventListener("success",r),s.addEventListener("error",i)});return e.then(e=>{e instanceof IDBCursor&&Te.set(e,s)}).catch(()=>{}),ke.set(e,s),e}(e);if(Se.has(e))return Se.get(e);var t=Re(e);return t!==e&&(Se.set(e,t),ke.set(t,e)),t}const De=e=>ke.get(e);function xe(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const a=indexedDB.open(e,t),o=Pe(a);return r&&a.addEventListener("upgradeneeded",e=>{r(Pe(a.result),e.oldVersion,e.newVersion,Pe(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 Oe(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",e=>t(e.oldVersion,e)),Pe(n).then(()=>{})}const Le=["get","getKey","getAll","getAllKeys","count"],Me=["put","add","delete","clear"],Fe=new Map;function Ue(e,t){if(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t){if(Fe.get(t))return Fe.get(t);const i=t.replace(/FromIndex$/,""),s=t!==i,a=Me.includes(i);if(i in(s?IDBIndex:IDBObjectStore).prototype&&(a||Le.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 Fe.set(t,n),n}}}Ae={..._=Ae,get:(e,t,n)=>Ue(e,t)||_.get(e,t,n),has:(e,t)=>!!Ue(e,t)||_.has(e,t)};class Ve{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 qe="@firebase/app",je="0.10.15",Be=new ye("@firebase/app");var ze;const Ke="[DEFAULT]",$e={"@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/data-connect":"fire-data-connect","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","@firebase/vertexai":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},We=new Map,Ge=new Map,He=new Map;function Qe(t,n){try{t.container.addComponent(n)}catch(e){Be.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function Ye(e,t){e.container.addOrOverwriteComponent(t)}function Je(e){var t=e.name;if(He.has(t))return Be.debug(`There were multiple attempts to register component ${t}.`),!1;He.set(t,e);for(const n of We.values())Qe(n,e);for(const r of Ge.values())Qe(r,e);return!0}function Xe(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function Ze(e){return void 0!==e.options}function et(e){return void 0!==e.settings}const tt=new O("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."});class nt{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 ue("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 tt.create("app-deleted",{appName:this._name})}}class rt extends nt{constructor(e,t,n,r){var i=void 0!==t.automaticDataCollectionEnabled&&t.automaticDataCollectionEnabled,s={name:n,automaticDataCollectionEnabled:i};void 0!==e.apiKey?super(e,s,r):super(e.options,s,r),this._serverConfig=Object.assign({automaticDataCollectionEnabled:i},t),this._finalizationRegistry=null,"undefined"!=typeof FinalizationRegistry&&(this._finalizationRegistry=new FinalizationRegistry(()=>{this.automaticCleanup()})),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=void 0,t.releaseOnDeref=void 0,ct(qe,je,"serverapp")}toJSON(){}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,void 0!==e&&null!==this._finalizationRegistry&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){ot(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw tt.create("server-app-deleted")}}const it="11.0.1";function st(e,t={}){let n=e;if("object"!=typeof t){const i=t;t={name:i}}var r=Object.assign({name:Ke,automaticDataCollectionEnabled:!1},t);const i=r.name;if("string"!=typeof i||!i)throw tt.create("bad-app-name",{appName:String(i)});if(n=n||g(),!n)throw tt.create("no-options");var s=We.get(i);if(s){if(z(n,s.options)&&z(r,s.config))return s;throw tt.create("duplicate-app",{appName:i})}const a=new pe(i);for(const o of He.values())a.addComponent(o);r=new nt(n,r,a);return We.set(i,r),r}function at(e=Ke){var t=We.get(e);if(!t&&e===Ke&&g())return st();if(!t)throw tt.create("no-app",{appName:e});return t}async function ot(e){let t=!1;var n=e.name;if(We.has(n))t=!0,We.delete(n);else if(Ge.has(n)){const r=e;r.decRefCount()<=0&&(Ge.delete(n),t=!0)}t&&(await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function ct(e,t,n){let r=null!==(s=$e[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 Be.warn(a.join(" "))}Je(new ue(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function lt(e,t){if(null!==e&&"function"!=typeof e)throw tt.create("invalid-log-argument");!function(s,e){for(const t of fe){let i=null;e&&e.level&&(i=ge[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 ut(e){var t;t=e,fe.forEach(e=>{e.setLogLevel(t)})}const ht="firebase-heartbeat-database",dt=1,pt="firebase-heartbeat-store";let ft=null;function gt(){return ft=ft||xe(ht,dt,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(pt)}catch(e){console.warn(e)}}}).catch(e=>{throw tt.create("idb-open",{originalErrorMessage:e.message})}),ft}async function mt(e,t){try{const r=await gt(),i=r.transaction(pt,"readwrite"),s=i.objectStore(pt);await s.put(t,vt(e)),await i.done}catch(e){var n;e instanceof x?Be.warn(e.message):(n=tt.create("idb-set",{originalErrorMessage:null==e?void 0:e.message}),Be.warn(n.message))}}function vt(e){return`${e.name}!${e.options.appId}`}class _t{constructor(e){this.container=e,this._heartbeatsCache=null;var t=this.container.getProvider("app").getImmediate();this._storage=new wt(t),this._heartbeatsCachePromise=this._storage.read().then(e=>this._heartbeatsCache=e)}async triggerHeartbeat(){var e,t;try{const r=this.container.getProvider("platform-logger").getImmediate();var n=r.getPlatformInfoString();const i=yt();return null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)&&(this._heartbeatsCache=await this._heartbeatsCachePromise,null==(null===(t=this._heartbeatsCache)||void 0===t?void 0:t.heartbeats))?void 0:this._heartbeatsCache.lastSentHeartbeatDate===i||this._heartbeatsCache.heartbeats.some(e=>e.date===i)?void 0:(this._heartbeatsCache.heartbeats.push({date:i,agent:n}),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))}catch(e){Be.warn(e)}}async getHeartbeatsHeader(){var e;try{if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";var t=yt(),{heartbeatsToSend:n,unsentEntries:r}=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),bt(n)>t){s.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),bt(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),i=s(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,0<r.length?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return Be.warn(e),""}}}function yt(){const e=new Date;return e.toISOString().substring(0,10)}class wt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!R()&&P().then(()=>!0).catch(()=>!1)}async read(){if(await this._canUseIndexedDBPromise){var e=await async function(e){try{const n=await gt(),r=n.transaction(pt);var t=await r.objectStore(pt).get(vt(e));return await r.done,t}catch(e){e instanceof x?Be.warn(e.message):(t=tt.create("idb-get",{originalErrorMessage:null==e?void 0:e.message}),Be.warn(t.message))}}(this.app);return null!=e&&e.heartbeats?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){var n=await this.read();return mt(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 mt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function bt(e){return s(JSON.stringify({version:2,heartbeats:e})).length}ze="",Je(new ue("platform-logger",e=>new Ve(e),"PRIVATE")),Je(new ue("heartbeat",e=>new _t(e),"PRIVATE")),ct(qe,je,ze),ct(qe,je,"esm2017"),ct("fire-js","");var It=Object.freeze({__proto__:null,SDK_VERSION:it,_DEFAULT_ENTRY_NAME:Ke,_addComponent:Qe,_addOrOverwriteComponent:Ye,_apps:We,_clearComponents:function(){He.clear()},_components:He,_getProvider:Xe,_isFirebaseApp:Ze,_isFirebaseServerApp:et,_registerComponent:Je,_removeServiceInstance:function(e,t,n=Ke){Xe(e,t).clearInstance(n)},_serverApps:Ge,deleteApp:ot,getApp:at,getApps:function(){return Array.from(We.values())},initializeApp:st,initializeServerApp:function(e,t){if(("undefined"!=typeof window||E())&&!E())throw tt.create("invalid-server-app-environment");void 0===t.automaticDataCollectionEnabled&&(t.automaticDataCollectionEnabled=!1);let n;n=Ze(e)?e.options:e;const r=Object.assign(Object.assign({},t),n);if(void 0!==r.releaseOnDeref&&delete r.releaseOnDeref,void 0!==t.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw tt.create("finalization-registry-not-supported",{});var i=""+[...JSON.stringify(r)].reduce((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0,0);const s=Ge.get(i);if(s)return s.incRefCount(t.releaseOnDeref),s;const a=new pe(i);for(const c of He.values())a.addComponent(c);var o=new rt(n,t,i,a);return Ge.set(i,o),o},onLog:lt,registerVersion:ct,setLogLevel:ut,FirebaseError:x});class Tt{constructor(e,t){this._delegate=e,this.firebase=t,Qe(e,new ue("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),ot(this._delegate)))}_getService(e,t=Ke){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=Ke){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){Qe(this._delegate,e)}_addOrOverwriteComponent(e){Ye(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const Et=new O("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 Ct(i){const s={},a={__esModule:!0,initializeApp:function(e,t={}){var n=st(e,t);if(V(s,n.name))return s[n.name];var r=new i(n,a);return s[n.name]=r},app:o,registerVersion:ct,setLogLevel:ut,onLog:lt,apps:null,SDK_VERSION:it,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;Je(n)&&"PUBLIC"===n.type&&(e=(e=o())=>{if("function"!=typeof e[t])throw Et.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:It}};function o(e){if(e=e||Ke,!V(s,e))throw Et.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 St=function e(){const t=Ct(Tt);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){c(t,e)},createSubscribe:Q,ErrorFactory:O,deepExtend:c}),t}();const kt=new ye("@firebase/app-compat");try{var At=o();if(void 0!==At.firebase){kt.warn(`
Warning: Firebase is already defined in the global scope. Please make sure
Firebase library is only loaded once.
`);const UP=At.firebase.SDK_VERSION;UP&&0<=UP.indexOf("LITE")&&kt.warn(`
Warning: You are trying to load Firebase while using Firebase Performance standalone script.
You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.
`)}}catch(e){}const Nt=St;ct("@firebase/app-compat","0.2.45",void 0);Nt.registerVersion("firebase","11.0.1","app-compat");var Rt="@firebase/installations",Pt="0.6.10";const Dt=1e4,xt=`w:${Pt}`,Ot="FIS_v2",Lt="https://firebaseinstallations.googleapis.com/v1",Mt=36e5;const Ft=new O("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 Ut(e){return e instanceof x&&e.code.includes("request-failed")}function Vt({projectId:e}){return`${Lt}/projects/${e}/installations`}function qt(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function jt(e,t){var n=(await t.json()).error;return Ft.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function Bt({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function zt(e,{refreshToken:t}){const n=Bt(e);return n.append("Authorization",(t=t,`${Ot} ${t}`)),n}async function Kt(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function $t(t){return new Promise(e=>{setTimeout(e,t)})}const Wt=/^[cdef][\w-]{21}$/,Gt="";function Ht(){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 Wt.test(e)?e:Gt}catch(e){return Gt}}function Qt(e){return`${e.appName}!${e.appId}`}const Yt=new Map;function Jt(e,t){var n=Qt(e);Xt(n,t),function(e,t){const n=function(){!Zt&&"BroadcastChannel"in self&&(Zt=new BroadcastChannel("[Firebase] FID Change"),Zt.onmessage=e=>{Xt(e.data.key,e.data.fid)});return Zt}();n&&n.postMessage({key:e,fid:t});0===Yt.size&&Zt&&(Zt.close(),Zt=null)}(n,t)}function Xt(e,t){var n=Yt.get(e);if(n)for(const r of n)r(t)}let Zt=null;const en="firebase-installations-store";let tn=null;function nn(){return tn=tn||xe("firebase-installations-database",1,{upgrade:(e,t)=>{0===t&&e.createObjectStore(en)}}),tn}async function rn(e,t){var n=Qt(e);const r=await nn(),i=r.transaction(en,"readwrite"),s=i.objectStore(en);var a=await s.get(n);return await s.put(t,n),await i.done,a&&a.fid===t.fid||Jt(e,t.fid),t}async function sn(e){var t=Qt(e);const n=await nn(),r=n.transaction(en,"readwrite");await r.objectStore(en).delete(t),await r.done}async function an(e,t){var n=Qt(e);const r=await nn(),i=r.transaction(en,"readwrite"),s=i.objectStore(en);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||Jt(e,o.fid),o}async function on(n){let r;var e=await an(n.appConfig,e=>{var t=ln(e||{fid:Ht(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await cn(e.appConfig);for(;1===t.registrationStatus;)await $t(100),t=await cn(e.appConfig);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await on(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(Ft.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=Vt(e),i=Bt(e),s=t.getImmediate({optional:!0});!s||(a=await s.getHeartbeatsHeader())&&i.append("x-firebase-client",a);var a={fid:n,authVersion:Ot,appId:e.appId,sdkVersion:xt};const o={method:"POST",headers:i,body:JSON.stringify(a)},c=await Kt(()=>fetch(r,o));if(c.ok){a=await c.json();return{fid:a.fid||n,registrationStatus:2,refreshToken:a.refreshToken,authToken:qt(a.authToken)}}throw await jt("Create Installation",c)}(t,n);return rn(t.appConfig,e)}catch(e){throw Ut(e)&&409===e.customData.serverCode?await sn(t.appConfig):await rn(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===Gt?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function cn(e){return an(e,e=>{if(!e)throw Ft.create("installation-not-found");return ln(e)})}function ln(e){return 1===(t=e).registrationStatus&&t.registrationTime+Dt<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function un({appConfig:e,heartbeatServiceProvider:t},n){const r=([i,s]=[e,n["fid"]],`${Vt(i)}/${s}/authTokens:generate`);var i,s;const a=zt(e,n),o=t.getImmediate({optional:!0});!o||(c=await o.getHeartbeatsHeader())&&a.append("x-firebase-client",c);var c={installation:{sdkVersion:xt,appId:e.appId}};const l={method:"POST",headers:a,body:JSON.stringify(c)},u=await Kt(()=>fetch(r,l));if(u.ok)return qt(await u.json());throw await jt("Generate Auth Token",u)}async function hn(r,i=!1){let s;var e=await an(r.appConfig,e=>{if(!pn(e))throw Ft.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+Mt}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await dn(e.appConfig);for(;1===n.authToken.requestStatus;)await $t(100),n=await dn(e.appConfig);var r=n.authToken;return 0===r.requestStatus?hn(e,t):r}(r,i),e;if(!navigator.onLine)throw Ft.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 un(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await rn(t.appConfig,e),r}catch(e){throw!Ut(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await rn(t.appConfig,r)):await sn(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function dn(e){return an(e,e=>{if(!pn(e))throw Ft.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+Dt<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function pn(e){return void 0!==e&&2===e.registrationStatus}async function fn(e,t=!1){var n,r=e;return await((n=(await on(r)).registrationPromise)&&await n),(await hn(r,t)).token}function gn(e){return Ft.create("missing-app-config-values",{valueName:e})}const mn="installations",vn=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw gn("App Configuration");if(!e.name)throw gn("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw gn(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),heartbeatServiceProvider:Xe(t,"heartbeat"),_delete:()=>Promise.resolve()}},_n=e=>{const t=Xe(e.getProvider("app").getImmediate(),mn).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await on(t);return(r||hn(t)).catch(console.error),n.fid}(t),getToken:e=>fn(t,e)}};Je(new ue(mn,vn,"PUBLIC")),Je(new ue("installations-internal",_n,"PRIVATE")),ct(Rt,Pt),ct(Rt,Pt,"esm2017");const yn="analytics",wn="firebase_id",bn="origin",In="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Tn="https://www.googletagmanager.com/gtag/js",En=new ye("@firebase/analytics"),Cn=new O("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-initialized 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 Sn(e){if(e.startsWith(Tn))return e;var t=Cn.create("invalid-gtag-resource",{gtagURL:e});return En.warn(t.message),""}function kn(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function An(e,t){const n=function(e,t){let n;return window.trustedTypes&&(n=window.trustedTypes.createPolicy(e,t)),n}("firebase-js-sdk-policy",{createScriptURL:Sn}),r=document.createElement("script");var i=`${Tn}?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 Nn(d,p,f,g){return async function(e,...t){try{var n,r,i,s,a,o,c,l,u,h;"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 kn(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){En.error(e)}}(d,p,f,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 kn(n);var o=c.find(e=>e.measurementId===i);o&&await t[o.appId]}}catch(e){En.error(e)}e("config",i,s)}(d,p,f,g,i,s)):"consent"===e?([a,o]=t,d("consent",a,o)):"get"===e?([c,l,u]=t,d("get",c,l,u)):"set"===e?([h]=t,d("set",h)):d(e,...t)}catch(e){En.error(e)}}}const Rn=30;const Pn=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 Dn(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=In.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 Cn.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function xn(e,t=Pn,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw Cn.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw Cn.create("no-api-key")}var a=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const o=new Mn;return setTimeout(async()=>{o.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=Pn){var a;const{appId:o,measurementId:c}=n;try{await On(i,e)}catch(e){if(c)return En.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 Dn(n);return s.deleteThrottleMetadata(o),l}catch(e){const u=e;if(!Ln(u)){if(s.deleteThrottleMetadata(o),c)return En.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)?ce(r,s.intervalMillis,Rn):ce(r,s.intervalMillis),d={throttleEndTimeMillis:Date.now()+h,backoffCount:r+1};return s.setThrottleMetadata(o,d),En.debug(`Calling attemptFetch again in ${h} millis`),t(n,d,i,s)}}({appId:r,apiKey:i,measurementId:s},a,o,t)}function On(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(Cn.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function Ln(e){if(!(e instanceof x&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class Mn{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function Fn(t,e,n,r,i,s,a){const o=xn(t);o.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&En.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=>En.error(e)),e.push(o);var c=async function(){if(!R())return En.warn(Cn.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await P()}catch(e){return En.warn(Cn.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(Tn)&&n.src.includes(e))return n}(s)&&An(s,l.measurementId),i("js",new Date);const h=null!==(c=null==a?void 0:a.config)&&void 0!==c?c:{};return h[bn]="firebase",h.update=!0,null!=u&&(h[wn]=u),i("config",l.measurementId,h),l.measurementId}class Un{constructor(e){this.app=e}_delete(){return delete Vn[this.app.options.appId],Promise.resolve()}}let Vn={},qn=[];const jn={};let Bn="dataLayer",zn="gtag",Kn,$n,Wn=!1;function Gn(e){if(Wn)throw Cn.create("already-initialized");e.dataLayerName&&(Bn=e.dataLayerName),e.gtagName&&(zn=e.gtagName)}function Hn(e,t,n){!function(){const e=[];var t;C()&&e.push("This is a browser extension environment."),D()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=Cn.create("invalid-analytics-context",{errorInfo:t}),En.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw Cn.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Cn.create("no-api-key");En.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!=Vn[s])throw Cn.create("already-exists",{id:s});return Wn||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(Bn),{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]=Nn(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(Vn,qn,jn,Bn,zn),$n=r,Kn=i,Wn=!0),Vn[s]=Fn(e,qn,jn,t,Kn,Bn,n),new Un(e)}async function Qn(){if(C())return!1;if(!D())return!1;if(!R())return!1;try{return await P()}catch(e){return!1}}function Yn(e,t,n){e=le(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})}($n,Vn[e.app.options.appId],t,n).catch(e=>En.error(e))}function Jn(e,t,n){e=le(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})}($n,Vn[e.app.options.appId],t,n).catch(e=>En.error(e))}function Xn(e,t,n){e=le(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})}($n,Vn[e.app.options.appId],t,n).catch(e=>En.error(e))}function Zn(e,t){e=le(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(Vn[e.app.options.appId],t).catch(e=>En.error(e))}function er(e,t,n,r){e=le(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})))}($n,Vn[e.app.options.appId],t,n,r).catch(e=>En.error(e))}const tr="@firebase/analytics";Je(new ue(yn,(e,{options:t})=>{return Hn(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),Je(new ue("analytics-internal",function(e){try{const r=e.getProvider(yn).getImmediate();return{logEvent:(e,t,n)=>er(r,e,t,n)}}catch(e){throw Cn.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),ct(tr,"0.10.9"),ct(tr,"0.10.9","esm2017");var nr,rr;class ir{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){er(this._delegate,e,t,n)}setCurrentScreen(e,t){Yn(this._delegate,e,t)}setUserId(e,t){Jn(this._delegate,e,t)}setUserProperties(e,t){Xn(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){Zn(this._delegate,e)}}(St=nr=nr||{}).ADD_SHIPPING_INFO="add_shipping_info",St.ADD_PAYMENT_INFO="add_payment_info",St.ADD_TO_CART="add_to_cart",St.ADD_TO_WISHLIST="add_to_wishlist",St.BEGIN_CHECKOUT="begin_checkout",St.CHECKOUT_PROGRESS="checkout_progress",St.EXCEPTION="exception",St.GENERATE_LEAD="generate_lead",St.LOGIN="login",St.PAGE_VIEW="page_view",St.PURCHASE="purchase",St.REFUND="refund",St.REMOVE_FROM_CART="remove_from_cart",St.SCREEN_VIEW="screen_view",St.SEARCH="search",St.SELECT_CONTENT="select_content",St.SELECT_ITEM="select_item",St.SELECT_PROMOTION="select_promotion",St.SET_CHECKOUT_OPTION="set_checkout_option",St.SHARE="share",St.SIGN_UP="sign_up",St.TIMING_COMPLETE="timing_complete",St.VIEW_CART="view_cart",St.VIEW_ITEM="view_item",St.VIEW_ITEM_LIST="view_item_list",St.VIEW_PROMOTION="view_promotion",St.VIEW_SEARCH_RESULTS="view_search_results";const sr=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new ir(t,n)};rr={Analytics:ir,settings:Gn,isSupported:Qn,EventName:nr},Nt.INTERNAL.registerComponent(new ue("analytics-compat",sr,"PUBLIC").setServiceProps(rr).setMultipleInstances(!0)),Nt.registerVersion("@firebase/analytics-compat","0.2.15");const ar=new Map,or={activated:!1,tokenObservers:[]},cr={initialized:!1,enabled:!1};function lr(e){return ar.get(e)||Object.assign({},or)}const ur="https://content-firebaseappcheck.googleapis.com/v1",hr="exchangeDebugToken",dr={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class pr{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,this.pending.promise.catch(e=>{}),t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new y,this.pending.promise.catch(e=>{}),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 fr=new O("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 gr(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function mr(e){if(!lr(e).activated)throw fr.create("use-before-activation",{appName:e.name})}function vr(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+=_r(n)+"d:"),r&&(s+=_r(r)+"h:"),s+=_r(i)+"m:"+_r(t)+"s",s}function _r(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function yr({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 fr.create("fetch-network-error",{originalErrorMessage:null==e?void 0:e.message})}if(200!==a.status)throw fr.create("fetch-status-error",{httpStatus:a.status});let o;try{o=await a.json()}catch(e){throw fr.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 fr.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 wr(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${ur}/projects/${n}/apps/${r}:${hr}?key=${i}`,body:{debug_token:t}}}const br="firebase-app-check-database",Ir=1,Tr="firebase-app-check-store",Er="debug-token";let Cr=null;function Sr(){return Cr||(Cr=new Promise((t,n)=>{try{const e=indexedDB.open(br,Ir);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(fr.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(Tr,{keyPath:"compositeKey"})}}catch(e){n(fr.create("storage-open",{originalErrorMessage:null==e?void 0:e.message}))}}),Cr)}async function kr(e,t){const n=await Sr(),r=n.transaction(Tr,"readwrite"),i=r.objectStore(Tr),s=i.put({compositeKey:e,value:t});return new Promise((t,n)=>{s.onsuccess=e=>{t()},r.onerror=e=>{var t;n(fr.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function Ar(e){const t=await Sr(),i=t.transaction(Tr,"readonly"),n=i.objectStore(Tr),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(fr.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function Nr(e){return`${e.options.appId}-${e.name}`}const Rr=new ye("@firebase/app-check");async function Pr(t){if(R()){let e=void 0;try{e=await Ar(Nr(t))}catch(e){Rr.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function Dr(e,t){return R()?kr(Nr(e),t).catch(e=>{Rr.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function xr(){let e=void 0;try{e=await Ar(Er)}catch(e){}if(e)return e;var t,n=ne();return t=n,kr(Er,t).catch(e=>Rr.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),n}function Or(){return cr.enabled}async function Lr(){var e=cr;if(e.enabled&&e.token)return e.token.promise;throw Error(`
Can't get debug token in production mode.
`)}const Mr={error:"UNKNOWN_ERROR"};async function Fr(e,t=!1){var n=e.app;mr(n);const r=lr(n);let i=r.token,s=void 0;if(i&&!Br(i)&&(r.token=void 0,i=void 0),i||(o=await r.cachedTokenPromise)&&(Br(o)?i=o:await Dr(n,void 0)),!t&&i&&Br(i))return{token:i.token};let a=!1;if(Or()){r.exchangeTokenPromise||(r.exchangeTokenPromise=yr(wr(n,await Lr()),e.heartbeatServiceProvider).finally(()=>{r.exchangeTokenPromise=void 0}),a=!0);var o=await r.exchangeTokenPromise;return await Dr(n,o),{token:(r.token=o).token}}try{r.exchangeTokenPromise||(r.exchangeTokenPromise=r.provider.getToken().finally(()=>{r.exchangeTokenPromise=void 0}),a=!0),i=await lr(n).exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?Rr.warn(e.message):Rr.error(e),s=e}let c;return i?s?c=Br(i)?{token:i.token,internalError:s}:zr(s):(c={token:i.token},r.token=i,await Dr(n,i)):c=zr(s),a&&jr(n,c),c}function Ur(e,t,n,r){var i=e["app"];const s=lr(i);i={next:n,error:r,type:t};if(s.tokenObservers=[...s.tokenObservers,i],s.token&&Br(s.token)){const a=s.token;Promise.resolve().then(()=>{n({token:a.token}),qr(e)}).catch(()=>{})}s.cachedTokenPromise.then(()=>qr(e))}function Vr(e,t){const n=lr(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 qr(e){var t=e["app"];const n=lr(t);let r=n.tokenRefresher;r||(r=function(n){const r=n["app"];return new pr(async()=>{var e=lr(r);let t;if(t=e.token?await Fr(n,!0):await Fr(n),t.error)throw t.error;if(t.internalError)throw t.internalError},()=>!0,()=>{var e=lr(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},dr.RETRIAL_MIN_WAIT,dr.RETRIAL_MAX_WAIT)}(e),n.tokenRefresher=r),!r.isRunning()&&n.isTokenAutoRefreshEnabled&&r.start()}function jr(e,t){for(const n of lr(e).tokenObservers)try{"EXTERNAL"===n.type&&null!=t.error?n.error(t.error):n.next(t)}catch(e){}}function Br(e){return 0<e.expireTimeMillis-Date.now()}function zr(e){return{token:(t=Mr,r.encodeString(JSON.stringify(t),!1)),error:e};var t}class Kr{constructor(e,t){this.app=e,this.heartbeatServiceProvider=t}_delete(){var e=lr(this.app)["tokenObservers"];for(const t of e)Vr(this.app,t.next);return Promise.resolve()}}function $r(t){return{getToken:e=>Fr(t,e),getLimitedUseToken:()=>async function(e){var t=e.app;mr(t);const n=lr(t)["provider"];if(Or()){var r=(await yr(wr(t,await Lr()),e.heartbeatServiceProvider))["token"];return{token:r}}return{token:r=(await n.getToken())["token"]}}(t),addTokenListener:e=>Ur(t,"INTERNAL",e),removeTokenListener:e=>Vr(t.app,e)}}const Wr="https://www.google.com/recaptcha/api.js",Gr="https://www.google.com/recaptcha/enterprise.js";function Hr(t,n){const r=new y,e=lr(t);e.reCAPTCHAState={initialized:r};const i=Jr(t);var s=gr(!1);return s?Yr(t,n,s,i,r):function(e){const t=document.createElement("script");t.src=Wr,t.onload=e,document.head.appendChild(t)}(()=>{var e=gr(!1);if(!e)throw new Error("no recaptcha");Yr(t,n,e,i,r)}),r.promise}function Qr(t,n){const r=new y,e=lr(t);e.reCAPTCHAState={initialized:r};const i=Jr(t);var s=gr(!0);return s?Yr(t,n,s,i,r):function(e){const t=document.createElement("script");t.src=Gr,t.onload=e,document.head.appendChild(t)}(()=>{var e=gr(!0);if(!e)throw new Error("no recaptcha");Yr(t,n,e,i,r)}),r.promise}function Yr(e,t,n,r,i){n.ready(()=>{!function(e,t,n,r){const i=n.render(r,{sitekey:t,size:"invisible",callback:()=>{lr(e).reCAPTCHAState.succeeded=!0},"error-callback":()=>{lr(e).reCAPTCHAState.succeeded=!1}}),s=lr(e);s.reCAPTCHAState=Object.assign(Object.assign({},s.reCAPTCHAState),{widgetId:i})}(e,t,n,r),i.resolve(n)})}function Jr(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 Xr(r){mr(r);const i=await lr(r).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const n=lr(r).reCAPTCHAState;i.ready(()=>{e(i.execute(n.widgetId,{action:"fire_app_check"}))})})}class Zr{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;ri(this._throttleData);var t=await Xr(this._app).catch(e=>{throw fr.create("recaptcha-error")});if(null===(e=lr(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw fr.create("recaptcha-error");let n;try{n=await yr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${ur}/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=ni(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),fr.create("throttled",{time:vr(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,n}initialize(e){this._app=e,this._heartbeatServiceProvider=Xe(e,"heartbeat"),Hr(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof Zr&&this._siteKey===e._siteKey}}class ei{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){var e;ri(this._throttleData);var t=await Xr(this._app).catch(e=>{throw fr.create("recaptcha-error")});if(null===(e=lr(this._app).reCAPTCHAState)||void 0===e||!e.succeeded)throw fr.create("recaptcha-error");let n;try{n=await yr(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${ur}/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=ni(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),fr.create("throttled",{time:vr(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,n}initialize(e){this._app=e,this._heartbeatServiceProvider=Xe(e,"heartbeat"),Qr(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof ei&&this._siteKey===e._siteKey}}class ti{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=function(e){const t=U(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 ti&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function ni(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var n=t?t.backoffCount:0,r=ce(n,1e3,2);return{backoffCount:n+1,allowRequestsAfter:Date.now()+r,httpStatus:e}}function ri(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw fr.create("throttled",{time:vr(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function ii(e=at(),t){const n=Xe(e=le(e),"app-check");if(cr.initialized||function(){var e=o();const t=cr;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(xr())}}(),Or()&&Lr().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 fr.create("already-initialized",{appName:e.name})}r=n.initialize({options:t});return function(t,e,n){const r=function(e,t){return ar.set(e,t),ar.get(e)}(t,Object.assign({},or));r.activated=!0,r.provider=e,r.cachedTokenPromise=Pr(t).then(e=>(e&&Br(e)&&(r.token=e,jr(t,{token:e.token})),e)),r.isTokenAutoRefreshEnabled=void 0===n?t.automaticDataCollectionEnabled:n,r.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),lr(e).isTokenAutoRefreshEnabled&&Ur(r,"INTERNAL",()=>{}),r}const si="app-check-internal";Je(new ue("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("heartbeat");return t=n,e=r,new Kr(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(si).initialize()})),Je(new ue(si,e=>{return $r(e.getProvider("app-check").getImmediate())},"PUBLIC").setInstantiationMode("EXPLICIT")),ct("@firebase/app-check","0.8.9");const ai=new O("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 oi{constructor(e){this.app=e}activate(e,t){let n;n="string"==typeof e?new Zr(e):e instanceof ei||e instanceof Zr||e instanceof ti?e:new ti({getToken:e.getToken}),this._delegate=ii(this.app,{provider:n,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw ai.create("use-before-activation",{appName:this.app.name});!function(e,t){const n=lr(e.app);n.tokenRefresher&&(!0===t?n.tokenRefresher.start():n.tokenRefresher.stop()),n.isTokenAutoRefreshEnabled=t}(this._delegate,e)}getToken(e){if(!this._delegate)throw ai.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await Fr(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw ai.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),Ur(e,"EXTERNAL",r,i),()=>Vr(e.app,r)}(this._delegate,e,t)}}const ci=e=>{var t=e.getProvider("app-compat").getImmediate();return new oi(t)};function li(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}Nt.INTERNAL.registerComponent(new ue("appCheck-compat",ci,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:ei,ReCaptchaV3Provider:Zr,CustomProvider:ti})),Nt.registerVersion("@firebase/app-check-compat","0.3.16");const ui={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},hi={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 di(){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 pi(){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 registered for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is incorrect, malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is 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 fi=di,gi=new O("auth","Firebase",di()),mi=new ye("@firebase/auth");function vi(e,...t){mi.logLevel<=m.ERROR&&mi.error(`Auth (${it}): ${e}`,...t)}function _i(e,...t){throw Ti(e,...t)}function yi(e,...t){return Ti(e,...t)}function wi(e,t,n){var r=Object.assign(Object.assign({},fi()),{[t]:n});const i=new O("auth","Firebase",r);return i.create(t,{appName:e.name})}function bi(e){return wi(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Ii(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&_i(e,"argument-error"),wi(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function Ti(e,...t){if("string"==typeof e)return gi.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 Ei(e,t,...n){if(!e)throw Ti(t,...n)}function Ci(e){var t="INTERNAL ASSERTION FAILED: "+e;throw vi(t),new Error(t)}function Si(e,t){e||Ci(t)}function ki(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Ai(){return"http:"===Ni()||"https:"===Ni()}function Ni(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Ri{constructor(e,t){Si((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=I()||S()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(Ai()||C()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function Pi(e,t){Si(e.emulator,"Emulator should always be set here");var n=e.emulator["url"];return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class Di{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:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void Ci("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:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void Ci("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:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void Ci("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}const xi={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},Oi=new Ri(3e4,6e4);function Li(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function Mi(s,a,o,c,e={}){return Fi(s,e,async()=>{let e={},t={};c&&("GET"===a?t=c:e={body:JSON.stringify(c)});var n=$(Object.assign({key:s.config.apiKey},t)).slice(1);const r=await s._getAdditionalHeaders();r["Content-Type"]="application/json",s.languageCode&&(r["X-Firebase-Locale"]=s.languageCode);const i=Object.assign({method:a,headers:r},e);return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||(i.referrerPolicy="no-referrer"),Di.fetch()(Vi(s,s.config.apiHost,o,n),i)})}async function Fi(t,e,n){t._canInitEmulator=!1;var r=Object.assign(Object.assign({},xi),e);try{const a=new qi(t),o=await Promise.race([n(),a.promise]);a.clearNetworkTimeout();var i=await o.json();if("needConfirmation"in i)throw ji(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 ji(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===l)throw ji(t,"email-already-in-use",i);if("USER_DISABLED"===l)throw ji(t,"user-disabled",i);var s=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw wi(t,s,u);_i(t,s)}}catch(e){if(e instanceof x)throw e;_i(t,"network-request-failed",{message:String(e)})}}async function Ui(e,t,n,r,i={}){var s=await Mi(e,t,n,r,i);return"mfaPendingCredential"in s&&_i(e,"multi-factor-auth-required",{_serverResponse:s}),s}function Vi(e,t,n,r){var i=`${t}${n}?${r}`;return e.config.emulator?Pi(e.config,i):`${e.config.apiScheme}://${i}`}class qi{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(yi(this.auth,"network-request-failed")),Oi.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function ji(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=yi(e,t,r);return i.customData._tokenResponse=n,i}function Bi(e){return void 0!==e&&void 0!==e.getResponse}function zi(e){return void 0!==e&&void 0!==e.enterprise}class Ki{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return function(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function $i(e,t){return Mi(e,"GET","/v2/recaptchaConfig",Li(e,t))}async function Wi(e,t){return Mi(e,"POST","/v1/accounts:lookup",t)}function Gi(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Hi(e){return 1e3*Number(e)}function Qi(e){var[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return vi("JWT malformed, contained fewer than 3 sections"),null;try{var i=a(n);return i?JSON.parse(i):(vi("Failed to decode base64 JWT payload"),null)}catch(e){return vi("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}function Yi(e){var t=Qi(e);return Ei(t,"internal-error"),Ei(void 0!==t.exp,"internal-error"),Ei(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function Ji(t,n,e=!1){if(e)return n;try{return n}catch(e){throw e instanceof x&&(n=[e["code"]][0],"auth/user-disabled"===n||"auth/user-token-expired"===n)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class Xi{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 Zi{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Gi(this.lastLoginAt),this.creationTime=Gi(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function es(e){var t=e.auth,n=await e.getIdToken(),r=await Ji(e,Wi(t,{idToken:n}));Ei(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?ts(i.providerUserInfo):[],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 Zi(i.createdAt,i.lastLoginAt),isAnonymous:t};Object.assign(e,t)}function ts(e){return e.map(e=>{var t=e["providerId"],n=li(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})}class ns{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){Ei(e.idToken,"internal-error"),Ei(void 0!==e.idToken,"internal-error"),Ei(void 0!==e.refreshToken,"internal-error");var t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):Yi(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){Ei(0!==e.length,"internal-error");var t=Yi(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(Ei(this.refreshToken,e,"user-token-expired"),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null):this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){var i,s,{accessToken:n,refreshToken:r,expiresIn:a}=(s=t,await{accessToken:(a=await Fi(i=e,{},async()=>{var e=$({grant_type:"refresh_token",refresh_token:s}).slice(1),{tokenApiHost:t,apiKey:n}=i.config,n=Vi(i,t,"/v1/token",`key=${n}`);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",Di.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 ns;return n&&(Ei("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(Ei("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(Ei("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 ns,this.toJSON())}_performRefresh(){return Ci("not implemented")}}function rs(e,t){Ei("string"==typeof e||void 0===e,"internal-error",{appName:t})}class is{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=li(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new Xi(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 Zi(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await Ji(this,this.stsTokenManager.getToken(this.auth,e));return Ei(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=le(e);var r=await n.getIdToken(t),i=Qi(r);Ei(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:Gi(Hi(i.auth_time)),issuedAtTime:Gi(Hi(i.iat)),expirationTime:Gi(Hi(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=le(e);await es(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(Ei(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 is(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){Ei(!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 es(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(et(this.auth.app))return Promise.reject(bi(this.auth));var e=await this.getIdToken();return await Ji(this,async function(e,t){return Mi(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;Ei(u&&f,e,"internal-error");var g=ns.fromJSON(this.name,f);Ei("string"==typeof u,e,"internal-error"),rs(n,e.name),rs(r,e.name),Ei("boolean"==typeof h,e,"internal-error"),Ei("boolean"==typeof d,e,"internal-error"),rs(i,e.name),rs(s,e.name),rs(a,e.name),rs(o,e.name),rs(c,e.name),rs(l,e.name);const m=new is({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 ns;r.updateFromServerResponse(t);var i=new is({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await es(i),i}static async _fromGetAccountInfoResponse(e,t,n){var r=t.users[0];Ei(void 0!==r.localId,"internal-error");var i=void 0!==r.providerUserInfo?ts(r.providerUserInfo):[],s=!(r.email&&r.passwordHash||null!=i&&i.length);const a=new ns;a.updateFromIdToken(n);s=new is({uid:r.localId,auth:e,stsTokenManager:a,isAnonymous:s}),i={uid:r.localId,displayName:r.displayName||null,photoURL:r.photoUrl||null,email:r.email||null,emailVerified:r.emailVerified||!1,phoneNumber:r.phoneNumber||null,tenantId:r.tenantId||null,providerData:i,metadata:new Zi(r.createdAt,r.lastLoginAt),isAnonymous:!(r.email&&r.passwordHash||null!=i&&i.length)};return Object.assign(s,i),s}}const ss=new Map;function as(e){Si(e instanceof Function,"Expected a class definition");let t=ss.get(e);return t?Si(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,ss.set(e,t)),t}class os{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){}}os.type="NONE";const cs=os;function ls(e,t,n){return`firebase:${e}:${t}:${n}`}class us{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;var{config:r,name:i}=this.auth;this.fullUserKey=ls(this.userKey,r.apiKey,i),this.fullPersistenceKey=ls("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?is._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 us(as(cs),e,n);const r=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let i=r[0]||as(cs);const s=ls(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=is._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 us(i,e,n)}}function hs(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(gs(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(ds(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(vs(t))return"Blackberry";if(_s(t))return"Webos";if(ps(t))return"Safari";if((t.includes("chrome/")||fs(t))&&!t.includes("edge/"))return"Chrome";if(ms(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 ds(e=b()){return/firefox\//i.test(e)}function ps(e=b()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function fs(e=b()){return/crios\//i.test(e)}function gs(e=b()){return/iemobile/i.test(e)}function ms(e=b()){return/android/i.test(e)}function vs(e=b()){return/blackberry/i.test(e)}function _s(e=b()){return/webos/i.test(e)}function ys(e=b()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function ws(e=b()){return ys(e)||ms(e)||_s(e)||vs(e)||/windows phone/i.test(e)||gs(e)}function bs(e,t=[]){let n;switch(e){case"Browser":n=hs(b());break;case"Worker":n=`${hs(b())}-${e}`;break;default:n=e}var r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${it}/${r}`}class Is{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 Ts{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 Es{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 Ss(this),this.idTokenSubscription=new Ss(this),this.beforeStateQueue=new Is(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=gi,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=as(n)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await us.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 initializeCurrentUserFromIdToken(e){try{var t=await Wi(this,{idToken:e}),n=await is._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(n)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(et(this.app)){const o=this.app.settings.authIdToken;return o?new Promise(e=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(o).then(e,e))}):this.directlySetCurrentUser(null)}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 Ei(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 es(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){if(et(this.app))return Promise.reject(bi(this));const t=e?le(e):null;return t&&Ei(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&&Ei(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 et(this.app)?Promise.reject(bi(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return et(this.app)?Promise.reject(bi(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(as(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 Mi(e=this,"GET","/v2/passwordPolicy",Li(e,{})),t=new Ts(t);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new O("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise((e,t)=>{if(this.currentUser)e();else{const n=this.onAuthStateChanged(()=>{n(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){const n={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(n.tenantId=this.tenantId),t=this,e=n,await Mi(t,"POST","/v2/accounts:revokeToken",Li(t,e))}var 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||(Ei(t=e&&as(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await us.create(this,[as(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(Ei(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 Ei(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=bs(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=[],mi.logLevel<=m.WARN&&mi.warn(`Auth (${it}): ${e}`,...t)),null==n?void 0:n.token}}function Cs(e){return le(e)}class Ss{constructor(e){this.auth=e,this.observer=null,this.addObserver=Q(e=>this.observer=e)}get next(){return Ei(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let ks={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function As(e){return ks.loadJS(e)}function Ns(e){return`__${e}${Math.floor(1e6*Math.random())}`}class Rs{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 xs(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 Ps{constructor(){this.enterprise=new Ds}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class Ds{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class xs{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;Ei(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 Os="NO_RECAPTCHA";class Ls{constructor(e){this.type="recaptcha-enterprise",this.auth=Cs(e)}async verify(i="verify",e=!1){function s(e,t,n){const r=window.grecaptcha;zi(r)?r.enterprise.ready(()=>{r.enterprise.execute(e,{action:i}).then(e=>{t(e)}).catch(()=>{t(Os)})}):n(Error("No reCAPTCHA enterprise script loaded."))}if(this.auth.settings.appVerificationDisabledForTesting){const t=new Ps;return t.execute("siteKey",{action:"verify"})}return new Promise((n,r)=>{!async function(i){if(!e){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)=>{$i(i,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(e=>{if(void 0!==e.recaptchaKey){var t=new Ki(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)})})}(this.auth).then(t=>{if(!e&&zi(window.grecaptcha))s(t,n,r);else if("undefined"!=typeof window){let e=ks.recaptchaEnterpriseScript;0!==e.length&&(e+=t),As(e).then(()=>{s(t,n,r)}).catch(e=>{r(e)})}else r(new Error("RecaptchaVerifier is only supported in browser"))}).catch(e=>{r(e)})})}}async function Ms(e,t,n,r=!1,i=!1){const s=new Ls(e);let a;if(i)a=Os;else try{a=await s.verify(n)}catch(e){a=await s.verify(n,!0)}var o,c,l=Object.assign({},t);return"mfaSmsEnrollment"===n||"mfaSmsSignIn"===n?"phoneEnrollmentInfo"in l?(o=l.phoneEnrollmentInfo.phoneNumber,c=l.phoneEnrollmentInfo.recaptchaToken,Object.assign(l,{phoneEnrollmentInfo:{phoneNumber:o,recaptchaToken:c,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})):"phoneSignInInfo"in l&&(c=l.phoneSignInInfo.recaptchaToken,Object.assign(l,{phoneSignInInfo:{recaptchaToken:c,captchaResponse:a,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})):(r?Object.assign(l,{captchaResp:a}):Object.assign(l,{captchaResponse:a}),Object.assign(l,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(l,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"})),l}async function Fs(n,r,i,s,e){var t;if("EMAIL_PASSWORD_PROVIDER"===e){if(null!==(t=n._getRecaptchaConfig())&&void 0!==t&&t.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){var a=await Ms(n,r,i,"getOobCode"===i);return s(n,a)}return s(n,r).catch(async e=>{if("auth/missing-recaptcha-token"!==e.code)return Promise.reject(e);console.log(`${i} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);var t=await Ms(n,r,i,"getOobCode"===i);return s(n,t)})}if("PHONE_PROVIDER"!==e)return Promise.reject(e+" provider is not supported.");if(null!==(a=n._getRecaptchaConfig())&&void 0!==a&&a.isProviderEnabled("PHONE_PROVIDER")){var o=await Ms(n,r,i);return s(n,o).catch(async e=>{if("AUDIT"!==(null===(t=n._getRecaptchaConfig())||void 0===t?void 0:t.getProviderEnforcementState("PHONE_PROVIDER"))||"auth/missing-recaptcha-token"!==e.code&&"auth/invalid-app-credential"!==e.code)return Promise.reject(e);console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${i} flow.`);var t=await Ms(n,r,i,!1,!0);return s(n,t)})}o=await Ms(n,r,i,!1,!0);return s(n,o)}function Us(e,t,n){const r=Cs(e);Ei(r._canInitEmulator,r,"emulator-config-failed"),Ei(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");var i=!(null==n||!n.disableWarnings);const s=Vs(t);var{host:a,port:o}=function(e){const t=Vs(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:qs(r.substr(s.length+1))}}var[a,s]=r.split(":");return{host:a,port:qs(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 Vs(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function qs(e){if(!e)return null;var t=Number(e);return isNaN(t)?null:t}class js{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return Ci("not implemented")}_getIdTokenResponse(e){return Ci("not implemented")}_linkToIdToken(e,t){return Ci("not implemented")}_getReauthenticationResolver(e){return Ci("not implemented")}}async function Bs(e,t){return Mi(e,"POST","/v1/accounts:resetPassword",Li(e,t))}async function zs(e,t){return Mi(e,"POST","/v1/accounts:signUp",t)}async function Ks(e,t){return Ui(e,"POST","/v1/accounts:signInWithPassword",Li(e,t))}async function $s(e,t){return Mi(e,"POST","/v1/accounts:sendOobCode",Li(e,t))}async function Ws(e,t){return $s(e,t)}async function Gs(e,t){return $s(e,t)}class Hs extends js{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new Hs(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new Hs(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(e){switch(this.signInMethod){case"password":return Fs(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",Ks,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function(e,t){return Ui(e,"POST","/v1/accounts:signInWithEmailLink",Li(e,t))}(e,{email:this._email,oobCode:this._password});default:_i(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Fs(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",zs,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function(e,t){return Ui(e,"POST","/v1/accounts:signInWithEmailLink",Li(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:_i(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Qs(e,t){return Ui(e,"POST","/v1/accounts:signInWithIdp",Li(e,t))}class Ys extends js{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new Ys(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):_i("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=li(t,["providerId","signInMethod"]);if(!n||!r)return null;const i=new Ys(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 Qs(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Qs(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Qs(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=$(t)}return e}}async function Js(e,t){return Mi(e,"POST","/v1/accounts:sendVerificationCode",Li(e,t))}const Xs={USER_NOT_FOUND:"user-not-found"};class Zs extends js{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Zs({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Zs({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return Ui(e,"POST","/v1/accounts:signInWithPhoneNumber",Li(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await Ui(e,"POST","/v1/accounts:signInWithPhoneNumber",Li(e,t));if(n.temporaryProof)throw ji(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return Ui(e,"POST","/v1/accounts:signInWithPhoneNumber",Li(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Xs)}(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 Zs({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class ea{constructor(e){var t=W(G(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);Ei(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=W(G(e=e)).link,n=t?W(G(t)).deep_link_id:null,((r=W(G(e)).deep_link_id)?W(G(r)).link:null)||r||n||t||e);try{return new ea(t)}catch(e){return null}}}class ta{constructor(){this.providerId=ta.PROVIDER_ID}static credential(e,t){return Hs._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var n=ea.parseLink(t);return Ei(n,"argument-error"),Hs._fromEmailAndCode(e,n.code,n.tenantId)}}ta.PROVIDER_ID="password",ta.EMAIL_PASSWORD_SIGN_IN_METHOD="password",ta.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class na{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 ra extends na{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class ia extends ra{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return Ei("providerId"in t&&"signInMethod"in t,"argument-error"),Ys._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return Ei(e.idToken||e.accessToken,"argument-error"),Ys._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return ia.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return ia.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 ia(a)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class sa extends ra{constructor(){super("facebook.com")}static credential(e){return Ys._fromParams({providerId:sa.PROVIDER_ID,signInMethod:sa.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return sa.credentialFromTaggedObject(e)}static credentialFromError(e){return sa.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return sa.credential(e.oauthAccessToken)}catch(e){return null}}}sa.FACEBOOK_SIGN_IN_METHOD="facebook.com",sa.PROVIDER_ID="facebook.com";class aa extends ra{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Ys._fromParams({providerId:aa.PROVIDER_ID,signInMethod:aa.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return aa.credentialFromTaggedObject(e)}static credentialFromError(e){return aa.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return aa.credential(t,n)}catch(e){return null}}}aa.GOOGLE_SIGN_IN_METHOD="google.com",aa.PROVIDER_ID="google.com";class oa extends ra{constructor(){super("github.com")}static credential(e){return Ys._fromParams({providerId:oa.PROVIDER_ID,signInMethod:oa.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return oa.credentialFromTaggedObject(e)}static credentialFromError(e){return oa.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return oa.credential(e.oauthAccessToken)}catch(e){return null}}}oa.GITHUB_SIGN_IN_METHOD="github.com",oa.PROVIDER_ID="github.com";class ca extends js{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return Qs(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Qs(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Qs(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 ca(t,r):null}static _create(e,t){return new ca(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class la extends na{constructor(e){Ei(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return la.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return la.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=ca.fromJSON(e);return Ei(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 ca._create(n,t)}catch(e){return null}}}class ua extends ra{constructor(){super("twitter.com")}static credential(e,t){return Ys._fromParams({providerId:ua.PROVIDER_ID,signInMethod:ua.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return ua.credentialFromTaggedObject(e)}static credentialFromError(e){return ua.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return ua.credential(t,n)}catch(e){return null}}}async function ha(e,t){return Ui(e,"POST","/v1/accounts:signUp",Li(e,t))}ua.TWITTER_SIGN_IN_METHOD="twitter.com",ua.PROVIDER_ID="twitter.com";class da{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 is._fromIdTokenResponse(e,n,r),s=pa(n);return new da({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);var r=pa(n);return new da({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function pa(e){return e.providerId||("phoneNumber"in e?"phone":null)}class fa extends x{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,fa.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 fa(e,t,n,r)}}function ga(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 fa._fromErrorAndOperation(t,e,n,r);throw e})}function ma(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function va(e,t){const n=le(e);await ya(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await Mi(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=ma(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 _a(e,t,n=!1){var r=await Ji(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return da._forOperation(e,"link",r)}async function ya(e,t,n){await es(t);const r=ma(t.providerData);var i=!1===e?"provider-already-linked":"no-such-provider";Ei(r.has(n)===e,t.auth,i)}async function wa(e,t,n=!1){var r=e["auth"];if(et(r.app))return Promise.reject(bi(r));var i="reauthenticate";try{var s=await Ji(e,ga(r,i,t,e),n);Ei(s.idToken,r,"internal-error");var a=Qi(s.idToken);Ei(a,r,"internal-error");var o=a["sub"];return Ei(e.uid===o,r,"user-mismatch"),da._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&_i(r,"user-mismatch"),e}}async function ba(e,t,n=!1){if(et(e.app))return Promise.reject(bi(e));var r=await ga(e,"signIn",t),r=await da._fromIdTokenResponse(e,"signIn",r);return n||await e._updateCurrentUser(r.user),r}async function Ia(e,t){return ba(Cs(e),t)}async function Ta(e,t){var n=le(e);return await ya(!1,n,t.providerId),_a(n,t)}async function Ea(e,t){return wa(le(e),t)}async function Ca(e,t){if(et(e.app))return Promise.reject(bi(e));const n=Cs(e);var r=await Ui(n,"POST","/v1/accounts:signInWithCustomToken",Li(n,{token:t,returnSecureToken:!0})),r=await da._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?ka._fromServerResponse(e,t):"totpInfo"in t?Aa._fromServerResponse(e,t):_i(e,"internal-error")}}class ka extends Sa{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new ka(t)}}class Aa extends Sa{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new Aa(t)}}function Na(e,t,n){var r;Ei(0<(null===(r=n.url)||void 0===r?void 0:r.length),e,"invalid-continue-uri"),Ei(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&&(Ei(0<n.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(Ei(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 Ra(e){const t=Cs(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function Pa(e,t){await Mi(e=le(e),"POST","/v1/accounts:update",Li(e,{oobCode:t}))}async function Da(e,t){var n=le(e),r=await Bs(n,{oobCode:t}),i=r.requestType;switch(Ei(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":Ei(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":Ei(r.mfaInfo,n,"internal-error");default:Ei(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=Sa._fromServerResponse(Cs(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 xa(e,t){var n=Ai()?ki():"http://localhost",n=(await Mi(e=le(e),"POST","/v1/accounts:createAuthUri",Li(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function Oa(e,t){var n=le(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&Na(n.auth,r,t);var r=(await $s(n.auth,r))["email"];r!==e.email&&await e.reload()}async function La(e,t,n){var r=le(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&Na(r.auth,i,n);var i=(await $s(r.auth,i))["email"];i!==e.email&&await e.reload()}async function Ma(e,{displayName:t,photoURL:n}){if(void 0!==t||void 0!==n){const i=le(e);var r=await i.getIdToken(),r=await Ji(i,async function(e,t){return Mi(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 Fa(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 Ji(e,async function(e,t){return Mi(e,"POST","/v1/accounts:update",t)}(r,i));await e._updateTokensIfNecessary(r,!0)}class Ua{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class Va extends Ua{constructor(e,t,n,r){super(e,t,n),this.username=r}}class qa extends Ua{constructor(e,t){super(e,"facebook.com",t)}}class ja extends Va{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 Ua{constructor(e,t){super(e,"google.com",t)}}class za extends Va{constructor(e,t,n){super(e,"twitter.com",t,n)}}function Ka(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=Qi(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 Ua(r,i)}}if(!t)return null;switch(t){case"facebook.com":return new qa(r,n);case"github.com":return new ja(r,n);case"google.com":return new Ba(r,n);case"twitter.com":return new za(r,n,e.screenName||null);case"custom":case"anonymous":return new Ua(r,null);default:return new Ua(r,t,n)}}(n)}class $a{constructor(e,t,n){this.type=e,this.credential=t,this.user=n}static _fromIdtoken(e,t){return new $a("enroll",e,t)}static _fromMfaPendingCredential(e){return new $a("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 $a._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.idToken)return $a._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Wa{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,i){const s=Cs(e),a=i.customData._serverResponse;var t=(a.mfaInfo||[]).map(e=>Sa._fromServerResponse(s,e));Ei(a.mfaPendingCredential,s,"internal-error");const o=$a._fromMfaPendingCredential(a.mfaPendingCredential);return new Wa(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 da._fromIdTokenResponse(s,i.operationType,n);return await s._updateCurrentUser(r.user),r;case"reauthenticate":return Ei(i.user,s,"internal-error"),da._forOperation(i.user,i.operationType,n);default:_i(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}function Ga(e,t){return Mi(e,"POST","/v2/accounts/mfaEnrollment:start",Li(e,t))}class Ha{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 Ha(e)}async getSession(){return $a._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const n=e;var r=await this.getSession(),r=await Ji(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 Ji(this.user,(n=this.user.auth,r={idToken:i,mfaEnrollmentId:t},Mi(n,"POST","/v2/accounts/mfaEnrollment:withdraw",Li(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 Qa=new WeakMap;const Ya="__sak";class Ja{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Ya,"1"),this.storage.removeItem(Ya),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 Xa extends Ja{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=ws(),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 i=e.key;t?this.detachListener():this.stopPolling();var n=()=>{var e=this.storage.getItem(i);!t&&this.localCache[i]===e||this.notifyListeners(i,e)},r=this.storage.getItem(i);k()&&10===document.documentMode&&r!==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]}}Xa.type="LOCAL";const Za=Xa;class eo extends Ja{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}eo.type="SESSION";const to=eo;class no{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 no(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 ro(e="",t=10){let n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}no.receivers=[];class io{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=ro("",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 so(){return window}function ao(){return void 0!==so().WorkerGlobalScope&&"function"==typeof so().importScripts}const oo="firebaseLocalStorageDb",co="firebaseLocalStorage",lo="fbase_key";class uo{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 ho(e,t){return e.transaction([co],t?"readwrite":"readonly").objectStore(co)}function po(){const r=indexedDB.open(oo,1);return new Promise((n,t)=>{r.addEventListener("error",()=>{t(r.error)}),r.addEventListener("upgradeneeded",()=>{const e=r.result;try{e.createObjectStore(co,{keyPath:lo})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains(co)?n(e):(e.close(),t=indexedDB.deleteDatabase(oo),await new uo(t).toPromise(),n(await po()))})})}async function fo(e,t,n){var r=ho(e,!0).put({fbase_key:t,value:n});return new uo(r).toPromise()}function go(e,t){var n=ho(e,!0).delete(t);return new uo(n).toPromise()}class mo{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 po(),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 ao()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=no._getInstance(ao()?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 io(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 po();return await fo(e,Ya,"1"),await go(e,Ya),!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=>fo(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=ho(e,!1).get(t);return void 0===(n=await new uo(n).toPromise())?null:n.value}(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>go(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e=await this._withRetries(e=>{var t=ho(e,!1).getAll();return new uo(t).toPromise()});if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;if(0!==e.length)for(var{fbase_key:r,value:i}of e)n.add(r),JSON.stringify(this.localCache[r])!==JSON.stringify(i)&&(this.notifyListeners(r,i),t.push(r));for(const s of Object.keys(this.localCache))this.localCache[s]&&!n.has(s)&&(this.notifyListeners(s,null),t.push(s));return t}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()}}mo.type="LOCAL";const vo=mo;function _o(e,t){return Mi(e,"POST","/v2/accounts/mfaSignIn:start",Li(e,t))}const yo=Ns("rcb"),wo=new Ri(3e4,6e4);class bo{constructor(){var e;this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!(null===(e=so().grecaptcha)||void 0===e||!e.render)}load(s,a=""){var e;return Ei((e=a).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),s,"argument-error"),this.shouldResolveImmediately(a)&&Bi(so().grecaptcha)?Promise.resolve(so().grecaptcha):new Promise((t,n)=>{const i=so().setTimeout(()=>{n(yi(s,"network-request-failed"))},wo.get());so()[yo]=()=>{so().clearTimeout(i),delete so()[yo];const e=so().grecaptcha;if(e&&Bi(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(yi(s,"internal-error"))},As(`${ks.recaptchaV2Script}?${$({onload:yo,render:"explicit",hl:a})}`).catch(()=>{clearTimeout(i),n(yi(s,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){var t;return!(null===(t=so().grecaptcha)||void 0===t||!t.render)&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class Io{async load(e){return new Rs(e)}clearedOneInstance(){}}const To="recaptcha",Eo={theme:"light",type:"image"};class Co{constructor(e,t,n=Object.assign({},Eo)){this.parameters=n,this.type=To,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=Cs(e),this.isInvisible="invisible"===this.parameters.size,Ei("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var r="string"==typeof t?document.getElementById(t):t;Ei(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?Io:bo),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(){Ei(!this.parameters.sitekey,this.auth,"argument-error"),Ei(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),Ei("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=so()[n];"function"==typeof e&&e(t)}}}assertNotDestroyed(){Ei(!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(){Ei(Ai()&&!ao(),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 Mi(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");Ei(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return Ei(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class So{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Zs._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function ko(t,n,r){var i;if(!t._getRecaptchaConfig())try{await async function(e){const t=Cs(e);var n=await $i(t,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"});const r=new Ki(n);if(null==t.tenantId?t._agentRecaptchaConfig=r:t._tenantRecaptchaConfigs[t.tenantId]=r,r.isAnyProviderEnabled()){const i=new Ls(t);i.verify()}}(t)}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}try{let e;if(e="string"==typeof n?{phoneNumber:n}:n,"session"in e){var s=e.session;if("phoneNumber"in e){Ei("enroll"===s.type,t,"internal-error");var a={idToken:s.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"}};const u=Fs(t,a,"mfaSmsEnrollment",async(e,t)=>{return t.phoneEnrollmentInfo.captchaResponse!==Os?Ga(e,t):(Ei((null==r?void 0:r.type)===To,e,"argument-error"),Ga(e,await Ao(e,t,r)))},"PHONE_PROVIDER");return(await u.catch(e=>Promise.reject(e))).phoneSessionInfo.sessionInfo}{Ei("signin"===s.type,t,"internal-error");var o=(null===(i=e.multiFactorHint)||void 0===i?void 0:i.uid)||e.multiFactorUid;Ei(o,t,"missing-multi-factor-info");var c={mfaPendingCredential:s.credential,mfaEnrollmentId:o,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}};const h=Fs(t,c,"mfaSmsSignIn",async(e,t)=>{return t.phoneSignInInfo.captchaResponse!==Os?_o(e,t):(Ei((null==r?void 0:r.type)===To,e,"argument-error"),_o(e,await Ao(e,t,r)))},"PHONE_PROVIDER");return(await h.catch(e=>Promise.reject(e))).phoneResponseInfo.sessionInfo}}{var l={phoneNumber:e.phoneNumber,clientType:"CLIENT_TYPE_WEB"};const d=Fs(t,l,"sendVerificationCode",async(e,t)=>{return t.captchaResponse!==Os?Js(e,t):(Ei((null==r?void 0:r.type)===To,e,"argument-error"),Js(e,await Ao(e,t,r)))},"PHONE_PROVIDER");return(await d.catch(e=>Promise.reject(e))).sessionInfo}}finally{null!=r&&r._reset()}}async function Ao(e,t,n){Ei(n.type===To,e,"argument-error");var r=await n.verify();Ei("string"==typeof r,e,"argument-error");var i=Object.assign({},t);if("phoneEnrollmentInfo"in i){var s=i.phoneEnrollmentInfo.phoneNumber,a=i.phoneEnrollmentInfo.captchaResponse,o=i.phoneEnrollmentInfo.clientType,c=i.phoneEnrollmentInfo.recaptchaVersion;return Object.assign(i,{phoneEnrollmentInfo:{phoneNumber:s,recaptchaToken:r,captchaResponse:a,clientType:o,recaptchaVersion:c}}),i}if("phoneSignInInfo"in i){a=i.phoneSignInInfo.captchaResponse,o=i.phoneSignInInfo.clientType,c=i.phoneSignInInfo.recaptchaVersion;return Object.assign(i,{phoneSignInInfo:{recaptchaToken:r,captchaResponse:a,clientType:o,recaptchaVersion:c}}),i}return Object.assign(i,{recaptchaToken:r}),i}class No{constructor(e){this.providerId=No.PROVIDER_ID,this.auth=Cs(e)}verifyPhoneNumber(e,t){return ko(this.auth,e,le(t))}static credential(e,t){return Zs._fromVerification(e,t)}static credentialFromResult(e){var t=e;return No.credentialFromTaggedObject(t)}static credentialFromError(e){return No.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{phoneNumber:t,temporaryProof:n}=e;return t&&n?Zs._fromTokenResponse(t,n):null}}function Ro(e,t){return t?as(t):(Ei(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}No.PROVIDER_ID="phone",No.PHONE_SIGN_IN_METHOD="phone";class Po extends js{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Qs(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Qs(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Qs(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 Do(e){return ba(e.auth,new Po(e),e.bypassAuthState)}function xo(e){var{auth:t,user:n}=e;return Ei(n,t,"internal-error"),wa(n,new Po(e),e.bypassAuthState)}async function Oo(e){var{auth:t,user:n}=e;return Ei(n,t,"internal-error"),_a(n,new Po(e),e.bypassAuthState)}class Lo{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 Do;case"linkViaPopup":case"linkViaRedirect":return Oo;case"reauthViaPopup":case"reauthViaRedirect":return xo;default:_i(this.auth,"internal-error")}}resolve(e){Si(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){Si(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 Mo=new Ri(2e3,1e4);class Fo extends Lo{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,Fo.currentPopupAction&&Fo.currentPopupAction.cancel(),Fo.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return Ei(e,this.auth,"internal-error"),e}async onExecution(){Si(1===this.filter.length,"Popup operations only handle one event");var e=ro();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(yi(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(yi(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Fo.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(yi(this.auth,"popup-closed-by-user"))},8e3):this.pollId=window.setTimeout(t,Mo.get())};t()}}Fo.currentPopupAction=null;const Uo="pendingRedirect",Vo=new Map;class qo extends Lo{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=Ko(t),r=zo(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 jo(e,t){return zo(e)._set(Ko(t),"true")}function Bo(e,t){Vo.set(e._key(),t)}function zo(e){return as(e._redirectPersistence)}function Ko(e){return ls(Uo,e.config.apiKey,e.name)}function $o(e,t,n){return async function(e,t,n){if(et(e.app))return Promise.reject(bi(e));var r=Cs(e);Ii(e,t,na),await r._initializationPromise;const i=Ro(r,n);return await jo(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function Wo(e,t,n){return async function(e,t,n){var r=le(e);if(Ii(r.auth,t,na),et(r.auth.app))return Promise.reject(bi(r.auth));await r.auth._initializationPromise;const i=Ro(r.auth,n);await jo(i,r.auth);var s=await Qo(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function Go(e,t,n){return async function(e,t,n){var r=le(e);Ii(r.auth,t,na),await r.auth._initializationPromise;const i=Ro(r.auth,n);await ya(!1,r,t.providerId),await jo(i,r.auth);var s=await Qo(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function Ho(e,t,n=!1){if(et(e.app))return Promise.reject(bi(e));const r=Cs(e);var i=Ro(r,t);const s=new qo(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 Qo(e){var t=ro(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class Yo{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 Xo(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!Xo(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(yi(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(Jo(e))}saveEventToCache(e){this.cachedEventUids.add(Jo(e)),this.lastProcessedEventTime=Date.now()}}function Jo(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function Xo({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function Zo(e,t={}){return Mi(e,"GET","/v1/projects",t)}const ec=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,tc=/^https?/;async function nc(e){if(!e.config.emulator){var t=(await Zo(e))["authorizedDomains"];for(const n of t)try{if(function(e){const t=ki(),{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(!tc.test(n))return!1;if(ec.test(e))return r===e;const s=e.replace(/\./g,"\\."),a=new RegExp("^(.+\\."+s+"|"+s+")$","i");return a.test(r)}(n))return}catch(e){}_i(e,"unauthorized-domain")}}const rc=new Ri(3e4,6e4);function ic(){const t=so().___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}function sc(i){return new Promise((e,t)=>{function n(){ic(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{ic(),t(yi(i,"network-request-failed"))},timeout:rc.get()})}if(null!==(r=null===(r=so().gapi)||void 0===r?void 0:r.iframes)&&void 0!==r&&r.Iframe)e(gapi.iframes.getContext());else{if(null===(r=so().gapi)||void 0===r||!r.load){var r=Ns("iframefcb");return so()[r]=()=>{gapi.load?n():t(yi(i,"network-request-failed"))},As(`${ks.gapiScript}?onload=${r}`).catch(e=>t(e))}n()}}).catch(e=>{throw ac=null,e})}let ac=null;const oc=new Ri(5e3,15e3),cc="__/auth/iframe",lc="emulator/auth/iframe",uc={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},hc=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function dc(a){const e=(t=a,ac=ac||sc(t),await ac);var t,n=so().gapi;return Ei(n,a,"internal-error"),e.open({where:document.body,url:function(e){var t=e.config;Ei(t.authDomain,e,"auth-domain-config-required");var n=t.emulator?Pi(t,lc):`https://${e.config.authDomain}/${cc}`;const r={apiKey:t.apiKey,appName:e.name,v:it};(t=hc.get(e.config.apiHost))&&(r.eid=t);const i=e._getFrameworks();return i.length&&(r.fw=i.join(",")),`${n}?${$(r).slice(1)}`}(a),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:uc,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=yi(a,"network-request-failed"),r=so().setTimeout(()=>{t(n)},oc.get());function i(){so().clearTimeout(r),e(s)}s.ping(i).then(i,()=>{t(n)})}))}const pc={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class fc{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function gc(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({},pc),{width:r.toString(),height:i.toString(),top:s,left:a});s=b().toLowerCase();n&&(o=fs(s)?"_blank":n),ds(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],ys(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 fc(null);const u=window.open(t||"",o,a);Ei(u,e,"popup-blocked");try{u.focus()}catch(e){}return new fc(u)}const mc="__/auth/handler",vc="emulator/auth/handler",_c=encodeURIComponent("fac");async function yc(e,t,n,r,i,s){Ei(e.config.authDomain,e,"auth-domain-config-required"),Ei(e.config.apiKey,e,"invalid-api-key");const a={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:it,eventId:i};if(t instanceof na){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||"",j(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(var[o,c]of Object.entries(s||{}))a[o]=c}if(t instanceof ra){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?`#${_c}=${encodeURIComponent(u)}`:"";return`${e=[e["config"]][0],e.emulator?Pi(e,vc):`https://${e.authDomain}/${mc}`}?${$(l).slice(1)}${u}`}const wc="webStorageSupport";const bc=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=to,this._completeRedirectFn=Ho,this._overrideRedirectResult=Bo}async _openPopup(e,t,n,r){var i;return Si(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),gc(e,await yc(e,t,n,ki(),r),ro())}async _openRedirect(e,t,n,r){await this._originValidation(e);var i=await yc(e,t,n,ki(),r);return so().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):(Si(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 dc(t),n=new Yo(t);return e.register("authEvent",e=>{return Ei(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(wc,{type:wc},e=>{var t=null===(t=null==e?void 0:e[0])||void 0===t?void 0:t[wc];void 0!==t&&r(!!t),_i(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=nc(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return ws()||ps()||ys()}};class Ic 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 Ci("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new Ic(e)}_finalizeEnroll(e,t,n){return e=e,n={idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()},Mi(e,"POST","/v2/accounts/mfaEnrollment:finalize",Li(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},Mi(e,"POST","/v2/accounts/mfaSignIn:finalize",Li(e,t))}}class Tc{constructor(){}static assertion(e){return Ic._fromCredential(e)}}Tc.FACTOR_ID="phone";var Ec="@firebase/auth";class Cc{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(){Ei(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}var Sc,kc,Ac;function Nc(){return window}Sc="authIdTokenMaxAge",null===(kc=p())||void 0===kc||kc[`_${Sc}`],ks={loadJS(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=yi("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)})},gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="},Ac="Browser",Je(new ue("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;Ei(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:bs(Ac)},o=new Es(n,r,i,o);return function(e,t){const n=(null==t?void 0:t.persistence)||[];var r=(Array.isArray(n)?n:[n]).map(as);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()})),Je(new ue("auth-internal",e=>{var t=Cs(e.getProvider("auth").getImmediate());return e=t,new Cc(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),ct(Ec,"1.8.0",function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(Ac)),ct(Ec,"1.8.0","esm2017");async function Rc(e,t,n){var r=Nc()["BuildInfo"];Si(t.sessionId,"AuthEvent did not contain a session ID");var i=await async function(e){const t=function(e){if(Si(/[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 ys()?s.ibi=r.packageName:ms()?s.apn=r.packageName:_i(e,"operation-not-supported-in-this-environment"),r.displayName&&(s.appDisplayName=r.displayName),s.sessionId=i,yc(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,s)}function Pc(r){const i=Nc()["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 Dc=20;class xc extends Yo{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInitialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInitialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function Oc(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:function(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<Dc;r++){var n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}(),postBody:null,tenantId:e.tenantId,error:yi(e,"no-auth-event")}}async function Lc(e){var t=await Fc()._get(Uc(e));return t&&await Fc()._remove(Uc(e)),t}function Mc(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?yi(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 Fc(){return as(Za)}function Uc(e){return ls("authEvent",e.config.apiKey,e.name)}function Vc(e){if(null==e||!e.includes("?"))return{};const[,...t]=e.split("?");return W(t.join("?"))}const qc=class{constructor(){this._redirectPersistence=to,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=Ho,this._overrideRedirectResult=Bo}async _initialize(e){var t=e._key();let n=this.eventManagers.get(t);return n||(n=new xc(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){_i(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){var i,s;i=e,o=Nc(),Ei("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"}),Ei(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"}),Ei("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"}),Ei("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"}),Ei("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=Oc(e,n,r);n=e,r=o,await Fc()._set(Uc(n),r);o=await Pc(await Rc(e,o,t));return async function(a,o,c){const l=Nc()["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(yi(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),ms()&&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=Nc()["BuildInfo"];const n={};ys()?n.iosBundleId=t.packageName:ms()?n.androidPackageName=t.packageName:_i(e,"operation-not-supported-in-this-environment"),await Zo(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=Nc(),s=setTimeout(async()=>{await Lc(r),i.onEvent(jc())},500),a=async e=>{clearTimeout(s);var t=await Lc(r);let n=null;t&&null!=e&&e.url&&(n=Mc(t,e.url)),i.onEvent(n||jc())};void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,a);const o=t,c=`${n.packageName.toLowerCase()}://`;Nc().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&a({url:e}),"function"==typeof o)try{o(e)}catch(e){console.error(e)}}}};function jc(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:yi("no-auth-event")}}var Bc;function zc(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function Kc(e=b()){return!("file:"!==zc()&&"ionic:"!==zc()&&"capacitor:"!==zc()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function $c(e=b()){return k()&&11===(null===document||void 0===document?void 0:document.documentMode)||([e=b()]=[e],/Edge\/\d+/.test(e))}function Wc(){try{const t=self.localStorage;var e=ro();if(t)return t.setItem(e,"1"),t.removeItem(e),!$c()||R()}catch(e){return Gc()&&R()}return!1}function Gc(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function Hc(){return("http:"===zc()||"https:"===zc()||C()||Kc())&&!(S()||T())&&Wc()&&!Gc()}function Qc(){return Kc()&&"undefined"!=typeof document}const Yc={LOCAL:"local",NONE:"none",SESSION:"session"},Jc=Ei,Xc="persistence";async function Zc(e){await e._initializationPromise;const t=el();var n=ls(Xc,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function el(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}const tl=Ei;class nl{constructor(){this.browserResolver=as(bc),this.cordovaResolver=as(qc),this.underlyingResolver=null,this._redirectPersistence=to,this._completeRedirectFn=Ho,this._overrideRedirectResult=Bo}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 Qc()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return tl(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!Qc()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function rl(e){return e.unwrap()}function il(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 cl(e,(n=t,i=le(e),Ei((a=n).customData.operationType,i,"argument-error"),Ei(null===(r=a.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,i,"argument-error"),Wa._fromError(i,a)))}else if(s){var a=sl(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 sl(e){var t=(e instanceof x?e.customData:e)["_tokenResponse"];if(!t)return null;if(!(e instanceof x)&&"temporaryProof"in t&&"phoneNumber"in t)return No.credentialFromResult(e);const n=t.providerId;if(!n||n===ui.PASSWORD)return null;let r;switch(n){case ui.GOOGLE:r=aa;break;case ui.FACEBOOK:r=sa;break;case ui.GITHUB:r=oa;break;case ui.TWITTER:r=ua;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:a,pendingToken:o,nonce:c}=t;return s||a||i||o?o?n.startsWith("saml.")?ca._create(n,o):Ys._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:i,accessToken:s}):new ia(n).credential({idToken:i,accessToken:s,rawNonce:c}):null}return e instanceof x?r.credentialFromError(e):r.credentialFromResult(e)}function al(t,e){return e.catch(e=>{throw e instanceof x&&il(t,e),e}).then(e=>{var t=e.operationType,n=e.user;return{operationType:t,credential:sl(e),additionalUserInfo:Ka(e),user:ll.getOrCreate(n)}})}async function ol(t,e){const n=await e;return{verificationId:n.verificationId,confirm:e=>al(t,n.confirm(e))}}class cl{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 al(rl(this.auth),this.resolver.resolveSignIn(e))}}class ll{constructor(e){var t;this._delegate=e,this.multiFactor=(t=le(e),Qa.has(t)||Qa.set(t,Ha._fromUser(t)),Qa.get(t))}static getOrCreate(e){return ll.USER_MAP.has(e)||ll.USER_MAP.set(e,new ll(e)),ll.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 al(this.auth,Ta(this._delegate,e))}async linkWithPhoneNumber(e,t){return ol(this.auth,async function(e,t,n){const r=le(e);await ya(!1,r,"phone");var i=await ko(r.auth,t,le(n));return new So(i,e=>Ta(r,e))}(this._delegate,e,t))}async linkWithPopup(e){return al(this.auth,async function(e,t,n){var r=le(e);Ii(r.auth,t,na);var i=Ro(r.auth,n);const s=new Fo(r.auth,"linkViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,nl))}async linkWithRedirect(e){return await Zc(Cs(this.auth)),Go(this._delegate,e,nl)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return al(this.auth,Ea(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return ol(this.auth,async function(e,t,n){const r=le(e);if(et(r.auth.app))return Promise.reject(bi(r.auth));var i=await ko(r.auth,t,le(n));return new So(i,e=>Ea(r,e))}(this._delegate,e,t))}reauthenticateWithPopup(e){return al(this.auth,async function(e,t,n){var r=le(e);if(et(r.auth.app))return Promise.reject(yi(r.auth,"operation-not-supported-in-this-environment"));Ii(r.auth,t,na);var i=Ro(r.auth,n);const s=new Fo(r.auth,"reauthViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,nl))}async reauthenticateWithRedirect(e){return await Zc(Cs(this.auth)),Wo(this._delegate,e,nl)}sendEmailVerification(e){return Oa(this._delegate,e)}async unlink(e){return await va(this._delegate,e),this}updateEmail(e){return t=this._delegate,e=e,et((n=le(t)).auth.app)?Promise.reject(bi(n.auth)):Fa(n,e,null);var t,n}updatePassword(e){return Fa(le(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){var n=le(e);if(et(n.auth.app))return Promise.reject(bi(n.auth));await _a(n,t)}(this._delegate,e)}updateProfile(e){return Ma(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return La(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}}ll.USER_MAP=new WeakMap;const ul=Ei;class hl{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();var n=e.options["apiKey"];ul(n,"invalid-api-key",{appName:e.name}),ul(n,"invalid-api-key",{appName:e.name});var r="undefined"!=typeof window?nl:void 0;this._delegate=t.initialize({options:{persistence:function(e,t){const n=function(e,t){const n=el();if(!n)return[];var r=ls(Xc,e,t);switch(n.getItem(r)){case Yc.NONE:return[cs];case Yc.LOCAL:return[vo,to];case Yc.SESSION:return[to];default:return[]}}(e,t);"undefined"==typeof self||n.includes(vo)||n.push(vo);if("undefined"!=typeof window)for(const r of[Za,to])n.includes(r)||n.push(r);n.includes(cs)||n.push(cs);return n}(n,e.name),popupRedirectResolver:r}}),this._delegate._updateErrorMap(pi),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?ll.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){Us(this._delegate,e,t)}applyActionCode(e){return Pa(this._delegate,e)}checkActionCode(e){return Da(this._delegate,e)}confirmPasswordReset(e,t){return async function(t,e,n){await Bs(le(t),{oobCode:e,newPassword:n}).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&Ra(t),e})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return al(this._delegate,async function(t,e,n){if(et(t.app))return Promise.reject(bi(t));const r=Cs(t),i=Fs(r,{returnSecureToken:!0,email:e,password:n,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",ha,"EMAIL_PASSWORD_PROVIDER");var s=await i.catch(e=>{throw"auth/password-does-not-meet-requirements"===e.code&&Ra(t),e}),s=await da._fromIdTokenResponse(r,"signIn",s);return await r._updateCurrentUser(s.user),s}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return xa(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=ea.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){ul(Hc(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=nl,await Cs(e)._initializationPromise,await Ho(e,t,!1));return n?al(this._delegate,Promise.resolve(n)):{credential:null,user:null}}addFrameworkForLogging(e){Cs(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,n){var{next:r,error:i,complete:s}=dl(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=dl(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return async function(e,t,n){const r=Cs(e);var i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};t=i,Ei((n=n).handleCodeInApp,r,"argument-error"),n&&Na(r,t,n),await Fs(r,i,"getOobCode",Gs,"EMAIL_PASSWORD_PROVIDER")}(this._delegate,e,t)}sendPasswordResetEmail(e,t){return async function(e,t,n){var r=Cs(e),i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};n&&Na(r,i,n),await Fs(r,i,"getOobCode",Ws,"EMAIL_PASSWORD_PROVIDER")}(this._delegate,e,t||void 0)}async setPersistence(e){var t,n;t=this._delegate,n=e,Jc(Object.values(Yc).includes(n),t,"invalid-persistence-type"),S()?Jc(n!==Yc.SESSION,t,"unsupported-persistence-type"):T()?Jc(n===Yc.NONE,t,"unsupported-persistence-type"):Gc()?Jc(n===Yc.NONE||n===Yc.LOCAL&&R(),t,"unsupported-persistence-type"):Jc(n===Yc.NONE||Wc(),t,"unsupported-persistence-type");let r;switch(e){case Yc.SESSION:r=to;break;case Yc.LOCAL:var i=await as(vo)._isAvailable();r=i?vo:Za;break;case Yc.NONE:r=cs;break;default:return _i("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(r)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return al(this._delegate,async function(e){if(et(e.app))return Promise.reject(bi(e));const t=Cs(e);if(await t._initializationPromise,null!==(n=t.currentUser)&&void 0!==n&&n.isAnonymous)return new da({user:t.currentUser,providerId:null,operationType:"signIn"});var n=await ha(t,{returnSecureToken:!0}),n=await da._fromIdTokenResponse(t,"signIn",n,!0);return await t._updateCurrentUser(n.user),n}(this._delegate))}signInWithCredential(e){return al(this._delegate,Ia(this._delegate,e))}signInWithCustomToken(e){return al(this._delegate,Ca(this._delegate,e))}signInWithEmailAndPassword(e,t){return al(this._delegate,(n=this._delegate,e=e,t=t,et(n.app)?Promise.reject(bi(n)):Ia(le(n),ta.credential(e,t)).catch(async e=>{throw"auth/password-does-not-meet-requirements"===e.code&&Ra(n),e})));var n}signInWithEmailLink(e,t){return al(this._delegate,async function(e,t,n){if(et(e.app))return Promise.reject(bi(e));var r=le(e),i=ta.credentialWithLink(t,n||ki());return Ei(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),Ia(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return ol(this._delegate,async function(e,t,n){if(et(e.app))return Promise.reject(bi(e));const r=Cs(e);var i=await ko(r,t,le(n));return new So(i,e=>Ia(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return ul(Hc(),this._delegate,"operation-not-supported-in-this-environment"),al(this._delegate,async function(e,t,n){if(et(e.app))return Promise.reject(yi(e,"operation-not-supported-in-this-environment"));var r=Cs(e);Ii(e,t,na);var i=Ro(r,n);const s=new Fo(r,"signInViaPopup",t,i);return s.executeNotNull()}(this._delegate,e,nl))}async signInWithRedirect(e){return ul(Hc(),this._delegate,"operation-not-supported-in-this-environment"),await Zc(this._delegate),$o(this._delegate,e,nl)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await Da(le(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function dl(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&ll.getOrCreate(e)),error:t,complete:n}}hl.Persistence=Yc;class pl{constructor(){this.providerId="phone",this._delegate=new No(rl(Nt.auth()))}static credential(e,t){return No.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}pl.PHONE_SIGN_IN_METHOD=No.PHONE_SIGN_IN_METHOD,pl.PROVIDER_ID=No.PROVIDER_ID;const fl=Ei;class gl{constructor(e,t,n=Nt.app()){var r;fl(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new Co(n.auth(),e,t),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(Bc=Nt).INTERNAL.registerComponent(new ue("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new hl(t,n)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:hi.EMAIL_SIGNIN,PASSWORD_RESET:hi.PASSWORD_RESET,RECOVER_EMAIL:hi.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:hi.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:hi.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:hi.VERIFY_EMAIL}},EmailAuthProvider:ta,FacebookAuthProvider:sa,GithubAuthProvider:oa,GoogleAuthProvider:aa,OAuthProvider:ia,SAMLAuthProvider:la,PhoneAuthProvider:pl,PhoneMultiFactorGenerator:Tc,RecaptchaVerifier:gl,TwitterAuthProvider:ua,Auth:hl,AuthCredential:js,Error:x}).setInstantiationMode("LAZY").setMultipleInstances(!1)),Bc.registerVersion("@firebase/auth-compat","0.5.15");const ml="@firebase/database";let vl="";function _l(e){vl=e}class yl{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),F(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:M(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class wl{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return V(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}var bl,Il,Tl,El,Cl,Sl,Rt=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 yl(t)}}catch(e){}return new wl};function kl(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 H;return n.update(t),t=n.digest(),r.encodeByteArray(t)}const Al=Rt("localStorage"),Nl=Rt("sessionStorage"),Rl=new ye("@firebase/database"),Pl=function(){let e=1;return function(){return e++}}(),Dl=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+=Dl.apply(null,n):t+="object"==typeof n?F(n):n,t+=" "}return t};let xl=null,Ol=!0;function Ll(t){return function(...e){Bl(t,...e)}}function Ml(...e){var t="FIREBASE INTERNAL ERROR: "+Dl(...e);Rl.error(t)}function Fl(e,t){return e===t?0:e<t?-1:1}function Ul(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+F(t))}function Vl(e){if("object"!=typeof e||null===e)return F(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+=F(t[i]),n+=":",n+=Vl(e[t[i]]);return n+="}",n}function ql(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 jl=function(e,t){f(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(Rl.logLevel=m.VERBOSE,xl=Rl.log.bind(Rl),t&&Nl.set("logging_enabled",!0)):"function"==typeof e?xl=e:(xl=null,Nl.remove("logging_enabled"))},Bl=function(...e){var t;!0===Ol&&(Ol=!1,null===xl&&!0===Nl.get("logging_enabled")&&jl(!0)),xl&&(t=Dl.apply(null,e),xl(t))},zl=function(...e){var t=`FIREBASE FATAL ERROR: ${Dl(...e)}`;throw Rl.error(t),new Error(t)},Kl=function(...e){var t="FIREBASE WARNING: "+Dl(...e);Rl.warn(t)},$l=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Kl("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Wl=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},Gl="[MIN_NAME]",Hl="[MAX_NAME]",Ql=function(e,t){if(e===t)return 0;if(e===Gl||t===Hl)return-1;if(t===Gl||e===Hl)return 1;var n=Xl(e),r=Xl(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1};function Yl(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Jl(e){f(!Wl(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 Xl(e){if(eu.test(e)){var t=Number(e);if(t>=tu&&t<=nu)return t}return null}function Zl(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 eu=new RegExp("^-?(0*)\\d{1,10}$"),tu=-2147483648,nu=2147483647,ru=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw Kl("Exception was thrown by user callback.",e),t},Math.floor(0))}};class iu{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(){Kl(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class su{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/.',Kl(e)}}class au{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}au.OWNER="owner";const ou=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,cu="websocket",lu="long_polling";class uu{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=Al.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()&&Al.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 hu(e,t,n){f("string"==typeof t,"typeof type must == string"),f("object"==typeof n,"typeof params must == object");let r;if(t===cu)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==lu)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 Yl(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class du{constructor(){this.counters_={}}incrementCounter(e,t=1){V(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return c(void 0,this.counters_)}}const pu={},fu={};function gu(e){var t=e.toString();return pu[t]||(pu[t]=new du),pu[t]}class mu{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]&&ru(()=>{this.onMessage_(n[e])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class vu{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_=Ll(e),this.stats_=gu(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),hu(t,lu,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new mu(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 _u((...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&&ou.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(){vu.forceAllow_=!0}static forceDisallow(){vu.forceDisallow_=!0}static isAvailable(){return!!vu.forceAllow_||!(vu.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=F(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var t=i(t),n=ql(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=F(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class _u{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=Pl(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=_u.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 yu=null;"undefined"!=typeof MozWebSocket?yu=MozWebSocket:"undefined"!=typeof WebSocket&&(yu=WebSocket);class wu{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_=Ll(this.connId),this.stats_=gu(t),this.connURL=wu.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&&ou.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s.ac=r),i&&(s.p=i),hu(e,cu,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Al.set("previous_websocket_failure",!0);try{A(),this.mySock=new yu(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(){wu.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!==yu&&!wu.forceDisallow_}static previouslyFailed(){return Al.isInMemoryStorage||!0===Al.get("previous_websocket_failure")}markConnectionHealthy(){Al.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=M(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=F(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var n=ql(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)}}}wu.responsesRequiredToBeHealthy=2,wu.healthyTimeout=3e4;class bu{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[vu,wu]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){var t=wu&&wu.isAvailable();let n=t&&!wu.previouslyFailed();if(e.webSocketOnly&&(t||Kl("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[wu];else{const r=this.transports_=[];for(const i of bu.ALL_TRANSPORTS)i&&i.isAvailable()&&r.push(i);bu.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}}bu.globalTransportInitialized_=!1;class Iu{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_=Ll("c:"+this.id+":"),this.transportManager_=new bu(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_=Zl(()=>{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=Ul("t",e),n=Ul("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=Ul("t",e),n=Ul("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=Ul("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?Ml("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Ml("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&&Kl("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),Zl(()=>{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):Zl(()=>{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()&&(Al.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 Tu{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 Eu{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 Cu extends Eu{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 Cu}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 ku(){return new Su("")}function Au(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function Nu(e){return e.pieces_.length-e.pieceNum_}function Ru(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new Su(e.pieces_,t)}function Pu(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function Du(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function xu(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 Ou(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 Lu(e){return e.pieceNum_>=e.pieces_.length}function Mu(e,t){var n=Au(e),r=Au(t);if(null===n)return t;if(n===r)return Mu(Ru(e),Ru(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function Fu(e,t){var n=Du(e,0),r=Du(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Ql(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function Uu(e,t){if(Nu(e)!==Nu(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 Vu(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(Nu(e)>Nu(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class qu{constructor(e,t){this.errorPrefix_=t,this.parts_=Du(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=re(this.parts_[n]);ju(this)}}function ju(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 zu extends Eu{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 zu}getInitialEvent(e){return f("visible"===e,"Unknown event type: "+e),[this.visible_]}}class Ku extends Tu{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=Ku.nextPersistentConnectionId_++,this.log_=Ll("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&&!A())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");zu.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&Cu.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(F(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;Ku.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&&V(e,"w")){const i=q(e,"w");var n,r;Array.isArray(i)&&~i.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),Kl("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=U(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=U(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: "+F(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):Ml("Unrecognized action received from server: "+F(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+":"+Ku.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 Iu(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,r,u,e=>{Kl(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&Kl(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],j(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=>Vl(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."+vl.replace(/\./g,"-")]=1,I()?e["framework.cordova"]=1:S()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=Cu.getInstance().currentlyOnline();return j(this.interruptReasons_)&&e}}Ku.nextPersistentConnectionId_=0,Ku.nextConnectionId_=0;class $u{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new $u(e,t)}}class Wu{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new $u(Gl,e),r=new $u(Gl,t);return 0!==this.compare(n,r)}minPost(){return $u.MIN}}let Gu;class Hu extends Wu{static get __EMPTY_NODE(){return Gu}static set __EMPTY_NODE(e){Gu=e}compare(e,t){return Ql(e.name,t.name)}isDefinedOn(e){throw u("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return $u.MIN}maxPost(){return new $u(Hl,Gu)}makePost(e,t){return f("string"==typeof e,"KeyIndex indexValue must always be a string."),new $u(e,Gu)}toString(){return".key"}}const Qu=new Hu;class Yu{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 Ju{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:Ju.RED,this.left=null!=r?r:Zu.EMPTY_NODE,this.right=null!=i?i:Zu.EMPTY_NODE}copy(e,t,n,r,i){return new Ju(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 Zu.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 Zu.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,Ju.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,Ju.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)}}Ju.RED=!0,Ju.BLACK=!1;class Xu{copy(e,t,n,r,i){return this}insert(e,t,n){return new Ju(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 Zu{constructor(e,t=Zu.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Zu(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,Ju.BLACK,null,null))}remove(e){return new Zu(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Ju.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 Yu(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Yu(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Yu(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Yu(this.root_,null,this.comparator_,!0,e)}}function eh(e,t){return Ql(e.name,t.name)}function th(e,t){return Ql(e,t)}Zu.EMPTY_NODE=new Xu;let nh;function rh(e){return"number"==typeof e?"number:"+Jl(e):"string:"+e}function ih(e){var t;e.isLeafNode()?(t=e.val(),f("string"==typeof t||"number"==typeof t||"object"==typeof t&&V(t,".sv"),"Priority must be a string or number.")):f(e===nh||e.isEmpty(),"priority of unexpected type."),f(e===nh||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let sh;class ah{constructor(e,t=ah.__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."),ih(this.priorityNode_)}static set __childrenNodeConstructor(e){sh=e}static get __childrenNodeConstructor(){return sh}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new ah(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:ah.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return Lu(e)?this:".priority"===Au(e)?this.priorityNode_:ah.__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:ah.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=Au(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(f(".priority"!==n||1===Nu(e),".priority must be the last token in a path"),this.updateImmediateChild(n,ah.__childrenNodeConstructor.EMPTY_NODE.updateChild(Ru(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:"+rh(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"==t?Jl(this.value_):this.value_,this.lazyHash_=kl(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===ah.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof ah.__childrenNodeConstructor?-1:(f(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=ah.VALUE_TYPE_ORDER.indexOf(t),i=ah.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_))}}ah.VALUE_TYPE_ORDER=["object","boolean","number","string"];let oh,ch;const lh=new class extends Wu{compare(e,t){const n=e.node.getPriority();var r=t.node.getPriority(),r=n.compareTo(r);return 0===r?Ql(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return $u.MIN}maxPost(){return new $u(Hl,new ah("[PRIORITY-POST]",ch))}makePost(e,t){var n=oh(e);return new $u(t,new ah("[PRIORITY-POST]",n))}toString(){return".priority"}},uh=Math.log(2);class hh{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/uh,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 dh(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 Ju(i,r.node,Ju.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 Ju(i,r.node,Ju.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 Ju(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,Ju.BLACK):(t(r,Ju.BLACK),t(r,Ju.RED))}return a}(new hh(c.length));return new Zu(t||e,n)}let ph;const fh={};class gh{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return f((fh,lh),"ChildrenNode.ts has not been loaded"),ph=ph||new gh({".priority":fh},{".priority":lh}),ph}get(e){var t=q(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof Zu?t:null}hasIndex(e){return V(this.indexSet_,e.toString())}addIndex(e,t){f(e!==Qu,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator($u.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let a;a=r?dh(n,e.getCompare()):fh;var o=e.toString();const c=Object.assign({},this.indexSet_);c[o]=e;const l=Object.assign({},this.indexes_);return l[o]=a,new gh(l,c)}addToIndexes(a,o){var e=B(this.indexes_,(t,e)=>{const n=q(this.indexSet_,e);if(f(n,"Missing index implementation for "+e),t===fh){if(n.isDefinedOn(a.node)){const i=[],s=o.getIterator($u.Wrap);let e=s.getNext();for(;e;)e.name!==a.name&&i.push(e),e=s.getNext();return i.push(a),dh(i,n.getCompare())}return fh}{var r=o.get(a.name);let e=t;return r&&(e=e.remove(new $u(a.name,r))),e.insert(a,a.node)}});return new gh(e,this.indexSet_)}removeFromIndexes(n,r){var e=B(this.indexes_,e=>{if(e===fh)return e;var t=r.get(n.name);return t?e.remove(new $u(n.name,t)):e});return new gh(e,this.indexSet_)}}let mh;class vh{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&ih(this.priorityNode_),this.children_.isEmpty()&&f(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return mh=mh||new vh(new Zu(th),null,gh.Default)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||mh}updatePriority(e){return this.children_.isEmpty()?this:new vh(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?mh:t}getChild(e){var t=Au(e);return null===t?this:this.getImmediateChild(t).getChild(Ru(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 $u(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()?mh:this.priorityNode_;return new vh(e,i,t)}}updateChild(e,t){var n=Au(e);if(null===n)return t;f(".priority"!==Au(e)||1===Nu(e),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(Ru(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(lh,(e,t)=>{r[e]=t.val(n),i++,a&&vh.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:"+rh(this.getPriority().val())+":"),this.forEachChild(lh,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":kl(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new $u(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 $u(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 $u(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,$u.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,$u.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===yh?-1:0}withIndex(e){if(e===Qu||this.indexMap_.hasIndex(e))return this;var t=this.indexMap_.addIndex(e,this.children_);return new vh(this.children_,this.priorityNode_,t)}isIndexed(e){return e===Qu||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(lh),i=n.getIterator(lh);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===Qu?null:this.indexMap_.get(e.toString())}}vh.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class _h extends vh{constructor(){super(new Zu(th),vh.EMPTY_NODE,gh.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return vh.EMPTY_NODE}isEmpty(){return!1}}const yh=new _h;Object.defineProperties($u,{MIN:{value:new $u(Gl,vh.EMPTY_NODE)},MAX:{value:new $u(Hl,yh)}}),Hu.__EMPTY_NODE=vh.EMPTY_NODE,ah.__childrenNodeConstructor=vh,bl=yh,nh=bl,Il=yh,ch=Il;const wh=!0;function bh(i,e=null){if(null===i)return vh.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 ah(t,bh(e))}if(i instanceof Array||!wh){let r=vh.EMPTY_NODE;return Yl(i,(e,t)=>{if(V(i,e)&&"."!==e.substring(0,1)){const n=bh(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(bh(e))}{const s=[];let r=!1;if(Yl(i,(e,t)=>{if("."!==e.substring(0,1)){const n=bh(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new $u(e,n)))}}),0===s.length)return vh.EMPTY_NODE;var n=dh(s,eh,e=>e.name,th);if(r){t=dh(s,lh.getCompare());return new vh(n,bh(e),new gh({".priority":t},{".priority":lh}))}return new vh(n,bh(e),gh.Default)}}oh=bh;class Ih extends Wu{constructor(e){super(),this.indexPath_=e,f(!Lu(e)&&".priority"!==Au(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?Ql(e.name,t.name):r}makePost(e,t){var n=bh(e),n=vh.EMPTY_NODE.updateChild(this.indexPath_,n);return new $u(t,n)}maxPost(){var e=vh.EMPTY_NODE.updateChild(this.indexPath_,yh);return new $u(Hl,e)}toString(){return Du(this.indexPath_,0).join("/")}}const Th=new class extends Wu{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?Ql(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return $u.MIN}maxPost(){return $u.MAX}makePost(e,t){var n=bh(e);return new $u(t,n)}toString(){return".value"}};function Eh(e){return{type:"value",snapshotNode:e}}function Ch(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function Sh(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function kh(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class Ah{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(Ch(t,n)):s.trackChildChange(kh(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(lh,(e,t)=>{n.hasChild(e)||i.trackChildChange(Sh(e,t))}),n.isLeafNode()||n.forEachChild(lh,(e,t)=>{if(r.hasChild(e)){const n=r.getImmediateChild(e);n.equals(t)||i.trackChildChange(kh(e,t,n))}else i.trackChildChange(Ch(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?vh.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class Nh{constructor(e){this.indexedFilter_=new Ah(e.getIndex()),this.index_=e.getIndex(),this.startPost_=Nh.getStartPost_(e),this.endPost_=Nh.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 $u(t,n))||(n=vh.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?vh.EMPTY_NODE:t).withIndex(this.index_);r=r.updatePriority(vh.EMPTY_NODE);const i=this;return t.forEachChild(lh,(e,t)=>{i.matches(new $u(e,t))||(r=r.updateImmediateChild(e,vh.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 Rh{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 Nh(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 $u(t,n))||(n=vh.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=vh.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<n.numChildren()&&n.isIndexed(this.index_)){r=vh.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(vh.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,vh.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 $u(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(kh(t,n,u)),a.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(Sh(t,u));const p=a.updateImmediateChild(t,vh.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(Ch(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(Ch(t,n))),a.updateImmediateChild(t,n).updateImmediateChild(c.name,vh.EMPTY_NODE)):e}}class Ph{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_=lh}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_:Gl}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_:Hl}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_===lh}copy(){const e=new Ph;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 Dh(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 xh(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 Oh(e,t){const n=e.copy();return n.index_=t,n}function Lh(e){const t={};if(e.isDefault())return t;let n;var r;return n=e.index_===lh?"$priority":e.index_===Th?"$value":e.index_===Qu?"$key":(f(e.index_ instanceof Ih,"Unrecognized index type!"),e.index_.toString()),t.orderBy=F(n),e.startSet_&&(r=e.startAfterSet_?"startAfter":"startAt",t[r]=F(e.indexStartValue_),e.startNameSet_&&(t[r]+=","+F(e.indexStartName_))),e.endSet_&&(r=e.endBeforeSet_?"endBefore":"endAt",t[r]=F(e.indexEndValue_),e.endNameSet_&&(t[r]+=","+F(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function Mh(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_!==lh&&(n.i=t.index_.toString()),n}class Fh extends Tu{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=Ll("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=Fh.getListenId_(e,r),o={};this.listens_[a]=o;var n=Lh(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),q(this.listens_,a)===o){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=Fh.getListenId_(e,t);delete this.listens_[n]}get(e){var t=Lh(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+$(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=M(r.responseText)}catch(e){Kl("Failed to parse JSON response for "+n+": "+r.responseText)}a(null,e)}else 401!==r.status&&404!==r.status&&Kl("Got unsuccessful REST response for "+n+" Status: "+r.status),a(r.status);a=null}},r.open("GET",n,!0),r.send()})}}class Uh{constructor(){this.rootNode_=vh.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function Vh(){return{value:null,children:new Map}}function qh(e,t,n){var r;Lu(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=Au(t),e.children.has(r)||e.children.set(r,Vh()),qh(e.children.get(r),t=Ru(t),n))}function jh(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{jh(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_&&Yl(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class zh{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Bh(e);var n=1e4+2e4*Math.random();Zl(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();const n={};let r=!1;Yl(e,(e,t)=>{0<t&&V(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),Zl(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function Kh(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function $h(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function Wh(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(St=Tl=Tl||{})[St.OVERWRITE=0]="OVERWRITE",St[St.MERGE=1]="MERGE",St[St.ACK_USER_WRITE=2]="ACK_USER_WRITE",St[St.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class Gh{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=Tl.ACK_USER_WRITE,this.source=Kh()}operationForChild(e){if(Lu(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 Gh(ku(),t,this.revert)}return f(Au(this.path)===e,"operationForChild called for unrelated child."),new Gh(Ru(this.path),this.affectedTree,this.revert)}}class Hh{constructor(e,t){this.source=e,this.path=t,this.type=Tl.LISTEN_COMPLETE}operationForChild(e){return Lu(this.path)?new Hh(this.source,ku()):new Hh(this.source,Ru(this.path))}}class Qh{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=Tl.OVERWRITE}operationForChild(e){return Lu(this.path)?new Qh(this.source,ku(),this.snap.getImmediateChild(e)):new Qh(this.source,Ru(this.path),this.snap)}}class Yh{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=Tl.MERGE}operationForChild(e){if(Lu(this.path)){const t=this.children.subtree(new Su(e));return t.isEmpty()?null:t.value?new Qh(this.source,ku(),t.value):new Yh(this.source,ku(),t)}return f(Au(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Yh(this.source,Ru(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Jh{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(Lu(e))return this.isFullyInitialized()&&!this.filtered_;var t=Au(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class Xh{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function Zh(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}))}),ed(n,i,"child_removed",e,r,t),ed(n,i,"child_added",e,r,t),ed(n,i,"child_moved",s,r,t),ed(n,i,"child_changed",e,r,t),ed(n,i,"value",e,r,t),i}function ed(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 $u(t.childName,t.snapshotNode),i=new $u(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 td(e,t){return{eventCache:e,serverCache:t}}function nd(e,t,n,r){return td(new Jh(t,n,r),e.serverCache)}function rd(e,t,n,r){return td(e.eventCache,new Jh(t,n,r))}function id(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function sd(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let ad;class od{constructor(e,t=(ad=ad||new Zu(Fl),ad)){this.value=e,this.children=t}static fromObject(e){let n=new od(null);return Yl(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:ku(),value:this.value};if(Lu(e))return null;{var n=Au(e);const i=this.children.get(n);if(null===i)return null;var r=i.findRootMostMatchingPathAndValue(Ru(e),t);return null==r?null:{path:Ou(new Su(n),r.path),value:r.value}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(Lu(e))return this;{var t=Au(e);const n=this.children.get(t);return null!==n?n.subtree(Ru(e)):new od(null)}}set(e,t){if(Lu(e))return new od(t,this.children);{var n=Au(e);const i=this.children.get(n)||new od(null);var r=i.set(Ru(e),t),r=this.children.insert(n,r);return new od(this.value,r)}}remove(t){if(Lu(t))return this.children.isEmpty()?new od(null):new od(null,this.children);{var n=Au(t);const r=this.children.get(n);if(r){const i=r.remove(Ru(t));let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&e.isEmpty()?new od(null):new od(this.value,e)}return this}}get(e){if(Lu(e))return this.value;{var t=Au(e);const n=this.children.get(t);return n?n.get(Ru(e)):null}}setTree(t,n){if(Lu(t))return n;{var r=Au(t);const i=this.children.get(r)||new od(null),s=i.setTree(Ru(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new od(this.value,e)}}fold(e){return this.fold_(ku(),e)}fold_(n,r){const i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(Ou(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,ku(),t)}findOnPath_(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(Lu(e))return null;{r=Au(e);const i=this.children.get(r);return i?i.findOnPath_(Ru(e),Ou(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,ku(),t)}foreachOnPath_(e,t,n){if(Lu(e))return this;{this.value&&n(t,this.value);var r=Au(e);const i=this.children.get(r);return i?i.foreachOnPath_(Ru(e),Ou(t,r),n):new od(null)}}foreach(e){this.foreach_(ku(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(Ou(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class cd{constructor(e){this.writeTree_=e}static empty(){return new cd(new od(null))}}function ld(t,n,r){if(Lu(n))return new cd(new od(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=Mu(s,n);return e=e.updateChild(i,r),new cd(t.writeTree_.set(s,e))}s=new od(r),s=t.writeTree_.setTree(n,s);return new cd(s)}function ud(e,n,t){let r=e;return Yl(t,(e,t)=>{r=ld(r,Ou(n,e),t)}),r}function hd(e,t){if(Lu(t))return cd.empty();var n=e.writeTree_.setTree(t,new od(null));return new cd(n)}function dd(e,t){return null!=pd(e,t)}function pd(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(Mu(n.path,t)):null}function fd(e){const n=[],t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(lh,(e,t)=>{n.push(new $u(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new $u(e,t.value))}),n}function gd(e,t){if(Lu(t))return e;var n=pd(e,t);return null!=n?new cd(new od(n)):new cd(e.writeTree_.subtree(t))}function md(e){return e.writeTree_.isEmpty()}function vd(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(Ou(i,e),t,s)}),s=!s.getChild(i).isEmpty()&&null!==n?s.updateChild(Ou(i,".priority"),n):s}}}(ku(),e.writeTree_,t)}function _d(e,t){return Rd(t,e)}function yd(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 Vu(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&Vu(Ou(e.path,n),t))return!0;return!1}}(c,i.path)?s=!1:Vu(i.path,c.path)&&(a=!0)),o--}return!!s&&(a?((e=t).visibleWrites=bd(e.allWrites,wd,ku()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=hd(t.visibleWrites,i.path):Yl(i.children,e=>{t.visibleWrites=hd(t.visibleWrites,Ou(i.path,e))}),!0)}function wd(e){return e.visible}function bd(e,t,n){let r=cd.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)Vu(n,i)?(e=Mu(n,i),r=ld(r,e,a.snap)):Vu(i,n)&&(e=Mu(i,n),r=ld(r,ku(),a.snap.getChild(e)));else{if(!a.children)throw u("WriteRecord should have .snap or .children");if(Vu(n,i))e=Mu(n,i),r=ud(r,e,a.children);else if(Vu(i,n))if(e=Mu(i,n),Lu(e))r=ud(r,ku(),a.children);else{const o=q(a.children,Au(e));o&&(i=o.getChild(Ru(e)),r=ld(r,ku(),i))}}}}return r}function Id(e,t,n,r,i){if(r||i){var s=gd(e.visibleWrites,t);if(!i&&md(s))return n;if(i||null!=n||dd(s,ku()))return vd(bd(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(Vu(e.path,t)||Vu(t,e.path))},t),n||vh.EMPTY_NODE);return null}s=pd(e.visibleWrites,t);if(null!=s)return s;s=gd(e.visibleWrites,t);return md(s)?n:null!=n||dd(s,ku())?vd(s,n||vh.EMPTY_NODE):null}function Td(e,t,n,r){return Id(e.writeTree,e.treePath,t,n,r)}function Ed(e,t){return function(e,t,n){let r=vh.EMPTY_NODE;const i=pd(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(lh,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const s=gd(e.visibleWrites,t);return n.forEachChild(lh,(e,t)=>{var n=vd(gd(s,new Su(e)),t);r=r.updateImmediateChild(e,n)}),fd(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return fd(gd(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function Cd(e,t,n,r){return function(e,t,n,r,i){f(r||i,"Either existingEventSnap or existingServerSnap must exist");var s=Ou(t,n);return dd(e.visibleWrites,s)?null:md(s=gd(e.visibleWrites,s))?i.getChild(n):vd(s,i.getChild(n))}(e.writeTree,e.treePath,t,n,r)}function Sd(e,t){return n=e.writeTree,t=Ou(e.treePath,t),pd(n.visibleWrites,t);var n}function kd(e,t,n,r,i,s){return function(e,t,n,r,i,s,a){let o;var c=gd(e.visibleWrites,t),l=pd(c,ku());if(null!=l)o=l;else{if(null==n)return[];o=vd(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 Ad(e,t,n){return r=e.writeTree,e=e.treePath,n=n,i=Ou(e,t=t),null!=(s=pd(r.visibleWrites,i))?s:n.isCompleteForChild(t)?vd(gd(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function Nd(e,t){return Rd(Ou(e.treePath,t),e.writeTree)}function Rd(e,t){return{treePath:e,writeTree:t}}class Pd{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,kh(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,Ch(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,kh(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const Dd=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class xd{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 Jh(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return Ad(this.writes_,e,n)}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:sd(this.viewCache_),r=kd(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function Od(e,t,n,r,i){const s=new Pd;let a,o;if(n.type===Tl.OVERWRITE){var c=n;a=c.source.fromUser?Fd(e,t,c.path,c.snap,r,i,s):(f(c.source.fromServer,"Unknown source."),o=c.source.tagged||t.serverCache.isFiltered()&&!Lu(c.path),Md(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=Ou(s,e);Ud(i,Au(n))&&(l=Fd(r,l,n,t,a,o,c))}),e.foreach((e,t)=>{var n=Ou(s,e);Ud(i,Au(n))||(l=Fd(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(),qd(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 xd(s,r,e);const u=r.eventCache.getNode();let t;if(Lu(i)||".priority"===Au(i)){let e;e=r.serverCache.isFullyInitialized()?Td(s,sd(r)):(l=r.serverCache.getNode(),f(l instanceof vh,"serverChildren would be complete if leaf node"),Ed(s,l)),e=e,t=n.filter.updateFullNode(u,e,a)}else{var l=Au(i);let e=Ad(s,l,r.serverCache);null==e&&r.serverCache.isCompleteForChild(l)&&(e=u.getImmediateChild(l)),t=null!=e?n.filter.updateChild(u,l,e,Ru(i),c,a):r.eventCache.getNode().hasChild(l)?n.filter.updateChild(u,l,vh.EMPTY_NODE,Ru(i),c,a):u,t.isEmpty()&&r.serverCache.isFullyInitialized()&&(o=Td(s,sd(r)),o.isLeafNode()&&(t=n.filter.updateFullNode(t,o,a)))}return o=r.serverCache.isFullyInitialized()||null!=Sd(s,ku()),nd(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(Lu(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return Md(e,t,i,l.getNode().getChild(i),s,a,c,o);if(Lu(i)){let n=new od(null);return l.getNode().forEachChild(Qu,(e,t)=>{n=n.set(new Su(e),t)}),qd(e,t,i,n,s,a,c,o)}return t}{let r=new od(null);return n.foreach((e,t)=>{var n=Ou(i,e);l.isCompleteForPath(n)&&(r=r.set(e,l.getNode().getChild(n)))}),qd(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=rd(t,s.getNode(),s.isFullyInitialized()||Lu(n),s.isFiltered());return Ld(e,a,n,r,Dd,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=id(e);(0<n.length||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(Eh(id(t)))}}(t,a,l),{viewCache:a,changes:l}}function Ld(r,i,s,a,o,c){const l=i.eventCache;if(null!=Sd(a,s))return i;{let t,n;if(Lu(s)){var e;f(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=Ed(a,(e=sd(i))instanceof vh?e:vh.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=Td(a,sd(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=Au(s);if(".priority"===u){f(1===Nu(s),"Can't have a priority with additional path components");var h=l.getNode();n=i.serverCache.getNode();var d=Cd(a,s,h,n);t=null!=d?r.filter.updatePriority(h,d):l.getNode()}else{h=Ru(s);let e;e=l.isCompleteForChild(u)?(n=i.serverCache.getNode(),null!=(d=Cd(a,s,l.getNode(),n))?l.getNode().getImmediateChild(u).updateChild(h,d):l.getNode().getImmediateChild(u)):Ad(a,u,i.serverCache),t=null!=e?r.filter.updateChild(l.getNode(),u,e,h,o,c):l.getNode()}}return nd(i,t,l.isFullyInitialized()||Lu(s),r.filter.filtersNodes())}}function Md(e,t,n,r,i,s,a,o){const c=t.serverCache;let l;const u=a?e.filter:e.filter.getIndexedFilter();if(Lu(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=Au(n);if(!c.isCompleteForPath(n)&&1<Nu(n))return t;var p=Ru(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,Dd,null)}p=rd(t,l,c.isFullyInitialized()||Lu(n),u.filtersNodes());return Ld(e,p,n,i,new xd(i,p,s),o)}function Fd(t,n,r,i,e,s,a){const o=n.eventCache;let c,l;const u=new xd(e,n,s);if(Lu(r))l=t.filter.updateFullNode(n.eventCache.getNode(),i,a),c=nd(n,l,!0,t.filter.filtersNodes());else{var h=Au(r);if(".priority"===h)l=t.filter.updatePriority(n.eventCache.getNode(),i),c=nd(n,l,o.isFullyInitialized(),o.isFiltered());else{var d=Ru(r);const p=o.getNode().getImmediateChild(h);let e;if(Lu(d))e=i;else{const f=u.getCompleteChild(h);e=null!=f?".priority"===Pu(d)&&f.getChild(xu(d)).isEmpty()?f:f.updateChild(d,i):vh.EMPTY_NODE}c=p.equals(e)?n:nd(n,t.filter.updateChild(o.getNode(),h,e,d,u,a),o.isFullyInitialized(),t.filter.filtersNodes())}}return c}function Ud(e,t){return e.eventCache.isCompleteForChild(t)}function Vd(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function qd(r,i,e,t,s,a,o,c){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let l=i,n;n=Lu(e)?t:new od(null).setTree(e,t);const u=i.serverCache.getNode();return n.children.inorderTraversal((e,t)=>{var n;u.hasChild(e)&&(n=Vd(0,i.serverCache.getNode().getImmediateChild(e),t),l=Md(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=Vd(0,i.serverCache.getNode().getImmediateChild(e),t),l=Md(r,l,new Su(e),n,s,a,o,c))}),l}class jd{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new Ah(n.getIndex()),i=(e=n).loadsAllData()?new Ah(e.getIndex()):new(e.hasLimit()?Rh:Nh)(e);this.processor_={filter:i};const s=t.serverCache,a=t.eventCache;var o=r.updateFullNode(vh.EMPTY_NODE,s.getNode(),null),c=i.updateFullNode(vh.EMPTY_NODE,a.getNode(),null),o=new Jh(o,s.isFullyInitialized(),r.filtersNodes()),c=new Jh(c,a.isFullyInitialized(),i.filtersNodes());this.viewCache_=td(c,o),this.eventGenerator_=new Xh(this.query_)}get query(){return this.query_}}function Bd(e){return 0===e.eventRegistrations_.length}function zd(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 Kd(e,t,n,r){t.type===Tl.MERGE&&null!==t.source.queryId&&(f(sd(e.viewCache_),"We should always have a full cache before handling merges"),f(id(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=Od(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,$d(e,s.changes,s.viewCache.eventCache.getNode(),null)}function $d(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return Zh(e.eventGenerator_,t,n,i)}let Wd;class Gd{constructor(){this.views=new Map}}function Hd(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."),Kd(e,n,r,i)}{let e=[];for(const s of t.views.values())e=e.concat(Kd(s,n,r,i));return e}}function Qd(e,n,r,i,s){var a=n._queryIdentifier,a=e.views.get(a);if(a)return a;{let e=Td(r,s?i:null),t=!1;t=!!e||(e=i instanceof vh?Ed(r,i):vh.EMPTY_NODE,!1);a=td(new Jh(e,t,!1),new Jh(i,s,!1));return new jd(n,a)}}function Yd(e,t,n,r,i,s){var a=Qd(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(lh,(e,t)=>{r.push(Ch(e,t))})}return n.isFullyInitialized()&&r.push(Eh(n.getNode())),$d(e,r,n.getNode(),t)}(a,n)}function Jd(e,t,n,r){var i=t._queryIdentifier;const s=[];let a=[];var o=np(e);if("default"===i)for(var[c,l]of e.views.entries())a=a.concat(zd(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(zd(u,n,r)),Bd(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return o&&!np(e)&&s.push((f(Wd,"Reference.ts has not been loaded"),new Wd(t._repo,t._path))),{removed:s,events:a}}function Xd(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function Zd(e,t){let n=null;for(const r of e.views.values())n=n||function(e,t){const n=sd(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!Lu(t)&&!n.getImmediateChild(Au(t)).isEmpty())?n.getChild(t):null}(r,t);return n}function ep(e,t){const n=t._queryParams;if(n.loadsAllData())return rp(e);var r=t._queryIdentifier;return e.views.get(r)}function tp(e,t){return null!=ep(e,t)}function np(e){return null!=rp(e)}function rp(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let ip;let sp=1;class ap{constructor(e){this.listenProvider_=e,this.syncPointTree_=new od(null),this.pendingWriteTree_={visibleWrites:cd.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function op(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=ld(s.visibleWrites,a,o)),s.lastWriteId=c,i?mp(e,new Qh(Kh(),t,n)):[]}function cp(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=ud(i.visibleWrites,s,a),i.lastWriteId=r;var o=od.fromObject(n);return mp(e,new Yh(Kh(),t,o))}function lp(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(yd(e.pendingWriteTree_,t)){let t=new od(null);return null!=r.snap?t=t.set(ku(),!0):Yl(r.children,e=>{t=t.set(new Su(e),!0)}),mp(e,new Gh(r.path,t,n))}return[]}function up(e,t,n){return mp(e,new Qh($h(),t,n))}function hp(n,e,t,r,i=!1){var s=e._path,a=n.syncPointTree_.get(s);let o=[];if(a&&("default"===e._queryIdentifier||tp(a,e))){var c=Jd(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)=>np(t));if(a&&!c){const p=n.syncPointTree_.subtree(s);if(!p.isEmpty()){var l=p.fold((e,t,r)=>{if(t&&np(t))return[rp(t)];{let n=[];return t&&(n=Xd(t)),Yl(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<l.length;++e){var u=l[e],h=u.query,u=_p(n,u);n.listenProvider_.startListening(Ep(h),yp(n,h),u.hashFn,u.onComplete)}}}!c&&0<d.length&&!r&&(a?n.listenProvider_.stopListening(Ep(e),null):d.forEach(e=>{var t=n.queryToTagMap.get(wp(e));n.listenProvider_.stopListening(Ep(e),t)}))}!function(e,t){for(let i=0;i<t.length;++i){const s=t[i];var n,r;s._queryParams.loadsAllData()||(n=wp(s),r=e.queryToTagMap.get(n),e.queryToTagMap.delete(n),e.tagToQueryMap.delete(r))}}(n,d)}return o}function dp(e,t,n,r){var i=bp(e,r);if(null==i)return[];var s=Ip(i),a=s.path,i=s.queryId,s=Mu(a,t);return Tp(e,a,new Qh(Wh(i),s,n))}function pp(e,t,n,r=!1){const i=t._path;let s=null,a=!1;e.syncPointTree_.foreachOnPath(i,(e,t)=>{var n=Mu(e,i);s=s||Zd(t,n),a=a||np(t)});let o=e.syncPointTree_.get(i);o?(a=a||np(o),s=s||Zd(o,ku())):(o=new Gd,e.syncPointTree_=e.syncPointTree_.set(i,o));let c;if(null!=s)c=!0;else{c=!1,s=vh.EMPTY_NODE;const p=e.syncPointTree_.subtree(i);p.foreachChild((e,t)=>{var n=Zd(t,ku());n&&(s=s.updateImmediateChild(e,n))})}var l,u=tp(o,t);u||t._queryParams.loadsAllData()||(h=wp(t),f(!e.queryToTagMap.has(h),"View does not exist, but we have a tag"),l=sp++,e.queryToTagMap.set(h,l),e.tagToQueryMap.set(l,h));var h=_d(e.pendingWriteTree_,i);let d=Yd(o,t,n,h,s,c);return u||a||r||(u=ep(o,t),d=d.concat(function(t,e,n){const r=e._path,i=yp(t,e),s=_p(t,n),a=t.listenProvider_.startListening(Ep(e),i,s.hashFn,s.onComplete),o=t.syncPointTree_.subtree(r);if(i)f(!np(o.value),"If we're adding a query, it shouldn't be shadowed");else{var c=o.fold((e,t,r)=>{if(!Lu(e)&&t&&np(t))return[rp(t).query];{let n=[];return t&&(n=n.concat(Xd(t).map(e=>e.query))),Yl(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e];t.listenProvider_.stopListening(Ep(l),yp(t,l))}}return a}(e,t,u))),d}function fp(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=Zd(t,Mu(e,r));if(n)return n});return Id(n,r,i,t,!0)}function gp(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=Mu(e,r);i=i||Zd(t,n)});let n=e.syncPointTree_.get(r);n?i=i||Zd(n,ku()):(n=new Gd,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i;const a=s?new Jh(i,!0,!1):null;var o=_d(e.pendingWriteTree_,t._path);return id(Qd(n,t,o,s?a.getNode():vh.EMPTY_NODE,s).viewCache_)}function mp(e,t){return function t(n,r,i,s){{if(Lu(n.path))return vp(n,r,i,s);{const a=r.get(ku());null==i&&null!=a&&(i=Zd(a,ku()));let e=[];const o=Au(n.path),c=n.operationForChild(o),l=r.children.get(o);if(l&&c){const u=i?i.getImmediateChild(o):null,h=Nd(s,o);e=e.concat(t(c,l,u,h))}return a&&(e=e.concat(Hd(a,n,s,i))),e}}}(t,e.syncPointTree_,null,_d(e.pendingWriteTree_,ku()))}function vp(s,e,a,o){var t=e.get(ku());null==a&&null!=t&&(a=Zd(t,ku()));let c=[];return e.children.inorderTraversal((e,t)=>{var n=a?a.getImmediateChild(e):null,r=Nd(o,e),i=s.operationForChild(e);i&&(c=c.concat(vp(i,t,n,r)))}),t&&(c=c.concat(Hd(t,s,o,a))),c}function _p(i,t){const s=t.query,a=yp(i,s);return{hashFn:()=>{const e=t.viewCache_.serverCache.getNode()||vh.EMPTY_NODE;return e.hash()},onComplete:e=>{if("ok"===e)return a?function(e,t,n){if(s=bp(e,n)){var r=Ip(s),i=r.path,s=r.queryId,r=Mu(i,t);return Tp(e,i,new Hh(Wh(s),r))}return[]}(i,s._path,a):(t=i,n=s._path,mp(t,new Hh($h(),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 hp(i,s,null,r)}}}function yp(e,t){var n=wp(t);return e.queryToTagMap.get(n)}function wp(e){return e._path.toString()+"$"+e._queryIdentifier}function bp(e,t){return e.tagToQueryMap.get(t)}function Ip(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 Tp(e,t,n){var r=e.syncPointTree_.get(t);return f(r,"Missing sync point for query tag that we're tracking"),Hd(r,n,_d(e.pendingWriteTree_,t),null)}function Ep(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(f(ip,"Reference.ts has not been loaded"),new ip(e._repo,e._path)):e}class Cp{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new Cp(t)}node(){return this.node_}}class Sp{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=Ou(this.path_,e);return new Sp(this.syncTree_,t)}node(){return fp(this.syncTree_,this.path_)}}function kp(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e}function Ap(e,t,n){return e&&"object"==typeof e?(f(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?Np(e[".sv"],t,n):"object"==typeof e[".sv"]?Rp(e[".sv"],t):void f(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const Np=function(e,t,n){if("timestamp"===e)return n.timestamp;f(!1,"Unexpected server value: "+e)},Rp=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},Pp=function(e,t,n,r){return xp(t,new Sp(n,e),r)},Dp=function(e,t,n){return xp(e,new Cp(t),n)};function xp(e,r,i){var t=e.getPriority().val(),n=Ap(t,r.getImmediateChild(".priority"),i);let s;if(e.isLeafNode()){const a=e;t=Ap(a.getValue(),r,i);return t!==a.getValue()||n!==a.getPriority().val()?new ah(t,bh(n)):e}{const o=e;return s=o,n!==o.getPriority().val()&&(s=s.updatePriority(new ah(n))),o.forEachChild(lh,(e,t)=>{var n=xp(t,r.getImmediateChild(e),i);n!==t&&(s=s.updateImmediateChild(e,n))}),s}}class Op{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function Lp(e,t){let n=t instanceof Su?t:new Su(t),r=e,i=Au(n);for(;null!==i;){var s=q(r.node.children,i)||{children:{},childCount:0};r=new Op(i,r,s),n=Ru(n),i=Au(n)}return r}function Mp(e){return e.node.value}function Fp(e,t){e.node.value=t,jp(e)}function Up(e){return 0<e.node.childCount}function Vp(n,r){Yl(n.node.children,(e,t)=>{r(new Op(e,n,t))})}function qp(e){return new Su(null===e.parent?e.name:qp(e.parent)+"/"+e.name)}function jp(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=function(e){return void 0===Mp(e)&&!Up(e)}(e=e),i=V(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,jp(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,jp(t)))}function Bp(e,t,n,r){r&&void 0===t||tf(Z(e,"value"),t,n)}function zp(e,t,r,n){if(!n||void 0!==t){const i=Z(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=[];Yl(t,(e,t)=>{const n=new Su(e);if(tf(i,t,Ou(r,n)),".priority"===Pu(n)&&!ef(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=Du(i);for(let e=0;e<s.length;e++)if((".priority"!==s[e]||e!==s.length-1)&&!Jp(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(Fu);let e=null;for(r=0;r<n.length;r++){if(i=n[r],null!==e&&Vu(e,i))throw new Error(t+"contains a path "+e.toString()+" that is ancestor of another path "+i.toString());e=i}}(i,s)}}function Kp(e,t,n){if(!n||void 0!==t){if(Wl(t))throw new Error(Z(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!ef(t))throw new Error(Z(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function $p(e,t,n,r){if(!(r&&void 0===n||Jp(n)))throw new Error(Z(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function Wp(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),nf(e,t,n,r)}function Gp(e,t){if(".info"===Au(t))throw new Error(e+" failed = Can't modify data under /.info/")}const Hp=/[\[\].#$\/\u0000-\u001F\u007F]/,Qp=/[\[\].#$\u0000-\u001F\u007F]/,Yp=10485760,Jp=function(e){return"string"==typeof e&&0!==e.length&&!Hp.test(e)},Xp=function(e){return"string"==typeof e&&0!==e.length&&!Qp.test(e)},Zp=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),Xp(e)},ef=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!Wl(e)||e&&"object"==typeof e&&V(e,".sv")},tf=function(a,e,t){const o=t instanceof Su?new qu(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(Wl(e))throw new Error(a+"contains "+e.toString()+" "+Bu(o));if("string"==typeof e&&e.length>Yp/3&&re(e)>Yp)throw new Error(a+"contains a string greater than "+Yp+" utf8 bytes "+Bu(o)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(Yl(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!Jp(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_+=re(e),ju(n),tf(a,t,o),t=o,r=t.parts_.pop(),t.byteLength_-=re(r),0<t.parts_.length&&--t.byteLength_}),i&&s)throw new Error(a+' contains ".value" child '+Bu(o)+" in addition to actual children.")}},nf=function(e,t,n,r){if(!(r&&void 0===n||Xp(n)))throw new Error(Z(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},rf=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!Jp(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!Zp(n))throw new Error(Z(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class sf{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function af(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i];var r=s.getPath();null===n||Uu(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 of(e,t,n){af(e,n),lf(e,e=>Uu(e,t))}function cf(e,t,n){af(e,n),lf(e,e=>Vu(e,t)||Vu(t,e))}function lf(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(),xl&&Bl("event: "+r.toString()),ru(t))}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}const uf="repo_interrupt",hf=25;class df{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 sf,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=Vh(),this.transactionQueueTree_=new Op,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function pf(a,e,t){if(a.stats_=gu(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 Fh(a.repoInfo_,(e,t,n,r)=>{mf(a,e,t,n,r)},a.authTokenProvider_,a.appCheckProvider_),setTimeout(()=>vf(a,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{F(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}a.persistentConnection_=new Ku(a.repoInfo_,e,(e,t,n,r)=>{mf(a,e,t,n,r)},e=>{vf(a,e)},e=>{var n;n=a,Yl(e,(e,t)=>{_f(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 zh(a.stats_,a.server_),n=e.toString(),fu[n]||(fu[n]=t()),fu[n]),a.infoData_=new Uh,a.infoSyncTree_=new ap({startListening:(e,t,n,r)=>{let i=[];const s=a.infoData_.getNode(e._path);return s.isEmpty()||(i=up(a.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),_f(a,"connected",!1),a.serverSyncTree_=new ap({startListening:(r,e,t,i)=>(a.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);cf(a.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{a.server_.unlisten(e,t)}})}function ff(e){const t=e.infoData_.getNode(new Su(".info/serverTimeOffset"));var n=t.val()||0;return(new Date).getTime()+n}function gf(e){return kp({timestamp:ff(e)})}function mf(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=B(n,e=>bh(e)),function(e,t,n,r){if(o=bp(e,r)){var i=Ip(o),s=i.path,a=i.queryId,o=Mu(s,t),i=od.fromObject(n);return Tp(e,s,new Yh(Wh(a),o,i))}return[]}(e.serverSyncTree_,o,s,i)):(s=bh(n),dp(e.serverSyncTree_,o,s,i)):r?(a=B(n,e=>bh(e)),t=e.serverSyncTree_,i=o,r=a,a=od.fromObject(r),mp(t,new Yh($h(),i,a))):(a=bh(n),up(e.serverSyncTree_,o,a));let l=o;0<c.length&&(l=Nf(e,o)),cf(e.eventQueue_,l,c)}function vf(e,t){_f(e,"connected",t),!1===t&&function(r){Cf(r,"onDisconnectEvents");const i=gf(r),s=Vh();jh(r.onDisconnect_,ku(),(e,t)=>{var n=Pp(e,t,r.serverSyncTree_,i);qh(s,e,n)});let a=[];jh(s,ku(),(e,t)=>{a=a.concat(up(r.serverSyncTree_,e,t));var n=xf(r,e);Nf(r,n)}),r.onDisconnect_=Vh(),cf(r.eventQueue_,ku(),a)}(e)}function _f(e,t,n){var r=new Su("/.info/"+t),i=bh(n);e.infoData_.updateSnapshot(r,i);i=up(e.infoSyncTree_,r,i);cf(e.eventQueue_,r,i)}function yf(e){return e.nextWriteId_++}function wf(r,i,e,t,s){Cf(r,"set",{path:i.toString(),value:e,priority:t});var n=gf(r);const a=bh(e,t);var o=fp(r.serverSyncTree_,i),n=Dp(a,o,n);const c=yf(r);n=op(r.serverSyncTree_,i,n,c,!0);af(r.eventQueue_,n),r.server_.put(i.toString(),a.val(!0),(e,t)=>{var n="ok"===e;n||Kl("set at "+i+" failed: "+e);n=lp(r.serverSyncTree_,c,!n);cf(r.eventQueue_,i,n),Sf(0,s,e,t)});n=xf(r,i);Nf(r,n),cf(r.eventQueue_,n,[])}function bf(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(Lu(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(lh,(e,t)=>{qh(n,new Su(e),t)}),e(n,t)}}if(0<n.children.size){var r=Au(t);return t=Ru(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 If(n,r,e,i){const s=bh(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&qh(n.onDisconnect_,r,s),Sf(0,i,e,t)})}function Tf(e,t,n){let r;r=".info"===Au(t._path)?hp(e.infoSyncTree_,t,n):hp(e.serverSyncTree_,t,n),of(e.eventQueue_,t._path,r)}function Ef(e){e.persistentConnection_&&e.persistentConnection_.interrupt(uf)}function Cf(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),Bl(n,...t)}function Sf(e,r,i,s){r&&ru(()=>{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 kf(e,t,n){return fp(e.serverSyncTree_,t,n)||vh.EMPTY_NODE}function Af(t,e=t.transactionQueueTree_){if(e||Df(t,e),Mp(e)){const n=Pf(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=kf(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=Mu(s,h.path);n=n.updateChild(o,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{Cf(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(lp(i.serverSyncTree_,a[e].currentWriteId)),a[e].onComplete&&r.push(()=>a[e].onComplete(null,!0,a[e].currentOutputSnapshotResolved)),a[e].unwatcher();Df(i,Lp(i.transactionQueueTree_,s)),Af(i,i.transactionQueueTree_),cf(i.eventQueue_,s,n);for(let t=0;t<r.length;t++)ru(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{Kl("transaction at "+l.toString()+" failed: "+t);for(let e=0;e<a.length;e++)a[e].status=4,a[e].abortReason=t}Nf(i,s)}},r)}(t,qp(e),n)}else Up(e)&&Vp(e,e=>{Af(t,e)})}function Nf(e,t){var n=Rf(e,t),r=qp(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=Mu(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(lp(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=hf)e=!0,t="maxretry",n=n.concat(lp(i.serverSyncTree_,h.currentWriteId,!0));else{const d=kf(i,h.path,u);h.currentInputSnapshot=d;var c=s[r].update(d.val());if(void 0!==c){tf("transaction failed: Data returned ",c,h.path);let e=bh(c);"object"==typeof c&&null!=c&&V(c,".priority")||(e=e.updatePriority(d.getPriority()));o=h.currentWriteId,c=gf(i),c=Dp(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=yf(i),u.splice(u.indexOf(o),1),n=n.concat(op(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally)),n=n.concat(lp(i.serverSyncTree_,o,!0))}else e=!0,t="nodata",n=n.concat(lp(i.serverSyncTree_,h.currentWriteId,!0))}cf(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))))}Df(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)ru(l[e]);Af(i,i.transactionQueueTree_)}}(e,Pf(e,n),r),r}function Rf(e,t){let n,r=e.transactionQueueTree_;for(n=Au(t);null!==n&&void 0===Mp(r);)r=Lp(r,n),t=Ru(t),n=Au(t);return r}function Pf(e,t){const n=[];return function t(n,e,r){const i=Mp(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);Vp(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function Df(t,n){const r=Mp(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,Fp(n,0<r.length?r:void 0)}Vp(n,e=>{Df(t,e)})}function xf(t,e){var n=qp(Rf(t,e)),r=Lp(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=>{Of(t,e)}),Of(t,r),function t(e,n,r,i){r&&!i&&n(e),Vp(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{Of(t,e)}),n}function Of(i,s){const a=Mp(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(lp(i.serverSyncTree_,a[n].currentWriteId,!0)),a[n].onComplete&&o.push(a[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?Fp(s,void 0):a.length=t+1,cf(i.eventQueue_,qp(s),e);for(let r=0;r<o.length;r++)ru(o[r])}}const Lf=function(e,t){var n=Mf(e),r=n.namespace;"firebase.com"===n.domain&&zl(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||zl("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||$l();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new uu(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new Su(n.pathString)}},Mf=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]):Kl(`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}},Ff="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Uf=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]=Ff.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+=Ff.charAt(a[n]);return f(20===i.length,"nextPushId: Length should be 20."),i}}();class Vf{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+":"+F(this.snapshot.exportVal())}}class qf{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 jf{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 bf(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){Gp("OnDisconnect.remove",this._path);const e=new y;return If(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){Gp("OnDisconnect.set",this._path),Bp("OnDisconnect.set",e,this._path,!1);const t=new y;return If(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){Gp("OnDisconnect.setWithPriority",this._path),Bp("OnDisconnect.setWithPriority",e,this._path,!1),Kp("OnDisconnect.setWithPriority",t,!1);const n=new y;return function(n,r,e,t,i){const s=bh(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&qh(n.onDisconnect_,r,s),Sf(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){Gp("OnDisconnect.update",this._path),zp("OnDisconnect.update",e,this._path,!1);const t=new y;return function(r,i,n,s){if(j(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&&Yl(n,(e,t)=>{var n=bh(t);qh(r.onDisconnect_,Ou(i,e),n)}),Sf(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class zf{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return Lu(this._path)?null:Pu(this._path)}get ref(){return new Gf(this._repo,this._path)}get _queryIdentifier(){var e=Mh(this._queryParams),e=Vl(e);return"{}"===e?"default":e}get _queryObject(){return Mh(this._queryParams)}isEqual(e){if(!((e=le(e))instanceof zf))return!1;var t=this._repo===e._repo,n=Uu(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 Kf(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function $f(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===Qu){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()!==Gl)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==Hl)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===lh){if(null!=t&&!ef(t)||null!=n&&!ef(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 Ih||e.getIndex()===Th,"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 Wf(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 Gf extends zf{constructor(e,t){super(e,t,new Ph,!1)}get parent(){var e=xu(this._path);return null===e?null:new Gf(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class Hf{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=Jf(this.ref,e);return new Hf(this._node.getChild(t),n,lh)}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 Hf(t,Jf(this.ref,e),lh)))}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 Qf(e,t){return(e=le(e))._checkNotDeleted("ref"),void 0!==t?Jf(e._root,t):e._root}function Yf(e,t){(e=le(e))._checkNotDeleted("refFromURL");const n=Lf(t,e._repo.repoInfo_.nodeAdmin);rf("refFromURL",n);var r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||zl("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),Qf(e,n.path.toString())}function Jf(e,t){return(null===Au((e=le(e))._path)?Wp:nf)("child","path",t,!1),new Gf(e._repo,Ou(e._path,t))}function Xf(e,t){e=le(e),Gp("set",e._path),Bp("set",t,e._path,!1);const n=new y;return wf(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Zf(e,t){zp("update",t,e._path,!1);const n=new y;return function(i,s,e,a){Cf(i,"update",{path:s.toString(),value:e});let n=!0;const r=gf(i),o={};if(Yl(e,(e,t)=>{n=!1,o[e]=Pp(Ou(s,e),bh(t),i.serverSyncTree_,r)}),n)Bl("update() called with empty data. Don't do anything."),Sf(0,a,"ok",void 0);else{const c=yf(i);var t=cp(i.serverSyncTree_,s,o,c);af(i.eventQueue_,t),i.server_.merge(s.toString(),e,(e,t)=>{var n="ok"===e;n||Kl("update at "+s+" failed: "+e);var r=lp(i.serverSyncTree_,c,!n),n=0<r.length?Nf(i,s):s;cf(i.eventQueue_,n,r),Sf(0,a,e,t)}),Yl(e,e=>{var t=xf(i,Ou(s,e));Nf(i,t)}),cf(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function eg(t){t=le(t);var i,s,a,e=new jf(()=>{}),e=new tg(e);return i=t._repo,s=t,a=e,(null!=(e=gp(i.serverSyncTree_,s))?Promise.resolve(e):i.server_.get(s).then(e=>{var t,n=bh(e).withIndex(s._queryParams.getIndex());pp(i.serverSyncTree_,s,a,!0);let r;return r=s._queryParams.loadsAllData()?up(i.serverSyncTree_,s._path,n):(t=yp(i.serverSyncTree_,s),dp(i.serverSyncTree_,s._path,n,t)),cf(i.eventQueue_,s._path,r),hp(i.serverSyncTree_,s,a,null,!0),n},e=>(Cf(i,"get for query "+F(s)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new Hf(e,new Gf(t._repo,t._path),t._queryParams.getIndex()))}class tg{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new Vf("value",this,new Hf(e.snapshotNode,new Gf(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 qf(this,e,t):null}matches(e){return e instanceof tg&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class ng{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 qf(this,e,t):null}createEvent(e,t){f(null!=e.childName,"Child events should have a childName.");var n=Jf(new Gf(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new Vf(e.type,this,new Hf(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 ng&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function rg(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 jf(t,s||void 0);const o="value"===e?new tg(a):new ng(e,a);return function(e,t,n){let r;r=".info"===Au(t._path)?pp(e.infoSyncTree_,t,n):pp(e.serverSyncTree_,t,n),of(e.eventQueue_,t._path,r)}(n._repo,n,o),()=>Tf(n._repo,n,o)}function ig(e,t,n,r){return rg(e,"value",t,n,r)}function sg(e,t,n,r){return rg(e,"child_added",t,n,r)}function ag(e,t,n,r){return rg(e,"child_changed",t,n,r)}function og(e,t,n,r){return rg(e,"child_moved",t,n,r)}function cg(e,t,n,r){return rg(e,"child_removed",t,n,r)}function lg(e,t,n){let r=null;var i=n?new jf(n):null;"value"===t?r=new tg(i):t&&(r=new ng(t,i)),Tf(e._repo,e,r)}class ug{}class hg extends ug{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){Bp("endAt",this._value,e._path,!0);var t=xh(e._queryParams,this._value,this._key);if(Wf(t),$f(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new zf(e._repo,e._path,t,e._orderByCalled)}}class dg extends ug{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){Bp("endBefore",this._value,e._path,!1);var t=function(e,t,n){let r;return r=e.index_===Qu||n?xh(e,t,n):xh(e,t,Gl),r.endBeforeSet_=!0,r}(e._queryParams,this._value,this._key);if(Wf(t),$f(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new zf(e._repo,e._path,t,e._orderByCalled)}}class pg extends ug{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){Bp("startAt",this._value,e._path,!0);var t=Dh(e._queryParams,this._value,this._key);if(Wf(t),$f(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new zf(e._repo,e._path,t,e._orderByCalled)}}class fg extends ug{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){Bp("startAfter",this._value,e._path,!1);var t=function(e,t,n){let r;return r=e.index_===Qu||n?Dh(e,t,n):Dh(e,t,Hl),r.startAfterSet_=!0,r}(e._queryParams,this._value,this._key);if(Wf(t),$f(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new zf(e._repo,e._path,t,e._orderByCalled)}}class gg extends ug{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new zf(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 mg extends ug{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new zf(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 vg extends ug{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){Kf(e,"orderByChild");var t=new Su(this._path);if(Lu(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new Ih(t),t=Oh(e._queryParams,t);return $f(t),new zf(e._repo,e._path,t,!0)}}class _g extends ug{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){Kf(e,"orderByKey");var t=Oh(e._queryParams,Qu);return $f(t),new zf(e._repo,e._path,t,!0)}}class yg extends ug{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){Kf(e,"orderByPriority");var t=Oh(e._queryParams,lh);return $f(t),new zf(e._repo,e._path,t,!0)}}class wg extends ug{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){Kf(e,"orderByValue");var t=Oh(e._queryParams,Th);return $f(t),new zf(e._repo,e._path,t,!0)}}class bg extends ug{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_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 hg(this._value,this._key)._apply(new pg(this._value,this._key)._apply(e))}}function Ig(e,...t){let n=le(e);for(const r of t)n=r._apply(n);return n}El=Gf,f(!Wd,"__referenceConstructor has already been defined"),Wd=El,Cl=Gf,f(!ip,"__referenceConstructor has already been defined"),ip=Cl;const Tg="FIREBASE_DATABASE_EMULATOR_HOST",Eg={};let Cg=!1;function Sg(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||zl("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=Lf(s,i),o=a.repoInfo,c,l=void 0;"undefined"!=typeof process&&process.env&&(l=process.env[Tg]),l?(c=!0,s=`http://${l}?ns=${o.namespace}`,a=Lf(s,i),o=a.repoInfo):c=!a.repoInfo.secure;var u=i&&c?new au(au.OWNER):new su(e.name,e.options,t);rf("Invalid Firebase Database URL",a),Lu(a.path)||zl("Database URL must point to the root of a Firebase Database (not including a child path).");u=function(e,t,n,r){let i=Eg[t.name];i||(i={},Eg[t.name]=i);var s=i[e.toURLString()];s&&zl("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new df(e,Cg,n,r),i[e.toURLString()]=s}(o,e,u,new iu(e.name,n));return new kg(u,e)}class kg{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(pf(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new Gf(this._repo,ku())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=Eg[t];n&&n[e.key]===e||zl(`Database ${t}(${e.repoInfo_}) has already been deleted.`),Ef(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&zl("Cannot call "+e+" on a deleted database.")}}function Ag(){bu.IS_TRANSPORT_INITIALIZED&&Kl("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function Ng(){Ag(),vu.forceDisallow()}function Rg(){Ag(),wu.forceDisallow(),vu.forceAllow()}function Pg(e,t,n,r={}){(e=le(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&zl("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let a=void 0;s.repoInfo_.nodeAdmin?(r.mockUserToken&&zl('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 au(au.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:w(r.mockUserToken,e.app.options.projectId),a=new au(i)),r=s,e=t,t=n,n=a,r.repoInfo_=new uu(`${e}:${t}`,!1,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams,!0),n&&(r.authTokenProvider_=n)}function Dg(e){(e=le(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(uf)}function xg(e,t){jl(e,t)}const Og={".sv":"timestamp"};class Lg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function Mg(i,e,t){if(i=le(i),Gp("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=ig(i,()=>{});return function(t,n,e,r,i,s){Cf(t,"transaction on "+n);const a={path:n,update:e,onComplete:r,status:null,order:Pl(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},o=kf(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{tf("transaction failed: Data returned ",c,a.path),a.status=0;var l=Lp(t.transactionQueueTree_,n);const u=Mp(l)||[];u.push(a),Fp(l,u);let e;if("object"==typeof c&&null!==c&&V(c,".priority"))e=q(c,".priority"),f(ef(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=fp(t.serverSyncTree_,n)||vh.EMPTY_NODE;e=h.getPriority().val()}l=gf(t),c=bh(c,e),l=Dp(c,o,l);a.currentOutputSnapshotRaw=c,a.currentOutputSnapshotResolved=l,a.currentWriteId=yf(t);l=op(t.serverSyncTree_,n,l,a.currentWriteId,a.applyLocally);cf(t.eventQueue_,n,l),Af(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new Hf(n,new Gf(i._repo,i._path),lh),s.resolve(new Lg(t,r)))},r,n),s.promise}Ku.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},Ku.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},_l(it),Je(new ue("database",(e,{instanceIdentifier:t})=>{return Sg(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),ct(ml,"1.0.9",Sl),ct(ml,"1.0.9","esm2017");function Fg(e){var t="FIREBASE WARNING: "+e;Ug.warn(t)}const Ug=new ye("@firebase/database-compat");class Vg{constructor(e){this._delegate=e}cancel(t){X("OnDisconnect.cancel",0,1,arguments.length),ee("OnDisconnect.cancel","onComplete",t,!0);const e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){X("OnDisconnect.remove",0,1,arguments.length),ee("OnDisconnect.remove","onComplete",t,!0);const e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){X("OnDisconnect.set",1,2,arguments.length),ee("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){X("OnDisconnect.setWithPriority",2,3,arguments.length),ee("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(X("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,Fg("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.")}ee("OnDisconnect.update","onComplete",n,!0);const e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class qg{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return X("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class jg{constructor(e,t){this._database=e,this._delegate=t}val(){return X("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return X("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return X("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return X("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return X("DataSnapshot.child",0,1,arguments.length),e=String(e),nf("DataSnapshot.child","path",e,!1),new jg(this._database,this._delegate.child(e))}hasChild(e){return X("DataSnapshot.hasChild",1,1,arguments.length),nf("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return X("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return X("DataSnapshot.forEach",1,1,arguments.length),ee("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new jg(this._database,e)))}hasChildren(){return X("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return X("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return X("DataSnapshot.ref",0,0,arguments.length),new zg(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;X("Query.on",2,4,arguments.length),ee("Query.on","callback",n,!1);const s=Bg.getCancelAndContextArgs_("Query.on",t,r);var a=(e,t)=>{n.call(s.context,new jg(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 ig(this._delegate,a,o),n;case"child_added":return sg(this._delegate,a,o),n;case"child_removed":return cg(this._delegate,a,o),n;case"child_changed":return ag(this._delegate,a,o),n;case"child_moved":return og(this._delegate,a,o),n;default:throw new Error(Z("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;X("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(Z(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}("Query.off",e,!0),ee("Query.off","callback",t,!0),te("Query.off","context",n,!0),t?((r=()=>{}).userCallback=t,r.context=n,lg(this._delegate,e,r)):lg(this._delegate,e)}get(){return eg(this._delegate).then(e=>new jg(this.database,e))}once(e,r,t,n){X("Query.once",1,4,arguments.length),ee("Query.once","callback",r,!0);const i=Bg.getCancelAndContextArgs_("Query.once",t,n),s=new y;var a=(e,t)=>{var n=new jg(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":ig(this._delegate,a,o,{onlyOnce:!0});break;case"child_added":sg(this._delegate,a,o,{onlyOnce:!0});break;case"child_removed":cg(this._delegate,a,o,{onlyOnce:!0});break;case"child_changed":ag(this._delegate,a,o,{onlyOnce:!0});break;case"child_moved":og(this._delegate,a,o,{onlyOnce:!0});break;default:throw new Error(Z("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 X("Query.limitToFirst",1,1,arguments.length),new Bg(this.database,Ig(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 gg(e)}(e)))}limitToLast(e){return X("Query.limitToLast",1,1,arguments.length),new Bg(this.database,Ig(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 mg(e)}(e)))}orderByChild(e){return X("Query.orderByChild",1,1,arguments.length),new Bg(this.database,Ig(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 nf("orderByChild","path",e,!1),new vg(e)}(e)))}orderByKey(){return X("Query.orderByKey",0,0,arguments.length),new Bg(this.database,Ig(this._delegate,new _g))}orderByPriority(){return X("Query.orderByPriority",0,0,arguments.length),new Bg(this.database,Ig(this._delegate,new yg))}orderByValue(){return X("Query.orderByValue",0,0,arguments.length),new Bg(this.database,Ig(this._delegate,new wg))}startAt(e=null,t){return X("Query.startAt",0,2,arguments.length),new Bg(this.database,Ig(this._delegate,([e=null,t]=[e,t],$p("startAt","key",t,!0),new pg(e,t))))}startAfter(e=null,t){return X("Query.startAfter",0,2,arguments.length),new Bg(this.database,Ig(this._delegate,(e=e,t=t,$p("startAfter","key",t,!0),new fg(e,t))))}endAt(e=null,t){return X("Query.endAt",0,2,arguments.length),new Bg(this.database,Ig(this._delegate,(e=e,t=t,$p("endAt","key",t,!0),new hg(e,t))))}endBefore(e=null,t){return X("Query.endBefore",0,2,arguments.length),new Bg(this.database,Ig(this._delegate,(e=e,t=t,$p("endBefore","key",t,!0),new dg(e,t))))}equalTo(e,t){return X("Query.equalTo",1,2,arguments.length),new Bg(this.database,Ig(this._delegate,(e=e,t=t,$p("equalTo","key",t,!0),new bg(e,t))))}toString(){return X("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return X("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(X("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,ee(e,"cancel",r.cancel,!0),r.context=n,te(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(Z(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new zg(this.database,new Gf(this._delegate._repo,this._delegate._path))}}class zg extends Bg{constructor(e,t){super(e,new zf(t._repo,t._path,new Ph,!1)),this.database=e,this._delegate=t}getKey(){return X("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return X("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new zg(this.database,Jf(this._delegate,e))}getParent(){X("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new zg(this.database,e):null}getRoot(){return X("Reference.root",0,0,arguments.length),new zg(this.database,this._delegate.root)}set(e,t){X("Reference.set",1,2,arguments.length),ee("Reference.set","onComplete",t,!0);const n=Xf(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(X("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,Fg("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.")}Gp("Reference.update",this._delegate._path),ee("Reference.update","onComplete",n,!0);const e=Zf(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){X("Reference.setWithPriority",2,3,arguments.length),ee("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(Gp("setWithPriority",e._path),Bp("setWithPriority",t,e._path,!1),Kp("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new y;return wf(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){X("Reference.remove",0,1,arguments.length),ee("Reference.remove","onComplete",t,!0);const e=(n=this._delegate,Gp("remove",n._path),Xf(n,null));var n;return t&&e.then(()=>t(null),e=>t(e)),e}transaction(e,t,n){X("Reference.transaction",1,3,arguments.length),ee("Reference.transaction","transactionUpdate",e,!1),ee("Reference.transaction","onComplete",t,!0),function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(Z(e,t)+"must be a boolean.")}("Reference.transaction","applyLocally",n,!0);const r=Mg(this._delegate,e,{applyLocally:n}).then(e=>new qg(e.committed,new jg(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){X("Reference.setPriority",1,2,arguments.length),ee("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=le(e),Gp("setPriority",e._path),Kp("setPriority",t,!1);const n=new y;return wf(e._repo,Ou(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){X("Reference.push",0,2,arguments.length),ee("Reference.push","onComplete",t,!0);const n=function(e,t){e=le(e),Gp("push",e._path),Bp("push",t,e._path,!0);var n=ff(e._repo),n=Uf(n);const r=Jf(e,n),i=Jf(e,n);let s;return s=null!=t?Xf(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 zg(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new zg(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return Gp("Reference.onDisconnect",this._delegate._path),new Vg(new Bf(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class Kg{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:Ng,forceLongPolling:Rg}}useEmulator(e,t,n={}){Pg(this._delegate,e,t,n)}ref(e){if(X("database.ref",0,1,arguments.length),e instanceof zg){var t=Yf(this._delegate,e.toString());return new zg(this,t)}t=Qf(this._delegate,e);return new zg(this,t)}refFromURL(e){X("database.refFromURL",1,1,arguments.length);var t=Yf(this._delegate,e);return new zg(this,t)}goOffline(){var e;X("database.goOffline",0,0,arguments.length),(e=le(e=this._delegate))._checkNotDeleted("goOffline"),Ef(e._repo)}goOnline(){return X("database.goOnline",0,0,arguments.length),Dg(this._delegate)}}Kg.ServerValue={TIMESTAMP:Og,increment:e=>({".sv":{increment:e}})};var $g,Wg=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:i,namespace:s,nodeAdmin:a=!1}){_l(n);var o=new pe("database-standalone");const c=new de("auth-internal",o);c.setComponent(new ue("auth-internal",()=>r,"PRIVATE"));let l=void 0;return i&&(l=new de("app-check-internal",o),l.setComponent(new ue("app-check-internal",()=>i,"PRIVATE"))),{instance:new Kg(Sg(e,c,l,t,a),e),namespace:s}}});const Gg=Kg.ServerValue;($g=Nt).INTERNAL.registerComponent(new ue("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new Kg(r,n)},"PUBLIC").setServiceProps({Reference:zg,Query:Bg,Database:Kg,DataSnapshot:jg,enableLogging:xg,INTERNAL:Wg,ServerValue:Gg}).setMultipleInstances(!0)),$g.registerVersion("@firebase/database-compat","2.0.0");var Hg,Qg,Pt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!(function(){var e,t,s;function n(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}function r(){}function a(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 l(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}t=n,r.prototype=(s=function(){this.blockSize=-1}).prototype,t.D=s.prototype,t.prototype=new r,(t.prototype.constructor=t).C=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)},n.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},n.prototype.u=function(e,t){for(var n=(t=void 0===t?e.length:t)-this.blockSize,r=this.B,i=this.h,s=0;s<t;){if(0==i)for(;s<=n;)a(this,e,s),s+=this.blockSize;if("string"==typeof e){for(;s<t;)if(r[i++]=e.charCodeAt(s++),i==this.blockSize){a(this,r),i=0;break}}else for(;s<t;)if(r[i++]=e[s++],i==this.blockSize){a(this,r),i=0;break}}this.h=i,this.o+=t},n.prototype.v=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.o,t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.u(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 i={};function o(e){return-128<=e&&e<128?(t=e,n=function(e){return new l([0|e],e<0?-1:0)},r=i,Object.prototype.hasOwnProperty.call(r,t)?r[t]:r[t]=n(t)):new l([0|e],e<0?-1:0);var t,n,r}function u(e){if(isNaN(e)||!isFinite(e))return h;if(e<0)return g(u(-e));for(var t=[],n=1,r=0;n<=e;r++)t[r]=e/n|0,n*=4294967296;return new l(t,0)}var h=o(0),c=o(1),d=o(16777216);function p(e){if(0==e.h){for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return;return 1}}function f(e){return-1==e.h}function g(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new l(n,~e.h).add(c)}function m(e,t){return e.add(g(t))}function v(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function _(e,t){this.g=e,this.h=t}function y(e,t){if(p(t))throw Error("division by zero");if(p(e))return new _(h,h);if(f(e))return t=y(g(e),t),new _(g(t.g),g(t.h));if(f(t))return t=y(e,g(t)),new _(g(t.g),t.h);if(30<e.g.length){if(f(e)||f(t))throw Error("slowDivide_ only works with positive integers.");for(var n=c,r=t;r.l(e)<=0;)n=w(n),r=w(r);for(var i=b(n,1),s=b(r,1),r=b(r,2),n=b(n,2);!p(r);){var a=s.add(r);a.l(e)<=0&&(i=i.add(n),s=a),r=b(r,1),n=b(n,1)}return t=m(e,i.j(t)),new _(i,t)}for(i=h;0<=e.l(t);){for(n=Math.max(1,Math.floor(e.m()/t.m())),r=(r=Math.ceil(Math.log(n)/Math.LN2))<=48?1:Math.pow(2,r-48),a=(s=u(n)).j(t);f(a)||0<a.l(e);)a=(s=u(n-=r)).j(t);p(s)&&(s=c),i=i.add(s),e=m(e,a)}return new _(i,e)}function w(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.i(r)<<1|e.i(r-1)>>>31;return new l(n,e.h)}function b(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.i(s+n)>>>t|e.i(s+n+1)<<32-t:e.i(s+n);return new l(i,e.h)}(e=l.prototype).m=function(){if(f(this))return-g(this).m();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.i(n);e+=(0<=r?r:4294967296+r)*t,t*=4294967296}return e},e.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(p(this))return"0";if(f(this))return"-"+g(this).toString(e);for(var t=u(Math.pow(e,6)),n=this,r="";;){var i=y(n,t).g,s=((0<(n=m(n,i.j(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(p(n=i))return s+r;for(;s.length<6;)s="0"+s;r=s+r}},e.i=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},e.l=function(e){return f(e=m(this,e))?-1:p(e)?0:1},e.abs=function(){return f(this)?g(this):this},e.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.i(i))+(65535&e.i(i)),a=(s>>>16)+(this.i(i)>>>16)+(e.i(i)>>>16),r=a>>>16;s&=65535,a&=65535,n[i]=a<<16|s}return new l(n,-2147483648&n[n.length-1]?-1:0)},e.j=function(e){if(p(this)||p(e))return h;if(f(this))return f(e)?g(this).j(g(e)):g(g(this).j(e));if(f(e))return g(this.j(g(e)));if(this.l(d)<0&&e.l(d)<0)return u(this.m()*e.m());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var i=0;i<e.g.length;i++){var s=this.i(r)>>>16,a=65535&this.i(r),o=e.i(i)>>>16,c=65535&e.i(i);n[2*r+2*i]+=a*c,v(n,2*r+2*i),n[2*r+2*i+1]+=s*c,v(n,2*r+2*i+1),n[2*r+2*i+1]+=a*o,v(n,2*r+2*i+1),n[2*r+2*i+2]+=s*o,v(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 l(n,0)},e.A=function(e){return y(this,e).h},e.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)&e.i(r);return new l(n,this.h&e.h)},e.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)|e.i(r);return new l(n,this.h|e.h)},e.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)^e.i(r);return new l(n,this.h^e.h)},n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,Qg=n,l.prototype.multiply=l.prototype.j,l.prototype.modulo=l.prototype.A,l.prototype.compare=l.prototype.l,l.prototype.toNumber=l.prototype.m,l.prototype.getBits=l.prototype.i,l.fromNumber=u,l.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 g(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=u(Math.pow(n,8)),i=h,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=u(Math.pow(n,a)),i.j(a).add(u(o))):(i=i.j(r)).add(u(o));return i},Hg=l}).apply(void 0!==Pt?Pt:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var Yg,Jg,Xg,Zg,em,tm,nm,rm,im,sm,am,om="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};!(function(){var e,s="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.value),e};var a=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof om&&om];for(var t=0;t<e.length;++t){var n=e[t];if(n&&n.Math==Math)return n}throw Error("Cannot find global object")}(this);!function(e,t){if(t)e:{var n=a;e=e.split(".");for(var r=0;r<e.length-1;r++){var i=e[r];if(!(i in n))break e;n=n[i]}(t=t(r=n[e=e[e.length-1]]))!=r&&null!=t&&s(n,e,{configurable:!0,writable:!0,value:t})}}("Array.prototype.values",function(e){return e||function(){return function(t,n){t instanceof String&&(t+="");var r=0,i=!1,e={next:function(){if(!i&&r<t.length){var e=r++;return{value:n(e,t[e]),done:!1}}return{done:i=!0,value:void 0}}};return e[Symbol.iterator]=function(){return e},e}(this,function(e,t){return t})}});var o=o||{},E=this||self;function c(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function l(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function r(e,t,n){return e.call.apply(e.bind,arguments)}function i(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 m(e,t,n){return(m=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?r:i).apply(null,arguments)}function u(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 t(e,s){function t(){}t.prototype=s.prototype,e.aa=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Qb=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 h(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 n(t){for(let e=1;e<arguments.length;e++){var n=arguments[e];if(c(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 C(e){return/^[\s\xa0]*$/.test(e)}function d(){var e=E.navigator;return(e=e&&e.userAgent)?e:""}function p(e){return p[" "](e),e}p[" "]=function(){};var f=!(-1==d().indexOf("Gecko")||-1!=d().toLowerCase().indexOf("webkit")&&-1==d().indexOf("Edge")||-1!=d().indexOf("Trident")||-1!=d().indexOf("MSIE")||-1!=d().indexOf("Edge"));function g(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function v(e){const t={};for(const n in e)t[n]=e[n];return t}const _="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function y(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<_.length;e++)n=_[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}var w=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 b,e=>e.reset());class b{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 I,T=!1,S=new class{constructor(){this.h=this.g=null}add(e,t){const n=w.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},k=()=>{const e=E.Promise.resolve(void 0);I=()=>{e.then(A)}};var A=()=>{for(var e;e=function(){var e=S;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){E.setTimeout(()=>{throw e},0)}(e)}var t=w;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}T=!1};function N(){this.s=this.s,this.C=this.C}function R(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}N.prototype.s=!1,N.prototype.ma=function(){this.s||(this.s=!0,this.N())},N.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},R.prototype.h=function(){this.defaultPrevented=!0};var P=function(){if(!E.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{var n=()=>{};E.addEventListener("test",n,t),E.removeEventListener("test",n,t)}catch(e){}return e}();function D(e,t){if(R.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(f){e:{try{p(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:x[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&D.aa.h.call(this)}}t(D,R);var x={2:"touch",3:"pen",4:"mouse"};D.prototype.h=function(){D.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var O="closure_listenable_"+(1e6*Math.random()|0),L=0;function M(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ha=i,this.key=++L,this.da=this.fa=!1}function F(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function U(e){this.src=e,this.g={},this.h=0}function V(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=Array.prototype.indexOf.call(n,t,void 0)))&&Array.prototype.splice.call(n,r,1),i&&(F(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function q(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.da&&s.listener==t&&s.capture==!!n&&s.ha==r)return i}return-1}U.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var a=q(e,t,r,i);return-1<a?(t=e[a],n||(t.fa=!1)):((t=new M(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var j="closure_lm_"+(1e6*Math.random()|0),B={};function z(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=Y(r);return t&&t[O]?t.L(n,r,l(i)?!!i.capture:!!i,s):K(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)z(e,t[s],n,r,i);return null}return n=Y(n),e&&e[O]?e.K(t,n,l(r)?!!r.capture:!!r,i):K(e,t,n,!1,r,i)}function K(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var a=l(i)?!!i.capture:!!i,o=H(e);if(o||(e[j]=o=new U(e)),(n=o.add(t,n,r,a,s)).proxy)return n;if(r=function(){const n=G;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=!P?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(W(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function $(e){var t,n,r;"number"!=typeof e&&e&&!e.da&&((t=e.src)&&t[O]?V(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(W(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=H(t))?(V(n,e),0==n.h&&(n.src=null,t[j]=null)):F(e)))}function W(e){return e in B?B[e]:B[e]="on"+e}function G(e,t){var n,r;return e=!!e.da||(t=new D(t,this),n=e.listener,r=e.ha||e.src,e.fa&&$(e),n.call(r,t))}function H(e){return(e=e[j])instanceof U?e:null}var Q="__closure_events_fn_"+(1e9*Math.random()>>>0);function Y(t){return"function"==typeof t?t:(t[Q]||(t[Q]=function(e){return t.handleEvent(e)}),t[Q])}function J(){N.call(this),this.i=new U(this),(this.M=this).F=null}function X(e,t){var n,r=e.F;if(r)for(n=[];r;r=r.F)n.push(r);if(e=e.M,r=t.type||t,"string"==typeof t?t=new R(t,e):t instanceof R?t.target=t.target||e:(a=t,y(t=new R(r,e),a)),a=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],a=Z(s,r,!0,t)&&a;if(a=Z(s=t.g=e,r,!0,t)&&a,a=Z(s,r,!1,t)&&a,n)for(i=0;i<n.length;i++)a=Z(s=t.g=n[i],r,!1,t)&&a}function Z(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.da&&c.capture==n&&(a=c.listener,o=c.ha||c.src,c.fa&&V(e.i,c),i=!1!==a.call(o,r)&&i)}return i&&!r.defaultPrevented}function ee(e,t,n){if("function"==typeof e)n&&(e=m(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=m(e.handleEvent,e)}return 2147483647<Number(t)?-1:E.setTimeout(e,t||0)}t(J,N),J.prototype[O]=!0,J.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=l(i)?!!i.capture:!!i,r=Y(r),t&&t[O]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=q(a=t.g[n],r,i,s))&&(F(a[r]),Array.prototype.splice.call(a,r,1),0==a.length&&(delete t.g[n],t.h--))):(t=t&&H(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?q(n,r,i,s):t)?n[t]:null)&&$(r))}(this,e,t,n,r)},J.prototype.N=function(){if(J.aa.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)F(n[r]);delete t.g[e],t.h--}}this.F=null},J.prototype.K=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},J.prototype.L=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};class te extends N{constructor(e,t){super(),this.m=e,this.l=t,this.h=null,this.i=!1,this.g=null}j(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=ee(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.l);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}N(){super.N(),this.g&&(E.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function ne(e){N.call(this),this.h=e,this.g={}}t(ne,N);var re=[];function ie(e){g(e.g,function(e,t){this.g.hasOwnProperty(t)&&$(e)},e),e.g={}}ne.prototype.N=function(){ne.aa.N.call(this),ie(this)},ne.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var se=E.JSON.stringify,ae=E.JSON.parse,oe=class{stringify(e){return E.JSON.stringify(e,void 0)}parse(e){return E.JSON.parse(e,void 0)}};function ce(){}function le(e){return e.h||(e.h=e.i())}function ue(){}ce.prototype.h=null;var he={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function de(){R.call(this,"d")}function pe(){R.call(this,"c")}t(de,R),t(pe,R);var fe={},ge=null;function me(){return ge=ge||new J}function ve(e){R.call(this,fe.La,e)}function _e(){var e=me();X(e,new ve(e))}function ye(e,t){R.call(this,fe.STAT_EVENT,e),this.stat=t}function we(e){var t=me();X(t,new ye(t,e))}function be(e,t){R.call(this,fe.Ma,e),this.size=t}function Ie(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return E.setTimeout(function(){e()},t)}function Te(){this.g=!0}function Ee(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 se(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}fe.La="serverreachability",t(ve,R),fe.STAT_EVENT="statevent",t(ye,R),fe.Ma="timingevent",t(be,R),Te.prototype.xa=function(){this.g=!1},Te.prototype.info=function(){};var Ce={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Se={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function ke(){}function Ae(e,t,n,r){this.j=e,this.i=t,this.l=n,this.R=r||1,this.U=new ne(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Ne}function Ne(){this.i=null,this.g="",this.h=!1}t(ke,ce),ke.prototype.g=function(){return new XMLHttpRequest},ke.prototype.i=function(){return{}};var Re=new ke,Pe={},De={};function xe(e,t,n){e.L=1,e.v=it(Ze(t)),e.m=n,e.P=!0,Oe(e,null)}function Oe(e,t){e.F=Date.now(),Me(e),e.A=Ze(e.v);var n=e.A,r=e.R;Array.isArray(r)||(r=[String(r)]),_t(n.i,"t",r),e.C=0,n=e.j.J,e.h=new Ne,e.g=sn(e.j,n?t:null,!e.m),0<e.O&&(e.M=new te(m(e.Y,e,e.g),e.O)),t=e.U;var n=e.g,r=e.ca,i="readystatechange";Array.isArray(i)||(i&&(re[0]=i.toString()),i=re);for(var a,o,c,l,u,h,s=0;s<i.length;s++){var d=z(n,i[s],r||t.handleEvent,!1,t.h||t);if(!d)break;t.g[d.key]=d}t=e.H?v(e.H):{},e.m?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.m,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),_e(),a=e.i,o=e.u,c=e.A,l=e.l,u=e.R,h=e.m,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 Le(e){return e.g&&("GET"==e.u&&2!=e.L&&e.j.Ca)}function Me(e){e.S=Date.now()+e.I,Fe(e,e.I)}function Fe(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=Ie(m(e.ba,e),t)}function Ue(e){e.B&&(E.clearTimeout(e.B),e.B=null)}function Ve(e){0==e.j.G||e.J||Zt(e.j,e)}function qe(e){Ue(e);var t=e.M;t&&"function"==typeof t.ma&&t.ma(),e.M=null,ie(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.ma())}function je(e,t){try{var n=e.j;if(0!=n.G&&(n.g==e||We(n.h,e)))if(!e.K&&We(n.h,e)&&3==n.G){try{var r=n.Da.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;Xt(n),Bt(n)}Qt(n),we(18)}}else n.za=i[1],0<n.za-n.T&&i[2]<37500&&n.F&&0==n.v&&!n.C&&(n.C=Ie(m(n.Za,n),6e3));if($e(n.h)<=1&&n.ca){try{n.ca()}catch(e){}n.ca=void 0}}else tn(n,11)}else if(!e.K&&n.g!=e||Xt(n),!C(t))for(i=n.Da.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.T=s[0],s=s[1],2==n.G)if("c"==s[0]){n.K=s[1],n.ia=s[2];var a=s[3];null!=a&&(n.la=a,n.j.info("VER="+n.la));var o=s[4];null!=o&&(n.Aa=o,n.j.info("SVER="+n.Aa));var c,l,u=s[5];null!=u&&"number"==typeof u&&0<u&&(r=1.5*u,n.L=r,n.j.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.h).g||-1==g.indexOf("spdy")&&-1==g.indexOf("quic")&&-1==g.indexOf("h2")||(c.j=c.l,c.g=new Set,c.h&&(Ge(c,c.h),c.h=null))),!r.D||(l=f.g?f.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.ya=l,rt(r.I,r.D,l))}n.G=3,n.l&&n.l.ua(),n.ba&&(n.R=Date.now()-e.F,n.j.info("Handshake RTT: "+n.R+"ms"));var h,d,p=e;(r=n).qa=rn(r,r.J?r.ia:null,r.W),p.K?(He(r.h,p),h=p,(d=r.L)&&(h.I=d),h.B&&(Ue(h),Me(h)),r.g=p):Ht(r),0<n.i.length&&Kt(n)}else"stop"!=s[0]&&"close"!=s[0]||tn(n,7);else 3==n.G&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?tn(n,7):jt(n):"noop"!=s[0]&&n.l&&n.l.ta(s),n.v=0)}_e()}catch(e){}}Ae.prototype.ca=function(e){e=e.target;const t=this.M;t&&3==Ft(e)?t.j():this.Y(e)},Ae.prototype.Y=function(e){try{if(e==this.g)e:{var t=Ft(this.g),n=this.g.Ba();this.g.Z();if(!(t<3)&&(3!=t||this.g&&(this.h.h||this.g.oa()||Ut(this.g)))){this.J||4!=t||7==n||_e(),Ue(this);var r=this.g.Z();this.X=r;t:if(Le(this)){var i=Ut(this.g);e="";var s=i.length,a=4==Ft(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){qe(this),Ve(this);var o="";break t}this.h.i=new E.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:!(a&&n==s-1)});i.length=0,this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.oa();if(this.o=200==r,v=this.i,_=this.u,y=this.A,w=this.l,b=this.R,I=t,T=r,v.info(function(){return"XMLHTTP RESP ("+w+") [ attempt "+b+"]: "+_+"\n"+y+"\n"+I+" "+T}),this.o){if(this.T&&!this.K){t:{if(this.g){var c,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!C(c)){var u=c;break t}}u=null}if(!(r=u)){this.o=!1,this.s=3,we(12),qe(this),Ve(this);break e}Ee(this.i,this.l,r,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,je(this,r)}if(this.P){for(var h,d,r=!0;!this.J&&this.C<o.length;){if(f=o,m=g=void 0,g=(p=this).C,(h=-1==(m=f.indexOf("\n",g))?De:(g=Number(f.substring(g,m)),isNaN(g)?Pe:(m+=1)+g>f.length?De:(f=f.slice(m,m+g),p.C=m+g,f)))==De){4==t&&(this.s=4,we(14),r=!1),Ee(this.i,this.l,null,"[Incomplete Response]");break}if(h==Pe){this.s=4,we(15),Ee(this.i,this.l,o,"[Invalid Chunk]"),r=!1;break}Ee(this.i,this.l,h,null),je(this,h)}Le(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=t||0!=o.length||this.h.h||(this.s=1,we(16),r=!1),this.o=this.o&&r,r?0<o.length&&!this.W&&(this.W=!0,(d=this.j).g==this&&d.ba&&!d.M&&(d.j.info("Great, no buffering proxy detected. Bytes received: "+o.length),Yt(d),d.M=!0,we(11))):(Ee(this.i,this.l,o,"[Invalid Chunked Response]"),qe(this),Ve(this))}else Ee(this.i,this.l,o,null),je(this,o);4==t&&qe(this),this.o&&!this.J&&(4==t?Zt(this.j,this):(this.o=!1,Me(this)))}else(function(e){const t={};e=(e.g&&2<=Ft(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let i=0;i<e.length;i++)if(!C(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.s=3,we(12)):(this.s=0,we(13)),qe(this),Ve(this)}}}catch(e){}var p,f,g,m,v,_,y,w,b,I,T},Ae.prototype.cancel=function(){this.J=!0,qe(this)},Ae.prototype.ba=function(){this.B=null;var e,t,n=Date.now();0<=n-this.S?(e=this.i,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.L&&(_e(),we(17)),qe(this),this.s=2,Ve(this)):Fe(this,this.S-n)};var Be=class{constructor(e,t){this.g=e,this.map=t}};function ze(e){this.l=e||10,e=E.PerformanceNavigationTiming?0<(e=E.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(E.chrome&&E.chrome.loadTimes&&E.chrome.loadTimes()&&E.chrome.loadTimes().wasFetchedViaSpdy),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Ke(e){return e.h||e.g&&e.g.size>=e.j}function $e(e){return e.h?1:e.g?e.g.size:0}function We(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function Ge(e,t){e.g?e.g.add(t):e.h=t}function He(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function Qe(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return h(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function Ye(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(c(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.na&&"function"==typeof e.na)return e.na();if(!e.V||"function"!=typeof e.V){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(c(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.V&&"function"==typeof e.V)return e.V();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(c(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)}ze.prototype.cancel=function(){if(this.i=Qe(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 Je=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function Xe(e){var t,n;this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof Xe?(this.h=e.h,et(this,e.j),this.o=e.o,this.g=e.g,tt(this,e.s),this.l=e.l,t=e.i,(n=new ft).i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),nt(this,n),this.m=e.m):e&&(t=String(e).match(Je))?(this.h=!1,et(this,t[1]||"",!0),this.o=st(t[2]||""),this.g=st(t[3]||"",!0),tt(this,t[4]),this.l=st(t[5]||"",!0),nt(this,t[6]||"",!0),this.m=st(t[7]||"")):(this.h=!1,this.i=new ft(null,this.h))}function Ze(e){return new Xe(e)}function et(e,t,n){e.j=n?st(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function tt(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.s=t}else e.s=null}function nt(e,t,n){var r,i;t instanceof ft?(e.i=t,r=e.i,(i=e.h)&&!r.j&&(gt(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(mt(this,t),_t(this,n,e))},r)),r.j=i):(n||(t=at(t,dt)),e.i=new ft(t,e.h))}function rt(e,t,n){e.i.set(t,n)}function it(e){return rt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function st(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function at(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,ot),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function ot(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}Xe.prototype.toString=function(){var e=[],t=this.j;t&&e.push(at(t,lt,!0),":");var n=this.g;return!n&&"file"!=t||(e.push("//"),(t=this.o)&&e.push(at(t,lt,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.s)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(at(n,"/"==n.charAt(0)?ht:ut,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.m)&&e.push("#",at(n,pt)),e.join("")};var ct,lt=/[#\/\?@]/g,ut=/[#\?:]/g,ht=/[#\?]/g,dt=/[#\?@]/g,pt=/#/g;function ft(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function gt(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 mt(e,t){gt(e),t=yt(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function vt(e,t){return gt(e),t=yt(e,t),e.g.has(t)}function _t(e,t,n){mt(e,t),0<n.length&&(e.i=null,e.g.set(yt(e,t),h(n)),e.h+=n.length)}function yt(e,t){return t=String(t),t=e.j?t.toLowerCase():t}function wt(e,t,n,r,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),r(n)}catch(e){}}function bt(){this.g=new oe}function It(e){this.l=e.Ub||null,this.j=e.eb||!1}function Tt(e,t){J.call(this),this.D=e,this.o=t,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}function Et(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function Ct(e){e.readyState=4,e.l=null,e.j=null,e.v=null,St(e)}function St(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function kt(e){let n="";return g(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}function At(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=kt(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):rt(e,t,n))}function Nt(e){J.call(this),this.headers=new Map,this.o=e||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}(e=ft.prototype).add=function(e,t){gt(this),this.i=null,e=yt(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},e.forEach=function(n,r){gt(this),this.g.forEach(function(e,t){e.forEach(function(e){n.call(r,e,t,this)},this)},this)},e.na=function(){gt(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},e.V=function(t){gt(this);let n=[];if("string"==typeof t)vt(this,t)&&(n=n.concat(this.g.get(yt(this,t))));else{t=Array.from(this.g.values());for(let e=0;e<t.length;e++)n=n.concat(t[e])}return n},e.set=function(e,t){return gt(this),this.i=null,vt(this,e=yt(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},e.get=function(e,t){return e&&0<(e=this.V(e)).length?String(e[0]):t},e.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.V(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("&")},t(It,ce),It.prototype.g=function(){return new Tt(this.l,this.j)},It.prototype.i=(ct={},function(){return ct}),t(Tt,J),(e=Tt.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.B=e,this.A=t,this.readyState=1,St(this)},e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.u,method:this.B,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||E).fetch(new Request(this.A,t)).then(this.Sa.bind(this),this.ga.bind(this))},e.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Ct(this)),this.readyState=0},e.Sa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,St(this)),this.g&&(this.readyState=3,St(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==E.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;Et(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))},e.Pa=function(e){var t;this.g&&(this.o&&e.value?this.response.push(e.value):this.o||(t=e.value||new Uint8Array(0),(t=this.v.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?Ct:St)(this),3==this.readyState&&Et(this))},e.Ra=function(e){this.g&&(this.response=this.responseText=e,Ct(this))},e.Qa=function(e){this.g&&(this.response=e,Ct(this))},e.ga=function(){this.g&&Ct(this)},e.setRequestHeader=function(e,t){this.u.append(e,t)},e.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},e.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(Tt.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),t(Nt,J);var Rt=/^https?$/i,Pt=["POST","PUT"];function Dt(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.m=5,xt(e),Lt(e)}function xt(e){e.A||(e.A=!0,X(e,"complete"),X(e,"error"))}function Ot(e){if(e.h&&void 0!==o&&(!e.v[1]||4!=Ft(e)||2!=e.Z()))if(e.u&&4==Ft(e))ee(e.Ea,0,e);else if(X(e,"readystatechange"),4==Ft(e)){e.h=!1;try{var t,n,r,i=e.Z();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.D).match(Je)[1]||null)&&E.self&&E.self.location&&(r=E.self.location.protocol.slice(0,-1)),n=!Rt.test(r?r.toLowerCase():"")),t=n),t)X(e,"complete"),X(e,"success");else{e.m=6;try{var a=2<Ft(e)?e.g.statusText:""}catch(e){a=""}e.l=a+" ["+e.Z()+"]",xt(e)}}finally{Lt(e)}}}function Lt(e,t){if(e.g){Mt(e);const n=e.g,r=e.v[0]?()=>{}:null;e.g=null,e.v=null,t||X(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Mt(e){e.I&&(E.clearTimeout(e.I),e.I=null)}function Ft(e){return e.g?e.g.readyState:0}function Ut(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.H){case"":case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Vt(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function qt(e){this.Aa=0,this.i=[],this.j=new Te,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=Vt("failFast",!1,e),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=Vt("baseRetryDelayMs",5e3,e),this.cb=Vt("retryDelaySeedMs",1e4,e),this.Wa=Vt("forwardChannelMaxRetries",2,e),this.wa=Vt("forwardChannelRequestTimeoutMs",2e4,e),this.pa=e&&e.xmlHttpFactory||void 0,this.Xa=e&&e.Tb||void 0,this.Ca=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.h=new ze(e&&e.concurrentRequestLimit),this.Da=new bt,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=e&&e.Rb||!1,e&&e.xa&&this.j.xa(),e&&e.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&e&&e.detectBufferingProxy||!1,this.ja=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ja=e.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}function jt(e){if(zt(e),3==e.G){var t=e.U++,n=Ze(e.I);if(rt(n,"SID",e.K),rt(n,"RID",t),rt(n,"TYPE","terminate"),Wt(e,n),(t=new Ae(e,e.j,t)).L=2,t.v=it(Ze(n)),n=!1,E.navigator&&E.navigator.sendBeacon)try{n=E.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&E.Image&&((new Image).src=t.v,n=!0),n||(t.g=sn(t.j,null),t.g.ea(t.v)),t.F=Date.now(),Me(t)}nn(e)}function Bt(e){e.g&&(Yt(e),e.g.cancel(),e.g=null)}function zt(e){Bt(e),e.u&&(E.clearTimeout(e.u),e.u=null),Xt(e),e.h.cancel(),e.s&&("number"==typeof e.s&&E.clearTimeout(e.s),e.s=null)}function Kt(e){var t;Ke(e.h)||e.s||(e.s=!0,t=e.Ga,I||k(),T||(I(),T=!0),S.add(t,e),e.B=0)}function $t(e,t){var n=t?t.l:e.U++,r=Ze(e.I);rt(r,"SID",e.K),rt(r,"RID",n),rt(r,"AID",e.T),Wt(e,r),e.m&&e.o&&At(r,e.m,e.o),n=new Ae(e,e.j,n,e.B+1),null===e.m&&(n.H=e.o),t&&(e.i=t.D.concat(e.i)),t=Gt(e,n,1e3),n.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),Ge(e.h,n),xe(n,r,t)}function Wt(e,n){e.H&&g(e.H,function(e,t){rt(n,t,e)}),e.l&&Ye({},function(e,t){rt(n,t,e)})}function Gt(e,t,r){r=Math.min(e.i.length,r);var i=e.l?m(e.l.Na,e.l,e):null;e:{var s=e.i;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{Ye(e,function(e,t){let n=e;l(e)&&(n=se(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.i.splice(0,r),t.D=e,i}function Ht(e){var t;e.g||e.u||(e.Y=1,t=e.Fa,I||k(),T||(I(),T=!0),S.add(t,e),e.v=0)}function Qt(e){return!(e.g||e.u||3<=e.v)&&(e.Y++,e.u=Ie(m(e.Fa,e),en(e,e.v)),e.v++,1)}function Yt(e){null!=e.A&&(E.clearTimeout(e.A),e.A=null)}function Jt(e){e.g=new Ae(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var t=Ze(e.qa);rt(t,"RID","rpc"),rt(t,"SID",e.K),rt(t,"AID",e.T),rt(t,"CI",e.F?"0":"1"),!e.F&&e.ja&&rt(t,"TO",e.ja),rt(t,"TYPE","xmlhttp"),Wt(e,t),e.m&&e.o&&At(t,e.m,e.o),e.L&&(e.g.I=e.L);var n=e.g;e=e.ia,n.L=1,n.v=it(Ze(t)),n.m=null,n.P=!0,Oe(n,e)}function Xt(e){null!=e.C&&(E.clearTimeout(e.C),e.C=null)}function Zt(e,t){var n,r,i,s=null;if(e.g==t){Xt(e),Yt(e),e.g=null;var a=2}else{if(!We(e.h,t))return;s=t.D,He(e.h,t),a=1}if(0!=e.G)if(t.o)1==a?(s=t.m?t.m.length:0,t=Date.now()-t.F,n=e.B,X(a=me(),new be(a,s)),Kt(e)):Ht(e);else if(3==(n=t.s)||0==n&&0<t.X||(1!=a||(i=t,$e((r=e).h)>=r.h.j-(r.s?1:0)||(r.s?(r.i=i.D.concat(r.i),0):1==r.G||2==r.G||r.B>=(r.Va?0:r.Wa)||(r.s=Ie(m(r.Ga,r,i),en(r,r.B)),r.B++,0))))&&(2!=a||!Qt(e)))switch(s&&0<s.length&&(t=e.h,t.i=t.i.concat(s)),n){case 1:tn(e,5);break;case 4:tn(e,10);break;case 3:tn(e,6);break;default:tn(e,2)}}function en(e,t){let n=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(n*=2),n*t}function tn(e,t){var n,r,i;e.j.info("Error code "+t),2==t?(n=m(e.fb,e),r=!(i=e.Xa),i=new Xe(i||"//www.google.com/images/cleardot.gif"),E.location&&"http"==E.location.protocol||et(i,"https"),it(i),(r?function(e,t){var n=new Te;if(E.Image){const r=new Image;r.onload=u(wt,n,"TestLoadImage: loaded",!0,t,r),r.onerror=u(wt,n,"TestLoadImage: error",!1,t,r),r.onabort=u(wt,n,"TestLoadImage: abort",!1,t,r),r.ontimeout=u(wt,n,"TestLoadImage: timeout",!1,t,r),E.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}:function(e,t){const n=new Te,r=new AbortController,i=setTimeout(()=>{r.abort(),wt(n,0,!1,t)},1e4);fetch(e,{signal:r.signal}).then(e=>{clearTimeout(i),e.ok?wt(n,0,!0,t):wt(n,0,!1,t)}).catch(()=>{clearTimeout(i),wt(n,0,!1,t)})})(i.toString(),n)):we(2),e.G=0,e.l&&e.l.sa(t),nn(e),zt(e)}function nn(e){var t;e.G=0,e.ka=[],e.l&&(0==(t=Qe(e.h)).length&&0==e.i.length||(n(e.ka,t),n(e.ka,e.i),e.h.i.length=0,h(e.i),e.i.length=0),e.l.ra())}function rn(e,t,n){var r,i,s=n instanceof Xe?Ze(n):new Xe(n);return""!=s.g?(t&&(s.g=t+"."+s.g),tt(s,s.s)):(s=(r=E.location).protocol,t=t?t+"."+r.hostname:r.hostname,r=+r.port,i=new Xe(null),s&&et(i,s),t&&(i.g=t),r&&tt(i,r),n&&(i.l=n),s=i),n=e.D,t=e.ya,n&&t&&rt(s,n,t),rt(s,"VER",e.la),Wt(e,s),s}function sn(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=e.Ca&&!e.pa?new Nt(new It({eb:n})):new Nt(e.pa)).Ha(e.J),t}function an(){}function on(){}function cn(e,t){J.call(this),this.g=new qt(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.o=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.va&&(e?e["X-WebChannel-Client-Profile"]=t.va:e={"X-WebChannel-Client-Profile":t.va}),this.g.S=e,(e=t&&t.Sb)&&!C(e)&&(this.g.m=e),this.v=t&&t.supportsCrossDomainXhr||!1,this.u=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!C(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new hn(this)}function ln(e){de.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 un(){pe.call(this),this.status=1}function hn(e){this.g=e}(e=Nt.prototype).Ha=function(e){this.J=e},e.ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+e);t=t?t.toUpperCase():"GET",this.D=e,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=(this.o||Re).g(),this.v=this.o?le(this.o):le(Re),this.g.onreadystatechange=m(this.Ea,this);try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void Dt(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 o of r.keys())n.set(o,r.get(o))}r=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),i=E.FormData&&e instanceof E.FormData,0<=Array.prototype.indexOf.call(Pt,t,void 0)&&!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.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Mt(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){Dt(this,e)}},e.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=e||7,X(this,"complete"),X(this,"abort"),Lt(this))},e.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Lt(this,!0)),Nt.aa.N.call(this)},e.Ea=function(){this.s||(this.B||this.u||this.j?Ot(this):this.bb())},e.bb=function(){Ot(this)},e.isActive=function(){return!!this.g},e.Z=function(){try{return 2<Ft(this)?this.g.status:-1}catch(e){return-1}},e.oa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},e.Oa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),ae(t)}},e.Ba=function(){return this.m},e.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(e=qt.prototype).la=8,e.G=1,e.connect=function(e,t,n,r){we(0),this.W=e,this.H=t||{},n&&void 0!==r&&(this.H.OSID=n,this.H.OAID=r),this.F=this.X,this.I=rn(this,null,this.W),Kt(this)},e.Ga=function(t){if(this.s)if(this.s=null,1==this.G){if(!t){this.U=Math.floor(1e5*Math.random()),t=this.U++;const s=new Ae(this,this.j,t);let e=this.o;if(this.S&&(e?(e=v(e),y(e,this.S)):e=this.S),null!==this.m||this.O||(s.H=e,e=null),this.P)e:{for(var n=0,r=0;r<this.i.length;r++){var i=this.i[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.i.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=Gt(this,s,n),rt(r=Ze(this.I),"RID",t),rt(r,"CVER",22),this.D&&rt(r,"X-HTTP-Session-Id",this.D),Wt(this,r),e&&(this.O?n="headers="+encodeURIComponent(String(kt(e)))+"&"+n:this.m&&At(r,this.m,e)),Ge(this.h,s),this.Ua&&rt(r,"TYPE","init"),this.P?(rt(r,"$req",n),rt(r,"SID","null"),s.T=!0,xe(s,r,null)):xe(s,r,n),this.G=2}}else 3==this.G&&(t?$t(this,t):0==this.i.length||Ke(this.h)||$t(this))},e.Fa=function(){var e;this.u=null,Jt(this),this.ba&&!(this.M||null==this.g||this.R<=0)&&(e=2*this.R,this.j.info("BP detection timer enabled: "+e),this.A=Ie(m(this.ab,this),e))},e.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,we(10),Bt(this),Jt(this))},e.Za=function(){null!=this.C&&(this.C=null,Bt(this),Qt(this),we(19))},e.fb=function(e){e?(this.j.info("Successfully pinged google.com"),we(2)):(this.j.info("Failed to ping google.com"),we(1))},e.isActive=function(){return!!this.l&&this.l.isActive(this)},(e=an.prototype).ua=function(){},e.ta=function(){},e.sa=function(){},e.ra=function(){},e.isActive=function(){return!0},e.Na=function(){},on.prototype.g=function(e,t){return new cn(e,t)},t(cn,J),cn.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},cn.prototype.close=function(){jt(this.g)},cn.prototype.o=function(e){var t,n=this.g;"string"==typeof e?((t={}).__data__=e,e=t):this.u&&((t={}).__data__=se(e),e=t),n.i.push(new Be(n.Ya++,e)),3==n.G&&Kt(n)},cn.prototype.N=function(){this.g.l=null,delete this.j,jt(this.g),delete this.g,cn.aa.N.call(this)},t(ln,de),t(un,pe),t(hn,an),hn.prototype.ua=function(){X(this.g,"a")},hn.prototype.ta=function(e){X(this.g,new ln(e))},hn.prototype.sa=function(e){X(this.g,new un)},hn.prototype.ra=function(){X(this.g,"b")},on.prototype.createWebChannel=on.prototype.g,cn.prototype.send=cn.prototype.o,cn.prototype.open=cn.prototype.m,rm=function(){return new on},nm=me,tm=fe,em={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},Ce.NO_ERROR=0,Ce.TIMEOUT=8,Ce.HTTP_ERROR=6,Zg=Ce,Se.COMPLETE="complete",Xg=Se,(ue.EventType=he).OPEN="a",he.CLOSE="b",he.ERROR="c",he.MESSAGE="d",J.prototype.listen=J.prototype.K,Jg=ue,Nt.prototype.listenOnce=Nt.prototype.L,Nt.prototype.getLastError=Nt.prototype.Ka,Nt.prototype.getLastErrorCode=Nt.prototype.Ba,Nt.prototype.getStatus=Nt.prototype.Z,Nt.prototype.getResponseJson=Nt.prototype.Oa,Nt.prototype.getResponseText=Nt.prototype.oa,Nt.prototype.send=Nt.prototype.ea,Nt.prototype.setWithCredentials=Nt.prototype.Ha,Yg=Nt}).apply(void 0!==om?om:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});const cm="@firebase/firestore";class lm{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}}lm.UNAUTHENTICATED=new lm(null),lm.GOOGLE_CREDENTIALS=new lm("google-credentials-uid"),lm.FIRST_PARTY=new lm("first-party-uid"),lm.MOCK_USER=new lm("mock-user");let um="11.0.1";const hm=new ye("@firebase/firestore");function dm(){return hm.logLevel}function pm(e,...t){var n;hm.logLevel<=m.DEBUG&&(n=t.map(mm),hm.debug(`Firestore (${um}): ${e}`,...n))}function fm(e,...t){var n;hm.logLevel<=m.ERROR&&(n=t.map(mm),hm.error(`Firestore (${um}): ${e}`,...n))}function gm(e,...t){var n;hm.logLevel<=m.WARN&&(n=t.map(mm),hm.warn(`Firestore (${um}): ${e}`,...n))}function mm(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function vm(e="Unexpected state"){var t=`FIRESTORE (${um}) INTERNAL ASSERTION FAILED: `+e;throw fm(t),new Error(t)}function _m(e){e||vm()}const ym={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 wm extends x{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class bm{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class Im{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class Tm{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(lm.UNAUTHENTICATED))}shutdown(){}}class Em{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 Cm{constructor(e){this.t=e,this.currentUser=lm.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){_m(void 0===this.o);let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new bm;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new bm,t.enqueueRetryable(()=>i(this.currentUser))};const a=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},o=e=>{pm("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(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):(pm("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new bm))},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?(pm("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(_m("string"==typeof e.accessToken),new Im(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){var e=this.auth&&this.auth.getUid();return _m(null===e||"string"==typeof e),new lm(e)}}class Sm{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=lm.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 km{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new Sm(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable(()=>t(lm.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class Am{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 Nm{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(t,n){_m(void 0===this.o);const r=e=>{null!=e.error&&pm("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,pm("FirebaseAppCheckTokenProvider",`Received ${t?"new":"existing"} token.`),t?n(e.token):Promise.resolve()};this.o=e=>{t.enqueueRetryable(()=>r(e))};const i=e=>{pm("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>i(e)),setTimeout(()=>{var e;this.appCheck||((e=this.A.getImmediate({optional:!0}))?i(e):pm("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(_m("string"==typeof e.token),this.R=e.token,new Am(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class Rm{static newId(){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 Pm(e,t){return e<t?-1:t<e?1:0}function Dm(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function xm(e){return e+"\0"}class Om{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new wm(ym.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new wm(ym.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new wm(ym.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new wm(ym.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return Om.fromMillis(Date.now())}static fromDate(e){return Om.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new Om(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?Pm(this.nanoseconds,e.nanoseconds):Pm(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 Lm{constructor(e){this.timestamp=e}static fromTimestamp(e){return new Lm(e)}static min(){return new Lm(new Om(0,0))}static max(){return new Lm(new Om(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 Mm{constructor(e,t,n){void 0===t?t=0:t>e.length&&vm(),void 0===n?n=e.length-t:n>e.length-t&&vm(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===Mm.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof Mm?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 Fm extends Mm{construct(e,t,n){return new Fm(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new wm(ym.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new Fm(t)}static emptyPath(){return new Fm([])}}const Um=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class Vm extends Mm{construct(e,t,n){return new Vm(e,t,n)}static isValidIdentifier(e){return Um.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!Vm.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new Vm(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new wm(ym.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 wm(ym.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new wm(ym.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 wm(ym.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new Vm(t)}static emptyPath(){return new Vm([])}}class qm{constructor(e){this.path=e}static fromPath(e){return new qm(Fm.fromString(e))}static fromName(e){return new qm(Fm.fromString(e).popFirst(5))}static empty(){return new qm(Fm.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===Fm.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return Fm.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new qm(new Fm(e.slice()))}}class jm{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function Bm(e){return e.fields.find(e=>2===e.kind)}function zm(e){return e.fields.filter(e=>2!==e.kind)}jm.UNKNOWN_ID=-1;class Km{constructor(e,t){this.fieldPath=e,this.kind=t}}class $m{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new $m(0,Hm.min())}}function Wm(e,t){var n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,r=Lm.fromTimestamp(1e9===r?new Om(n+1,0):new Om(n,r));return new Hm(r,qm.empty(),t)}function Gm(e){return new Hm(e.readTime,e.key,-1)}class Hm{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Hm(Lm.min(),qm.empty(),-1)}static max(){return new Hm(Lm.max(),qm.empty(),-1)}}function Qm(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=qm.comparator(e.documentKey,t.documentKey),0!==n?n:Pm(e.largestBatchId,t.largestBatchId))}const Ym="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class Jm{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function Xm(e){if(e.code!==ym.FAILED_PRECONDITION||e.message!==Ym)throw e;pm("LocalStore","Unexpectedly lost primary lease")}class Zm{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&&vm(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new Zm((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 Zm?t:Zm.resolve(t)}catch(e){return Zm.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):Zm.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):Zm.reject(t)}static resolve(n){return new Zm((e,t)=>{e(n)})}static reject(n){return new Zm((e,t)=>{t(n)})}static waitFor(e){return new Zm((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=Zm.resolve(!1);for(const n of e)t=t.next(e=>e?Zm.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 Zm((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 Zm((e,t)=>{const n=()=>{!0===r()?i().next(()=>{n()},t):e()};n()})}}class ev{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.V=new bm,this.transaction.oncomplete=()=>{this.V.resolve()},this.transaction.onabort=()=>{e.error?this.V.reject(new iv(n,e.error)):this.V.resolve()},this.transaction.onerror=e=>{var t=lv(e.target.error);this.V.reject(new iv(n,t))}}static open(e,t,n,r){try{return new ev(t,e.transaction(r,n))}catch(e){throw new iv(t,e)}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(pm("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}g(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){var t=this.transaction.objectStore(e);return new av(t)}}class tv{constructor(e,t,n){this.name=e,this.version=t,this.p=n,12.2===tv.S(b())&&fm("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 pm("SimpleDb","Removing database:",e),ov(window.indexedDB.deleteDatabase(e)).toPromise()}static D(){if(!R())return!1;if(tv.v())return!0;const e=b(),t=tv.S(e),n=0<t&&t<10,r=nv(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.__PRIVATE_env)||void 0===e?void 0:e.C)}static F(e,t){return e.store(t)}static S(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)}async M(s){return this.db||(pm("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 iv(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 wm(ym.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 wm(ym.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 iv(s,t))},i.onupgradeneeded=e=>{pm("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.p.O(t,i.transaction,e.oldVersion,this.version).next(()=>{pm("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.N&&(this.db.onversionchange=e=>this.N(e)),this.db}L(t){this.N=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.M(e);const t=ev.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.g(),e)).catch(e=>(t.abort(e),Zm.reject(e))).toPromise();return s.catch(()=>{}),await t.m,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(pm("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}function nv(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}class rv{constructor(e){this.B=e,this.k=!1,this.q=null}get isDone(){return this.k}get K(){return this.q}set cursor(e){this.B=e}done(){this.k=!0}$(e){this.q=e}delete(){return ov(this.B.delete())}}class iv extends wm{constructor(e,t){super(ym.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function sv(e){return"IndexedDbTransactionError"===e.name}class av{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(pm("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(pm("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),ov(n)}add(e){return pm("SimpleDb","ADD",this.store.name,e,e),ov(this.store.add(e))}get(t){return ov(this.store.get(t)).next(e=>(pm("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return pm("SimpleDb","DELETE",this.store.name,e),ov(this.store.delete(e))}count(){return pm("SimpleDb","COUNT",this.store.name),ov(this.store.count())}U(e,n){const t=this.options(e,n),r=t.index?this.store.index(t.index):this.store;if("function"==typeof r.getAll){const e=r.getAll(t.range);return new Zm((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{const e=this.cursor(t),n=[];return this.W(e,(e,t)=>{n.push(t)}).next(()=>n)}}G(e,t){const r=this.store.getAll(e,null===t?void 0:t);return new Zm((t,n)=>{r.onerror=e=>{n(e.target.error)},r.onsuccess=e=>{t(e.target.result)}})}j(e,t){pm("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.H=!1;var r=this.cursor(n);return this.W(r,(e,t,n)=>n.delete())}J(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.W(r,t)}Y(i){const e=this.cursor({});return new Zm((n,r)=>{e.onerror=e=>{var t=lv(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()}})}W(e,s){const a=[];return new Zm((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new rv(t),r=s(t.primaryKey,t.value,n);if(r instanceof Zm){const e=r.catch(e=>(n.done(),Zm.reject(e)));a.push(e)}n.isDone?i():null===n.K?t.continue():t.continue(n.K)}else i()}}).next(()=>Zm.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.H?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function ov(e){return new Zm((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=lv(e.target.error);r(t)}})}let cv=!1;function lv(e){const t=tv.S(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 wm("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 cv||(cv=!0,setTimeout(()=>{throw e},0)),e}}return e}class uv{constructor(e,t){this.asyncQueue=e,this.Z=t,this.task=null}start(){this.X(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}X(e){pm("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{pm("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){sv(e)?pm("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await Xm(e)}await this.X(6e4)})}}class hv{constructor(e,t){this.localStore=e,this.persistence=t}async ee(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.te(e,t))}te(e,t){const n=new Set;let r=t,i=!0;return Zm.doWhile(()=>!0===i&&0<r,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>null===t||n.has(t)?void(i=!1):(pm("IndexBackfiller",`Processing collection: ${t}`),this.ne(e,t,r).next(e=>{r-=e,n.add(t)})))).next(()=>t-r)}ne(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.re(n,e)).next(e=>(pm("IndexBackfiller",`Updating offset: ${e}`),this.localStore.indexManager.updateCollectionGroup(r,i,e))).next(()=>t.size)}))}re(e,t){let r=e;return t.changes.forEach((e,t)=>{var n=Gm(t);0<Qm(n,r)&&(r=n)}),new Hm(r.readTime,r.documentKey,Math.max(t.batchId,e.largestBatchId))}}class dv{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ie(e),this.se=e=>t.writeSequenceNumber(e))}ie(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.se&&this.se(e),e}}function pv(e){return null==e}function fv(e){return 0===e&&1/e==-1/0}function gv(e){return"number"==typeof e&&Number.isInteger(e)&&!fv(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function mv(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=vv(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 vv(t)}function vv(e){return e+""}function _v(t){const n=t.length;if(_m(2<=n),2===n)return _m(""===t.charAt(0)&&""===t.charAt(1)),Fm.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)&&vm(),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:vm()}a=n+2}return new Fm(r)}dv.oe=-1;const yv=["userId","batchId"];function wv(e,t){return[e,mv(t)]}function bv(e,t,n){return[e,mv(t),n]}const Iv={},Tv=["prefixPath","collectionGroup","readTime","documentId"],Ev=["prefixPath","collectionGroup","documentId"],Cv=["collectionGroup","readTime","prefixPath","documentId"],Sv=["canonicalId","targetId"],kv=["targetId","path"],Av=["path","targetId"],Nv=["collectionId","parent"],Rv=["indexId","uid"],Pv=["uid","sequenceNumber"],Dv=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],xv=["indexId","uid","orderedDocumentKey"],Ov=["userId","collectionPath","documentId"],Lv=["userId","collectionPath","largestBatchId"],Mv=["userId","collectionGroup","largestBatchId"],Fv=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],Uv=[...Fv,"documentOverlays"],Vv=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],qv=Vv,jv=[...qv,"indexConfiguration","indexState","indexEntries"],Bv=jv,zv=[...jv,"globals"];class Kv extends Jm{constructor(e,t){super(),this._e=e,this.currentSequenceNumber=t}}function $v(e,t){var n=e;return tv.F(n._e,t)}function Wv(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function Gv(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function Hv(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class Qv{constructor(e,t){this.comparator=e,this.root=t||Jv.EMPTY}insert(e,t){return new Qv(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Jv.BLACK,null,null))}remove(e){return new Qv(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Jv.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 Yv(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Yv(this.root,e,this.comparator,!1)}getReverseIterator(){return new Yv(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Yv(this.root,e,this.comparator,!0)}}class Yv{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 Jv{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:Jv.RED,this.left=null!=r?r:Jv.EMPTY,this.right=null!=i?i:Jv.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new Jv(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 Jv.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 Jv.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,Jv.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,Jv.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 vm();if(this.right.isRed())throw vm();var e=this.left.check();if(e!==this.right.check())throw vm();return e+(this.isRed()?0:1)}}Jv.EMPTY=null,Jv.RED=!0,Jv.BLACK=!1,Jv.EMPTY=new class{constructor(){this.size=0}get key(){throw vm()}get value(){throw vm()}get color(){throw vm()}get left(){throw vm()}get right(){throw vm()}copy(e,t,n,r,i){return this}insert(e,t,n){return new Jv(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 Xv{constructor(e){this.comparator=e,this.data=new Qv(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 Zv(this.data.getIterator())}getIteratorFrom(e){return new Zv(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 Xv))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 Xv(this.comparator);return t.data=e,t}}class Zv{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function e_(e){return e.hasNext()?e.getNext():void 0}class t_{constructor(e){(this.fields=e).sort(Vm.comparator)}static empty(){return new t_([])}unionWith(e){let t=new Xv(Vm.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new t_(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Dm(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class n_ extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class r_{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 n_("Invalid base64 string: "+e):e}}(e);return new r_(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 r_(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 Pm(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}r_.EMPTY_BYTE_STRING=new r_("");const i_=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function s_(t){if(_m(!!t),"string"!=typeof t)return{seconds:a_(t.seconds),nanos:a_(t.nanos)};{let e=0;var n=i_.exec(t);_m(!!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 a_(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function o_(e){return"string"==typeof e?r_.fromBase64String(e):r_.fromUint8Array(e)}function c_(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 l_(e){var t=e.mapValue.fields.__previous_value__;return c_(t)?l_(t):t}function u_(e){var t=s_(e.mapValue.fields.__local_write_time__.timestampValue);return new Om(t.seconds,t.nanos)}class h_{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 d_{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new d_("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof d_&&e.projectId===this.projectId&&e.database===this.database}}const p_={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},f_={nullValue:"NULL_VALUE"};function g_(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?c_(e)?4:R_(e)?9007199254740991:A_(e)?10:11:vm()}function m_(e,t){if(e===t)return!0;var n,r,i=g_(e);if(i!==g_(t))return!1;switch(i){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return u_(e).isEqual(u_(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=s_(e.timestampValue),r=s_(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,o_(e.bytesValue).isEqual(o_(r.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return n=t,a_((r=e).geoPointValue.latitude)===a_(n.geoPointValue.latitude)&&a_(r.geoPointValue.longitude)===a_(n.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return a_(e.integerValue)===a_(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=a_(e.doubleValue),r=a_(t.doubleValue);return n===r?fv(n)===fv(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return Dm(e.arrayValue.values||[],t.arrayValue.values||[],m_);case 10:case 11:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(Wv(n)!==Wv(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!m_(n[e],r[e])))return!1;return!0}(e,t);default:return vm()}}function v_(e,t){return void 0!==(e.values||[]).find(e=>m_(e,t))}function __(e,t){if(e===t)return 0;var n,r,i,s,a,o,c,l=g_(e),u=g_(t);if(l!==u)return Pm(l,u);switch(l){case 0:case 9007199254740991:return 0;case 1:return Pm(e.booleanValue,t.booleanValue);case 2:return a=t,o=a_((s=e).integerValue||s.doubleValue),c=a_(a.integerValue||a.doubleValue),o<c?-1:c<o?1:o===c?0:isNaN(o)?isNaN(c)?0:-1:1;case 3:return y_(e.timestampValue,t.timestampValue);case 4:return y_(u_(e),u_(t));case 5:return Pm(e.stringValue,t.stringValue);case 6:return function(e,t){const n=o_(e),r=o_(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=Pm(n[i],r[i]);if(0!==t)return t}return Pm(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(i=Pm(a_(n.latitude),a_(r.latitude)))?i:Pm(a_(n.longitude),a_(r.longitude));case 9:return w_(e.arrayValue,t.arrayValue);case 10:return n=e.mapValue,r=t.mapValue,o=n.fields||{},c=r.fields||{},o=null===(i=o.value)||void 0===i?void 0:i.arrayValue,c=null===(i=c.value)||void 0===i?void 0:i.arrayValue,0!==(i=Pm((null===(i=null==o?void 0:o.values)||void 0===i?void 0:i.length)||0,(null===(i=null==c?void 0:c.values)||void 0===i?void 0:i.length)||0))?i:w_(o,c);case 11:return function(e,t){if(e===p_.mapValue&&t===p_.mapValue)return 0;if(e===p_.mapValue)return 1;if(t===p_.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=Pm(r[o],s[o]);if(0!==t)return t;var a=__(n[r[o]],i[s[o]]);if(0!==a)return a}return Pm(r.length,s.length)}(e.mapValue,t.mapValue);default:throw vm()}}function y_(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Pm(e,t);var n=s_(e),r=s_(t),i=Pm(n.seconds,r.seconds);return 0!==i?i:Pm(n.nanos,r.nanos)}function w_(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=__(n[i],r[i]);if(t)return t}return Pm(n.length,r.length)}function b_(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=s_(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return o_(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return qm.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):vm()}(e)}function I_(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function T_(e){return!!e&&"integerValue"in e}function E_(e){return!!e&&"arrayValue"in e}function C_(e){return e&&"nullValue"in e}function S_(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function k_(e){return e&&"mapValue"in e}function A_(e){var t;return"__vector__"===(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 N_(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 Gv(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=N_(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=N_(t.arrayValue.values[e]);return r}return Object.assign({},t)}function R_(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}const P_={mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{}}}}};function D_(e,t){var n=__(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function x_(e,t){var n=__(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class O_{constructor(e){this.value=e}static empty(){return new O_({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)],!k_(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=N_(t)}setAll(e){let n=Vm.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()]=N_(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());k_(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return m_(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)];k_(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){Gv(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new O_(N_(this.value))}}class L_{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 L_(e,0,Lm.min(),Lm.min(),Lm.min(),O_.empty(),0)}static newFoundDocument(e,t,n,r){return new L_(e,1,t,Lm.min(),n,r,0)}static newNoDocument(e,t){return new L_(e,2,t,Lm.min(),Lm.min(),O_.empty(),0)}static newUnknownDocument(e,t){return new L_(e,3,t,Lm.min(),Lm.min(),O_.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(Lm.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=O_.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=O_.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=Lm.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 L_&&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 L_(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 M_{constructor(e,t){this.position=e,this.inclusive=t}}function F_(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()?qm.comparator(qm.fromName(a.referenceValue),n.key):__(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function U_(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(!m_(e.position[n],t.position[n]))return!1;return!0}class V_{constructor(e,t="asc"){this.field=e,this.dir=t}}class q_{}class j_ extends q_{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 Q_(e,t,n):"array-contains"===t?new Z_(e,n):"in"===t?new ey(e,n):"not-in"===t?new ty(e,n):"array-contains-any"===t?new ny(e,n):new j_(e,t,n)}static createKeyFieldInFilter(e,t,n){return new("in"===t?Y_:J_)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(__(t,this.value)):null!==t&&g_(this.value)===g_(t)&&this.matchesComparison(__(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 vm()}}isInequality(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class B_ extends q_{constructor(e,t){super(),this.filters=e,this.op=t,this.ae=null}static create(e,t){return new B_(e,t)}matches(t){return z_(this)?void 0===this.filters.find(e=>!e.matches(t)):void 0!==this.filters.find(e=>e.matches(t))}getFlattenedFilters(){return null!==this.ae||(this.ae=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.ae}getFilters(){return Object.assign([],this.filters)}}function z_(e){return"and"===e.op}function K_(e){return"or"===e.op}function $_(e){return W_(e)&&z_(e)}function W_(e){for(const t of e.filters)if(t instanceof B_)return!1;return!0}function G_(e,t){var n=e.filters.concat(t);return B_.create(n,e.op)}function H_(e){return e instanceof j_?`${(t=e).field.canonicalString()} ${t.op} ${b_(t.value)}`:e instanceof B_?(e=e).op.toString()+" {"+e.getFilters().map(H_).join(" ,")+"}":"Filter";var t}class Q_ extends j_{constructor(e,t,n){super(e,t,n),this.key=qm.fromName(n.referenceValue)}matches(e){var t=qm.comparator(e.key,this.key);return this.matchesComparison(t)}}class Y_ extends j_{constructor(e,t){super(e,"in",t),this.keys=X_(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class J_ extends j_{constructor(e,t){super(e,"not-in",t),this.keys=X_(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function X_(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>qm.fromName(e.referenceValue))}class Z_ extends j_{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return E_(t)&&v_(t.arrayValue,this.value)}}class ey extends j_{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&v_(this.value.arrayValue,t)}}class ty extends j_{constructor(e,t){super(e,"not-in",t)}matches(e){if(v_(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!v_(this.value.arrayValue,t)}}class ny extends j_{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!E_(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>v_(this.value.arrayValue,e))}}class ry{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.ue=null}}function iy(e,t=null,n=[],r=[],i=null,s=null,a=null){return new ry(e,t,n,r,i,s,a)}function sy(e){const t=e;if(null===t.ue){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 j_)return e.field.canonicalString()+e.op.toString()+b_(e.value);if($_(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(","),pv(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map(e=>b_(e)).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map(e=>b_(e)).join(",")),t.ue=e}return t.ue}function ay(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 j_?(n=e,(s=t)instanceof j_&&n.op===s.op&&n.field.isEqual(s.field)&&m_(n.value,s.value)):e instanceof B_?(i=t)instanceof B_&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce((e,t,n)=>e&&r(t,i.filters[n]),!0):void vm();var i,n,s}(e.filters[s],t.filters[s]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!U_(e.startAt,t.startAt)&&U_(e.endAt,t.endAt)}function oy(e){return qm.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function cy(e,t){return e.filters.filter(e=>e instanceof j_&&e.field.isEqual(t))}function ly(t,n,r){let i=f_,s=!0;for(const r of cy(t,n)){let e=f_,t=!0;switch(r.op){case"<":case"<=":e="nullValue"in(a=r.value)?f_:"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?I_(d_.empty(),qm.empty()):"geoPointValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in a?{arrayValue:{}}:"mapValue"in a?A_(a)?P_:{mapValue:{}}:vm();break;case"==":case"in":case">=":e=r.value;break;case">":e=r.value,t=!1;break;case"!=":case"not-in":e=f_}D_({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];D_({value:i,inclusive:s},{value:t,inclusive:r.inclusive})<0&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}function uy(t,n,r){let i=p_,s=!0;for(const r of cy(t,n)){let e=p_,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?I_(d_.empty(),qm.empty()):"referenceValue"in a?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in a?{arrayValue:{}}:"arrayValue"in a?P_:"mapValue"in a?A_(a)?{mapValue:{}}:p_:vm(),t=!1;break;case"==":case"in":case"<=":e=r.value;break;case"<":e=r.value,t=!1;break;case"!=":case"not-in":e=p_}0<x_({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<x_({value:i,inclusive:s},{value:t,inclusive:r.inclusive})&&(i=t,s=r.inclusive);break}return{value:i,inclusive:s}}class hy{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.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function dy(e,t,n,r,i,s,a,o){return new hy(e,t,n,r,i,s,a,o)}function py(e){return new hy(e)}function fy(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 gy(e){return null!==e.collectionGroup}function my(t){const n=t;if(null===n.ce){n.ce=[];const t=new Set;for(const i of n.explicitOrderBy)n.ce.push(i),t.add(i.field.canonicalString());const r=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc",e=function(e){let t=new Xv(Vm.comparator);return e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t}(n);e.forEach(e=>{t.has(e.canonicalString())||e.isKeyField()||n.ce.push(new V_(e,r))}),t.has(Vm.keyField().canonicalString())||n.ce.push(new V_(Vm.keyField(),r))}return n.ce}function vy(e){const t=e;return t.le||(t.le=function(e,t){if("F"===e.limitType)return iy(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 V_(e.field,t)});var n=e.endAt?new M_(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new M_(e.startAt.position,e.startAt.inclusive):null;return iy(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}(t,my(e))),t.le}function _y(e,t){var n=e.filters.concat([t]);return new hy(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function yy(e,t,n){return new hy(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function wy(e,t){return ay(vy(e),vy(t))&&e.limitType===t.limitType}function by(e){return`${sy(vy(e))}|lt:${e.limitType}`}function Iy(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=>H_(e)).join(", ")}]`),pv(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=>b_(e)).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>b_(e)).join(",")),`Target(${t})`}(vy(e))}; limitType=${e.limitType})`}function Ty(e,t){return t.isFoundDocument()&&(i=e,a=(s=t).key.path,null!==i.collectionGroup?s.key.hasCollectionId(i.collectionGroup)&&i.path.isPrefixOf(a):qm.isDocumentKey(i.path)?i.path.isEqual(a):i.path.isImmediateParentOf(a))&&function(e,t){for(const n of my(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=my(t),r=F_(n,e,i),n.inclusive?r<=0:r<0))&&(!t.endAt||(n=t.endAt,t=my(t),r=F_(n,t,i),n.inclusive?0<=r:0<r)));var n,r,i,s,a}function Ey(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function Cy(i){return(e,t)=>{let n=!1;for(const r of my(i)){const i=function(e,t,n){var r=e.field.isKeyField()?qm.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?__(r,i):vm()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return vm()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}class Sy{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){Gv(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return Hv(this.inner)}size(){return this.innerSize}}const ky=new Qv(qm.comparator);const Ay=new Qv(qm.comparator);function Ny(...e){let t=Ay;for(const n of e)t=t.insert(n.key,n);return t}function Ry(e){let n=Ay;return e.forEach((e,t)=>n=n.insert(e,t.overlayedDocument)),n}function Py(){return new Sy(e=>e.toString(),(e,t)=>e.isEqual(t))}const Dy=new Qv(qm.comparator),xy=new Xv(qm.comparator);function Oy(...e){let t=xy;for(const n of e)t=t.add(n);return t}const Ly=new Xv(Pm);function My(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:fv(t)?"-0":t}}function Fy(e){return{integerValue:""+e}}function Uy(e,t){return gv(t)?Fy(t):My(e,t)}class Vy{constructor(){this._=void 0}}function qy(e,t){return e instanceof Wy?T_(e=t)||(e=e)&&"doubleValue"in e?t:{integerValue:0}:null}class jy extends Vy{}class By extends Vy{constructor(e){super(),this.elements=e}}function zy(e,t){const n=Hy(t);for(const t of e.elements)n.some(e=>m_(e,t))||n.push(t);return{arrayValue:{values:n}}}class Ky extends Vy{constructor(e){super(),this.elements=e}}function $y(e,t){let n=Hy(t);for(const t of e.elements)n=n.filter(e=>!m_(e,t));return{arrayValue:{values:n}}}class Wy extends Vy{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function Gy(e){return a_(e.integerValue||e.doubleValue)}function Hy(e){return E_(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class Qy{constructor(e,t){this.field=e,this.transform=t}}class Yy{constructor(e,t){this.version=e,this.transformResults=t}}class Jy{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Jy}static exists(e){return new Jy(void 0,e)}static updateTime(e){return new Jy(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 Xy(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Zy{}function ew(e,n){if(!e.hasLocalMutations||n&&0===n.fields.length)return null;if(null===n)return e.isNoDocument()?new lw(e.key,Jy.none()):new iw(e.key,e.data,Jy.none());{const i=e.data,s=O_.empty();let t=new Xv(Vm.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 sw(e.key,s,new t_(t.toArray()),Jy.none())}}function tw(e,t,n){e instanceof iw?function(e,t,n){const r=e.value.clone(),i=ow(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof sw?function(e,t,n){if(!Xy(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=ow(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(aw(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function nw(e,t,n,r){return e instanceof iw?function(e,t,n,r){if(!Xy(e.precondition,t))return n;const i=e.value.clone(),s=cw(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof sw?function(e,t,n,r){if(!Xy(e.precondition,t))return n;const i=cw(e.fieldTransforms,r,t),s=t.data;return s.setAll(aw(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,Xy(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n)}function rw(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&&Dm(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof By&&t instanceof By||e instanceof Ky&&t instanceof Ky?Dm(e.elements,t.elements,m_):e instanceof Wy&&t instanceof Wy?m_(e.Pe,t.Pe):e instanceof jy&&t instanceof jy)}(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 iw extends Zy{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 sw extends Zy{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 aw(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 ow(e,t,n){const r=new Map;_m(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 By?zy(o,c):o instanceof Ky?$y(o,c):l))}var o,c,l;return r}function cw(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 jy?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return(t=t&&c_(t)?l_(t):t)&&(n.fields.__previous_value__=t),{mapValue:n}}(a,s):i instanceof By?zy(i,s):i instanceof Ky?$y(i,s):(o=qy(i=i,s),c=Gy(o)+Gy(i.Pe),T_(o)&&T_(i.Pe)?Fy(c):My(i.serializer,c))))}var i,s,a,o,c;return r}class lw extends Zy{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class uw extends Zy{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class hw{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)&&tw(i,e,n[r])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=nw(n,e,t,this.localWriteTime));for(const r of this.mutations)r.key.isEqual(e.key)&&(t=nw(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(s,a){const o=Py();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=ew(n,r);null!==i&&o.set(e.key,i),n.isValidDocument()||n.convertToNoDocument(Lm.min())}),o}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Oy())}isEqual(e){return this.batchId===e.batchId&&Dm(this.mutations,e.mutations,(e,t)=>rw(e,t))&&Dm(this.baseMutations,e.baseMutations,(e,t)=>rw(e,t))}}class dw{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){_m(e.mutations.length===n.length);let r=Dy;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new dw(e,t,n,r)}}class pw{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 fw{constructor(e,t){this.count=e,this.unchangedNames=t}}function gw(e){switch(e){default:return vm();case ym.CANCELLED:case ym.UNKNOWN:case ym.DEADLINE_EXCEEDED:case ym.RESOURCE_EXHAUSTED:case ym.INTERNAL:case ym.UNAVAILABLE:case ym.UNAUTHENTICATED:return!1;case ym.INVALID_ARGUMENT:case ym.NOT_FOUND:case ym.ALREADY_EXISTS:case ym.PERMISSION_DENIED:case ym.FAILED_PRECONDITION:case ym.ABORTED:case ym.OUT_OF_RANGE:case ym.UNIMPLEMENTED:case ym.DATA_LOSS:return!0}}function mw(e){if(void 0===e)return fm("GRPC error has no .code"),ym.UNKNOWN;switch(e){case im.OK:return ym.OK;case im.CANCELLED:return ym.CANCELLED;case im.UNKNOWN:return ym.UNKNOWN;case im.DEADLINE_EXCEEDED:return ym.DEADLINE_EXCEEDED;case im.RESOURCE_EXHAUSTED:return ym.RESOURCE_EXHAUSTED;case im.INTERNAL:return ym.INTERNAL;case im.UNAVAILABLE:return ym.UNAVAILABLE;case im.UNAUTHENTICATED:return ym.UNAUTHENTICATED;case im.INVALID_ARGUMENT:return ym.INVALID_ARGUMENT;case im.NOT_FOUND:return ym.NOT_FOUND;case im.ALREADY_EXISTS:return ym.ALREADY_EXISTS;case im.PERMISSION_DENIED:return ym.PERMISSION_DENIED;case im.FAILED_PRECONDITION:return ym.FAILED_PRECONDITION;case im.ABORTED:return ym.ABORTED;case im.OUT_OF_RANGE:return ym.OUT_OF_RANGE;case im.UNIMPLEMENTED:return ym.UNIMPLEMENTED;case im.DATA_LOSS:return ym.DATA_LOSS;default:return vm()}}function vw(){return new TextEncoder}(Rt=im=im||{})[Rt.OK=0]="OK",Rt[Rt.CANCELLED=1]="CANCELLED",Rt[Rt.UNKNOWN=2]="UNKNOWN",Rt[Rt.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Rt[Rt.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Rt[Rt.NOT_FOUND=5]="NOT_FOUND",Rt[Rt.ALREADY_EXISTS=6]="ALREADY_EXISTS",Rt[Rt.PERMISSION_DENIED=7]="PERMISSION_DENIED",Rt[Rt.UNAUTHENTICATED=16]="UNAUTHENTICATED",Rt[Rt.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Rt[Rt.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Rt[Rt.ABORTED=10]="ABORTED",Rt[Rt.OUT_OF_RANGE=11]="OUT_OF_RANGE",Rt[Rt.UNIMPLEMENTED=12]="UNIMPLEMENTED",Rt[Rt.INTERNAL=13]="INTERNAL",Rt[Rt.UNAVAILABLE=14]="UNAVAILABLE",Rt[Rt.DATA_LOSS=15]="DATA_LOSS";const _w=new Hg([4294967295,4294967295],0);function yw(e){const t=vw().encode(e),n=new Qg;return n.update(t),new Uint8Array(n.digest())}function ww(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 Hg([n,r],0),new Hg([i,s],0)]}class bw{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||8<=t)throw new Iw(`Invalid padding: ${t}`);if(n<0)throw new Iw(`Invalid hash count: ${n}`);if(0<e.length&&0===this.hashCount)throw new Iw(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Iw(`Invalid padding when bitmap length is 0: ${t}`);this.Ie=8*e.length-t,this.Te=Hg.fromNumber(this.Ie)}Ee(e,t,n){let r=e.add(t.multiply(Hg.fromNumber(n)));return 1===r.compare(_w)&&(r=new Hg([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Te).toNumber()}de(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ie)return!1;const t=yw(e),[n,r]=ww(t);for(let i=0;i<this.hashCount;i++){const t=this.Ee(n,r,i);if(!this.de(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 bw(i,r,t);return n.forEach(e=>s.insert(e)),s}insert(t){if(0!==this.Ie){const n=yw(t),[r,i]=ww(n);for(let e=0;e<this.hashCount;e++){const n=this.Ee(r,i,e);this.Ae(n)}}}Ae(e){var t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class Iw extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Tw{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,Ew.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Tw(Lm.min(),r,new Qv(Pm),ky,Oy())}}class Ew{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 Ew(n,t,Oy(),Oy(),Oy())}}class Cw{constructor(e,t,n,r){this.Re=e,this.removedTargetIds=t,this.key=n,this.Ve=r}}class Sw{constructor(e,t){this.targetId=e,this.me=t}}class kw{constructor(e,t,n=r_.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class Aw{constructor(){this.fe=0,this.ge=Pw(),this.pe=r_.EMPTY_BYTE_STRING,this.ye=!1,this.we=!0}get current(){return this.ye}get resumeToken(){return this.pe}get Se(){return 0!==this.fe}get be(){return this.we}De(e){0<e.approximateByteSize()&&(this.we=!0,this.pe=e)}ve(){let n=Oy(),r=Oy(),i=Oy();return this.ge.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:vm()}}),new Ew(this.pe,this.ye,n,r,i)}Ce(){this.we=!1,this.ge=Pw()}Fe(e,t){this.we=!0,this.ge=this.ge.insert(e,t)}Me(e){this.we=!0,this.ge=this.ge.remove(e)}xe(){this.fe+=1}Oe(){--this.fe,_m(0<=this.fe)}Ne(){this.we=!0,this.ye=!0}}class Nw{constructor(e){this.Le=e,this.Be=new Map,this.ke=ky,this.qe=Rw(),this.Qe=new Qv(Pm)}Ke(e){for(const t of e.Re)e.Ve&&e.Ve.isFoundDocument()?this.$e(t,e.Ve):this.Ue(t,e.key,e.Ve);for(const n of e.removedTargetIds)this.Ue(n,e.key,e.Ve)}We(n){this.forEachTarget(n,e=>{const t=this.Ge(e);switch(n.state){case 0:this.ze(e)&&t.De(n.resumeToken);break;case 1:t.Oe(),t.Se||t.Ce(),t.De(n.resumeToken);break;case 2:t.Oe(),t.Se||this.removeTarget(e);break;case 3:this.ze(e)&&(t.Ne(),t.De(n.resumeToken));break;case 4:this.ze(e)&&(this.je(e),t.De(n.resumeToken));break;default:vm()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.Be.forEach((e,t)=>{this.ze(t)&&n(t)})}He(e){const t=e.targetId,n=e.me.count,r=this.Je(t);if(r){var i=r.target;if(oy(i))if(0===n){const e=new qm(i.path);this.Ue(t,e,L_.newNoDocument(e,Lm.min()))}else _m(1===n);else{const r=this.Ye(t);if(r!==n){const n=this.Ze(e),s=n?this.Xe(n,e,r):1;if(0!==s){this.je(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Qe=this.Qe.insert(t,e)}}}}}Ze(e){var t=e.me.unchangedNames;if(!t||!t.bits)return null;var{bits:{bitmap:n="",padding:r=0},hashCount:t=0}=t;let i,s;try{i=o_(n).toUint8Array()}catch(e){if(e instanceof n_)return gm("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 bw(i,r,t)}catch(e){return gm(e instanceof Iw?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ie?null:s}Xe(e,t,n){return t.me.count===n-this.nt(e,t.targetId)?0:2}nt(n,r){const e=this.Le.getRemoteKeysForTarget(r);let i=0;return e.forEach(e=>{var t=this.Le.tt(),t=`projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`;n.mightContain(t)||(this.Ue(r,e,null),i++)}),i}rt(r){const i=new Map;this.Be.forEach((e,t)=>{var n=this.Je(t);if(n){if(e.current&&oy(n.target)){const i=new qm(n.target.path);null!==this.ke.get(i)||this.it(t,i)||this.Ue(t,i,L_.newNoDocument(i,r))}e.be&&(i.set(t,e.ve()),e.Ce())}});let s=Oy();this.qe.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.Je(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.ke.forEach((e,t)=>t.setReadTime(r));var e=new Tw(r,i,this.Qe,this.ke,s);return this.ke=ky,this.qe=Rw(),this.Qe=new Qv(Pm),e}$e(e,t){var n;this.ze(e)&&(n=this.it(e,t.key)?2:0,this.Ge(e).Fe(t.key,n),this.ke=this.ke.insert(t.key,t),this.qe=this.qe.insert(t.key,this.st(t.key).add(e)))}Ue(e,t,n){if(this.ze(e)){const r=this.Ge(e);this.it(e,t)?r.Fe(t,1):r.Me(t),this.qe=this.qe.insert(t,this.st(t).delete(e)),n&&(this.ke=this.ke.insert(t,n))}}removeTarget(e){this.Be.delete(e)}Ye(e){var t=this.Ge(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}xe(e){this.Ge(e).xe()}Ge(e){let t=this.Be.get(e);return t||(t=new Aw,this.Be.set(e,t)),t}st(e){let t=this.qe.get(e);return t||(t=new Xv(Pm),this.qe=this.qe.insert(e,t)),t}ze(e){var t=null!==this.Je(e);return t||pm("WatchChangeAggregator","Detected inactive target",e),t}Je(e){var t=this.Be.get(e);return t&&t.Se?null:this.Le.ot(e)}je(t){this.Be.set(t,new Aw),this.Le.getRemoteKeysForTarget(t).forEach(e=>{this.Ue(t,e,null)})}it(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function Rw(){return new Qv(qm.comparator)}function Pw(){return new Qv(qm.comparator)}const Dw={asc:"ASCENDING",desc:"DESCENDING"},xw={"<":"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"},Ow={and:"AND",or:"OR"};class Lw{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function Mw(e,t){return e.useProto3Json||pv(t)?t:{value:t}}function Fw(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 Uw(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function Vw(e){return _m(!!e),Lm.fromTimestamp((t=s_(e),new Om(t.seconds,t.nanos)));var t}function qw(e,t){return jw(e,t).canonicalString()}function jw(e,t){const n=(e=e,new Fm(["projects",e.projectId,"databases",e.database]).child("documents"));return void 0===t?n:n.child(t)}function Bw(e){var t=Fm.fromString(e);return _m(ab(t)),t}function zw(e,t){return qw(e.databaseId,t.path)}function Kw(e,t){const n=Bw(t);if(n.get(1)!==e.databaseId.projectId)throw new wm(ym.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 wm(ym.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new qm(Hw(n))}function $w(e,t){return qw(e.databaseId,t)}function Ww(e){var t=Bw(e);return 4===t.length?Fm.emptyPath():Hw(t)}function Gw(e){return new Fm(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Hw(e){return _m(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function Qw(e,t,n){return{name:zw(e,t),fields:n.value.mapValue.fields}}function Yw(e,t,n){const r=Kw(e,t.name),i=Vw(t.updateTime),s=t.createTime?Vw(t.createTime):Lm.min(),a=new O_({mapValue:{fields:t.fields}}),o=L_.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function Jw(e,t){let n;if(t instanceof iw)n={update:Qw(e,t.key,t.value)};else if(t instanceof lw)n={delete:zw(e,t.key)};else if(t instanceof sw)n={update:Qw(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 uw))return vm();n={verify:zw(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof jy)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof By)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof Ky)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof Wy)return{fieldPath:e.field.canonicalString(),increment:t.Pe};throw vm()}(e))),t.precondition.isNone||(n.currentDocument=(r=e,void 0!==(e=t.precondition).updateTime?{updateTime:(t=e.updateTime,Fw(r,t.toTimestamp()))}:void 0!==e.exists?{exists:e.exists}:vm())),n;var r}function Xw(t,e){const n=e.currentDocument?void 0!==(i=e.currentDocument).updateTime?Jy.updateTime(Vw(i.updateTime)):void 0!==i.exists?Jy.exists(i.exists):Jy.none():Jy.none(),r=e.updateTransforms?e.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)_m("REQUEST_TIME"===t.setToServerValue),n=new jy;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new By(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new Ky(e)}else"increment"in t?n=new Wy(e,t.increment):vm();var r=Vm.fromServerFormat(t.fieldPath);return new Qy(r,n)}(t,e)):[];var i;if(e.update){e.update.name;var s=Kw(t,e.update.name),a=new O_({mapValue:{fields:e.update.fields}});if(e.updateMask){const t=function(e){const t=e.fieldPaths||[];return new t_(t.map(e=>Vm.fromServerFormat(e)))}(e.updateMask);return new sw(s,a,t,n,r)}return new iw(s,a,n,r)}if(e.delete){const r=Kw(t,e.delete);return new lw(r,n)}if(e.verify){const r=Kw(t,e.verify);return new uw(r,n)}return vm()}function Zw(e,t){return{documents:[$w(e,t.path)]}}function eb(e,t){const n={structuredQuery:{}},r=t.path;let i;null!==t.collectionGroup?(i=r,n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=r.popLast(),n.structuredQuery.from=[{collectionId:r.lastSegment()}]),n.parent=$w(e,i);var s=function(e){if(0!==e.length)return function n(e){return e instanceof j_?function(e){if("=="===e.op){if(S_(e.value))return{unaryFilter:{field:ib(e.field),op:"IS_NAN"}};if(C_(e.value))return{unaryFilter:{field:ib(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(S_(e.value))return{unaryFilter:{field:ib(e.field),op:"IS_NOT_NAN"}};if(C_(e.value))return{unaryFilter:{field:ib(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:ib(e.field),op:nb(e.op),value:e.value}}}(e):e instanceof B_?function(e){const t=e.getFilters().map(e=>n(e));return 1===t.length?t[0]:{compositeFilter:{op:rb(e.op),filters:t}}}(e):vm()}(B_.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);s=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:ib(e.field),direction:(e=e.dir,Dw[e])}}(e))}(t.orderBy);s&&(n.structuredQuery.orderBy=s);s=Mw(e,t.limit);return null!==s&&(n.structuredQuery.limit=s),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}),{_t:n,parent:i}}function tb(e){let t=Ww(e.parent);var n,r,i,s=e.structuredQuery,a=s.from?s.from.length:0;let o=null;if(0<a){_m(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=sb(e.unaryFilter.field);return j_.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=sb(e.unaryFilter.field);return j_.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=sb(e.unaryFilter.field);return j_.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=sb(e.unaryFilter.field);return j_.create(i,"!=",{nullValue:"NULL_VALUE"});default:return vm()}}(e):void 0!==e.fieldFilter?function(e){return j_.create(sb(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 vm()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return B_.create(e.compositeFilter.filters.map(e=>t(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return vm()}}(e.compositeFilter.op))}(e):vm()}(e);return t instanceof B_&&$_(t)?t.getFilters():[t]}(s.where));let l=[];s.orderBy&&(l=s.orderBy.map(e=>function(e){return new V_(sb(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,pv(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 M_(n,i)));let d=null;return s.endAt&&(d=(r=s.endAt,i=!r.before,s=r.values||[],new M_(s,i))),dy(t,o,l,c,u,"F",h,d)}function nb(e){return xw[e]}function rb(e){return Ow[e]}function ib(e){return{fieldPath:e.canonicalString()}}function sb(e){return Vm.fromServerFormat(e.fieldPath)}function ab(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}class ob{constructor(e,t,n,r,i=Lm.min(),s=Lm.min(),a=r_.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 ob(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new ob(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new ob(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new ob(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class cb{constructor(e){this.ct=e}}function lb(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:ub(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document={name:zw(i=e.ct,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:Fw(i,e.version.toTimestamp()),createTime:Fw(i,e.createTime.toTimestamp())};else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:hb(t.version)};else{if(!t.isUnknownDocument())return vm();r.unknownDocument={path:n.path.toArray(),version:hb(t.version)}}var i;return r}function ub(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function hb(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function db(e){var t=new Om(e.seconds,e.nanoseconds);return Lm.fromTimestamp(t)}function pb(t,e){const n=(e.baseMutations||[]).map(e=>Xw(t.ct,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=>Xw(t.ct,e)),i=Om.fromMillis(e.localWriteTimeMs);return new hw(e.batchId,i,n,r)}function fb(e){var t,n=db(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?db(e.lastLimboFreeSnapshotVersion):Lm.min(),i=void 0!==e.query.documents?(_m(1===(t=e.query).documents.length),vy(py(Ww(t.documents[0])))):vy(tb(e.query));return new ob(i,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,n,r,r_.fromBase64String(e.resumeToken))}function gb(e,t){var n=hb(t.snapshotVersion),r=hb(t.lastLimboFreeSnapshotVersion),i=oy(t.target)?Zw(e.ct,t.target):eb(e.ct,t.target)._t,s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:sy(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function mb(e){var t=tb({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?yy(t,t.limit,"L"):t}function vb(e,t){return new pw(t.largestBatchId,Xw(e.ct,t.overlayMutation))}function _b(e,t){var n=t.path.lastSegment();return[e,mv(t.path.popLast()),n]}function yb(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:hb(r.readTime),documentKey:mv(r.documentKey.path),largestBatchId:r.largestBatchId}}class wb{getBundleMetadata(e,t){return bb(e).get(t).next(e=>{if(e)return{id:(e=e).bundleId,createTime:db(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return bb(e).put({bundleId:(t=t).id,createTime:hb(Vw(t.createTime)),version:t.version})}getNamedQuery(e,t){return Ib(e).get(t).next(e=>{if(e)return{name:(e=e).name,query:mb(e.bundledQuery),readTime:db(e.readTime)}})}saveNamedQuery(e,t){return Ib(e).put({name:(t=t).name,readTime:hb(Vw(t.readTime)),bundledQuery:t.bundledQuery})}}function bb(e){return $v(e,"bundles")}function Ib(e){return $v(e,"namedQueries")}class Tb{constructor(e,t){this.serializer=e,this.userId=t}static lt(e,t){var n=t.uid||"";return new Tb(e,n)}getOverlay(e,t){return Eb(e).get(_b(this.userId,t)).next(e=>e?vb(this.serializer,e):null)}getOverlays(e,t){const n=Py();return Zm.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 pw(i,t);s.push(this.ht(r,n))}),Zm.waitFor(s)}removeOverlaysForBatchId(n,e,r){const t=new Set;e.forEach(e=>t.add(mv(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(Eb(n).j("collectionPathOverlayIndex",t))}),Zm.waitFor(i)}getOverlaysForCollection(e,t,n){const r=Py(),i=mv(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return Eb(e).U("collectionPathOverlayIndex",s).next(e=>{for(const t of e){const e=vb(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,i){const s=Py();let a;var r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return Eb(e).J({index:"collectionGroupOverlayIndex",range:r},(e,t,n)=>{const r=vb(this.serializer,t);s.size()<i||r.largestBatchId===a?(s.set(r.getKey(),r),a=r.largestBatchId):n.done()}).next(()=>s)}ht(e,t){return Eb(e).put(function(e,t,n){var[,r,i]=_b(t,n.mutation.key);return{userId:t,collectionPath:r,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:Jw(e.ct,n.mutation)}}(this.serializer,this.userId,t))}}function Eb(e){return $v(e,"documentOverlays")}class Cb{Pt(e){return $v(e,"globals")}getSessionToken(e){return this.Pt(e).get("sessionToken").next(e=>{var t=null==e?void 0:e.value;return t?r_.fromUint8Array(t):r_.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.Pt(e).put({name:"sessionToken",value:t.toUint8Array()})}}class Sb{constructor(){}It(e,t){this.Tt(e,t),t.Et()}Tt(t,n){if("nullValue"in t)this.dt(n,5);else if("booleanValue"in t)this.dt(n,10),n.At(t.booleanValue?1:0);else if("integerValue"in t)this.dt(n,15),n.At(a_(t.integerValue));else if("doubleValue"in t){var e=a_(t.doubleValue);isNaN(e)?this.dt(n,13):(this.dt(n,15),fv(e)?n.At(0):n.At(e))}else if("timestampValue"in t){let e=t.timestampValue;this.dt(n,20),"string"==typeof e&&(e=s_(e)),n.Rt(`${e.seconds||""}`),n.At(e.nanos||0)}else"stringValue"in t?(this.Vt(t.stringValue,n),this.ft(n)):"bytesValue"in t?(this.dt(n,30),n.gt(o_(t.bytesValue)),this.ft(n)):"referenceValue"in t?this.yt(t.referenceValue,n):"geoPointValue"in t?(e=t.geoPointValue,this.dt(n,45),n.At(e.latitude||0),n.At(e.longitude||0)):"mapValue"in t?R_(t)?this.dt(n,Number.MAX_SAFE_INTEGER):A_(t)?this.wt(t.mapValue,n):(this.St(t.mapValue,n),this.ft(n)):"arrayValue"in t?(this.bt(t.arrayValue,n),this.ft(n)):vm()}Vt(e,t){this.dt(t,25),this.Dt(e,t)}Dt(e,t){t.Rt(e)}St(e,t){var n=e.fields||{};this.dt(t,55);for(const e of Object.keys(n))this.Vt(e,t),this.Tt(n[e],t)}wt(e,t){var n=e.fields||{};this.dt(t,53);var r=(null===(r=null===(r=n.value.arrayValue)||void 0===r?void 0:r.values)||void 0===r?void 0:r.length)||0;this.dt(t,15),t.At(a_(r)),this.Vt("value",t),this.Tt(n.value,t)}bt(e,t){var n=e.values||[];this.dt(t,50);for(const e of n)this.Tt(e,t)}yt(e,t){this.dt(t,37),qm.fromName(e).path.forEach(e=>{this.dt(t,60),this.Dt(e,t)})}dt(e,t){e.At(t)}ft(e){e.At(2)}}function kb(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)}Sb.vt=new Sb;class Ab{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()}Lt(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()}Bt(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=kb(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=kb(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 Nb{constructor(e){this.jt=e}gt(e){this.jt.Ct(e)}Rt(e){this.jt.Lt(e)}At(e){this.jt.kt(e)}Et(){this.jt.$t()}}class Rb{constructor(e){this.jt=e}gt(e){this.jt.xt(e)}Rt(e){this.jt.Bt(e)}At(e){this.jt.Kt(e)}Et(){this.jt.Wt()}}class Pb{constructor(){this.jt=new Ab,this.Ht=new Nb(this.jt),this.Jt=new Rb(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 Db{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 Db(this.indexId,this.documentKey,this.arrayValue,n)}}function xb(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=Ob(e.arrayValue,t.arrayValue),0!==n?n:(n=Ob(e.directionalValue,t.directionalValue),0!==n?n:qm.comparator(e.documentKey,t.documentKey)))}function Ob(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 Lb{constructor(e){this.Xt=new Xv((e,t)=>Vm.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.en=e.orderBy,this.tn=[];for(const t of e.filters){const e=t;e.isInequality()?this.Xt=this.Xt.add(e):this.tn.push(e)}}get nn(){return 1<this.Xt.size}rn(e){if(_m(e.collectionGroup===this.collectionId),this.nn)return!1;const t=Bm(e);if(void 0!==t&&!this.sn(t))return!1;const n=zm(e);let r=new Set,i=0,s=0;for(;i<n.length&&this.sn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(0<this.Xt.size){const e=this.Xt.getIterator().getNext();if(!r.has(e.field.canonicalString())){const t=n[i];if(!this.on(e,t)||!this._n(this.en[s++],t))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.en.length||!this._n(this.en[s++],e))return!1}return!0}an(){if(this.nn)return null;let e=new Xv(Vm.comparator);const t=[];for(const n of this.tn)n.field.isKeyField()||("array-contains"===n.op||"array-contains-any"===n.op?t.push(new Km(n.field,2)):e.has(n.field)||(e=e.add(n.field),t.push(new Km(n.field,0))));for(const r of this.en)r.field.isKeyField()||e.has(r.field)||(e=e.add(r.field),t.push(new Km(r.field,"asc"===r.dir?0:1)));return new jm(jm.UNKNOWN_ID,this.collectionId,t,$m.empty())}sn(e){for(const t of this.tn)if(this.on(t,e))return!0;return!1}on(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}_n(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function Mb(e){if(0===e.getFilters().length)return[];const t=function t(e){if(_m(e instanceof j_||e instanceof B_),e instanceof j_)return e;if(1===e.filters.length)return t(e.filters[0]);const n=e.filters.map(e=>t(e));let r=B_.create(n,e.op);return r=Bb(r),Vb(r)?r:(_m(r instanceof B_),_m(z_(r)),_m(1<r.filters.length),r.filters.reduce((e,t)=>qb(e,t)))}(function t(n){var e;if(_m(n instanceof j_||n instanceof B_),n instanceof j_){if(n instanceof ey){const r=(null===(e=null===(e=n.value.arrayValue)||void 0===e?void 0:e.values)||void 0===e?void 0:e.map(e=>j_.create(n.field,"==",e)))||[];return B_.create(r,"or")}return n}const r=n.filters.map(e=>t(e));return B_.create(r,n.op)}(e));return _m(Vb(t)),Fb(t)||Ub(t)?[t]:t.getFilters()}function Fb(e){return e instanceof j_}function Ub(e){return e instanceof B_&&$_(e)}function Vb(e){return Fb(e)||Ub(e)||function(e){if(e instanceof B_&&K_(e)){for(const t of e.getFilters())if(!Fb(t)&&!Ub(t))return!1;return!0}return!1}(e)}function qb(e,t){var n,r;return _m(e instanceof j_||e instanceof B_),_m(t instanceof j_||t instanceof B_),Bb(e instanceof j_?t instanceof j_?(n=e,r=t,B_.create([n,r],"and")):jb(e,t):t instanceof j_?jb(t,e):function(e,t){if(_m(0<e.filters.length&&0<t.filters.length),z_(e)&&z_(t))return G_(e,t.getFilters());const n=K_(e)?e:t,r=K_(e)?t:e,i=n.filters.map(e=>qb(e,r));return B_.create(i,"or")}(e,t))}function jb(t,e){if(z_(e))return G_(e,t.getFilters());var n=e.filters.map(e=>qb(t,e));return B_.create(n,"or")}function Bb(t){if(_m(t instanceof j_||t instanceof B_),t instanceof j_)return t;const e=t.getFilters();if(1===e.length)return Bb(e[0]);if(W_(t))return t;const n=e.map(e=>Bb(e)),r=[];return n.forEach(e=>{e instanceof j_?r.push(e):e instanceof B_&&(e.op===t.op?r.push(...e.filters):r.push(e))}),1===r.length?r[0]:B_.create(r,t.op)}class zb{constructor(){this.un=new Kb}addToCollectionParentIndex(e,t){return this.un.add(t),Zm.resolve()}getCollectionParents(e,t){return Zm.resolve(this.un.getEntries(t))}addFieldIndex(e,t){return Zm.resolve()}deleteFieldIndex(e,t){return Zm.resolve()}deleteAllFieldIndexes(e){return Zm.resolve()}createTargetIndexes(e,t){return Zm.resolve()}getDocumentsMatchingTarget(e,t){return Zm.resolve(null)}getIndexType(e,t){return Zm.resolve(0)}getFieldIndexes(e,t){return Zm.resolve([])}getNextCollectionGroupToUpdate(e){return Zm.resolve(null)}getMinOffset(e,t){return Zm.resolve(Hm.min())}getMinOffsetFromCollectionGroup(e,t){return Zm.resolve(Hm.min())}updateCollectionGroup(e,t,n){return Zm.resolve()}updateIndexEntries(e,t){return Zm.resolve()}}class Kb{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new Xv(Fm.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 Xv(Fm.comparator)).toArray()}}const $b=new Uint8Array(0);class Wb{constructor(e,t){this.databaseId=t,this.cn=new Kb,this.ln=new Sy(e=>sy(e),(e,t)=>ay(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(this.cn.has(t))return Zm.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.cn.add(t)});r={collectionId:n,parent:mv(r)};return Gb(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[xm(n),""],!1,!0);return Gb(e).U(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(_v(t.parent))}return r})}addFieldIndex(e,t){const n=Qb(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=Yb(e);return i.next(e=>{n.put(yb(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){const n=Qb(e),r=Yb(e),i=Hb(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=Qb(e),n=Hb(e),r=Yb(e);return t.j().next(()=>n.j()).next(()=>r.j())}createTargetIndexes(n,e){return Zm.forEach(this.hn(e),t=>this.getIndexType(n,t).next(e=>{if(0===e||1===e){const e=new Lb(t).an();if(null!=e)return this.addFieldIndex(n,e)}}))}getDocumentsMatchingTarget(e,u){const h=Hb(e);let d=!0;const n=new Map;return Zm.forEach(this.hn(u),t=>this.Pn(e,t).next(e=>{d=d&&!!e,n.set(t,e)})).next(()=>{if(d){let l=Oy();const d=[];return Zm.forEach(n,(e,t)=>{var n;pm("IndexedDbIndexManager",`Using index ${n=e,`id=${n.indexId}|cg=${n.collectionGroup}|f=${n.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")}`} to execute ${sy(u)}`);var r=function(e,t){var n=Bm(t);if(void 0===n)return null;for(const t of cy(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 zm(t))for(const t of cy(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 zm(t)){const t=(0===i.kind?ly:uy)(e,i.fieldPath,e.startAt);n.push(t.value),r=r&&t.inclusive}return new M_(n,r)}(t,e),a=function(e,t){const n=[];let r=!0;for(const i of zm(t)){const t=(0===i.kind?uy:ly)(e,i.fieldPath,e.endAt);n.push(t.value),r=r&&t.inclusive}return new M_(n,r)}(t,e),o=this.In(e,t,s),c=this.In(e,t,a),i=this.Tn(e,t,i),i=this.En(e.indexId,r,o,s.inclusive,c,a.inclusive,i);return Zm.forEach(i,e=>h.G(e,u.limit).next(e=>{e.forEach(e=>{var t=qm.fromSegments(e.documentKey);l.has(t)||(l=l.add(t),d.push(t))})}))}).next(()=>d)}return Zm.resolve(null)})}hn(t){let e=this.ln.get(t);return e||(e=0===t.filters.length?[t]:Mb(B_.create(t.filters,"and")).map(e=>iy(t.path,t.collectionGroup,t.orderBy,e.getFilters(),t.limit,t.startAt,t.endAt)),this.ln.set(t,e),e)}En(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.dn(e[u/c]):$b,h=this.An(t,o,n[u%c],r),d=this.Rn(t,o,i[u%c],s),p=a.map(e=>this.An(t,o,e,!0));l.push(...this.createRange(h,d,p))}return l}An(e,t,n,r){const i=new Db(e,qm.empty(),t,n);return r?i:i.Zt()}Rn(e,t,n,r){const i=new Db(e,qm.empty(),t,n);return r?i.Zt():i}Pn(e,t){const r=new Lb(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.rn(n)&&(!t||n.fields.length>t.fields.length)&&(t=n);return t})}getIndexType(e,t){let n=2;const r=this.hn(t);return Zm.forEach(r,t=>this.Pn(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new Xv(Vm.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)}Vn(e,t){const n=new Pb;for(const i of zm(e)){const e=t.data.field(i.fieldPath);if(null==e)return null;var r=n.Yt(i.kind);Sb.vt.It(e,r)}return n.zt()}dn(e){const t=new Pb;return Sb.vt.It(e,t.Yt(0)),t.zt()}mn(e,t){const n=new Pb;return Sb.vt.It(I_(this.databaseId,t),n.Yt(0===(r=zm(e)).length?0:r[r.length-1].kind)),n.zt();var r}Tn(e,t,n){if(null===n)return[];let r=[];r.push(new Pb);let i=0;for(const s of zm(e)){const e=n[i++];for(const n of r)if(this.fn(t,s.fieldPath)&&E_(e))r=this.gn(r,s,e);else{const t=n.Yt(s.kind);Sb.vt.It(e,t)}}return this.pn(r)}In(e,t,n){return this.Tn(e,t,n.position)}pn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].zt();return t}gn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new Pb;r.seed(n.zt()),Sb.vt.It(e,r.Yt(t.kind)),i.push(r)}return i}fn(e,t){return!!e.filters.find(e=>e instanceof j_&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){const n=Qb(e),r=Yb(e);return(t?n.U("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.U()).next(e=>{const s=[];return Zm.forEach(e,i=>r.get([i.indexId,this.uid]).next(e=>{var t,n,r;s.push((t=i,n=(e=e)?new $m(e.sequenceNumber,new Hm(db(e.readTime),new qm(_v(e.documentKey)),e.largestBatchId)):$m.empty(),r=t.fields.map(([e,t])=>new Km(Vm.fromServerFormat(e),t)),new jm(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:Pm(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,n,r){const i=Qb(e),s=Yb(e);return this.yn(e).next(t=>i.U("collectionGroupIndex",IDBKeyRange.bound(n,n)).next(e=>Zm.forEach(e,e=>s.put(yb(e.indexId,this.uid,t,r)))))}updateIndexEntries(i,e){const n=new Map;return Zm.forEach(e,(t,r)=>{var e=n.get(t.collectionGroup);return(e?Zm.resolve(e):this.getFieldIndexes(i,t.collectionGroup)).next(e=>(n.set(t.collectionGroup,e),Zm.forEach(e,n=>this.wn(i,t,n).next(e=>{var t=this.Sn(r,n);return e.isEqual(t)?Zm.resolve():this.bn(i,r,n,e,t)}))))})}Dn(e,t,n,r){return Hb(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.mn(n,t.key),documentKey:t.key.path.toArray()})}vn(e,t,n,r){return Hb(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.mn(n,t.key),t.key.path.toArray()])}wn(e,n,r){const t=Hb(e);let i=new Xv(xb);return t.J({index:"documentKeyIndex",range:IDBKeyRange.only([r.indexId,this.uid,this.mn(r,n)])},(e,t)=>{i=i.add(new Db(r.indexId,n,t.arrayValue,t.directionalValue))}).next(()=>i)}Sn(e,t){let n=new Xv(xb);var r=this.Vn(t,e);if(null==r)return n;const i=Bm(t);if(null!=i){var s=e.data.field(i.fieldPath);if(E_(s))for(const i of s.arrayValue.values||[])n=n.add(new Db(t.indexId,e.key,this.dn(i),r))}else n=n.add(new Db(t.indexId,e.key,$b,r));return n}bn(t,n,r,e,i){pm("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=e_(s),c=e_(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=e_(a)):t?(i(o),o=e_(s)):(o=e_(s),c=e_(a))}}(e,i,xb,e=>{s.push(this.Dn(t,n,r,e))},e=>{s.push(this.vn(t,n,r,e))}),Zm.waitFor(s)}yn(e){let r=1;return Yb(e).J({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)=>xb(e,t)).filter((e,t,n)=>!t||0!==xb(e,n[t-1]));const r=[];r.push(e);for(const i of n){const n=xb(i,e),s=xb(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,$b,[]],n=[r[a+1].indexId,this.uid,r[a+1].arrayValue,r[a+1].directionalValue,$b,[]];i.push(IDBKeyRange.bound(t,n))}return i}Cn(e,t){return 0<xb(e,t)}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(Jb)}getMinOffset(t,e){return Zm.mapArray(this.hn(e),e=>this.Pn(t,e).next(e=>e||vm())).next(Jb)}}function Gb(e){return $v(e,"collectionParents")}function Hb(e){return $v(e,"indexEntries")}function Qb(e){return $v(e,"indexConfiguration")}function Yb(e){return $v(e,"indexState")}function Jb(e){_m(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;Qm(r,t)<0&&(t=r),n<r.largestBatchId&&(n=r.largestBatchId)}return new Hm(t.readTime,t.documentKey,n)}const Xb={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Zb{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new Zb(e,Zb.DEFAULT_COLLECTION_PERCENTILE,Zb.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function eI(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],a=IDBKeyRange.only(n.batchId);let o=0;const c=r.J({range:a},(e,t,n)=>(o++,n.delete()));s.push(c.next(()=>{_m(1===o)}));const l=[];for(const e of n.mutations){const r=bv(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return Zm.waitFor(s).next(()=>l)}function tI(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 vm();t=e.noDocument}return JSON.stringify(t).length}Zb.DEFAULT_COLLECTION_PERCENTILE=10,Zb.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Zb.DEFAULT=new Zb(41943040,Zb.DEFAULT_COLLECTION_PERCENTILE,Zb.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Zb.DISABLED=new Zb(-1,0,0);class nI{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.Fn={}}static lt(e,t,n,r){_m(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new nI(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return iI(e).J({index:"userMutationsIndex",range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,p){const f=sI(u),g=iI(u);return g.add({}).next(e=>{_m("number"==typeof e);const t=new hw(e,h,d,p),n=(i=this.serializer,s=this.userId,a=t,o=a.baseMutations.map(e=>Jw(i.ct,e)),c=a.mutations.map(e=>Jw(i.ct,e)),{userId:s,batchId:a.batchId,localWriteTimeMs:a.localWriteTime.toMillis(),baseMutations:o,mutations:c}),r=[];var i,s,a,o,c;let l=new Xv((e,t)=>Pm(e.canonicalString(),t.canonicalString()));for(const u of p){const h=bv(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(f.put(h,Iv))}return l.forEach(e=>{r.push(this.indexManager.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.Fn[e]=t.keys()}),Zm.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return iI(e).get(t).next(e=>e?(_m(e.userId===this.userId),pb(this.serializer,e)):null)}Mn(e,n){return this.Fn[n]?Zm.resolve(this.Fn[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Fn[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return iI(e).J({index:"userMutationsIndex",range:n},(e,t,n)=>{t.userId===this.userId&&(_m(t.batchId>=r),i=pb(this.serializer,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return iI(e).J({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 iI(e).U("userMutationsIndex",t).next(e=>e.map(e=>pb(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(a,o){const e=wv(this.userId,o.path),t=IDBKeyRange.lowerBound(e),c=[];return sI(a).J({range:t},(e,t,n)=>{var[r,i,s]=e,i=_v(i);if(r===this.userId&&o.path.isEqual(i))return iI(a).get(s).next(e=>{if(!e)throw vm();_m(e.userId===this.userId),c.push(pb(this.serializer,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let o=new Xv(Pm);const n=[];return e.forEach(a=>{var e=wv(this.userId,a.path),e=IDBKeyRange.lowerBound(e),e=sI(t).J({range:e},(e,t,n)=>{var[r,i,s]=e,i=_v(i);r===this.userId&&a.path.isEqual(i)?o=o.add(s):n.done()});n.push(e)}),Zm.waitFor(n).next(()=>this.xn(t,o))}getAllMutationBatchesAffectingQuery(e,t){const a=t.path,o=a.length+1,n=wv(this.userId,a),r=IDBKeyRange.lowerBound(n);let c=new Xv(Pm);return sI(e).J({range:r},(e,t,n)=>{var[r,i,s]=e,i=_v(i);r===this.userId&&a.isPrefixOf(i)?i.length===o&&(c=c.add(s)):n.done()}).next(()=>this.xn(e,c))}xn(t,e){const n=[],r=[];return e.forEach(e=>{r.push(iI(t).get(e).next(e=>{if(null===e)throw vm();_m(e.userId===this.userId),n.push(pb(this.serializer,e))}))}),Zm.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return eI(t._e,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.On(n.batchId)}),Zm.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}On(e){delete this.Fn[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return Zm.resolve();const t=IDBKeyRange.lowerBound([this.userId]),r=[];return sI(n).J({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=_v(e[1]);r.push(t)}else n.done()}).next(()=>{_m(0===r.length)})})}containsKey(e,t){return rI(e,this.userId,t)}Nn(e){return aI(e).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function rI(e,s,t){const n=wv(s,t.path),a=n[1],r=IDBKeyRange.lowerBound(n);let o=!1;return sI(e).J({range:r,H:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===a&&(o=!0),n.done()}).next(()=>o)}function iI(e){return $v(e,"mutations")}function sI(e){return $v(e,"documentMutations")}function aI(e){return $v(e,"mutationQueues")}class oI{constructor(e){this.Ln=e}next(){return this.Ln+=2,this.Ln}static Bn(){return new oI(0)}static kn(){return new oI(-1)}}class cI{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(n){return this.qn(n).next(e=>{const t=new oI(e.highestTargetId);return e.highestTargetId=t.next(),this.Qn(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.qn(e).next(e=>Lm.fromTimestamp(new Om(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.qn(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.qn(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.Kn(t,n).next(()=>this.qn(t).next(e=>(e.targetCount+=1,this.$n(n,e),this.Qn(t,e))))}updateTargetData(e,t){return this.Kn(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>lI(t).delete(e.targetId)).next(()=>this.qn(t)).next(e=>(_m(0<e.targetCount),--e.targetCount,this.Qn(t,e)))}removeTargets(r,i,s){let a=0;const o=[];return lI(r).J((e,t)=>{var n=fb(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(a++,o.push(this.removeTargetData(r,n)))}).next(()=>Zm.waitFor(o)).next(()=>a)}forEachTarget(e,r){return lI(e).J((e,t)=>{var n=fb(t);r(n)})}qn(e){return uI(e).get("targetGlobalKey").next(e=>(_m(null!==e),e))}Qn(e,t){return uI(e).put("targetGlobalKey",t)}Kn(e,t){return lI(e).put(gb(this.serializer,t))}$n(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.qn(e).next(e=>e.targetCount)}getTargetData(e,i){var t=sy(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return lI(e).J({range:t,index:"queryTargetsIndex"},(e,t,n)=>{var r=fb(t);ay(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=hI(n);return e.forEach(e=>{var t=mv(e.path);i.push(s.put({targetId:r,path:t})),i.push(this.referenceDelegate.addReference(n,r,e))}),Zm.waitFor(i)}removeMatchingKeys(n,e,r){const i=hI(n);return Zm.forEach(e,e=>{var t=mv(e.path);return Zm.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=hI(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=hI(e);let i=Oy();return r.J({range:n,H:!0},(e,t,n)=>{var r=_v(e[1]),r=new qm(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=mv(t.path),n=IDBKeyRange.bound([n],[xm(n)],!1,!0);let r=0;return hI(e).J({index:"documentTargetsIndex",H:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}ot(e,t){return lI(e).get(t).next(e=>e?fb(e):null)}}function lI(e){return $v(e,"targets")}function uI(e){return $v(e,"targetGlobal")}function hI(e){return $v(e,"targetDocuments")}function dI([e,t],[n,r]){var i=Pm(e,n);return 0===i?Pm(t,r):i}class pI{constructor(e){this.Un=e,this.buffer=new Xv(dI),this.Wn=0}Gn(){return++this.Wn}zn(e){var t=[e,this.Gn()];if(this.buffer.size<this.Un)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();dI(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class fI{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.jn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Hn(6e4)}stop(){this.jn&&(this.jn.cancel(),this.jn=null)}get started(){return null!==this.jn}Hn(e){pm("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.jn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.jn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){sv(e)?pm("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await Xm(e)}await this.Hn(3e5)})}}class gI{constructor(e,t){this.Jn=e,this.params=t}calculateTargetCount(e,t){return this.Jn.Yn(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return Zm.resolve(dv.oe);const n=new pI(t);return this.Jn.forEachTarget(e,e=>n.zn(e.sequenceNumber)).next(()=>this.Jn.Zn(e,e=>n.zn(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?(pm("LruGarbageCollector","Garbage collection skipped; disabled"),Zm.resolve(Xb)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(pm("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Xb):this.Xn(t,n))}getCacheSize(e){return this.Jn.getCacheSize(e)}Xn(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?(pm("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(),dm()<=m.DEBUG&&pm("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`),Zm.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}function mI(e,t){return new gI(e,t)}class vI{constructor(e,t){this.db=e,this.garbageCollector=mI(this,t)}Yn(e){const n=this.er(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}er(e){let t=0;return this.Zn(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Zn(e,n){return this.tr(e,(e,t)=>n(t))}addReference(e,t,n){return _I(e,n)}removeReference(e,t,n){return _I(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return _I(e,t)}nr(t,n){let r=!1;return aI(t).Y(e=>rI(t,e,n).next(e=>(e&&(r=!0),Zm.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let a=0;return this.tr(n,(t,e)=>{if(e<=r){const r=this.nr(n,t).next(e=>{if(!e)return a++,i.getEntry(n,t).next(()=>(i.removeEntry(t,Lm.min()),hI(n).delete(function(e){return[0,mv(e.path)]}(t))))});s.push(r)}}).next(()=>Zm.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 _I(e,t)}tr(e,r){const t=hI(e);let i,s=dv.oe;return t.J({index:"documentTargetsIndex"},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==dv.oe&&r(new qm(_v(i)),s),s=n,i=t):s=dv.oe}).next(()=>{s!==dv.oe&&r(new qm(_v(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function _I(e,t){return hI(e).put((e=e.currentSequenceNumber,{targetId:0,path:mv(t.path),sequenceNumber:e}))}class yI{constructor(){this.changes=new Sy(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,L_.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?Zm.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 wI{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return EI(e).put(n)}removeEntry(e,t,n){return EI(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],ub(t),n[n.length-1]]}(t,n))}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.rr(t,e)))}getEntry(e,n){let r=L_.newInvalidDocument(n);return EI(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(CI(n))},(e,t)=>{r=this.ir(n,t)}).next(()=>r)}sr(e,n){let r={size:0,document:L_.newInvalidDocument(n)};return EI(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(CI(n))},(e,t)=>{r={document:this.ir(n,t),size:tI(t)}}).next(()=>r)}getEntries(e,t){let r=ky;return this._r(e,t,(e,t)=>{var n=this.ir(e,t);r=r.insert(e,n)}).next(()=>r)}ar(e,t){let r=ky,i=new Qv(qm.comparator);return this._r(e,t,(e,t)=>{var n=this.ir(e,t);r=r.insert(e,n),i=i.insert(e,tI(t))}).next(()=>({documents:r,ur:i}))}_r(e,t,i){if(t.isEmpty())return Zm.resolve();let n=new Xv(kI);t.forEach(e=>n=n.add(e));const r=IDBKeyRange.bound(CI(n.first()),CI(n.last())),s=n.getIterator();let a=s.getNext();return EI(e).J({index:"documentKeyIndex",range:r},(e,t,n)=>{for(var r=qm.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);a&&kI(a,r)<0;)i(a,null),a=s.getNext();a&&a.isEqual(r)&&(i(a,t),a=s.hasNext()?s.getNext():null),a?n.$(CI(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(),ub(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 EI(e).U(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let t=ky;for(const i of e){const e=this.ir(qm.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Ty(n,e)||r.has(e.key))&&(t=t.insert(e.key,e))}return t})}getAllFromCollectionGroup(e,t,n,i){let s=ky;var r=SI(t,n),a=SI(t,Hm.max());return EI(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(r,a,!0)},(e,t,n)=>{var r=this.ir(qm.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 II(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return TI(e).get("remoteDocumentGlobalKey").next(e=>(_m(!!e),e))}rr(e,t){return TI(e).put("remoteDocumentGlobalKey",t)}ir(e,t){if(t){const e=function(e,t){let n;if(t.document)n=Yw(e.ct,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=qm.fromSegments(t.noDocument.path),i=db(t.noDocument.readTime);n=L_.newNoDocument(e,i),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return vm();{const e=qm.fromSegments(t.unknownDocument.path),s=db(t.unknownDocument.version);n=L_.newUnknownDocument(e,s)}}return t.readTime&&n.setReadTime((t=t.readTime,r=new Om(t[0],t[1]),Lm.fromTimestamp(r))),n;var r}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(Lm.min()))return e}return L_.newInvalidDocument(e)}}function bI(e){return new wI(e)}class II extends yI{constructor(e,t){super(),this.cr=e,this.trackRemovals=t,this.lr=new Sy(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const a=[];let o=0,c=new Xv((e,t)=>Pm(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.lr.get(e);if(a.push(this.cr.removeEntry(s,e,n.readTime)),t.isValidDocument()){var r=lb(this.cr.serializer,t);c=c.add(e.path.popLast());var i=tI(r);o+=i-n.size,a.push(this.cr.addEntry(s,e,r))}else if(o-=n.size,this.trackRemovals){const o=lb(this.cr.serializer,t.convertToNoDocument(Lm.min()));a.push(this.cr.addEntry(s,e,o))}}),c.forEach(e=>{a.push(this.cr.indexManager.addToCollectionParentIndex(s,e))}),a.push(this.cr.updateMetadata(s,o)),Zm.waitFor(a)}getFromCache(e,t){return this.cr.sr(e,t).next(e=>(this.lr.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.cr.ar(e,t).next(({documents:n,ur:e})=>(e.forEach((e,t)=>{this.lr.set(e,{size:t,readTime:n.get(e).readTime})}),n))}}function TI(e){return $v(e,"remoteDocumentGlobal")}function EI(e){return $v(e,"remoteDocumentsV14")}function CI(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function SI(e,t){const n=t.documentKey.path.toArray();return[e,ub(t.readTime),n.slice(0,n.length-2),0<n.length?n[n.length-1]:""]}function kI(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=Pm(n[s],r[s]),i)return i;return i=Pm(n.length,r.length),i||(i=Pm(n[n.length-2],r[r.length-2]),i||Pm(n[n.length-1],r[r.length-1]))}class AI{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class NI{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&&nw(r.mutation,e,t_.empty(),Om.now()),e))}getDocuments(t,e){return this.remoteDocumentCache.getEntries(t,e).next(e=>this.getLocalViewOfDocuments(t,e,Oy()).next(()=>e))}getLocalViewOfDocuments(e,t,n=Oy()){const r=Py();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let n=Ny();return e.forEach((e,t)=>{n=n.insert(e,t.overlayedDocument)}),n}))}getOverlayedDocuments(e,t){const n=Py();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,Oy()))}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=ky;const a=Py(),o=Py();return t.forEach((e,t)=>{const n=r.get(t.key);i.has(t.key)&&(void 0===n||n.mutation instanceof sw)?s=s.insert(t.key,t):void 0!==n?(a.set(t.key,n.mutation.getFieldMask()),nw(n.mutation,t,n.mutation.getFieldMask(),Om.now())):a.set(t.key,t_.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 AI(t,null!==(n=a.get(e))&&void 0!==n?n:null))}),o))}recalculateAndSaveOverlays(s,a){const o=Py();let c=new Qv((e,t)=>e-t),l=Oy();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)||t_.empty(),t=r.applyToLocalView(n,t),o.set(e,t),t=(c.get(r.batchId)||Oy()).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=Py();r.forEach(e=>{var t;l.has(e)||(null!==(t=ew(a.get(e),o.get(e)))&&i.set(e,t),l=l.add(e))}),e.push(this.documentOverlayCache.saveOverlays(s,n,i))}return Zm.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,qm.isDocumentKey(i.path)&&null===i.collectionGroup&&0===i.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):gy(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):Zm.resolve(Py());let r=-1,i=n;return e.next(e=>Zm.forEach(e,(t,e)=>(r<e.largestBatchId&&(r=e.largestBatchId),n.get(t)?Zm.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,Oy())).next(e=>({batchId:r,changes:Ry(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new qm(t)).next(e=>{let t=Ny();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(r,i,s,a){const o=i.collectionGroup;let c=Ny();return this.indexManager.getCollectionParents(r,o).next(e=>Zm.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new hy(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,L_.newInvalidDocument(n)))});let i=Ny();return r.forEach((e,t)=>{var n=a.get(e);void 0!==n&&nw(n.mutation,t,t_.empty(),Om.now()),Ty(s,t)&&(i=i.insert(e,t))}),i})}}class RI{constructor(e){this.serializer=e,this.hr=new Map,this.Pr=new Map}getBundleMetadata(e,t){return Zm.resolve(this.hr.get(t))}saveBundleMetadata(e,t){return this.hr.set(t.id,{id:t.id,version:t.version,createTime:Vw(t.createTime)}),Zm.resolve()}getNamedQuery(e,t){return Zm.resolve(this.Pr.get(t))}saveNamedQuery(e,t){return this.Pr.set(t.name,{name:(t=t).name,query:mb(t.bundledQuery),readTime:Vw(t.readTime)}),Zm.resolve()}}class PI{constructor(){this.overlays=new Qv(qm.comparator),this.Ir=new Map}getOverlay(e,t){return Zm.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Py();return Zm.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.ht(n,r,t)}),Zm.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.Ir.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.Ir.delete(n)),Zm.resolve()}getOverlaysForCollection(e,t,n){const r=Py(),i=t.length+1,s=new qm(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 Zm.resolve(r)}getOverlaysForCollectionGroup(t,e,n,r){let i=new Qv((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=Py(),i=i.insert(t.largestBatchId,e)),e.set(t.getKey(),t)}}const a=Py(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return Zm.resolve(a)}ht(e,t,n){var r=this.overlays.get(n.key);if(null!==r){const e=this.Ir.get(r.largestBatchId).delete(n.key);this.Ir.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new pw(t,n));let i=this.Ir.get(t);void 0===i&&(i=Oy(),this.Ir.set(t,i)),this.Ir.set(t,i.add(n.key))}}class DI{constructor(){this.sessionToken=r_.EMPTY_BYTE_STRING}getSessionToken(e){return Zm.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,Zm.resolve()}}class xI{constructor(){this.Tr=new Xv(OI.Er),this.dr=new Xv(OI.Ar)}isEmpty(){return this.Tr.isEmpty()}addReference(e,t){var n=new OI(e,t);this.Tr=this.Tr.add(n),this.dr=this.dr.add(n)}Rr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Vr(new OI(e,t))}mr(e,t){e.forEach(e=>this.removeReference(e,t))}gr(e){const t=new qm(new Fm([])),n=new OI(t,e),r=new OI(t,e+1),i=[];return this.dr.forEachInRange([n,r],e=>{this.Vr(e),i.push(e.key)}),i}pr(){this.Tr.forEach(e=>this.Vr(e))}Vr(e){this.Tr=this.Tr.delete(e),this.dr=this.dr.delete(e)}yr(e){var t=new qm(new Fm([])),n=new OI(t,e),t=new OI(t,e+1);let r=Oy();return this.dr.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new OI(e,0),t=this.Tr.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class OI{constructor(e,t){this.key=e,this.wr=t}static Er(e,t){return qm.comparator(e.key,t.key)||Pm(e.wr,t.wr)}static Ar(e,t){return Pm(e.wr,t.wr)||qm.comparator(e.key,t.key)}}class LI{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Sr=1,this.br=new Xv(OI.Er)}checkEmpty(e){return Zm.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){var i=this.Sr;this.Sr++,0<this.mutationQueue.length&&this.mutationQueue[this.mutationQueue.length-1];var s=new hw(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.br=this.br.add(new OI(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return Zm.resolve(s)}lookupMutationBatch(e,t){return Zm.resolve(this.Dr(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.vr(t+1),n=n<0?0:n;return Zm.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return Zm.resolve(0===this.mutationQueue.length?-1:this.Sr-1)}getAllMutationBatches(e){return Zm.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new OI(t,0),r=new OI(t,Number.POSITIVE_INFINITY),i=[];return this.br.forEachInRange([n,r],e=>{var t=this.Dr(e.wr);i.push(t)}),Zm.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new Xv(Pm);return t.forEach(e=>{var t=new OI(e,0),n=new OI(e,Number.POSITIVE_INFINITY);this.br.forEachInRange([t,n],e=>{r=r.add(e.wr)})}),Zm.resolve(this.Cr(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;qm.isDocumentKey(i)||(i=i.child(""));var s=new OI(new qm(i),0);let a=new Xv(Pm);return this.br.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.wr)),!0)},s),Zm.resolve(this.Cr(a))}Cr(e){const n=[];return e.forEach(e=>{var t=this.Dr(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){_m(0===this.Fr(r.batchId,"removed")),this.mutationQueue.shift();let i=this.br;return Zm.forEach(r.mutations,e=>{var t=new OI(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.br=i})}On(e){}containsKey(e,t){var n=new OI(t,0),n=this.br.firstAfterOrEqual(n);return Zm.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,Zm.resolve()}Fr(e,t){return this.vr(e)}vr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Dr(e){var t=this.vr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class MI{constructor(e){this.Mr=e,this.docs=new Qv(qm.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.Mr(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 Zm.resolve(n?n.document.mutableCopy():L_.newInvalidDocument(t))}getEntries(e,t){let n=ky;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():L_.newInvalidDocument(e))}),Zm.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=ky;const s=t.path,a=new qm(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||Qm(Gm(a),n)<=0||(r.has(a.key)||Ty(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return Zm.resolve(i)}getAllFromCollectionGroup(e,t,n,r){vm()}Or(e,t){return Zm.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new FI(this)}getSize(e){return Zm.resolve(this.size)}}class FI extends yI{constructor(e){super(),this.cr=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.cr.addEntry(n,t)):this.cr.removeEntry(e)}),Zm.waitFor(r)}getFromCache(e,t){return this.cr.getEntry(e,t)}getAllFromCache(e,t){return this.cr.getEntries(e,t)}}class UI{constructor(e){this.persistence=e,this.Nr=new Sy(e=>sy(e),ay),this.lastRemoteSnapshotVersion=Lm.min(),this.highestTargetId=0,this.Lr=0,this.Br=new xI,this.targetCount=0,this.kr=oI.Bn()}forEachTarget(e,n){return this.Nr.forEach((e,t)=>n(t)),Zm.resolve()}getLastRemoteSnapshotVersion(e){return Zm.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return Zm.resolve(this.Lr)}allocateTargetId(e){return this.highestTargetId=this.kr.next(),Zm.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Lr&&(this.Lr=t),Zm.resolve()}Kn(e){this.Nr.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.kr=new oI(t),this.highestTargetId=t),e.sequenceNumber>this.Lr&&(this.Lr=e.sequenceNumber)}addTargetData(e,t){return this.Kn(t),this.targetCount+=1,Zm.resolve()}updateTargetData(e,t){return this.Kn(t),Zm.resolve()}removeTargetData(e,t){return this.Nr.delete(t.target),this.Br.gr(t.targetId),--this.targetCount,Zm.resolve()}removeTargets(n,r,i){let s=0;const a=[];return this.Nr.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Nr.delete(e),a.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),Zm.waitFor(a).next(()=>s)}getTargetCount(e){return Zm.resolve(this.targetCount)}getTargetData(e,t){var n=this.Nr.get(t)||null;return Zm.resolve(n)}addMatchingKeys(e,t,n){return this.Br.Rr(t,n),Zm.resolve()}removeMatchingKeys(t,e,n){this.Br.mr(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),Zm.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Br.gr(t),Zm.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Br.yr(t);return Zm.resolve(n)}containsKey(e,t){return Zm.resolve(this.Br.containsKey(t))}}class VI{constructor(e,t){this.qr={},this.overlays={},this.Qr=new dv(0),this.Kr=!1,this.Kr=!0,this.$r=new DI,this.referenceDelegate=e(this),this.Ur=new UI(this),this.indexManager=new zb,this.remoteDocumentCache=(e=e=>this.referenceDelegate.Wr(e),new MI(e)),this.serializer=new cb(t),this.Gr=new RI(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Kr=!1,Promise.resolve()}get started(){return this.Kr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new PI,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.qr[e.toKey()];return n||(n=new LI(t,this.referenceDelegate),this.qr[e.toKey()]=n),n}getGlobalsCache(){return this.$r}getTargetCache(){return this.Ur}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Gr}runTransaction(e,t,n){pm("MemoryPersistence","Starting transaction:",e);const r=new qI(this.Qr.next());return this.referenceDelegate.zr(),n(r).next(e=>this.referenceDelegate.jr(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Hr(t,n){return Zm.or(Object.values(this.qr).map(e=>()=>e.containsKey(t,n)))}}class qI extends Jm{constructor(e){super(),this.currentSequenceNumber=e}}class jI{constructor(e){this.persistence=e,this.Jr=new xI,this.Yr=null}static Zr(e){return new jI(e)}get Xr(){if(this.Yr)return this.Yr;throw vm()}addReference(e,t,n){return this.Jr.addReference(n,t),this.Xr.delete(n.toString()),Zm.resolve()}removeReference(e,t,n){return this.Jr.removeReference(n,t),this.Xr.add(n.toString()),Zm.resolve()}markPotentiallyOrphaned(e,t){return this.Xr.add(t.toString()),Zm.resolve()}removeTarget(e,t){this.Jr.gr(t.targetId).forEach(e=>this.Xr.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Xr.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}zr(){this.Yr=new Set}jr(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return Zm.forEach(this.Xr,e=>{const t=qm.fromPath(e);return this.ei(n,t).next(e=>{e||r.removeEntry(t,Lm.min())})}).next(()=>(this.Yr=null,r.apply(n)))}updateLimboDocument(e,t){return this.ei(e,t).next(e=>{e?this.Xr.delete(t.toString()):this.Xr.add(t.toString())})}Wr(e){return 0}ei(e,t){return Zm.or([()=>Zm.resolve(this.Jr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Hr(e,t)])}}class BI{constructor(e,t){this.persistence=e,this.ti=new Sy(e=>mv(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=mI(this,t)}static Zr(e,t){return new BI(e,t)}zr(){}jr(e){return Zm.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}Yn(e){const n=this.er(e);return this.persistence.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}er(e){let t=0;return this.Zn(e,e=>{t++}).next(()=>t)}Zn(n,r){return Zm.forEach(this.ti,(e,t)=>this.nr(n,e,t).next(e=>e?Zm.resolve():r(t)))}removeTargets(e,t,n){return this.persistence.getTargetCache().removeTargets(e,t,n)}removeOrphanedDocuments(e,n){let r=0;const t=this.persistence.getRemoteDocumentCache(),i=t.newChangeBuffer();return t.Or(e,t=>this.nr(e,t,n).next(e=>{e||(r++,i.removeEntry(t,Lm.min()))})).next(()=>i.apply(e)).next(()=>r)}markPotentiallyOrphaned(e,t){return this.ti.set(t,e.currentSequenceNumber),Zm.resolve()}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.ti.set(n,e.currentSequenceNumber),Zm.resolve()}removeReference(e,t,n){return this.ti.set(n,e.currentSequenceNumber),Zm.resolve()}updateLimboDocument(e,t){return this.ti.set(t,e.currentSequenceNumber),Zm.resolve()}Wr(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function r(e){switch(g_(e)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:var t=l_(e);return t?16+r(t):16;case 5:return 2*e.stringValue.length;case 6:return o_(e.bytesValue).approximateByteSize();case 7:return e.referenceValue.length;case 9:return(e.arrayValue.values||[]).reduce((e,t)=>e+r(t),0);case 10:case 11:return function(e){let n=0;return Gv(e.fields,(e,t)=>{n+=e.length+r(t)}),n}(e.mapValue);default:throw vm()}}(e.data.value)),t}nr(e,t,n){return Zm.or([()=>this.persistence.Hr(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{var e=this.ti.get(t);return Zm.resolve(void 0!==e&&n<e)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class zI{constructor(e){this.serializer=e}O(t,e,n,r){const i=new ev("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",yv,{unique:!0}),s.createObjectStore("documentMutations"),KI(t),t.createObjectStore("remoteDocuments"));let a=Zm.resolve();return n<3&&3<=r&&(0!==n&&((s=t).deleteObjectStore("targetDocuments"),s.deleteObjectStore("targets"),s.deleteObjectStore("targetGlobal"),KI(t)),a=a.next(()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:Lm.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").U().next(e=>{r.deleteObjectStore("mutations"),r.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",yv,{unique:!0});const t=i.store("mutations"),n=e.map(e=>t.put(e));return Zm.waitFor(n)})}(t,i))),a=a.next(()=>{t.createObjectStore("clientMetadata",{keyPath:"clientId"})})),n<5&&5<=r&&(a=a.next(()=>this.ni(i))),n<6&&6<=r&&(a=a.next(()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(t),this.ri(i)))),n<7&&7<=r&&(a=a.next(()=>this.ii(i))),n<8&&8<=r&&(a=a.next(()=>this.si(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.oi(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:Ov});t.createIndex("collectionPathOverlayIndex",Lv,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",Mv,{unique:!1})}(t)})),n<13&&13<=r&&(a=a.next(()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:Tv});t.createIndex("documentKeyIndex",Ev),t.createIndex("collectionGroupIndex",Cv)}(t)).next(()=>this._i(t,i)).next(()=>t.deleteObjectStore("remoteDocuments"))),n<14&&14<=r&&(a=a.next(()=>this.ai(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:Rv}).createIndex("sequenceNumberIndex",Pv,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Dv}).createIndex("documentKeyIndex",xv,{unique:!1})}(t))),n<16&&16<=r&&(a=a.next(()=>{e.objectStore("indexState").clear()}).next(()=>{e.objectStore("indexEntries").clear()})),n<17&&17<=r&&(a=a.next(()=>{t.createObjectStore("globals",{keyPath:"name"})})),a}ri(t){let n=0;return t.store("remoteDocuments").J((e,t)=>{n+=tI(t)}).next(()=>{var e={byteSize:n};return t.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",e)})}ni(r){const e=r.store("mutationQueues"),t=r.store("mutations");return e.U().next(e=>Zm.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.U("userMutationsIndex",e).next(e=>Zm.forEach(e,e=>{_m(e.userId===n.userId);var t=pb(this.serializer,e);return eI(r,n.userId,t).next(()=>{})}))}))}ii(e){const a=e.store("targetDocuments"),t=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next(i=>{const s=[];return t.J((e,t)=>{const n=new Fm(e),r=[0,mv(n)];s.push(a.get(r).next(e=>e?Zm.resolve():(e=>a.put({targetId:0,path:mv(e),sequenceNumber:i.highestListenSequenceNumber}))(n)))}).next(()=>Zm.waitFor(s))})}si(e,t){e.createObjectStore("collectionParents",{keyPath:Nv});const n=t.store("collectionParents"),r=new Kb,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:mv(r)})}};return t.store("remoteDocuments").J({H:!0},(e,t)=>{const n=new Fm(e);return i(n.popLast())}).next(()=>t.store("documentMutations").J({H:!0},([,e],t)=>{const n=_v(e);return i(n.popLast())}))}oi(e){const r=e.store("targets");return r.J((e,t)=>{var n=fb(t),n=gb(this.serializer,n);return r.put(n)})}_i(e,a){const t=a.store("remoteDocuments"),o=[];return t.J((e,t)=>{const n=a.store("remoteDocumentsV14"),r=((s=t).document?new qm(Fm.fromString(s.document.name).popFirst(5)):s.noDocument?qm.fromSegments(s.noDocument.path):s.unknownDocument?qm.fromSegments(s.unknownDocument.path):vm()).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(()=>Zm.waitFor(o))}ai(e,s){const t=s.store("mutations"),a=bI(this.serializer),o=new VI(jI.Zr,this.serializer.ct);return t.U().next(e=>{const r=new Map;return e.forEach(e=>{var t;let n=null!==(t=r.get(e.userId))&&void 0!==t?t:Oy();pb(this.serializer,e).keys().forEach(e=>n=n.add(e)),r.set(e.userId,n)}),Zm.forEach(r,(e,t)=>{var n=new lm(t),r=Tb.lt(this.serializer,n),i=o.getIndexManager(n),n=nI.lt(n,this.serializer,i,o.referenceDelegate);return new NI(a,n,r,i).recalculateAndSaveOverlaysForDocumentKeys(new Kv(s,dv.oe),e).next()})})}}function KI(e){e.createObjectStore("targetDocuments",{keyPath:kv}).createIndex("documentTargetsIndex",Av,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Sv,{unique:!0}),e.createObjectStore("targetGlobal")}const $I="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 WI{constructor(e,t,n,r,i,s,a,o,c,l,u=17){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.ui=i,this.window=s,this.document=a,this.ci=c,this.li=l,this.hi=u,this.Qr=null,this.Kr=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Pi=null,this.inForeground=!1,this.Ii=null,this.Ti=null,this.Ei=Number.NEGATIVE_INFINITY,this.di=e=>Promise.resolve(),!WI.D())throw new wm(ym.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new vI(this,r),this.Ai=t+"main",this.serializer=new cb(o),this.Ri=new tv(this.Ai,this.hi,new zI(this.serializer)),this.$r=new Cb,this.Ur=new cI(this.referenceDelegate,this.serializer),this.remoteDocumentCache=bI(this.serializer),this.Gr=new wb,this.window&&this.window.localStorage?this.Vi=this.window.localStorage:(this.Vi=null,!1===l&&fm("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.mi().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new wm(ym.FAILED_PRECONDITION,$I);return this.fi(),this.gi(),this.pi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Ur.getHighestSequenceNumber(e))}).then(e=>{this.Qr=new dv(e,this.ci)}).then(()=>{this.Kr=!0}).catch(e=>(this.Ri&&this.Ri.close(),Promise.reject(e)))}yi(t){return this.di=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ri.L(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.ui.enqueueAndForget(async()=>{this.started&&await this.mi()}))}mi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>HI(t).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.wi(t).next(e=>{e||(this.isPrimary=!1,this.ui.enqueueRetryable(()=>this.di(!1)))})}).next(()=>this.Si(t)).next(e=>this.isPrimary&&!e?this.bi(t).next(()=>!1):!!e&&this.Di(t).next(()=>!0))).catch(e=>{if(sv(e))return pm("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return pm("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.ui.enqueueRetryable(()=>this.di(e)),this.isPrimary=e})}wi(e){return GI(e).get("owner").next(e=>Zm.resolve(this.vi(e)))}Ci(e){return HI(e).delete(this.clientId)}async Fi(){if(this.isPrimary&&!this.Mi(this.Ei,18e5)){this.Ei=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=$v(e,"clientMetadata");return r.U().next(e=>{const t=this.xi(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return Zm.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.Vi)for(const t of e)this.Vi.removeItem(this.Oi(t.clientId))}}pi(){this.Ti=this.ui.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.mi().then(()=>this.Fi()).then(()=>this.pi()))}vi(e){return!!e&&e.ownerId===this.clientId}Si(t){return this.li?Zm.resolve(!0):GI(t).get("owner").next(e=>{if(null!==e&&this.Mi(e.leaseTimestampMs,5e3)&&!this.Ni(e.ownerId)){if(this.vi(e)&&this.networkEnabled)return!0;if(!this.vi(e)){if(!e.allowTabSynchronization)throw new wm(ym.FAILED_PRECONDITION,$I);return!1}}return!(!this.networkEnabled||!this.inForeground)||HI(t).U().next(e=>void 0===this.xi(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&&pm("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Kr=!1,this.Li(),this.Ti&&(this.Ti.cancel(),this.Ti=null),this.Bi(),this.ki(),await this.Ri.runTransaction("shutdown","readwrite",["owner","clientMetadata"],e=>{const t=new Kv(e,dv.oe);return this.bi(t).next(()=>this.Ci(t))}),this.Ri.close(),this.qi()}xi(e,t){return e.filter(e=>this.Mi(e.updateTimeMs,t)&&!this.Ni(e.clientId))}Qi(){return this.runTransaction("getActiveClients","readonly",e=>HI(e).U().next(e=>this.xi(e,18e5).map(e=>e.clientId)))}get started(){return this.Kr}getGlobalsCache(){return this.$r}getMutationQueue(e,t){return nI.lt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Ur}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new Wb(e,this.serializer.ct.databaseId)}getDocumentOverlayCache(e){return Tb.lt(this.serializer,e)}getBundleCache(){return this.Gr}runTransaction(t,n,r){pm("IndexedDbPersistence","Starting transaction:",t);var e,i="readonly"===n?"readonly":"readwrite",s=17===(e=this.hi)?zv:16===e?Bv:15===e?jv:14===e?qv:13===e?Vv:12===e?Uv:11===e?Fv:void vm();let a;return this.Ri.runTransaction(t,i,s,e=>(a=new Kv(e,this.Qr?this.Qr.next():dv.oe),"readwrite-primary"===n?this.wi(a).next(e=>!!e||this.Si(a)).next(e=>{if(!e)throw fm(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.ui.enqueueRetryable(()=>this.di(!1)),new wm(ym.FAILED_PRECONDITION,Ym);return r(a)}).next(e=>this.Di(a).next(()=>e)):this.Ki(a).next(()=>r(a)))).then(e=>(a.raiseOnCommittedEvent(),e))}Ki(e){return GI(e).get("owner").next(e=>{if(null!==e&&this.Mi(e.leaseTimestampMs,5e3)&&!this.Ni(e.ownerId)&&!this.vi(e)&&!(this.li||this.allowTabSynchronization&&e.allowTabSynchronization))throw new wm(ym.FAILED_PRECONDITION,$I)})}Di(e){var t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return GI(e).put("owner",t)}static D(){return tv.D()}bi(e){const t=GI(e);return t.get("owner").next(e=>this.vi(e)?(pm("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):Zm.resolve())}Mi(e,t){var n=Date.now();return!(e<n-t||n<e&&(fm(`Detected an update time that is in the future: ${e} > ${n}`),1))}fi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Ii=()=>{this.ui.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.mi()))},this.document.addEventListener("visibilitychange",this.Ii),this.inForeground="visible"===this.document.visibilityState)}Bi(){this.Ii&&(this.document.removeEventListener("visibilitychange",this.Ii),this.Ii=null)}gi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Pi=()=>{this.Li();var e=/(?:Version|Mobile)\/1[456]/;N()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.ui.enterRestrictedMode(!0),this.ui.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Pi))}ki(){this.Pi&&(this.window.removeEventListener("pagehide",this.Pi),this.Pi=null)}Ni(e){var t;try{var n=null!==(null===(t=this.Vi)||void 0===t?void 0:t.getItem(this.Oi(e)));return pm("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return fm("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}Li(){if(this.Vi)try{this.Vi.setItem(this.Oi(this.clientId),String(Date.now()))}catch(e){fm("Failed to set zombie client id.",e)}}qi(){if(this.Vi)try{this.Vi.removeItem(this.Oi(this.clientId))}catch(e){}}Oi(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function GI(e){return $v(e,"owner")}function HI(e){return $v(e,"clientMetadata")}function QI(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class YI{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.$i=n,this.Ui=r}static Wi(e,t){let n=Oy(),r=Oy();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 YI(e,t.fromCache,n,r)}}class JI{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class XI{constructor(){this.Gi=!1,this.zi=!1,this.ji=100,this.Hi=N()?8:0<nv(b())?6:4}initialize(e,t){this.Ji=e,this.indexManager=t,this.Gi=!0}getDocumentsMatchingQuery(n,r,e,t){const i={result:null};return this.Yi(n,r).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.Zi(n,r,t,e).next(e=>{i.result=e})}).next(()=>{if(!i.result){const t=new JI;return this.Xi(n,r,t).next(e=>{if(i.result=e,this.zi)return this.es(n,r,t,e.size)})}}).next(()=>i.result)}es(e,t,n,r){return n.documentReadCount<this.ji?(dm()<=m.DEBUG&&pm("QueryEngine","SDK will not create cache indexes for query:",Iy(t),"since it only creates cache indexes for collection contains","more than or equal to",this.ji,"documents"),Zm.resolve()):(dm()<=m.DEBUG&&pm("QueryEngine","Query:",Iy(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Hi*r?(dm()<=m.DEBUG&&pm("QueryEngine","The SDK decides to create cache indexes for query:",Iy(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,vy(t))):Zm.resolve())}Yi(i,s){if(fy(s))return Zm.resolve(null);let t=vy(s);return this.indexManager.getIndexType(i,t).next(e=>0===e?null:(null!==s.limit&&1===e&&(s=yy(s,null,"F"),t=vy(s)),this.indexManager.getDocumentsMatchingTarget(i,t).next(e=>{const r=Oy(...e);return this.Ji.getDocuments(i,r).next(n=>this.indexManager.getMinOffset(i,t).next(e=>{var t=this.ts(s,n);return this.ns(s,t,r,e.readTime)?this.Yi(i,yy(s,null,"F")):this.rs(i,t,s,e)}))})))}Zi(n,r,i,s){return fy(r)||s.isEqual(Lm.min())?Zm.resolve(null):this.Ji.getDocuments(n,i).next(e=>{var t=this.ts(r,e);return this.ns(r,t,i,s)?Zm.resolve(null):(dm()<=m.DEBUG&&pm("QueryEngine","Re-using previous result from %s to execute query: %s",s.toString(),Iy(r)),this.rs(n,t,r,Wm(s,-1)).next(e=>e))})}ts(n,e){let r=new Xv(Cy(n));return e.forEach((e,t)=>{Ty(n,t)&&(r=r.add(t))}),r}ns(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))}Xi(e,t,n){return dm()<=m.DEBUG&&pm("QueryEngine","Using full collection scan to execute query:",Iy(t)),this.Ji.getDocumentsMatchingQuery(e,t,Hm.min(),n)}rs(e,n,t,r){return this.Ji.getDocumentsMatchingQuery(e,t,r).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t))}}class ZI{constructor(e,t,n,r){this.persistence=e,this.ss=t,this.serializer=r,this.os=new Qv(Pm),this._s=new Sy(e=>sy(e),ay),this.us=new Map,this.cs=e.getRemoteDocumentCache(),this.Ur=e.getTargetCache(),this.Gr=e.getBundleCache(),this.ls(n)}ls(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new NI(this.cs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.cs.setIndexManager(this.indexManager),this.ss.initialize(this.localDocuments,this.indexManager)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.os))}}function eT(e,t,n,r){return new ZI(e,t,n,r)}async function tT(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.ls(t),a.mutationQueue.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=Oy();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=>({hs:e,removedBatchIds:t,addedBatchIds:n}))})})}function nT(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Ur.getLastRemoteSnapshotVersion(e))}function rT(e,l){const u=e,h=l.snapshotVersion;let d=u.os;return u.persistence.runTransaction("Apply remote event","readwrite-primary",o=>{const e=u.cs.newChangeBuffer({trackRemovals:!0});d=u.os;const c=[];l.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){c.push(u.Ur.removeMatchingKeys(o,t.removedDocuments,n).next(()=>u.Ur.addMatchingKeys(o,t.addedDocuments,n)));let e=r.withSequenceNumber(o.currentSequenceNumber);var i,s,a;null!==l.targetMismatches.get(n)?e=e.withResumeToken(r_.EMPTY_BYTE_STRING,Lm.min()).withLastLimboFreeSnapshotVersion(Lm.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.Ur.updateTargetData(o,e))}});let t=ky,n=Oy();if(l.documentUpdates.forEach(e=>{l.resolvedLimboDocuments.has(e)&&c.push(u.persistence.referenceDelegate.updateLimboDocument(o,e))}),c.push(iT(o,e,l.documentUpdates).next(e=>{t=e.Ps,n=e.Is})),!h.isEqual(Lm.min())){const l=u.Ur.getLastRemoteSnapshotVersion(o).next(e=>u.Ur.setTargetsMetadata(o,o.currentSequenceNumber,h));c.push(l)}return Zm.waitFor(c).next(()=>e.apply(o)).next(()=>u.localDocuments.getLocalViewOfDocuments(o,t,n)).next(()=>t)}).then(e=>(u.os=d,e))}function iT(e,s,t){let n=Oy(),a=Oy();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=ky;return t.forEach((e,t)=>{const n=r.get(e);t.isFoundDocument()!==n.isFoundDocument()&&(a=a.add(e)),t.isNoDocument()&&t.version.isEqual(Lm.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)):pm("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),{Ps:i,Is:a}})}function sT(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Ur.getTargetData(t,r).next(e=>e?(n=e,Zm.resolve(n)):i.Ur.allocateTargetId(t).next(e=>(n=new ob(r,e,"TargetPurposeListen",t.currentSequenceNumber),i.Ur.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.os.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.os=i.os.insert(e.targetId,e),i._s.set(r,e.targetId)),e})}async function aT(e,t,n){const r=e,i=r.os.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(!sv(e))throw e;pm("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.os=r.os.remove(t),r._s.delete(i.target)}function oT(e,n,r){const i=e;let s=Lm.min(),a=Oy();return i.persistence.runTransaction("Execute query","readwrite",t=>function(e,t,n){const r=e,i=r._s.get(n);return void 0!==i?Zm.resolve(r.os.get(i)):r.Ur.getTargetData(t,n)}(i,t,vy(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Ur.getMatchingKeysForTargetId(t,e.targetId).next(e=>{a=e})}).next(()=>i.ss.getDocumentsMatchingQuery(t,n,r?s:Lm.min(),r?a:Oy())).next(e=>(uT(i,Ey(n),e),{documents:e,Ts:a})))}function cT(e,t){const n=e,r=n.Ur,i=n.os.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.ot(e,t).next(e=>e?e.target:null))}function lT(e,t){const n=e,r=n.us.get(t)||Lm.min();return n.persistence.runTransaction("Get new document changes","readonly",e=>n.cs.getAllFromCollectionGroup(e,t,Wm(r,-1),Number.MAX_SAFE_INTEGER)).then(e=>(uT(n,t,e),e))}function uT(e,t,n){let r=e.us.get(t)||Lm.min();n.forEach((e,t)=>{0<t.readTime.compareTo(r)&&(r=t.readTime)}),e.us.set(t,r)}function hT(e,t){return`firestore_clients_${e}_${t}`}function dT(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function pT(e,t){return`firestore_targets_${e}_${t}`}class fT{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Rs(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 wm(r.error.code,r.error.message))),s?new fT(e,t,r.state,i):(fm("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Vs(){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 gT{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Rs(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 wm(n.error.code,n.error.message))),i?new gT(e,n.state,r):(fm("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Vs(){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 mT{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Rs(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=Ly;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=gv(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new mT(e,i):(fm("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class vT{constructor(e,t){this.clientId=e,this.onlineState=t}static Rs(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new vT(t.clientId,t.onlineState):(fm("SharedClientState",`Failed to parse online state: ${e}`),null)}}class _T{constructor(){this.activeTargetIds=Ly}fs(e){this.activeTargetIds=this.activeTargetIds.add(e)}gs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Vs(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class yT{constructor(e,t,n,r,i){this.window=e,this.ui=t,this.persistenceKey=n,this.ps=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.ys=this.ws.bind(this),this.Ss=new Qv(Pm),this.started=!1,this.bs=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Ds=hT(this.persistenceKey,this.ps),this.vs=`firestore_sequence_number_${this.persistenceKey}`,this.Ss=this.Ss.insert(this.ps,new _T),this.Cs=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Fs=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.Ms=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.xs=`firestore_online_state_${this.persistenceKey}`,this.Os=`firestore_bundle_loaded_v2_${this.persistenceKey}`,this.window.addEventListener("storage",this.ys)}static D(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.Qi();for(const n of e)if(n!==this.ps){const e=this.getItem(hT(this.persistenceKey,n));var t;!e||(t=mT.Rs(n,e))&&(this.Ss=this.Ss.insert(t.clientId,t))}this.Ns();const n=this.storage.getItem(this.xs);if(n){const e=this.Ls(n);e&&this.Bs(e)}for(const e of this.bs)this.ws(e);this.bs=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.vs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.ks(this.Ss)}isActiveQueryTarget(n){let r=!1;return this.Ss.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.qs(e,"pending")}updateMutationState(e,t,n){this.qs(e,t,n),this.Qs(e)}addLocalQueryTarget(e,t=!0){let n="not-current";if(this.isActiveQueryTarget(e)){const t=this.storage.getItem(pT(this.persistenceKey,e));var r;!t||(r=gT.Rs(e,t))&&(n=r.state)}return t&&this.Ks.fs(e),this.Ns(),n}removeLocalQueryTarget(e){this.Ks.gs(e),this.Ns()}isLocalQueryTarget(e){return this.Ks.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(pT(this.persistenceKey,e))}updateQueryState(e,t,n){this.$s(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.Qs(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Us(e)}notifyBundleLoaded(e){this.Ws(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.ys),this.removeItem(this.Ds),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return pm("SharedClientState","READ",e,t),t}setItem(e,t){pm("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){pm("SharedClientState","REMOVE",e),this.storage.removeItem(e)}ws(e){const i=e;i.storageArea===this.storage&&(pm("SharedClientState","EVENT",i.key,i.newValue),i.key!==this.Ds?this.ui.enqueueRetryable(async()=>{if(this.started){if(null!==i.key)if(this.Cs.test(i.key)){if(null==i.newValue){var e=this.Gs(i.key);return this.zs(e,null)}e=this.js(i.key,i.newValue);if(e)return this.zs(e.clientId,e)}else if(this.Fs.test(i.key)){if(null!==i.newValue){var t=this.Hs(i.key,i.newValue);if(t)return this.Js(t)}}else if(this.Ms.test(i.key)){if(null!==i.newValue){t=this.Ys(i.key,i.newValue);if(t)return this.Zs(t)}}else if(i.key===this.xs){if(null!==i.newValue){var n=this.Ls(i.newValue);if(n)return this.Bs(n)}}else if(i.key===this.vs){n=function(e){let t=dv.oe;if(null!=e)try{var n=JSON.parse(e);_m("number"==typeof n),t=n}catch(e){fm("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(i.newValue);n!==dv.oe&&this.sequenceNumberHandler(n)}else if(i.key===this.Os){const r=this.Xs(i.newValue);await Promise.all(r.map(e=>this.syncEngine.eo(e)))}}else this.bs.push(i)}):fm("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get Ks(){return this.Ss.get(this.ps)}Ns(){this.setItem(this.Ds,this.Ks.Vs())}qs(e,t,n){const r=new fT(this.currentUser,e,t,n),i=dT(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Vs())}Qs(e){var t=dT(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Us(e){var t={clientId:this.ps,onlineState:e};this.storage.setItem(this.xs,JSON.stringify(t))}$s(e,t,n){const r=pT(this.persistenceKey,e),i=new gT(e,t,n);this.setItem(r,i.Vs())}Ws(e){var t=JSON.stringify(Array.from(e));this.setItem(this.Os,t)}Gs(e){var t=this.Cs.exec(e);return t?t[1]:null}js(e,t){var n=this.Gs(e);return mT.Rs(n,t)}Hs(e,t){var n=this.Fs.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return fT.Rs(new lm(n),r,t)}Ys(e,t){var n=this.Ms.exec(e),n=Number(n[1]);return gT.Rs(n,t)}Ls(e){return vT.Rs(e)}Xs(e){return JSON.parse(e)}async Js(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.no(e.batchId,e.state,e.error);pm("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}Zs(e){return this.syncEngine.ro(e.targetId,e.state,e.error)}zs(e,t){const n=t?this.Ss.insert(e,t):this.Ss.remove(e),r=this.ks(this.Ss),i=this.ks(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.io(s,a).then(()=>{this.Ss=n})}Bs(e){this.Ss.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}ks(e){let n=Ly;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class wT{constructor(){this.so=new _T,this.oo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.so.fs(e),this.oo[e]||"not-current"}updateQueryState(e,t,n){this.oo[e]=t}removeLocalQueryTarget(e){this.so.gs(e)}isLocalQueryTarget(e){return this.so.activeTargetIds.has(e)}clearQueryState(e){delete this.oo[e]}getAllActiveQueryTargets(){return this.so.activeTargetIds}isActiveQueryTarget(e){return this.so.activeTargetIds.has(e)}start(){return this.so=new _T,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class bT{_o(e){}shutdown(){}}class IT{constructor(){this.ao=()=>this.uo(),this.co=()=>this.lo(),this.ho=[],this.Po()}_o(e){this.ho.push(e)}shutdown(){window.removeEventListener("online",this.ao),window.removeEventListener("offline",this.co)}Po(){window.addEventListener("online",this.ao),window.addEventListener("offline",this.co)}uo(){pm("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.ho)e(0)}lo(){pm("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.ho)e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let TT=null;function ET(){return null===TT?TT=268435456+Math.round(2147483648*Math.random()):TT++,"0x"+TT.toString(16)}const CT={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class ST{constructor(e){this.Io=e.Io,this.To=e.To}Eo(e){this.Ao=e}Ro(e){this.Vo=e}mo(e){this.fo=e}onMessage(e){this.po=e}close(){this.To()}send(e){this.Io(e)}yo(){this.Ao()}wo(){this.Vo()}So(e){this.fo(e)}bo(e){this.po(e)}}const kT="WebChannelConnection";class AT 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.Do=t+"://"+e.host,this.vo=`projects/${n}/databases/${r}`,this.Co="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}get Fo(){return!1}Mo(t,e,n,r,i){const s=ET(),a=this.xo(t,e.toUriEncodedString());pm("RestConnection",`Sending RPC '${t}' ${s}:`,a,n);var o={"google-cloud-resource-prefix":this.vo,"x-goog-request-params":this.Co};return this.Oo(o,r,i),this.No(t,a,o,n).then(e=>(pm("RestConnection",`Received RPC '${t}' ${s}: `,e),e),e=>{throw gm("RestConnection",`RPC '${t}' ${s} failed with error: `,e,"url: ",a,"request:",n),e})}Lo(e,t,n,r,i,s){return this.Mo(e,t,n,r,i)}Oo(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+um,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)}xo(e,t){var n=CT[e];return`${this.Do}/v1/${t}:${n}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}No(c,t,n,r){const l=ET();return new Promise((s,a)=>{const o=new Yg;o.setWithCredentials(!0),o.listenOnce(Xg.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case Zg.NO_ERROR:var e=o.getResponseJson();pm(kT,`XHR for RPC '${c}' ${l} received:`,JSON.stringify(e)),s(e);break;case Zg.TIMEOUT:pm(kT,`RPC '${c}' ${l} timed out`),a(new wm(ym.DEADLINE_EXCEEDED,"Request time out"));break;case Zg.HTTP_ERROR:var t=o.getStatus();if(pm(kT,`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(ym).indexOf(i)?i:ym.UNKNOWN);a(new wm(c,n.message))}else a(new wm(ym.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new wm(ym.UNAVAILABLE,"Connection failed."));break;default:vm()}}finally{pm(kT,`RPC '${c}' ${l} completed.`)}var r,i});var e=JSON.stringify(r);pm(kT,`RPC '${c}' ${l} sending request:`,r),o.send(t,"POST",e,n,15)})}Bo(i,e,t){const s=ET(),n=[this.Do,"/","google.firestore.v1.Firestore","/",i,"/channel"],r=rm(),a=nm(),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.Oo(o.initMessageHeaders,e,t),o.encodeInitMessageHeaders=!0;var l=n.join("");pm(kT,`Creating RPC '${i}' stream ${s}: ${l}`,o);const u=r.createWebChannel(l,o);let h=!1,d=!1;const p=new ST({Io:e=>{d?pm(kT,`Not sending because RPC '${i}' stream ${s} is closed:`,e):(h||(pm(kT,`Opening RPC '${i}' stream ${s} transport.`),u.open(),h=!0),pm(kT,`RPC '${i}' stream ${s} sending:`,e),u.send(e))},To:()=>u.close()}),f=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return f(u,Jg.EventType.OPEN,()=>{d||(pm(kT,`RPC '${i}' stream ${s} transport opened.`),p.yo())}),f(u,Jg.EventType.CLOSE,()=>{d||(d=!0,pm(kT,`RPC '${i}' stream ${s} transport closed`),p.So())}),f(u,Jg.EventType.ERROR,e=>{d||(d=!0,gm(kT,`RPC '${i}' stream ${s} transport errored:`,e),p.So(new wm(ym.UNAVAILABLE,"The operation could not be completed")))}),f(u,Jg.EventType.MESSAGE,n=>{if(!d){var e=n.data[0];_m(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){pm(kT,`RPC '${i}' stream ${s} received error:`,r);const n=r.status;let e=function(e){var t=im[e];if(void 0!==t)return mw(t)}(n),t=r.message;void 0===e&&(e=ym.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),d=!0,p.So(new wm(e,t)),u.close()}else pm(kT,`RPC '${i}' stream ${s} received:`,e),p.bo(e)}}),f(a,tm.STAT_EVENT,e=>{e.stat===em.PROXY?pm(kT,`RPC '${i}' stream ${s} detected buffering proxy`):e.stat===em.NOPROXY&&pm(kT,`RPC '${i}' stream ${s} detected no buffering proxy`)}),setTimeout(()=>{p.wo()},0),p}}function NT(){return"undefined"!=typeof window?window:null}function RT(){return"undefined"!=typeof document?document:null}function PT(e){return new Lw(e,!0)}class DT{constructor(e,t,n=1e3,r=1.5,i=6e4){this.ui=e,this.timerId=t,this.ko=n,this.qo=r,this.Qo=i,this.Ko=0,this.$o=null,this.Uo=Date.now(),this.reset()}reset(){this.Ko=0}Wo(){this.Ko=this.Qo}Go(e){this.cancel();var t=Math.floor(this.Ko+this.zo()),n=Math.max(0,Date.now()-this.Uo),r=Math.max(0,t-n);0<r&&pm("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Ko} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.$o=this.ui.enqueueAfterDelay(this.timerId,r,()=>(this.Uo=Date.now(),e())),this.Ko*=this.qo,this.Ko<this.ko&&(this.Ko=this.ko),this.Ko>this.Qo&&(this.Ko=this.Qo)}jo(){null!==this.$o&&(this.$o.skipDelay(),this.$o=null)}cancel(){null!==this.$o&&(this.$o.cancel(),this.$o=null)}zo(){return(Math.random()-.5)*this.Ko}}class xT{constructor(e,t,n,r,i,s,a,o){this.ui=e,this.Ho=n,this.Jo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Yo=0,this.Zo=null,this.Xo=null,this.stream=null,this.e_=0,this.t_=new DT(e,t)}n_(){return 1===this.state||5===this.state||this.r_()}r_(){return 2===this.state||3===this.state}start(){this.e_=0,4!==this.state?this.auth():this.i_()}async stop(){this.n_()&&await this.close(0)}s_(){this.state=0,this.t_.reset()}o_(){this.r_()&&null===this.Zo&&(this.Zo=this.ui.enqueueAfterDelay(this.Ho,6e4,()=>this.__()))}a_(e){this.u_(),this.stream.send(e)}async __(){if(this.r_())return this.close(0)}u_(){this.Zo&&(this.Zo.cancel(),this.Zo=null)}c_(){this.Xo&&(this.Xo.cancel(),this.Xo=null)}async close(e,t){this.u_(),this.c_(),this.t_.cancel(),this.Yo++,4!==e?this.t_.reset():t&&t.code===ym.RESOURCE_EXHAUSTED?(fm(t.toString()),fm("Using maximum backoff delay to prevent overloading the backend."),this.t_.Wo()):t&&t.code===ym.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.l_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.mo(t)}l_(){}auth(){this.state=1;const e=this.h_(this.Yo),n=this.Yo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.Yo===n&&this.P_(e,t)},t=>{e(()=>{var e=new wm(ym.UNKNOWN,"Fetching auth token failed: "+t.message);return this.I_(e)})})}P_(e,t){const n=this.h_(this.Yo);this.stream=this.T_(e,t),this.stream.Eo(()=>{n(()=>this.listener.Eo())}),this.stream.Ro(()=>{n(()=>(this.state=2,this.Xo=this.ui.enqueueAfterDelay(this.Jo,1e4,()=>(this.r_()&&(this.state=3),Promise.resolve())),this.listener.Ro()))}),this.stream.mo(e=>{n(()=>this.I_(e))}),this.stream.onMessage(e=>{n(()=>1==++this.e_?this.E_(e):this.onNext(e))})}i_(){this.state=5,this.t_.Go(async()=>{this.state=0,this.start()})}I_(e){return pm("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}h_(t){return e=>{this.ui.enqueueAndForget(()=>this.Yo===t?e():(pm("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class OT extends xT{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}T_(e,t){return this.connection.Bo("Listen",e,t)}E_(e){return this.onNext(e)}onNext(e){this.t_.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:vm(),i=t.targetChange.targetIds||[],s=(p=t.targetChange.resumeToken,e.useProto3Json?(_m(void 0===p||"string"==typeof p),r_.fromBase64String(p||"")):(_m(void 0===p||p instanceof Buffer||p instanceof Uint8Array),r_.fromUint8Array(p||new Uint8Array))),a=t.targetChange.cause,o=a&&(o=void 0===(p=a).code?ym.UNKNOWN:mw(p.code),new wm(o,p.message||""));n=new kw(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=Kw(e,c.document.name),o=Vw(c.document.updateTime),l=c.document.createTime?Vw(c.document.createTime):Lm.min(),u=new O_({mapValue:{fields:c.document.fields}}),l=L_.newFoundDocument(s,o,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new Cw(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=Kw(e,u.document),l=u.readTime?Vw(u.readTime):Lm.min(),l=L_.newNoDocument(c,l),u=u.removedTargetIds||[];n=new Cw([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=Kw(e,h.document),h=h.removedTargetIds||[];n=new Cw([],h,d,null)}else{if(!("filter"in t))return vm();{t.filter;const e=t.filter;e.targetId;var{count:h=0,unchangedNames:d}=e,h=new fw(h,d),d=e.targetId;n=new Sw(d,h)}}var o,p;return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return Lm.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?Vw(t.readTime):Lm.min()}(e);return this.listener.d_(t,n)}A_(e){const t={};t.database=Gw(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=oy(r)?{documents:Zw(e,r)}:{query:eb(e,r)._t},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()){n.resumeToken=Uw(e,t.resumeToken);const r=Mw(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(0<t.snapshotVersion.compareTo(Lm.min())){n.readTime=Fw(e,t.snapshotVersion.toTimestamp());const r=Mw(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 vm()}}(e.purpose))?null:{"goog-listen-tags":n});n&&(t.labels=n),this.a_(t)}R_(e){const t={};t.database=Gw(this.serializer),t.removeTarget=e,this.a_(t)}}class LT extends xT{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}get V_(){return 0<this.e_}start(){this.lastStreamToken=void 0,super.start()}l_(){this.V_&&this.m_([])}T_(e,t){return this.connection.Bo("Write",e,t)}E_(e){return _m(!!e.streamToken),this.lastStreamToken=e.streamToken,_m(!e.writeResults||0===e.writeResults.length),this.listener.f_()}onNext(e){_m(!!e.streamToken),this.lastStreamToken=e.streamToken,this.t_.reset();var t,n,r=(t=e.writeResults,n=e.commitTime,t&&0<t.length?(_m(void 0!==n),t.map(e=>function(e,t){let n=e.updateTime?Vw(e.updateTime):Vw(t);return n.isEqual(Lm.min())&&(n=Vw(t)),new Yy(n,e.transformResults||[])}(e,n))):[]),i=Vw(e.commitTime);return this.listener.g_(i,r)}p_(){const e={};e.database=Gw(this.serializer),this.a_(e)}m_(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>Jw(this.serializer,e))};this.a_(t)}}class MT extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.y_=!1}w_(){if(this.y_)throw new wm(ym.FAILED_PRECONDITION,"The client has already been terminated.")}Mo(n,r,i,s){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.Mo(n,jw(r,i),s,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===ym.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new wm(ym.UNKNOWN,e.toString())})}Lo(n,r,i,s,a){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.connection.Lo(n,jw(r,i),s,e,t,a)).catch(e=>{throw"FirebaseError"===e.name?(e.code===ym.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new wm(ym.UNKNOWN,e.toString())})}terminate(){this.y_=!0,this.connection.terminate()}}class FT{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.S_=0,this.b_=null,this.D_=!0}v_(){0===this.S_&&(this.C_("Unknown"),this.b_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.b_=null,this.F_("Backend didn't respond within 10 seconds."),this.C_("Offline"),Promise.resolve())))}M_(e){"Online"===this.state?this.C_("Unknown"):(this.S_++,1<=this.S_&&(this.x_(),this.F_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.C_("Offline")))}set(e){this.x_(),this.S_=0,"Online"===e&&(this.D_=!1),this.C_(e)}C_(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.D_?(fm(t),this.D_=!1):pm("OnlineStateTracker",t)}x_(){null!==this.b_&&(this.b_.cancel(),this.b_=null)}}class UT{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.O_=[],this.N_=new Map,this.L_=new Set,this.B_=[],this.k_=i,this.k_._o(e=>{n.enqueueAndForget(async()=>{GT(this)&&(pm("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.L_.add(4),await qT(t),t.q_.set("Unknown"),t.L_.delete(4),await VT(t)}(this))})}),this.q_=new FT(n,r)}}async function VT(e){if(GT(e))for(const t of e.B_)await t(!0)}async function qT(e){for(const t of e.B_)await t(!1)}function jT(e,t){const n=e;n.N_.has(t.targetId)||(n.N_.set(t.targetId,t),WT(n)?$T(n):r0(n).r_()&&zT(n,t))}function BT(e,t){const n=e,r=r0(n);n.N_.delete(t),r.r_()&&KT(n,t),0===n.N_.size&&(r.r_()?r.o_():GT(n)&&n.q_.set("Unknown"))}function zT(e,t){var n;e.Q_.xe(t.targetId),(0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(Lm.min()))&&(n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size,t=t.withExpectedCount(n)),r0(e).A_(t)}function KT(e,t){e.Q_.xe(t),r0(e).R_(t)}function $T(t){t.Q_=new Nw({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),ot:e=>t.N_.get(e)||null,tt:()=>t.datastore.serializer.databaseId}),r0(t).start(),t.q_.v_()}function WT(e){return GT(e)&&!r0(e).n_()&&0<e.N_.size}function GT(e){return 0===e.L_.size}function HT(e){e.Q_=void 0}async function QT(e,t,n){if(!sv(t))throw t;e.L_.add(1),await qT(e),e.q_.set("Offline"),n=n||(()=>nT(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{pm("RemoteStore","Retrying IndexedDB access"),await n(),e.L_.delete(1),await VT(e)})}function YT(t,n){return n().catch(e=>QT(t,e,n))}async function JT(e){const t=e,n=i0(t);let r=0<t.O_.length?t.O_[t.O_.length-1].batchId:-1;for(;GT(i=t)&&i.O_.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.O_.length&&n.o_();break}r=e.batchId,function(e,t){e.O_.push(t);const n=i0(e);n.r_()&&n.V_&&n.m_(t.mutations)}(t,e)}catch(e){await QT(t,e)}var i;XT(t)&&ZT(t)}function XT(e){return GT(e)&&!i0(e).n_()&&0<e.O_.length}function ZT(e){i0(e).start()}async function e0(e,t){t&&i0(e).V_&&await async function(e,t){if(gw(n=t.code)&&n!==ym.ABORTED){const r=e.O_.shift();i0(e).s_(),await YT(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await JT(e)}var n}(e,t),XT(e)&&ZT(e)}async function t0(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),pm("RemoteStore","RemoteStore received new credentials");var r=GT(n);n.L_.add(3),await qT(n),r&&n.q_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.L_.delete(3),await VT(n)}async function n0(e,t){const n=e;t?(n.L_.delete(2),await VT(n)):(n.L_.add(2),await qT(n),n.q_.set("Unknown"))}function r0(t){return t.K_||(t.K_=function(e,t,n){const r=e;return r.w_(),new OT(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Eo:(async function(e){e.q_.set("Online")}).bind(null,t),Ro:(async function(n){n.N_.forEach((e,t)=>{zT(n,e)})}).bind(null,t),mo:(async function(e,t){HT(e),WT(e)?(e.q_.M_(t),$T(e)):e.q_.set("Unknown")}).bind(null,t),d_:(async function(e,t,n){if(e.q_.set("Online"),t instanceof kw&&2===t.state&&t.cause)try{await async function(e,t){var n=t.cause;for(const r of t.targetIds)e.N_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.N_.delete(r),e.Q_.removeTarget(r))}(e,t)}catch(n){pm("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await QT(e,n)}else if(t instanceof Cw?e.Q_.Ke(t):t instanceof Sw?e.Q_.He(t):e.Q_.We(t),!n.isEqual(Lm.min()))try{const t=await nT(e.localStore);0<=n.compareTo(t)&&await function(i,r){const e=i.Q_.rt(r);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=i.N_.get(t);n&&i.N_.set(t,n.withResumeToken(e.resumeToken,r))}}),e.targetMismatches.forEach((e,t)=>{const n=i.N_.get(e);var r;n&&(i.N_.set(e,n.withResumeToken(r_.EMPTY_BYTE_STRING,n.snapshotVersion)),KT(i,e),r=new ob(n.target,e,t,n.sequenceNumber),zT(i,r))}),i.remoteSyncer.applyRemoteEvent(e)}(e,n)}catch(t){pm("RemoteStore","Failed to raise snapshot:",t),await QT(e,t)}}).bind(null,t)}),t.B_.push(async e=>{e?(t.K_.s_(),WT(t)?$T(t):t.q_.set("Unknown")):(await t.K_.stop(),HT(t))})),t.K_}function i0(t){return t.U_||(t.U_=function(e,t,n){const r=e;return r.w_(),new LT(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(t.datastore,t.asyncQueue,{Eo:()=>Promise.resolve(),Ro:(async function(e){i0(e).p_()}).bind(null,t),mo:e0.bind(null,t),f_:(async function(e){const t=i0(e);for(const n of e.O_)t.m_(n.mutations)}).bind(null,t),g_:(async function(e,t,n){const r=e.O_.shift(),i=dw.from(r,t,n);await YT(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await JT(e)}).bind(null,t)}),t.B_.push(async e=>{e?(t.U_.s_(),await JT(t)):(await t.U_.stop(),0<t.O_.length&&(pm("RemoteStore",`Stopping write stream with ${t.O_.length} pending writes`),t.O_=[]))})),t.U_}class s0{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new bm,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 s0(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 wm(ym.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 a0(e,t){if(fm("AsyncQueue",`${t}: ${e}`),sv(e))return new wm(ym.UNAVAILABLE,`${t}: ${e}`);throw e}class o0{constructor(n){this.comparator=n?(e,t)=>n(e,t)||qm.comparator(e.key,t.key):(e,t)=>qm.comparator(e.key,t.key),this.keyedMap=Ny(),this.sortedSet=new Qv(this.comparator)}static emptySet(e){return new o0(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 o0))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 o0;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class c0{constructor(){this.W_=new Qv(qm.comparator)}track(e){var t=e.doc.key,n=this.W_.get(t);!n||0!==e.type&&3===n.type?this.W_=this.W_.insert(t,e):3===e.type&&1!==n.type?this.W_=this.W_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.W_=this.W_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.W_=this.W_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.W_=this.W_.remove(t):1===e.type&&2===n.type?this.W_=this.W_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.W_=this.W_.insert(t,{type:2,doc:e.doc}):vm()}G_(){const n=[];return this.W_.inorderTraversal((e,t)=>{n.push(t)}),n}}class l0{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 l0(e,t,o0.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)&&wy(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 u0{constructor(){this.z_=void 0,this.j_=[]}H_(){return this.j_.some(e=>e.J_())}}class h0{constructor(){this.queries=d0(),this.onlineState="Unknown",this.Y_=new Set}terminate(){!function(e,n){const t=e,r=t.queries;t.queries=d0(),r.forEach((e,t)=>{for(const e of t.j_)e.onError(n)})}(this,new wm(ym.ABORTED,"Firestore shutting down"))}}function d0(){return new Sy(e=>by(e),wy)}async function p0(e,t){const n=e;let r=3;var i=t.query;let s=n.queries.get(i);s?!s.H_()&&t.J_()&&(r=2):(s=new u0,r=t.J_()?0:1);try{switch(r){case 0:s.z_=await n.onListen(i,!0);break;case 1:s.z_=await n.onListen(i,!1);break;case 2:await n.onFirstRemoteStoreListen(i)}}catch(e){const n=a0(e,`Initialization of query '${Iy(t.query)}' failed`);return void t.onError(n)}n.queries.set(i,s),s.j_.push(t),t.Z_(n.onlineState),!s.z_||t.X_(s.z_)&&g0(n)}async function f0(e,t){const n=e,r=t.query;let i=3;const s=n.queries.get(r);if(s){const e=s.j_.indexOf(t);0<=e&&(s.j_.splice(e,1),0===s.j_.length?i=t.J_()?0:1:!s.H_()&&t.J_()&&(i=2))}switch(i){case 0:return n.queries.delete(r),n.onUnlisten(r,!0);case 1:return n.queries.delete(r),n.onUnlisten(r,!1);case 2:return n.onLastRemoteStoreUnlisten(r);default:return}}function g0(e){e.Y_.forEach(e=>{e.next()})}(sm=sm||{}).ea="default",sm.Cache="cache";class m0{constructor(e,t,n){this.query=e,this.ta=t,this.na=!1,this.ra=null,this.onlineState="Unknown",this.options=n||{}}X_(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new l0(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.na?this.ia(e)&&(this.ta.next(e),t=!0):this.sa(e,this.onlineState)&&(this.oa(e),t=!0),this.ra=e,t}onError(e){this.ta.error(e)}Z_(e){this.onlineState=e;let t=!1;return this.ra&&!this.na&&this.sa(this.ra,e)&&(this.oa(this.ra),t=!0),t}sa(e,t){return!e.fromCache||(!this.J_()||(!this.options._a||!("Offline"!==t))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t))}ia(e){if(0<e.docChanges.length)return!0;var t=this.ra&&this.ra.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}oa(e){e=l0.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.na=!0,this.ta.next(e)}J_(){return this.options.source!==sm.Cache}}class v0{constructor(e,t){this.aa=e,this.byteLength=t}ua(){return"metadata"in this.aa}}class _0{constructor(e){this.serializer=e}Es(e){return Kw(this.serializer,e)}ds(e){return e.metadata.exists?Yw(this.serializer,e.document,!1):L_.newNoDocument(this.Es(e.metadata.name),this.As(e.metadata.readTime))}As(e){return Vw(e)}}class y0{constructor(e,t,n){this.ca=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=w0(e)}la(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.aa.namedQuery)this.queries.push(e.aa.namedQuery);else if(e.aa.documentMetadata){this.documents.push({metadata:e.aa.documentMetadata}),e.aa.documentMetadata.exists||++t;const n=Fm.fromString(e.aa.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.aa.document&&(this.documents[this.documents.length-1].document=e.aa.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}ha(e){const t=new Map,n=new _0(this.serializer);for(const i of e)if(i.metadata.queries){const e=n.Es(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||Oy()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=Oy(),a=ky;for(const e of n){const n=t.Es(e.metadata.name);e.document&&(s=s.add(n));const l=t.ds(e);l.setReadTime(t.As(e.metadata.readTime)),a=a.insert(n,l)}const o=i.cs.newChangeBuffer({trackRemovals:!0}),c=await sT(i,(r=r,vy(py(Fm.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>iT(t,o,a).next(e=>(o.apply(t),e)).next(e=>i.Ur.removeMatchingKeysForTargetId(t,c.targetId).next(()=>i.Ur.addMatchingKeys(t,s,c.targetId)).next(()=>i.localDocuments.getLocalViewOfDocuments(t,e.Ps,e.Is)).next(()=>e.Ps)))}(this.localStore,new _0(this.serializer),this.documents,this.ca.id),t=this.ha(this.documents);for(const e of this.queries)await async function(e,n,r=Oy()){const i=await sT(e,vy(mb(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=Vw(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.Gr.saveNamedQuery(e,n);t=i.withResumeToken(r_.EMPTY_BYTE_STRING,t);return s.os=s.os.insert(t.targetId,t),s.Ur.updateTargetData(e,t).next(()=>s.Ur.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Ur.addMatchingKeys(e,r,i.targetId)).next(()=>s.Gr.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Pa:this.collectionGroups,Ia:e}}}function w0(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class b0{constructor(e){this.key=e}}class I0{constructor(e){this.key=e}}class T0{constructor(e,t){this.query=e,this.Ta=t,this.Ea=null,this.hasCachedResults=!1,this.current=!1,this.da=Oy(),this.mutatedKeys=Oy(),this.Aa=Cy(e),this.Ra=new o0(this.Aa)}get Va(){return this.Ta}ma(e,t){const o=t?t.fa:new c0,c=(t||this).Ra;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=Ty(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.ga(n,r)||(o.track({type:2,doc:r}),a=!0,(d&&0<this.Aa(r,d)||p&&this.Aa(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{Ra:u,fa:o,ns:h,mutatedKeys:l}}ga(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){var i=this.Ra;this.Ra=e.Ra,this.mutatedKeys=e.mutatedKeys;const s=e.fa.G_();s.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 vm()}};return n(e)-n(t)}(e.type,t.type)||this.Aa(e.doc,t.doc)),this.pa(n),r=null!=r&&r;var a=t&&!r?this.ya():[],o=0===this.da.size&&this.current&&!r?1:0,c=o!==this.Ea;return this.Ea=o,0!==s.length||c?{snapshot:new l0(this.query,e.Ra,i,s,e.mutatedKeys,0==o,c,!1,!!n&&0<n.resumeToken.approximateByteSize()),wa:a}:{wa:a}}Z_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ra:this.Ra,fa:new c0,mutatedKeys:this.mutatedKeys,ns:!1},!1)):{wa:[]}}Sa(e){return!this.Ta.has(e)&&!!this.Ra.has(e)&&!this.Ra.get(e).hasLocalMutations}pa(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)}ya(){if(!this.current)return[];const t=this.da;this.da=Oy(),this.Ra.forEach(e=>{this.Sa(e.key)&&(this.da=this.da.add(e.key))});const n=[];return t.forEach(e=>{this.da.has(e)||n.push(new I0(e))}),this.da.forEach(e=>{t.has(e)||n.push(new b0(e))}),n}ba(e){this.Ta=e.Ts,this.da=Oy();var t=this.ma(e.documents);return this.applyChanges(t,!0)}Da(){return l0.fromInitialDocuments(this.query,this.Ra,this.mutatedKeys,0===this.Ea,this.hasCachedResults)}}class E0{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class C0{constructor(e){this.key=e,this.va=!1}}class S0{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.Ca={},this.Fa=new Sy(e=>by(e),wy),this.Ma=new Map,this.xa=new Set,this.Oa=new Qv(qm.comparator),this.Na=new Map,this.La=new xI,this.Ba={},this.ka=new Map,this.qa=oI.kn(),this.onlineState="Unknown",this.Qa=void 0}get isPrimaryClient(){return!0===this.Qa}}async function k0(e,t,n,r){var i=await sT(e.localStore,vy(t)),s=i.targetId,a=e.sharedClientState.addLocalQueryTarget(s,n);let o;return r&&(o=await A0(e,t,s,"current"===a,i.resumeToken)),e.isPrimaryClient&&n&&jT(e.remoteStore,i),o}async function A0(r,e,t,n,i){r.Ka=(e,t,n)=>async function(e,t,n,r){let i=t.view.ma(n);i.ns&&(i=await oT(e.localStore,t.query,!1).then(({documents:e})=>t.view.ma(e,i)));var s=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),a=t.view.applyChanges(i,e.isPrimaryClient,s,a);return F0(e,t.targetId,a.wa),a.snapshot}(r,e,t,n);const s=await oT(r.localStore,e,!0),a=new T0(e,s.Ts),o=a.ma(s.documents),c=Ew.createSynthesizedTargetChangeForCurrentChange(t,n&&"Offline"!==r.onlineState,i),l=a.applyChanges(o,r.isPrimaryClient,c);F0(r,t,l.wa);var u=new E0(e,t,a);return r.Fa.set(e,u),r.Ma.has(t)?r.Ma.get(t).push(e):r.Ma.set(t,[e]),l.snapshot}async function N0(e,t,n){const r=K0(e);try{const e=await function(e,i){const s=e,a=Om.now(),o=i.reduce((e,t)=>e.add(t.key),Oy());let c,l;return s.persistence.runTransaction("Locally write mutations","readwrite",n=>{let t=ky,r=Oy();return s.cs.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=qy(r.transform,e||null);null!=i&&(null===n&&(n=O_.empty()),n.set(r.field,i))}return n||null}(n,c.get(n.key).overlayedDocument);null!=i&&t.push(new sw(n.key,i,function r(e){const i=[];return Gv(e.fields,(e,t)=>{const n=new Vm([e]);if(k_(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 t_(i)}(i.value.mapValue),Jy.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:Ry(c)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Ba[e.currentUser.toKey()];r=r||new Qv(Pm),r=r.insert(t,n),e.Ba[e.currentUser.toKey()]=r}(r,e.batchId,n),await V0(r,e.changes),await JT(r.remoteStore)}catch(e){const t=a0(e,"Failed to persist write");n.reject(t)}}async function R0(e,t){const r=e;try{const e=await rT(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Na.get(t);n&&(_m(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.va=!0:0<e.modifiedDocuments.size?_m(n.va):0<e.removedDocuments.size&&(_m(n.va),n.va=!1))}),await V0(r,e,t)}catch(e){await Xm(e)}}function P0(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.Fa.forEach((e,t)=>{var n=t.view.Z_(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.j_)e.Z_(n)&&(r=!0)}),r&&g0(t)}(t.eventManager,i),r.length&&t.Ca.d_(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function D0(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.cs.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let a=Zm.resolve();return n.forEach(n=>{a=a.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);_m(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=Oy();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);O0(n,r,null),x0(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await V0(n,e)}catch(e){await Xm(e)}}function x0(e,t){(e.ka.get(t)||[]).forEach(e=>{e.resolve()}),e.ka.delete(t)}function O0(e,t,n){const r=e;let i=r.Ba[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Ba[r.currentUser.toKey()]=i}}function L0(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Ma.get(e))t.Fa.delete(r),n&&t.Ca.$a(r,n);t.Ma.delete(e),t.isPrimaryClient&&t.La.gr(e).forEach(e=>{t.La.containsKey(e)||M0(t,e)})}function M0(e,t){e.xa.delete(t.path.canonicalString());var n=e.Oa.get(t);null!==n&&(BT(e.remoteStore,n),e.Oa=e.Oa.remove(t),e.Na.delete(n),U0(e))}function F0(e,t,n){for(const r of n)r instanceof b0?(e.La.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.Oa.get(n)||e.xa.has(r)||(pm("SyncEngine","New document in limbo: "+n),e.xa.add(r),U0(e))}(e,r)):r instanceof I0?(pm("SyncEngine","Document no longer in limbo: "+r.key),e.La.removeReference(r.key,t),e.La.containsKey(r.key)||M0(e,r.key)):vm()}function U0(e){for(;0<e.xa.size&&e.Oa.size<e.maxConcurrentLimboResolutions;){var t=e.xa.values().next().value;e.xa.delete(t);var n=new qm(Fm.fromString(t)),t=e.qa.next();e.Na.set(t,new C0(n)),e.Oa=e.Oa.insert(n,t),jT(e.remoteStore,new ob(vy(py(n.path)),t,"TargetPurposeLimboResolution",dv.oe))}}async function V0(e,t,r){const i=e,s=[],a=[],o=[];i.Fa.isEmpty()||(i.Fa.forEach((e,n)=>{o.push(i.Ka(n,t,r).then(e=>{var t;if((e||r)&&i.isPrimaryClient){const s=e?!e.fromCache:null===(t=null==r?void 0:r.targetChanges.get(n.targetId))||void 0===t?void 0:t.current;i.sharedClientState.updateQueryState(n.targetId,s?"current":"not-current")}if(e){s.push(e);const t=YI.Wi(n.targetId,e);a.push(t)}}))}),await Promise.all(o),i.Ca.d_(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>Zm.forEach(t,t=>Zm.forEach(t.$i,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>Zm.forEach(t.Ui,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!sv(e))throw e;pm("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.os.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.os=r.os.insert(t,i)}}}(i.localStore,a))}async function q0(r,e){const i=r;if(z0(i),K0(i),!0===e&&!0!==i.Qa){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await j0(i,r.toArray());i.Qa=!0,await n0(i.remoteStore,!0);for(const r of e)jT(i.remoteStore,r)}else if(!1===e&&!1!==i.Qa){const r=[];let n=Promise.resolve();i.Ma.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(L0(i,t),aT(i.localStore,t,!0))),BT(i.remoteStore,t)}),await n,await j0(i,r),function(e){const n=e;n.Na.forEach((e,t)=>{BT(n.remoteStore,t)}),n.La.pr(),n.Na=new Map,n.Oa=new Qv(qm.comparator)}(i),i.Qa=!1,await n0(i.remoteStore,!1)}}async function j0(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.Ma.get(t);if(u&&0!==u.length){e=await sT(r.localStore,vy(u[0]));for(const t of u){const n=r.Fa.get(t),u=(a=r,o=n,l=c=void 0,l=await oT((c=a).localStore,o.query,!0),l=o.view.ba(l),c.isPrimaryClient&&F0(c,o.targetId,l.wa),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await cT(r.localStore,t);e=await sT(r.localStore,u),await A0(r,B0(u),t,!1,e.resumeToken)}i.push(e)}var a,o,c,l;return r.Ca.d_(s),i}function B0(e){return dy(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function z0(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=R0.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Na.get(t);if(r&&r.va)return Oy().add(r.key);{let e=Oy();const r=n.Ma.get(t);if(!r)return e;for(const t of r){const r=n.Fa.get(t);e=e.unionWith(r.view.Va)}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.Na.get(t),s=i&&i.key;if(s){let e=new Qv(qm.comparator);e=e.insert(s,L_.newNoDocument(s,Lm.min()));const n=Oy().add(s),i=new Tw(Lm.min(),new Map,new Qv(Pm),e,n);await R0(r,i),r.Oa=r.Oa.remove(s),r.Na.delete(t),U0(r)}else await aT(r.localStore,t,!1).then(()=>L0(r,t,n)).catch(Xm)}).bind(null,t),t.Ca.d_=(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.j_)t.X_(e)&&(r=!0);i.z_=e}}r&&g0(n)}).bind(null,t.eventManager),t.Ca.$a=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.j_)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function K0(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=D0.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=>(_m(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);O0(r,t,n),x0(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await V0(r,e)}catch(n){await Xm(n)}}).bind(null,t),t}class $0{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=PT(e.databaseInfo.databaseId),this.sharedClientState=this.Wa(e),this.persistence=this.Ga(e),await this.persistence.start(),this.localStore=this.za(e),this.gcScheduler=this.ja(e,this.localStore),this.indexBackfillerScheduler=this.Ha(e,this.localStore)}ja(e,t){return null}Ha(e,t){return null}za(e){return eT(this.persistence,new XI,e.initialUser,this.serializer)}Ga(e){return new VI(jI.Zr,this.serializer)}Wa(e){return new wT}async terminate(){var e;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(e=this.indexBackfillerScheduler)||void 0===e||e.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}$0.provider={build:()=>new $0};class W0 extends $0{constructor(e){super(),this.cacheSizeBytes=e}ja(e,t){_m(this.persistence.referenceDelegate instanceof BI);var n=this.persistence.referenceDelegate.garbageCollector;return new fI(n,e.asyncQueue,t)}Ga(e){const t=void 0!==this.cacheSizeBytes?Zb.withCacheSize(this.cacheSizeBytes):Zb.DEFAULT;return new VI(e=>BI.Zr(e,t),this.serializer)}}class G0 extends $0{constructor(e,t,n){super(),this.Ja=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Ja.initialize(this,e),await K0(this.Ja.syncEngine),await JT(this.Ja.remoteStore),await this.persistence.yi(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}za(e){return eT(this.persistence,new XI,e.initialUser,this.serializer)}ja(e,t){var n=this.persistence.referenceDelegate.garbageCollector;return new fI(n,e.asyncQueue,t)}Ha(e,t){var n=new hv(t,this.persistence);return new uv(e.asyncQueue,n)}Ga(e){var t=QI(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Zb.withCacheSize(this.cacheSizeBytes):Zb.DEFAULT;return new WI(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,NT(),RT(),this.serializer,this.sharedClientState,!!this.forceOwnership)}Wa(e){return new wT}}class H0 extends G0{constructor(e,t){super(e,t,!1),this.Ja=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Ja.syncEngine;this.sharedClientState instanceof yT&&(this.sharedClientState.syncEngine={no:(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.Mn(t,n).next(e=>e?r.localDocuments.getDocuments(t,e):Zm.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await JT(i.remoteStore):"acknowledged"===n||"rejected"===n?(O0(i,t,r||null),x0(i,t),i.localStore.mutationQueue.On(t)):vm(),await V0(i,s)):pm("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),ro:(async function(e,t,n,r){const i=e;if(i.Qa)pm("SyncEngine","Ignoring unexpected query state notification.");else{var s=i.Ma.get(t);if(s&&0<s.length)switch(n){case"current":case"not-current":{const e=await lT(i.localStore,Ey(s[0])),r=Tw.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,r_.EMPTY_BYTE_STRING);await V0(i,e,r);break}case"rejected":await aT(i.localStore,t,!0),L0(i,t,r);break;default:vm()}}}).bind(null,t),io:(async function(e,t,n){const r=z0(e);if(r.Qa){for(const e of t)if(r.Ma.has(e)&&r.sharedClientState.isActiveQueryTarget(e))pm("SyncEngine","Adding an already active target "+e);else{const t=await cT(r.localStore,e),n=await sT(r.localStore,t);await A0(r,B0(t),n.targetId,!1,n.resumeToken),jT(r.remoteStore,n)}for(const e of n)r.Ma.has(e)&&await aT(r.localStore,e,!1).then(()=>{BT(r.remoteStore,e),L0(r,e)}).catch(Xm)}}).bind(null,t),Qi:(function(e){return e.localStore.persistence.Qi()}).bind(null,t),eo:(async function(e,t){const n=e;return lT(n.localStore,t).then(e=>V0(n,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.yi(async e=>{await q0(this.Ja.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())})}Wa(e){var t=NT();if(!yT.D(t))throw new wm(ym.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=QI(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new yT(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class Q0{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=>P0(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){pm("SyncEngine","User change. New user:",t.toKey());const i=await tT(n.localStore,t);n.currentUser=t,e=n,r="'waitForPendingWrites' promise is rejected due to a user change.",e.ka.forEach(e=>{e.forEach(e=>{e.reject(new wm(ym.CANCELLED,r))})}),e.ka.clear(),n.sharedClientState.handleUserChange(t,i.removedBatchIds,i.addedBatchIds),await V0(n,i.hs)}var r}).bind(null,this.syncEngine),await n0(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new h0}createDatastore(e){var t,n,r,i=PT(e.databaseInfo.databaseId),s=(r=e.databaseInfo,new AT(r));return t=e.authCredentials,n=e.appCheckCredentials,r=s,e=i,new MT(t,n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>P0(this.syncEngine,e,0),e=new(IT.D()?IT:bT),new UT(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 S0(e,t,n,r,i,s);return a&&(o.Qa=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e;await async function(e){const t=e;pm("RemoteStore","RemoteStore shutting down."),t.L_.add(5),await qT(t),t.k_.shutdown(),t.q_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate(),null===(e=this.eventManager)||void 0===e||e.terminate()}}function Y0(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()}}Q0.provider={build:()=>new Q0};class J0{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ya(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ya(this.observer.error,e):fm("Uncaught Error in snapshot listener:",e.toString()))}Za(){this.muted=!0}Ya(e,t){setTimeout(()=>{this.muted||e(t)},0)}}class X0{constructor(e,t){this.Xa=e,this.serializer=t,this.metadata=new bm,this.buffer=new Uint8Array,this.eu=new TextDecoder("utf-8"),this.tu().then(e=>{e&&e.ua()?this.metadata.resolve(e.aa.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.aa)}`))},e=>this.metadata.reject(e))}close(){return this.Xa.cancel()}async getMetadata(){return this.metadata.promise}async Ua(){return await this.getMetadata(),this.tu()}async tu(){var e=await this.nu();if(null===e)return null;var t=this.eu.decode(e),n=Number(t);isNaN(n)&&this.ru(`length string (${t}) is not valid number`);t=await this.iu(n);return new v0(JSON.parse(t),e.length+n)}su(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async nu(){for(;this.su()<0&&!await this.ou(););if(0===this.buffer.length)return null;var e=this.su();e<0&&this.ru("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 iu(e){for(;this.buffer.length<e;)await this.ou()&&this.ru("Reached the end of bundle when more is expected.");var t=this.eu.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}ru(e){throw this.Xa.cancel(),new Error(`Invalid bundle format: ${e}`)}async ou(){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 Z0{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw this.lastTransactionError=new wm(ym.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const t=await async function(e,t){const r=e,n={documents:t.map(e=>zw(r.serializer,e))},i=await r.Lo("BatchGetDocuments",r.serializer.databaseId,Fm.emptyPath(),n,t.length),s=new Map;i.forEach(e=>{const t=(n=r.serializer,"found"in(e=e)?function(e,t){_m(!!t.found),t.found.name,t.found.updateTime;var n=Kw(e,t.found.name),r=Vw(t.found.updateTime),i=t.found.createTime?Vw(t.found.createTime):Lm.min(),s=new O_({mapValue:{fields:t.found.fields}});return L_.newFoundDocument(n,r,i,s)}(n,e):"missing"in e?function(e,t){_m(!!t.missing),_m(!!t.readTime);var n=Kw(e,t.missing),r=Vw(t.readTime);return L_.newNoDocument(n,r)}(n,e):vm());var n;s.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=s.get(e.toString());_m(!!t),a.push(t)}),a}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new lw(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=qm.fromPath(t);this.mutations.push(new uw(n,this.precondition(n)))}),await async function(e,t){const n=e,r={writes:t.map(e=>Jw(n.serializer,e))};await n.Mo("Commit",n.serializer.databaseId,Fm.emptyPath(),r)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw vm();t=Lm.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new wm(ym.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(Lm.min())?Jy.exists(!1):Jy.updateTime(t):Jy.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Jy.exists(!0);if(t.isEqual(Lm.min()))throw new wm(ym.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Jy.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class eE{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this._u=n.maxAttempts,this.t_=new DT(this.asyncQueue,"transaction_retry")}au(){--this._u,this.uu()}uu(){this.t_.Go(async()=>{const t=new Z0(this.datastore),e=this.cu(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.lu(e)}))}).catch(e=>{this.lu(e)})})}cu(e){try{var t=this.updateFunction(e);return!pv(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}}lu(e){0<this._u&&this.hu(e)?(--this._u,this.asyncQueue.enqueueAndForget(()=>(this.uu(),Promise.resolve()))):this.deferred.reject(e)}hu(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!gw(t)}}class tE{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=lm.UNAUTHENTICATED,this.clientId=Rm.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async e=>{pm("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(pm("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();const n=new bm;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=a0(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function nE(e,t){e.asyncQueue.verifyOperationInProgress(),pm("FirestoreClient","Initializing OfflineComponentProvider");var n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await tT(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function rE(e,n){e.asyncQueue.verifyOperationInProgress();var t=await iE(e);pm("FirestoreClient","Initializing OnlineComponentProvider"),await n.initialize(t,e.configuration),e.setCredentialChangeListener(e=>t0(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>t0(n.remoteStore,t)),e._onlineComponents=n}async function iE(t){if(!t._offlineComponents)if(t._uninitializedComponentsProvider){pm("FirestoreClient","Using user provided OfflineComponentProvider");try{await nE(t,t._uninitializedComponentsProvider._offline)}catch(e){var n=e;if(!("FirebaseError"===(r=n).name?r.code===ym.FAILED_PRECONDITION||r.code===ym.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&r instanceof DOMException)||22===r.code||20===r.code||11===r.code))throw n;gm("Error using user provided cache. Falling back to memory cache: "+n),await nE(t,new $0)}}else pm("FirestoreClient","Using default OfflineComponentProvider"),await nE(t,new W0(void 0));var r;return t._offlineComponents}async function sE(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(pm("FirestoreClient","Using user provided OnlineComponentProvider"),await rE(e,e._uninitializedComponentsProvider._online)):(pm("FirestoreClient","Using default OnlineComponentProvider"),await rE(e,new Q0))),e._onlineComponents}function aE(e){return iE(e).then(e=>e.persistence)}function oE(e){return iE(e).then(e=>e.localStore)}function cE(e){return sE(e).then(e=>e.remoteStore)}function lE(e){return sE(e).then(e=>e.syncEngine)}async function uE(e){const t=await sE(e),n=t.eventManager;return n.onListen=(async function(e,t,n=!0){const r=z0(e);let i;const s=r.Fa.get(t);return i=s?(r.sharedClientState.addLocalQueryTarget(s.targetId),s.view.Da()):await k0(r,t,n,!0),i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t,n){const r=e,i=r.Fa.get(t),s=r.Ma.get(i.targetId);if(1<s.length)return r.Ma.set(i.targetId,s.filter(e=>!wy(e,t))),void r.Fa.delete(t);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(i.targetId),r.sharedClientState.isActiveQueryTarget(i.targetId)||await aT(r.localStore,i.targetId,!1).then(()=>{r.sharedClientState.clearQueryState(i.targetId),n&&BT(r.remoteStore,i.targetId),L0(r,i.targetId)}).catch(Xm)):(L0(r,i.targetId),await aT(r.localStore,i.targetId,!0))}).bind(null,t.syncEngine),n.onFirstRemoteStoreListen=(async function(e,t){await k0(z0(e),t,!0,!1)}).bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=(async function(e,t){const n=e,r=n.Fa.get(t),i=n.Ma.get(r.targetId);n.isPrimaryClient&&1===i.length&&(n.sharedClientState.removeLocalQueryTarget(r.targetId),BT(n.remoteStore,r.targetId))}).bind(null,t.syncEngine),n}function hE(e,t,n={}){const r=new bm;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,a){const o=new J0({next:e=>{o.Za(),r.enqueueAndForget(()=>f0(n,c));var t=e.docs.has(i);!t&&e.fromCache?a.reject(new wm(ym.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?a.reject(new wm(ym.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)}),c=new m0(py(i.path),o,{includeMetadataChanges:!0,_a:!0});return p0(n,c)}(await uE(e),e.asyncQueue,t,n,r)),r.promise}function dE(e,t,n={}){const r=new bm;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new J0({next:e=>{s.Za(),n.enqueueAndForget(()=>f0(t,a)),e.fromCache&&"server"===r.source?i.reject(new wm(ym.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 m0(e,s,{includeMetadataChanges:!0,_a:!0});return p0(t,a)}(await uE(e),e.asyncQueue,t,n,r)),r.promise}function pE(e,t,n,r){const i=(n=n,t=PT(t),s="string"==typeof n?vw().encode(n):n,n=function(e,t){if(e instanceof Uint8Array)return Y0(e,t);if(e instanceof ArrayBuffer)return Y0(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 X0(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=Vw(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Gr.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(w0(i));const a=new y0(i,t.localStore,n.serializer);let e=await n.Ua();for(;e;){const t=await a.la(e);t&&r._updateProgress(t),e=await n.Ua()}var s=await a.complete();return await V0(t,s.Ia,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Gr.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress),Promise.resolve(s.Pa)}catch(t){return gm("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t),Promise.resolve(new Set)}}(r,t,n).then(e=>{r.sharedClientState.notifyBundleLoaded(e)})}(await lE(e),i,r)})}function fE(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const gE=new Map;function mE(e,t,n){if(!n)throw new wm(ym.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function vE(e,t,n,r){if(!0===t&&!0===r)throw new wm(ym.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function _E(e){if(!qm.isDocumentKey(e))throw new wm(ym.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function yE(e){if(qm.isDocumentKey(e))throw new wm(ym.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function wE(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":vm();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 bE(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new wm(ym.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=wE(e);throw new wm(ym.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function IE(e,t){if(t<=0)throw new wm(ym.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class TE{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new wm(ym.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 wm(ym.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}vE("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=fE(null!==(t=e.experimentalLongPollingOptions)&&void 0!==t?t:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new wm(ym.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new wm(ym.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(30<e.timeoutSeconds)throw new wm(ym.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 EE{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 TE({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new wm(ym.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new wm(ym.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 TE(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new Tm;switch(e.type){case"firstParty":return new km(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new wm(ym.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=gE.get(e);t&&(pm("ComponentProvider","Removing Datastore"),gE.delete(e),t.terminate())}(this),Promise.resolve()}}class CE{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new CE(this.firestore,e,this._query)}}class SE{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 kE(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new SE(this.firestore,e,this._key)}}class kE extends CE{constructor(e,t,n){super(e,t,py(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 SE(this.firestore,null,new qm(e))}withConverter(e){return new kE(this.firestore,e,this._path)}}function AE(e,t,...n){if(e=le(e),mE("collection","path",t),e instanceof EE){var r=Fm.fromString(t,...n);return yE(r),new kE(e,null,r)}if(!(e instanceof SE||e instanceof kE))throw new wm(ym.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Fm.fromString(t,...n));return yE(r),new kE(e.firestore,null,r)}function NE(e,t,...n){if(e=le(e),mE("doc","path",t=1===arguments.length?Rm.newId():t),e instanceof EE){var r=Fm.fromString(t,...n);return _E(r),new SE(e,null,new qm(r))}if(!(e instanceof SE||e instanceof kE))throw new wm(ym.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(Fm.fromString(t,...n));return _E(r),new SE(e.firestore,e instanceof kE?e.converter:null,new qm(r))}function RE(e,t){return e=le(e),t=le(t),(e instanceof SE||e instanceof kE)&&(t instanceof SE||t instanceof kE)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function PE(e,t){return e=le(e),t=le(t),e instanceof CE&&t instanceof CE&&e.firestore===t.firestore&&wy(e._query,t._query)&&e.converter===t.converter}class DE{constructor(e=Promise.resolve()){this.Pu=[],this.Iu=!1,this.Tu=[],this.Eu=null,this.du=!1,this.Au=!1,this.Ru=[],this.t_=new DT(this,"async_queue_retry"),this.Vu=()=>{var e=RT();e&&pm("AsyncQueue","Visibility state changed to "+e.visibilityState),this.t_.jo()},this.mu=e;const t=RT();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.Vu)}get isShuttingDown(){return this.Iu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.fu(),this.gu(e)}enterRestrictedMode(e){if(!this.Iu){this.Iu=!0,this.Au=e||!1;const t=RT();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Vu)}}enqueue(e){if(this.fu(),this.Iu)return new Promise(()=>{});const t=new bm;return this.gu(()=>this.Iu&&this.Au?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Pu.push(e),this.pu()))}async pu(){if(0!==this.Pu.length){try{await this.Pu[0](),this.Pu.shift(),this.t_.reset()}catch(e){if(!sv(e))throw e;pm("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Pu.length&&this.t_.Go(()=>this.pu())}}gu(e){var t=this.mu.then(()=>(this.du=!0,e().catch(e=>{throw this.Eu=e,this.du=!1,fm("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.du=!1,e))));return this.mu=t}enqueueAfterDelay(e,t,n){this.fu(),-1<this.Ru.indexOf(e)&&(t=0);var r=s0.createAndSchedule(this,e,t,n,e=>this.yu(e));return this.Tu.push(r),r}fu(){this.Eu&&vm()}verifyOperationInProgress(){}async wu(){for(var e;await(e=this.mu),e!==this.mu;);}Su(e){for(const t of this.Tu)if(t.timerId===e)return!0;return!1}bu(t){return this.wu().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.wu()})}Du(e){this.Ru.push(e)}yu(e){var t=this.Tu.indexOf(e);this.Tu.splice(t,1)}}function xE(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 OE{constructor(){this._progressObserver={},this._taskCompletionResolver=new bm,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 LE,ME,FE,UE;class VE extends EE{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new DE,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){var e;this._firestoreClient&&(e=this._firestoreClient.terminate(),this._queue=new DE(e),this._firestoreClient=void 0,await e)}}function qE(e){if(e._terminated)throw new wm(ym.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||jE(e),e._firestoreClient}function jE(e){var t,n,r,i,s,a,o=e._freezeSettings(),c=(r=e._databaseId,i=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",s=e._persistenceKey,a=o,new h_(r,i,s,a.host,a.ssl,a.experimentalForceLongPolling,a.experimentalAutoDetectLongPolling,fE(a.experimentalLongPollingOptions),a.useFetchStreams));e._componentsProvider||null!==(t=o.localCache)&&void 0!==t&&t._offlineComponentProvider&&null!==(n=o.localCache)&&void 0!==n&&n._onlineComponentProvider&&(e._componentsProvider={_offline:o.localCache._offlineComponentProvider,_online:o.localCache._onlineComponentProvider}),e._firestoreClient=new tE(e._authCredentials,e._appCheckCredentials,e._queue,c,e._componentsProvider&&(e=e._componentsProvider,c=null==e?void 0:e._online.build(),{_offline:null==e?void 0:e._offline.build(c),_online:c}))}function BE(e,t,n){if((e=bE(e,VE))._firestoreClient||e._terminated)throw new wm(ym.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");if(e._componentsProvider||e._getSettings().localCache)throw new wm(ym.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:t,_offline:n},jE(e)}function zE(e){return function(e){const t=new bm;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;GT(n.remoteStore)||pm("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.ka.get(e)||[];r.push(t),n.ka.set(e,r)}catch(e){const n=a0(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await lE(e),t)),t.promise}(qE(e=bE(e,VE)))}function KE(e){return(n=qE(e=bE(e,VE))).asyncQueue.enqueue(async()=>{const e=await aE(n),t=await cE(n);return e.setNetworkEnabled(!0),function(e){const t=e;return t.L_.delete(0),VT(t)}(t)});var n}function $E(e){return(n=qE(e=bE(e,VE))).asyncQueue.enqueue(async()=>{const e=await aE(n),t=await cE(n);return e.setNetworkEnabled(!1),async function(e){const t=e;t.L_.add(0),await qT(t),t.q_.set("Offline")}(t)});var n}function WE(t,e){return n=qE(t=bE(t,VE)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Gr.getNamedQuery(e,t))}(await oE(n),r)).then(e=>e?new CE(t,null,e.query):null);var n,r}class GE{constructor(e){this._byteString=e}static fromBase64String(e){try{return new GE(r_.fromBase64String(e))}catch(e){throw new wm(ym.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new GE(r_.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 HE{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new wm(ym.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Vm(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class QE{constructor(e){this._methodName=e}}class YE{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new wm(ym.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new wm(ym.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 Pm(this._lat,e._lat)||Pm(this._long,e._long)}}class JE{constructor(e){this._values=(e||[]).map(e=>e)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}(this._values,e._values)}}const XE=/^__.*__$/;class ZE{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new sw(e,this.data,this.fieldMask,t,this.fieldTransforms):new iw(e,this.data,t,this.fieldTransforms)}}class eC{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new sw(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function tC(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw vm()}}class nC{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.vu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Cu(){return this.settings.Cu}Fu(e){return new nC(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Mu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Fu({path:n,xu:!1});return r.Ou(e),r}Nu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Fu({path:n,xu:!1});return r.vu(),r}Lu(e){return this.Fu({path:void 0,xu:!0})}Bu(e){return IC(e,this.settings.methodName,this.settings.ku||!1,this.path,this.settings.qu)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}vu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Ou(this.path.get(e))}Ou(e){if(0===e.length)throw this.Bu("Document fields must not be empty");if(tC(this.Cu)&&XE.test(e))throw this.Bu('Document fields cannot begin and end with "__"')}}class rC{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||PT(e)}Qu(e,t,n,r=!1){return new nC({Cu:e,methodName:t,qu:n,path:Vm.emptyPath(),xu:!1,ku:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function iC(e){var t=e._freezeSettings(),n=PT(e._databaseId);return new rC(e._databaseId,!!t.ignoreUndefinedProperties,n)}function sC(e,t,n,r,i,s={}){const a=e.Qu(s.merge||s.mergeFields?2:0,t,n,i);_C("Data must be an object, but it was:",a,r);var o=mC(r,a);let c,l;if(s.merge)c=new t_(a.fieldMask),l=a.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=yC(t,r,n);if(!a.contains(i))throw new wm(ym.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);TC(e,i)||e.push(i)}c=new t_(e),l=a.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=a.fieldTransforms;return new ZE(new O_(o),c,l)}class aC extends QE{_toFieldTransform(e){if(2!==e.Cu)throw 1===e.Cu?e.Bu(`${this._methodName}() can only appear at the top level of your update data`):e.Bu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof aC}}function oC(e,t,n){return new nC({Cu:3,qu:t.settings.qu,methodName:e._methodName,xu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class cC extends QE{_toFieldTransform(e){return new Qy(e.path,new jy)}isEqual(e){return e instanceof cC}}class lC extends QE{constructor(e,t){super(e),this.Ku=t}_toFieldTransform(e){const t=oC(this,e,!0),n=this.Ku.map(e=>gC(e,t)),r=new By(n);return new Qy(e.path,r)}isEqual(e){return e instanceof lC&&z(this.Ku,e.Ku)}}class uC extends QE{constructor(e,t){super(e),this.Ku=t}_toFieldTransform(e){const t=oC(this,e,!0),n=this.Ku.map(e=>gC(e,t)),r=new Ky(n);return new Qy(e.path,r)}isEqual(e){return e instanceof uC&&z(this.Ku,e.Ku)}}class hC extends QE{constructor(e,t){super(e),this.$u=t}_toFieldTransform(e){var t=new Wy(e.serializer,Uy(e.serializer,this.$u));return new Qy(e.path,t)}isEqual(e){return e instanceof hC&&this.$u===e.$u}}function dC(e,i,s,t){const a=e.Qu(1,i,s);_C("Data must be an object, but it was:",a,t);const o=[],c=O_.empty();Gv(t,(e,t)=>{var n=bC(i,e,s);t=le(t);var r=a.Nu(n);if(t instanceof aC)o.push(n);else{const e=gC(t,r);null!=e&&(o.push(n),c.set(n,e))}});var n=new t_(o);return new eC(c,n,a.fieldTransforms)}function pC(e,t,n,r,i,s){const a=e.Qu(1,t,n),o=[yC(t,r,n)],c=[i];if(s.length%2!=0)throw new wm(ym.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(yC(t,s[p])),c.push(s[p+1]);const l=[],u=O_.empty();for(let f=o.length-1;0<=f;--f)if(!TC(l,o[f])){const t=o[f];var h=le(h=c[f]);const r=a.Nu(t);if(h instanceof aC)l.push(t);else{const e=gC(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new t_(l);return new eC(u,d,a.fieldTransforms)}function fC(e,t,n,r=!1){return gC(n,e.Qu(r?4:3,t))}function gC(e,t){if(vC(e=le(e)))return _C("Unsupported field value:",t,e),mC(e,t);if(e instanceof QE)return function(e,t){if(!tC(t.Cu))throw t.Bu(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Bu(`${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.xu&&4!==t.Cu)throw t.Bu("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=gC(i,t.Lu(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=le(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return Uy(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=Om.fromDate(e);return{timestampValue:Fw(t.serializer,n)}}if(e instanceof Om){n=new Om(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:Fw(t.serializer,n)}}if(e instanceof YE)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof GE)return{bytesValue:Uw(t.serializer,e._byteString)};if(e instanceof SE){const i=t.databaseId,s=e.firestore._databaseId;if(!s.isEqual(i))throw t.Bu(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${i.projectId}/${i.database}`);return{referenceValue:qw(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof JE)return r=t,{mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw r.Bu("VectorValues must only contain numeric values.");return My(r.serializer,e)})}}}}};var r;throw t.Bu(`Unsupported field value: ${wE(e)}`)}(e,t)}function mC(e,r){const i={};return Hv(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):Gv(e,(e,t)=>{var n=gC(t,r.Mu(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function vC(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Om||e instanceof YE||e instanceof GE||e instanceof SE||e instanceof QE||e instanceof JE)}function _C(e,t,n){if(!vC(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=wE(n);throw"an object"===r?t.Bu(e+" a custom object"):t.Bu(e+" "+r)}var i}function yC(e,t,n){if((t=le(t))instanceof HE)return t._internalPath;if("string"==typeof t)return bC(e,t);throw IC("Field path arguments must be of type string or ",e,!1,void 0,n)}const wC=new RegExp("[~\\*/\\[\\]]");function bC(t,n,r){if(0<=n.search(wC))throw IC(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new HE(...n.split("."))._internalPath}catch(e){throw IC(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function IC(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 wm(ym.INVALID_ARGUMENT,o+e+c)}function TC(e,t){return e.some(e=>e.isEqual(t))}class EC{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 SE(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new CC(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(SC("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class CC extends EC{data(){return super.data()}}function SC(e,t){return"string"==typeof t?bC(e,t):(t instanceof HE?t:t._delegate)._internalPath}function kC(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new wm(ym.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class AC{}class NC extends AC{}function RC(e,t,...n){let r=[];t instanceof AC&&r.push(t),r=r.concat(n),function(e){var t=e.filter(e=>e instanceof DC).length,n=e.filter(e=>e instanceof PC).length;if(1<t||0<t&&0<n)throw new wm(ym.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 PC extends NC{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new PC(e,t,n)}_apply(e){var t=this._parse(e);return qC(e._query,t),new CE(e.firestore,e.converter,_y(e._query,t))}_parse(e){var t=iC(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 wm(ym.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){VC(a,s);const t=[];for(const n of a)t.push(UC(r,e,n));o={arrayValue:{values:t}}}else o=UC(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||VC(a,s),o=fC(n,t,a,"in"===s||"not-in"===s);return j_.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}class DC extends AC{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new DC(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]:B_.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())qC(n,e),n=_y(n,e)}(e._query,t),new CE(e.firestore,e.converter,_y(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class xC extends NC{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new xC(e,t)}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new wm(ym.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new wm(ym.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new V_(t,n)}(e._query,this._field,this._direction);return new CE(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new hy(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class OC extends NC{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new OC(e,t,n)}_apply(e){return new CE(e.firestore,e.converter,yy(e._query,this._limit,this._limitType))}}class LC extends NC{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new LC(e,t,n)}_apply(e){var t,n=FC(e,this.type,this._docOrFields,this._inclusive);return new CE(e.firestore,e.converter,(t=e._query,e=n,new hy(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class MC extends NC{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new MC(e,t,n)}_apply(e){var t,n=FC(e,this.type,this._docOrFields,this._inclusive);return new CE(e.firestore,e.converter,(t=e._query,e=n,new hy(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function FC(e,t,n,r){if(n[0]=le(n[0]),n[0]instanceof EC)return function(e,t,n,r,i){if(!r)throw new wm(ym.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of my(e))if(n.field.isKeyField())s.push(I_(t,r.key));else{const e=r.data.field(n.field);if(c_(e))throw new wm(ym.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 wm(ym.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 M_(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=iC(e.firestore);return function(e,t,n,r,i,s){const a=e.explicitOrderBy;if(i.length>a.length)throw new wm(ym.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 wm(ym.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!gy(e)&&-1!==l.indexOf("/"))throw new wm(ym.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(Fm.fromString(l));if(!qm.isDocumentKey(n))throw new wm(ym.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 qm(n);o.push(I_(t,i))}else{const e=fC(n,r,l);o.push(e)}}return new M_(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function UC(e,t,n){if("string"==typeof(n=le(n))){if(""===n)throw new wm(ym.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!gy(t)&&-1!==n.indexOf("/"))throw new wm(ym.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(Fm.fromString(n));if(!qm.isDocumentKey(r))throw new wm(ym.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 I_(e,new qm(r))}if(n instanceof SE)return I_(e,n._key);throw new wm(ym.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${wE(n)}.`)}function VC(e,t){if(!Array.isArray(e)||0===e.length)throw new wm(ym.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function qC(e,t){const n=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!==n)throw n===t.op?new wm(ym.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new wm(ym.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}class jC{convertValue(e,t="none"){switch(g_(e)){case 0:return null;case 1:return e.booleanValue;case 2:return a_(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(o_(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw vm()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,n="none"){const r={};return Gv(e,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertVectorValue(e){var t=null===(t=null===(t=null===(t=e.fields)||void 0===t?void 0:t.value.arrayValue)||void 0===t?void 0:t.values)||void 0===t?void 0:t.map(e=>a_(e.doubleValue));return new JE(t)}convertGeoPoint(e){return new YE(a_(e.latitude),a_(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=l_(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(u_(e));default:return null}}convertTimestamp(e){var t=s_(e);return new Om(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=Fm.fromString(e);_m(ab(n));const r=new d_(n.get(1),n.get(3)),i=new qm(n.popFirst(5));return r.isEqual(t)||fm(`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 BC(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class zC extends jC{constructor(e){super(),this.firestore=e}convertBytes(e){return new GE(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new SE(this.firestore,null,t)}}class KC{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class $C extends EC{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 WC(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(SC("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class WC extends $C{data(e={}){return super.data(e)}}class GC{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new KC(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 WC(this._firestore,this._userDataWriter,e.key,e,new KC(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 wm(ym.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 WC(s._firestore,s._userDataWriter,e.doc.key,e.doc,new KC(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 WC(s._firestore,s._userDataWriter,e.doc.key,e.doc,new KC(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 vm()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function HC(e,t){return e instanceof $C&&t instanceof $C?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 GC&&t instanceof GC&&e._firestore===t._firestore&&PE(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}class QC extends jC{constructor(e){super(),this.firestore=e}convertBytes(e){return new GE(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new SE(this.firestore,null,t)}}function YC(t){t=bE(t,SE);const n=bE(t.firestore,VE),e=qE(n),r=new QC(n);return function(e,t){const n=new bm;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 wm(ym.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=a0(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await oE(e),t,n)),n.promise}(e,t._key).then(e=>new $C(n,r,t._key,e,new KC(null!==e&&e.hasLocalMutations,!0),t.converter))}function JC(t){t=bE(t,CE);const n=bE(t.firestore,VE),e=qE(n),r=new QC(n);return function(e,t){const n=new bm;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await oT(e,t,!0),s=new T0(t,i.Ts),a=s.ma(i.documents),o=s.applyChanges(a,!1);n.resolve(o.snapshot)}catch(e){var r=a0(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await oE(e),t,n)),n.promise}(e,t._query).then(e=>new GC(n,r,t,e))}function XC(e,t,n){e=bE(e,SE);var r=bE(e.firestore,VE),i=BC(e.converter,t,n);return nS(r,[sC(iC(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Jy.none())])}function ZC(e,t,n,...r){e=bE(e,SE);var i=bE(e.firestore,VE),s=iC(i);let a;return a="string"==typeof(t=le(t))||t instanceof HE?pC(s,"updateDoc",e._key,t,n,r):dC(s,"updateDoc",e._key,t),nS(i,[a.toMutation(e._key,Jy.exists(!0))])}function eS(t,...n){var e;t=le(t);let r={includeMetadataChanges:!1,source:"default"},i=0;"object"!=typeof n[i]||xE(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges,source:r.source};if(xE(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 SE)o=bE(t.firestore,VE),c=py(t._key.path),a={next:e=>{n[i]&&n[i](rS(o,t,e))},error:n[i+1],complete:n[i+2]};else{const l=bE(t,CE);o=bE(l.firestore,VE),c=l._query;const u=new QC(o);a={next:e=>{n[i]&&n[i](new GC(o,u,l,e))},error:n[i+1],complete:n[i+2]},kC(t._query)}return function(e,t,n,r){const i=new J0(r),s=new m0(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>p0(await uE(e),s)),()=>{i.Za(),e.asyncQueue.enqueueAndForget(async()=>f0(await uE(e),s))}}(qE(o),c,s,a)}function tS(e,t){return function(e,t){const n=new J0(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Y_.add(t),t.next()}(await uE(e),n)),()=>{n.Za(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.Y_.delete(t)}(await uE(e),n))}}(qE(e=bE(e,VE)),xE(t)?t:{next:t})}function nS(e,t){return function(e,t){const n=new bm;return e.asyncQueue.enqueueAndForget(async()=>N0(await lE(e),t,n)),n.promise}(qE(e),t)}function rS(e,t,n){var r=n.docs.get(t._key),i=new QC(e);return new $C(e,i,t._key,r,new KC(n.hasPendingWrites,n.fromCache),t.converter)}const iS={maxAttempts:5};class sS{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=iC(e)}set(e,t,n){this._verifyNotCommitted();const r=aS(e,this._firestore),i=BC(r.converter,t,n),s=sC(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,Jy.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=aS(e,this._firestore);let s;return s="string"==typeof(t=le(t))||t instanceof HE?pC(this._dataReader,"WriteBatch.update",i._key,t,n,r):dC(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Jy.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=aS(e,this._firestore);return this._mutations=this._mutations.concat(new lw(t._key,Jy.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 wm(ym.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function aS(e,t){if((e=le(e)).firestore!==t)throw new wm(ym.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class oS extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=iC(e)}get(e){const n=aS(e,this._firestore),r=new zC(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return vm();const t=e[0];if(t.isFoundDocument())return new EC(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new EC(this._firestore,r,n._key,null,n.converter);throw vm()})}set(e,t,n){var r=aS(e,this._firestore),i=BC(r.converter,t,n),i=sC(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=aS(e,this._firestore),s="string"==typeof(t=le(t))||t instanceof HE?pC(this._dataReader,"Transaction.update",i._key,t,n,r):dC(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=aS(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=aS(e,this._firestore),n=new QC(this._firestore);return super.get(e).then(e=>new $C(this._firestore,n,t._key,e._document,new KC(!1,!1),t.converter))}}function cS(t,n,e){t=bE(t,VE);var r=Object.assign(Object.assign({},iS),e);return function(e){if(e.maxAttempts<1)throw new wm(ym.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(t,n,r){const i=new bm;return t.asyncQueue.enqueueAndForget(async()=>{var e=await sE(t).then(e=>e.datastore);new eE(t.asyncQueue,e,r,n,i).au()}),i.promise}(qE(t),e=>n(new oS(t,e)),r)}LE=!0,St=it,um=St,Je(new ue("firestore",(e,{instanceIdentifier:t,options:n})=>{const r=e.getProvider("app").getImmediate(),i=new VE(new Cm(e.getProvider("auth-internal")),new Nm(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new wm(ym.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new d_(e.options.projectId,t)}(r,t),r);return n=Object.assign({useFetchStreams:LE},n),i._setSettings(n),i},"PUBLIC").setMultipleInstances(!0)),ct(cm,"4.7.4",QS),ct(cm,"4.7.4","esm2017");function lS(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new wm("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function uS(){if("undefined"==typeof Uint8Array)throw new wm("unimplemented","Uint8Arrays are not available in this environment.")}function hS(){if("undefined"==typeof atob)throw new wm("unimplemented","Blobs are unavailable in Firestore in this environment.")}class dS{constructor(e){this._delegate=e}static fromBase64String(e){return hS(),new dS(GE.fromBase64String(e))}static fromUint8Array(e){return uS(),new dS(GE.fromUint8Array(e))}toBase64(){return hS(),this._delegate.toBase64()}toUint8Array(){return uS(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function pS(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 fS{enableIndexedDbPersistence(e,t){return function(e,t){gm("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const n=e._freezeSettings();return BE(e,Q0.provider,{build:e=>new G0(e,n.cacheSizeBytes,null==t?void 0:t.forceOwnership)}),Promise.resolve()}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return async function(e){gm("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const t=e._freezeSettings();BE(e,Q0.provider,{build:e=>new H0(e,t.cacheSizeBytes)})}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new wm(ym.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new bm;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!tv.D())return Promise.resolve();var t=e+"main";await tv.delete(t)}(QI(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class gS{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof d_||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||gm("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=bE(n,EE))._getSettings(),a=`${e}:${t}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&gm("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=lm.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 wm(ym.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new lm(s)}n._authCredentials=new Em(new Im(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return KE(this._delegate)}disableNetwork(){return $E(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,vE("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 zE(this._delegate)}onSnapshotsInSync(e){return tS(this._delegate,e)}get app(){if(!this._appCompat)throw new wm("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new NS(this,AE(this._delegate,e))}catch(e){throw bS(e,"collection()","Firestore.collection()")}}doc(e){try{return new wS(this,NE(this._delegate,e))}catch(e){throw bS(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new SS(this,function(e,t){if(e=bE(e,EE),mE("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new wm(ym.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new CE(e,null,(t=t,new hy(Fm.emptyPath(),t)))}(this._delegate,e))}catch(e){throw bS(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return cS(this._delegate,e=>t(new vS(this,e)))}batch(){return qE(this._delegate),new _S(new sS(this._delegate,e=>nS(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=qE(t=bE(t,VE)),r=new OE,pE(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return WE(this._delegate,e).then(e=>e?new SS(this,e):null)}}class mS extends jC{constructor(e){super(),this.firestore=e}convertBytes(e){return new dS(new GE(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return wS.forKey(t,this.firestore,null)}}class vS{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new mS(e)}get(e){const t=RS(e);return this._delegate.get(t).then(e=>new ES(this._firestore,new $C(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=RS(e);return n?(lS("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=RS(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=RS(e);return this._delegate.delete(t),this}}class _S{constructor(e){this._delegate=e}set(e,t,n){var r=RS(e);return n?(lS("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=RS(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=RS(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class yS{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new WC(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new CS(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=yS.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new yS(e,new mS(e),t),r.set(t,i)),i}}yS.INSTANCES=new WeakMap;class wS{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new mS(e)}static forPath(e,t,n){if(e.length%2!=0)throw new wm("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new wS(t,new SE(t._delegate,n,new qm(e)))}static forKey(e,t,n){return new wS(t,new SE(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new NS(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new NS(this.firestore,AE(this._delegate,e))}catch(e){throw bS(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=le(e))instanceof SE&&RE(this._delegate,e)}set(e,t){t=lS("DocumentReference.set",t);try{return t?XC(this._delegate,e,t):XC(this._delegate,e)}catch(e){throw bS(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?ZC(this._delegate,e):ZC(this._delegate,e,t,...n)}catch(e){throw bS(e,"updateDoc()","DocumentReference.update()")}}delete(){return nS(bE((e=this._delegate).firestore,VE),[new lw(e._key,Jy.none())]);var e}onSnapshot(...e){var t=IS(e),n=TS(e,e=>new ES(this.firestore,new $C(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return eS(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?YC:"server"===(null==e?void 0:e.source)?function(t){t=bE(t,SE);const n=bE(t.firestore,VE);return hE(qE(n),t._key,{source:"server"}).then(e=>rS(n,t,e))}:function(t){t=bE(t,SE);const n=bE(t.firestore,VE);return hE(qE(n),t._key).then(e=>rS(n,t,e))})(this._delegate),t.then(e=>new ES(this.firestore,new $C(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new wS(this.firestore,e?this._delegate.withConverter(yS.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function bS(e,t,n){return e.message=e.message.replace(t,n),e}function IS(e){for(const t of e)if("object"==typeof t&&!pS(t))return t;return{}}function TS(e,t){var n;let r;return r=pS(e[0])?e[0]:pS(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 ES{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new wS(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 HC(this._delegate,e._delegate)}}class CS extends ES{data(e){var t=this._delegate.data(e);return this._delegate._converter||void 0!==t||vm(),t}}class SS{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new mS(e)}where(e,t,n){try{return new SS(this.firestore,RC(this._delegate,(r=n,i=t,s=SC("where",e),PC._create(s,i,r))))}catch(e){throw bS(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new SS(this.firestore,RC(this._delegate,([n,r="asc"]=[e,t],i=r,s=SC("orderBy",n),xC._create(s,i))))}catch(e){throw bS(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new SS(this.firestore,RC(this._delegate,(IE("limit",t=e),OC._create("limit",t,"F"))))}catch(e){throw bS(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new SS(this.firestore,RC(this._delegate,(IE("limitToLast",t=e),OC._create("limitToLast",t,"L"))))}catch(e){throw bS(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new SS(this.firestore,RC(this._delegate,function(...e){return LC._create("startAt",e,!0)}(...e)))}catch(e){throw bS(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new SS(this.firestore,RC(this._delegate,function(...e){return LC._create("startAfter",e,!1)}(...e)))}catch(e){throw bS(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new SS(this.firestore,RC(this._delegate,function(...e){return MC._create("endBefore",e,!1)}(...e)))}catch(e){throw bS(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new SS(this.firestore,RC(this._delegate,function(...e){return MC._create("endAt",e,!0)}(...e)))}catch(e){throw bS(e,"endAt()","Query.endAt()")}}isEqual(e){return PE(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?JC:"server"===(null==e?void 0:e.source)?function(t){t=bE(t,CE);const n=bE(t.firestore,VE),e=qE(n),r=new QC(n);return dE(e,t._query,{source:"server"}).then(e=>new GC(n,r,t,e))}:function(t){t=bE(t,CE);const n=bE(t.firestore,VE),e=qE(n),r=new QC(n);return kC(t._query),dE(e,t._query).then(e=>new GC(n,r,t,e))})(this._delegate),t.then(e=>new AS(this.firestore,new GC(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=IS(e),n=TS(e,e=>new AS(this.firestore,new GC(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return eS(this._delegate,t,n)}withConverter(e){return new SS(this.firestore,e?this._delegate.withConverter(yS.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class kS{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new CS(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class AS{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new SS(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 CS(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new kS(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new CS(this._firestore,e))})}isEqual(e){return HC(this._delegate,e._delegate)}}class NS extends SS{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 wS(this.firestore,e):null}doc(e){try{return void 0===e?new wS(this.firestore,NE(this._delegate)):new wS(this.firestore,NE(this._delegate,e))}catch(e){throw bS(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=bE(e.firestore,VE),r=NE(e),i=BC(e.converter,t);return nS(n,[sC(iC(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,Jy.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new wS(this.firestore,e))}isEqual(e){return RE(this._delegate,e._delegate)}withConverter(e){return new NS(this.firestore,e?this._delegate.withConverter(yS.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function RS(e){return bE(e,SE)}const PS={Firestore:gS,GeoPoint:YE,Timestamp:Om,Blob:dS,Transaction:vS,WriteBatch:_S,DocumentReference:wS,DocumentSnapshot:ES,Query:SS,QueryDocumentSnapshot:CS,QuerySnapshot:AS,CollectionReference:NS,FieldPath:class VP{constructor(...e){this._delegate=new HE(...e)}static documentId(){return new VP(Vm.keyField().canonicalString())}isEqual(e){return(e=le(e))instanceof HE&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class qP{constructor(e){this._delegate=e}static serverTimestamp(){const e=new cC("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new qP(e)}static delete(){const e=new aC("deleteField");return e._methodName="FieldValue.delete",new qP(e)}static arrayUnion(...e){const t=function(...e){return new lC("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new qP(t)}static arrayRemove(...e){const t=function(...e){return new uC("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new qP(t)}static increment(e){const t=new hC("increment",e);return t._methodName="FieldValue.increment",new qP(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,hm.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};ME=Nt,FE=(e,t)=>new gS(e,t,new fS),ME.INTERNAL.registerComponent(new ue("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return FE(t,n)},"PUBLIC").setServiceProps(Object.assign({},PS))),ME.registerVersion("@firebase/firestore-compat","0.3.39");const DS="type.googleapis.com/google.protobuf.Int64Value",xS="type.googleapis.com/google.protobuf.UInt64Value";function OS(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function LS(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case DS:case xS: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=>LS(e)):"function"==typeof e||"object"==typeof e?OS(e,e=>LS(e)):e}const MS="functions",FS={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 US extends x{constructor(e,t,n){super(`${MS}/${e}`,t||""),this.details=n,Object.setPrototypeOf(this,US.prototype)}}function VS(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(!FS[e])return new US("internal","internal");n=FS[e],r=e}var a=s.message;"string"==typeof a&&(r=a),i=s.details,void 0!==i&&(i=LS(i))}}catch(e){}return"ok"===n?null:new US(n,r,i)}class qS{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 jS="us-central1";class BS{constructor(e,t,n,r,i=jS){this.app=e,this.emulatorOrigin=null,this.contextProvider=new qS(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var s=new URL(i);this.customDomain=s.origin+("/"===s.pathname?"":s.pathname),this.region=jS}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 zS(i,s,a){return e=>{return t=e,n=a||{},r=(e=i)._url(s),KS(e,r,t,n);var t,n,r}}async function KS(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 OS(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 US("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{r&&clearTimeout(r)}}}(r.timeout||7e4);a=await Promise.race([async function(e,t,n){n["Content-Type"]="application/json";let r;try{r=await fetch(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let i=null;try{i=await r.json()}catch(e){}return{status:r.status,json:i}}(t,i,s),o.promise,e.cancelAllRequests]);if(o.cancel(),!a)throw new US("cancelled","Firebase Functions instance was deleted.");i=VS(a.status,a.json);if(i)throw i;if(!a.json)throw new US("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 US("internal","Response is missing data field.");return{data:LS(c)}}const $S="@firebase/functions";function WS(e,t,n){le(e).emulatorOrigin=`http://${t}:${n}`}function GS(e,t,n){return r=le(e),i=t,s=n,e=>KS(r,i,e,s||{});var r,i,s}Je(new ue(MS,(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 BS(n,r,i,s,t)},"PUBLIC").setMultipleInstances(!0)),ct($S,"0.11.9",UE),ct($S,"0.11.9","esm2017");var HS,QS,YS,JS,XS;class ZS{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return zS(le(this._delegate),e,t)}httpsCallableFromURL(e,t){return GS(this._delegate,e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new x("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new x("functions","Port missing in origin provided to useFunctionsEmulator()");return WS(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return WS(this._delegate,e,t)}}const ek="us-central1",tk=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:ek});return new ZS(n,r)};HS={Functions:ZS},Nt.INTERNAL.registerComponent(new ue("functions-compat",tk,"PUBLIC").setServiceProps(HS).setMultipleInstances(!0)),Nt.registerVersion("@firebase/functions-compat","0.3.15");const nk="/firebase-messaging-sw.js",rk="/firebase-cloud-messaging-push-scope",ik="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",sk="https://fcmregistrations.googleapis.com/v1",ak="google.c.a.c_id",ok="google.c.a.e";function ck(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(QS=bR=bR||{})[QS.DATA_MESSAGE=1]="DATA_MESSAGE",QS[QS.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(Pt=YS=YS||{}).PUSH_RECEIVED="push-received",Pt.NOTIFICATION_CLICKED="notification-clicked";const lk="fcm_token_details_db",uk="fcm_token_object_Store";async function hk(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(lk))return null}let l=null;const e=await xe(lk,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(uk)){const o=r.objectStore(uk);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:ck(s.vapidKey)}}):3===t?(s=a,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:ck(s.auth),p256dh:ck(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:ck(s.vapidKey)}}):4===t&&(a=a,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:ck(a.auth),p256dh:ck(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:ck(a.vapidKey)}}))}}});return e.close(),await Oe(lk),await Oe("fcm_vapid_details_db"),await Oe("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 dk="firebase-messaging-database",pk=1,fk="firebase-messaging-store";let gk=null;function mk(){return gk=gk||xe(dk,pk,{upgrade:(e,t)=>{0===t&&e.createObjectStore(fk)}}),gk}async function vk(e){var t=yk(e);const n=await mk();t=await n.transaction(fk).objectStore(fk).get(t);if(t)return t;t=await hk(e.appConfig.senderId);return t?(await _k(e,t),t):void 0}async function _k(e,t){var n=yk(e);const r=await mk(),i=r.transaction(fk,"readwrite");return await i.objectStore(fk).put(t,n),await i.done,t}function yk({appConfig:e}){return e.appId}const wk=new O("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 bk(e,t){var n={method:"DELETE",headers:await Tk(e)};try{const s=await fetch(`${Ik(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw wk.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw wk.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function Ik({projectId:e}){return`${sk}/projects/${e}/registrations`}async function Tk({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 Ek({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==ik&&(i.web.applicationPubKey=r),i}const Ck=6048e5;async function Sk(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:ck(t.getKey("auth")),p256dh:ck(t.getKey("p256dh"))},c=await vk(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+Ck?async function(e,t){try{var n=await async function(e,t){var n=await Tk(e),r=Ek(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${Ik(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw wk.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw wk.create("token-update-failed",{errorInfo:r})}if(!i.token)throw wk.create("token-update-no-token");return i.token}(e.firebaseDependencies,t),r=Object.assign(Object.assign({},t),{token:n,createTime:Date.now()});return await _k(e.firebaseDependencies,r),n}catch(e){throw e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await bk(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return Ak(e.firebaseDependencies,o)}return Ak(e.firebaseDependencies,o)}async function kk(e){var t=await vk(e.firebaseDependencies);t&&(await bk(e.firebaseDependencies,t.token),await async function(e){var t=yk(e);const n=await mk(),r=n.transaction(fk,"readwrite");await r.objectStore(fk).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function Ak(e,t){var n={token:await async function(e,t){var n=await Tk(e),r=Ek(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(Ik(e.appConfig),r);i=await s.json()}catch(e){throw wk.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw wk.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw wk.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await _k(e,n),n.token}function Nk(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 Rk(e){return wk.create("missing-app-config-values",{valueName:e})}!function(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));n.join("")}("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Pk{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 Rk("App Configuration Object");if(!e.name)throw Rk("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw Rk(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 Dk(e){try{e.swRegistration=await navigator.serviceWorker.register(nk,{scope:rk}),e.swRegistration.update().catch(()=>{})}catch(e){throw wk.create("failed-service-worker-registration",{browserErrorMessage:null==e?void 0:e.message})}}async function xk(e,t){if(!navigator)throw wk.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw wk.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=ik)),await async function(e,t){if(t||e.swRegistration||await Dk(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw wk.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),Sk(e)}async function Ok(e,t,n){var r=function(e){switch(e){case YS.NOTIFICATION_CLICKED:return"notification_open";case YS.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[ak],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 Lk(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===YS.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(Nk(r)):e.onMessageHandler.next(Nk(r))),n=r.data,"object"==typeof(t=n)&&t&&ak in t&&"1"===n[ok]&&await Ok(e,r.messageType,n))}const Mk="@firebase/messaging",Fk="0.12.13",Uk=e=>{const t=new Pk(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>Lk(t,e)),t},Vk=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>xk(t,e)}};function qk(e){return async function(e){if(!navigator)throw wk.create("only-available-in-window");return e.swRegistration||await Dk(e),kk(e)}(e=le(e))}function jk(e,t){return function(e,t){if(!navigator)throw wk.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=le(e),t)}Je(new ue("messaging",Uk,"PUBLIC")),Je(new ue("messaging-internal",Vk,"PRIVATE")),ct(Mk,Fk),ct(Mk,Fk,"esm2017");const Bk="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",zk="https://fcmregistrations.googleapis.com/v1",Kk="FCM_MSG",$k="google.c.a.c_id",Wk=3,Gk=1;function Hk(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(Pt=JS=JS||{})[Pt.DATA_MESSAGE=1]="DATA_MESSAGE",Pt[Pt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(Pt=XS=XS||{}).PUSH_RECEIVED="push-received",Pt.NOTIFICATION_CLICKED="notification-clicked";const Qk="fcm_token_details_db",Yk="fcm_token_object_Store";async function Jk(c){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(Qk))return null}let l=null;const e=await xe(Qk,5,{upgrade:async(e,t,n,r)=>{var i;if(!(t<2)&&e.objectStoreNames.contains(Yk)){const o=r.objectStore(Yk);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:Hk(s.vapidKey)}}):3===t?(s=a,l={token:s.fcmToken,createTime:s.createTime,subscriptionOptions:{auth:Hk(s.auth),p256dh:Hk(s.p256dh),endpoint:s.endpoint,swScope:s.swScope,vapidKey:Hk(s.vapidKey)}}):4===t&&(a=a,l={token:a.fcmToken,createTime:a.createTime,subscriptionOptions:{auth:Hk(a.auth),p256dh:Hk(a.p256dh),endpoint:a.endpoint,swScope:a.swScope,vapidKey:Hk(a.vapidKey)}}))}}});return e.close(),await Oe(Qk),await Oe("fcm_vapid_details_db"),await Oe("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 Xk="firebase-messaging-database",Zk=1,eA="firebase-messaging-store";let tA=null;function nA(){return tA=tA||xe(Xk,Zk,{upgrade:(e,t)=>{0===t&&e.createObjectStore(eA)}}),tA}async function rA(e){var t=sA(e);const n=await nA();t=await n.transaction(eA).objectStore(eA).get(t);if(t)return t;t=await Jk(e.appConfig.senderId);return t?(await iA(e,t),t):void 0}async function iA(e,t){var n=sA(e);const r=await nA(),i=r.transaction(eA,"readwrite");return await i.objectStore(eA).put(t,n),await i.done,t}function sA({appConfig:e}){return e.appId}const aA=new O("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 oA(e,t){var n={method:"DELETE",headers:await lA(e)};try{const s=await fetch(`${cA(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw aA.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw aA.create("token-unsubscribe-failed",{errorInfo:null==e?void 0:e.toString()})}}function cA({projectId:e}){return`${zk}/projects/${e}/registrations`}async function lA({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 uA({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==Bk&&(i.web.applicationPubKey=r),i}async function hA(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:Hk(t.getKey("auth")),p256dh:Hk(t.getKey("p256dh"))},c=await rA(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(e,t){try{var n=await async function(e,t){var n=await lA(e),r=uA(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${cA(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw aA.create("token-update-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw aA.create("token-update-failed",{errorInfo:r})}if(!i.token)throw aA.create("token-update-no-token");return i.token}(e.firebaseDependencies,t),r=Object.assign(Object.assign({},t),{token:n,createTime:Date.now()});return await iA(e.firebaseDependencies,r),n}catch(e){throw e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:o}):c.token;try{await oA(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return pA(e.firebaseDependencies,o)}return pA(e.firebaseDependencies,o)}async function dA(e){var t=await rA(e.firebaseDependencies);t&&(await oA(e.firebaseDependencies,t.token),await async function(e){var t=sA(e);const n=await nA(),r=n.transaction(eA,"readwrite");await r.objectStore(eA).delete(t),await r.done}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function pA(e,t){var n={token:await async function(e,t){var n=await lA(e),r=uA(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(cA(e.appConfig),r);i=await s.json()}catch(e){throw aA.create("token-subscribe-failed",{errorInfo:null==e?void 0:e.toString()})}if(i.error){r=i.error.message;throw aA.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw aA.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await iA(e,n),n.token}async function fA(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=JS.DISPLAY_NOTIFICATION.toString():r.message_type=JS.DATA_MESSAGE.toString();r.sdk_platform=Wk.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=Gk.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,n){const r={};r.event_time_ms=Math.floor(Date.now()).toString(),r.source_extension_json_proto3=JSON.stringify({messaging_client_event:t}),n&&(r.compliance_data=function(e){var t={privacy_context:{prequest:{origin_associated_product_id:e}}};return t}(n));e.logEvents.push(r)}(e,n,t.productId)}async function gA(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 fA(t,n);var r,i,s,a,o=await vA();if(o.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=XS.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={[Kk]: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 mA(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[Kk];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&&$k 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 vA();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=XS.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function vA(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function _A(e){return aA.create("missing-app-config-values",{valueName:e})}!function(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));n.join("")}("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class yA{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 _A("App Configuration Object");if(!e.name)throw _A("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw _A(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 wA=e=>{const t=new yA(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(gA(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await rA(t.firebaseDependencies),await dA(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:Bk,await hA(t)):await dA(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(mA(e))}),t};function bA(e,t){return function(e,t){if(void 0!==self.document)throw aA.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=le(e),t)}Je(new ue("messaging-sw",wA,"PUBLIC"));var IA,TA,EA,CA;class SA{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return xk(e=le(e),t)}(this._delegate,e)}async deleteToken(){return qk(this._delegate)}onMessage(e){return jk(this._delegate,e)}onBackgroundMessage(e){return bA(this._delegate,e)}}const kA=e=>self&&"ServiceWorkerGlobalScope"in self?new SA(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new SA(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),AA={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?R()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&R()&&D()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};Nt.INTERNAL.registerComponent(new ue("messaging-compat",kA,"PUBLIC").setServiceProps(AA)),Nt.registerVersion("@firebase/messaging-compat","0.2.13");const NA="firebasestorage.googleapis.com",RA="storageBucket";class PA extends x{constructor(e,t,n=0){super(DA(e),`Firebase Storage: ${t} (${DA(e)})`),this.status_=n,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,PA.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return DA(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 DA(e){return"storage/"+e}function xA(){return new PA(IA.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function OA(){return new PA(IA.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function LA(){return new PA(IA.CANCELED,"User canceled the upload/download.")}function MA(){return new PA(IA.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function FA(e){return new PA(IA.INVALID_ARGUMENT,e)}function UA(){return new PA(IA.APP_DELETED,"The Firebase app was deleted.")}function VA(e){return new PA(IA.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 qA(e,t){return new PA(IA.INVALID_FORMAT,"String does not match format '"+e+"': "+t)}function jA(e){throw new PA(IA.INTERNAL_ERROR,"Internal error: "+e)}(Rt=IA=IA||{}).UNKNOWN="unknown",Rt.OBJECT_NOT_FOUND="object-not-found",Rt.BUCKET_NOT_FOUND="bucket-not-found",Rt.PROJECT_NOT_FOUND="project-not-found",Rt.QUOTA_EXCEEDED="quota-exceeded",Rt.UNAUTHENTICATED="unauthenticated",Rt.UNAUTHORIZED="unauthorized",Rt.UNAUTHORIZED_APP="unauthorized-app",Rt.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",Rt.INVALID_CHECKSUM="invalid-checksum",Rt.CANCELED="canceled",Rt.INVALID_EVENT_NAME="invalid-event-name",Rt.INVALID_URL="invalid-url",Rt.INVALID_DEFAULT_BUCKET="invalid-default-bucket",Rt.NO_DEFAULT_BUCKET="no-default-bucket",Rt.CANNOT_SLICE_BLOB="cannot-slice-blob",Rt.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",Rt.NO_DOWNLOAD_URL="no-download-url",Rt.INVALID_ARGUMENT="invalid-argument",Rt.INVALID_ARGUMENT_COUNT="invalid-argument-count",Rt.APP_DELETED="app-deleted",Rt.INVALID_ROOT_OPERATION="invalid-root-operation",Rt.INVALID_FORMAT="invalid-format",Rt.INTERNAL_ERROR="internal-error",Rt.UNSUPPORTED_ENVIRONMENT="unsupported-environment";class BA{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=BA.makeFromUrl(t,e)}catch(e){return new BA(t,"")}if(""===n.path)return n;throw t=t,new PA(IA.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===NA?"(?: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 BA(u,e),d.postModify(n);break}}if(null==n)throw t=e,new PA(IA.INVALID_URL,"Invalid URL '"+t+"'.");return n}}class zA{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function KA(e){return"string"==typeof e||e instanceof String}function $A(e){return WA()&&e instanceof Blob}function WA(){return"undefined"!=typeof Blob}function GA(e,t,n,r){if(r<t)throw FA(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw FA(`Invalid value for '${e}'. Expected ${n} or less.`)}function HA(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function QA(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 YA(e,t){var n=500<=e&&e<600,r=-1!==[408,429].indexOf(e),i=-1!==t.indexOf(e);return n||r||i}(Rt=TA=TA||{})[Rt.NO_ERROR=0]="NO_ERROR",Rt[Rt.NETWORK_ERROR=1]="NETWORK_ERROR",Rt[Rt.ABORT=2]="ABORT";class JA{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 XA(!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()===TA.NO_ERROR,t=r.getStatus();!e||YA(t,this.additionalRetryCodes_)&&this.retry?(e=r.getErrorCode()===TA.ABORT,n(!1,new XA(!1,null,e))):(t=-1!==this.successCodes_.indexOf(t),n(!0,new XA(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=xA();o.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,o)):r(o)}else{var a;t.canceled?(a=(this.appDelete_?UA:LA)(),r(a)):(a=OA(),r(a))}};this.canceled_?t(0,new XA(!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 XA{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function ZA(...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(WA())return new Blob(t);throw new PA(IA.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}function eN(e){if("undefined"==typeof atob)throw new PA(IA.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 tN={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class nN{constructor(e,t){this.data=e,this.contentType=t||null}}function rN(e,t){switch(e){case tN.RAW:return new nN(iN(t));case tN.BASE64:case tN.BASE64URL:return new nN(sN(e,t));case tN.DATA_URL:return new nN((n=t,(r=new aN(n)).base64?sN(tN.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw qA(tN.DATA_URL,"Malformed data URL.")}return iN(t)}(r.rest)),(n=t,new aN(n).contentType))}var n,r;throw xA()}function iN(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 sN(t,e){switch(t){case tN.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw qA(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case tN.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw qA(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=eN(e)}catch(e){if(e.message.includes("polyfill"))throw e;throw qA(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 aN{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw qA(tN.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 oN{constructor(e,t){let n=0,r="";$A(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($A(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 oN(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new oN(n,!0)}static getBlob(...e){if(WA()){var t=e.map(e=>e instanceof oN?e.data_:e);return new oN(ZA.apply(null,t))}{const r=e.map(e=>KA(e)?rN(tN.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 oN(i,!0)}}uploadData(){return this.data_}}function cN(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function lN(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function uN(e,t){return t}class hN{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||uN}}let dN=null;function pN(){if(dN)return dN;const e=[];e.push(new hN("bucket")),e.push(new hN("generation")),e.push(new hN("metageneration")),e.push(new hN("name","fullPath",!0));const t=new hN("name");t.xform=function(e,t){return!KA(t=t)||t.length<2?t:lN(t)},e.push(t);const n=new hN("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new hN("timeCreated")),e.push(new hN("updated")),e.push(new hN("md5Hash",null,!0)),e.push(new hN("cacheControl",null,!0)),e.push(new hN("contentDisposition",null,!0)),e.push(new hN("contentEncoding",null,!0)),e.push(new hN("contentLanguage",null,!0)),e.push(new hN("contentType",null,!0)),e.push(new hN("metadata","customMetadata",!0)),dN=e,dN}function fN(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new BA(e,t);return r._makeStorageReference(t)}})}function gN(e,t,n){var r=cN(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 fN(r,e),r}(e,r,n)}function mN(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 vN="prefixes";function _N(e,t,n){var r=cN(n);return null===r?null:function(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n[vN])for(const a of n[vN]){var i=a.replace(/\/$/,""),i=e._makeStorageReference(new BA(t,i));r.prefixes.push(i)}if(n.items)for(const o of n.items){var s=e._makeStorageReference(new BA(t,o.name));r.items.push(s)}return r}(e,t,r)}class yN{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 wN(e){if(!e)throw xA()}function bN(r,i){return function(e,t){var n=gN(r,t,i);return wN(null!==n),n}}function IN(r,i){return function(e,t){var n=_N(r,i,t);return wN(null!==n),n}}function TN(r,i){return function(e,t){var n=gN(r,t,i);return wN(null!==n),function(r,e,i,s){var t=cN(e);if(null===t)return null;if(!KA(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 HA("/b/"+a(t)+"/o/"+a(n),i,s)+QA({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function EN(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new PA(IA.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project."):new PA(IA.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new PA(IA.QUOTA_EXCEEDED,"Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(r=i.path,new PA(IA.UNAUTHORIZED,"User does not have permission to access '"+r+"'.")):t,n.status=e.getStatus(),n.serverResponse=t.serverResponse,n}}function CN(r){const i=EN(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new PA(IA.OBJECT_NOT_FOUND,"Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function SN(e,t,n){var r=HA(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new yN(r,"GET",bN(e,n),i);return s.errorHandler=CN(t),s}function kN(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 AN(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=kN(t,r,i),l="--"+o+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+mN(c,n)+"\r\n--"+o+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",o="\r\n--"+o+"--";const u=oN.getBlob(l,r,o);if(null===u)throw MA();o={name:c.fullPath},c=HA(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new yN(c,"POST",bN(e,n),s);return h.urlParams=o,h.headers=a,h.body=u.uploadData(),h.errorHandler=EN(t),h}class NN{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function RN(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){wN(!1)}const r=t||["active"];return wN(!!n&&-1!==r.indexOf(n)),n}function PN(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),a=kN(t,r,i),o={name:a.fullPath},c=HA(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=mN(a,n),a=e.maxUploadRetryTime;const u=new yN(c,"POST",function(e){RN(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){wN(!1)}return wN(KA(t)),t},a);return u.urlParams=o,u.headers=l,u.body=s,u.errorHandler=EN(t),u}function DN(e,t,n,i){var r=e.maxUploadRetryTime;const s=new yN(n,"POST",function(e){var t=RN(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){wN(!1)}n||wN(!1);var r=Number(n);return wN(!isNaN(r)),new NN(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=EN(t),s}function xN(e,a,t,o,n,c,r,i){const l=new NN(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 PA(IA.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 MA();d=a.maxUploadRetryTime;const g=new yN(t,"POST",function(e,t){var n=RN(e,["active","final"]),r=l.current+u,i=o.size();let s;return s="final"===n?bN(a,c)(e,t):null,new NN(r,i,"final"===n,s)},d);return g.headers=s,g.body=f.uploadData(),g.progressCallback=i||null,g.errorHandler=EN(e),g}const ON={STATE_CHANGED:"state_changed"},LN={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function MN(e){switch(e){case"running":case"pausing":case"canceling":return LN.RUNNING;case"paused":return LN.PAUSED;case"success":return LN.SUCCESS;case"canceled":return LN.CANCELED;default:return LN.ERROR}}class FN{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 UN(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class VN extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=TA.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=TA.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=TA.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw jA("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 jA("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw jA("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw jA("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw jA("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 qN(){return new VN}class jN{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=pN(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(IA.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{var t=this.isExponentialBackoffExpired();if(YA(e.status,[])){if(!t)return this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,void this.completeTransitions_();e=OA()}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(IA.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=PN(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,qN,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=DN(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,qN,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 NN(this._transferred,this._blob.size()),a=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=xN(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,qN,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=SN(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,qN,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=AN(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,qN,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=LA(),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=MN(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 FN(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(MN(this._state)){case LN.SUCCESS:UN(this._resolve.bind(null,this.snapshot))();break;case LN.CANCELED:case LN.ERROR:const t=this._reject;UN(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(MN(this._state)){case LN.RUNNING:case LN.PAUSED:e.next&&UN(e.next.bind(e,this.snapshot))();break;case LN.SUCCESS:e.complete&&UN(e.complete.bind(e))();break;case LN.CANCELED:case LN.ERROR:default:e.error&&UN(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 BN{constructor(e,t){this._service=e,t instanceof BA?this._location=t:this._location=BA.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new BN(e,t)}get root(){var e=new BA(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return lN(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 BA(this._location.bucket,e);return new BN(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw VA(e)}}function zN(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await KN(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 KN(e,t){null!=t&&"number"==typeof t.maxResults&&GA("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=HA(t.bucketOnlyServerUrl(),e.host,e._protocol),o=e.maxOperationRetryTime;const c=new yN(a,"GET",IN(e,t.bucket),o);return c.urlParams=s,c.errorHandler=EN(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,qN)}function $N(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=HA(t.fullServerUrl(),e.host,e._protocol),s=mN(n,r),a=e.maxOperationRetryTime;const o=new yN(i,"PATCH",bN(e,r),a);return o.headers={"Content-Type":"application/json; charset=utf-8"},o.body=s,o.errorHandler=CN(t),o}(e.storage,e._location,t,pN());return e.storage.makeRequestWithTokens(n,qN)}function WN(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=HA(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new yN(r,"GET",TN(e,n),i);return s.errorHandler=CN(t),s}(e.storage,e._location,pN());return e.storage.makeRequestWithTokens(t,qN).then(e=>{if(null===e)throw new PA(IA.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return e})}function GN(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=HA(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new yN(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=CN(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,qN)}function HN(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 BA(e._location.bucket,r);return new BN(e.storage,r)}function QN(e,t){if(e instanceof XN){var n=e;if(null==n._bucket)throw new PA(IA.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+RA+"' property when initializing the app?");n=new BN(n,n._bucket);return null!=t?QN(n,t):n}return void 0!==t?HN(e,t):e}function YN(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof XN)return n=e,r=t,new BN(n,r);throw FA("To use ref(service, url), the first argument must be a Storage instance.")}return QN(e,t);var n,r}function JN(e,t){var n=null==t?void 0:t[RA];return null==n?null:BA.makeFromBucketSpec(n,e)}class XN{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=NA,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?BA.makeFromBucketSpec(r,this._host):JN(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=BA.makeFromBucketSpec(this._url,e):this._bucket=JN(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){GA("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){GA("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 BN(this,e)}_makeRequest(e,t,n,r,i=!0){if(this._deleted)return new zA(UA());{const u=([s,a,o,e,n,r,t=!0]=[e,this._appId,n,r,t,this._firebaseVersion,i],c=QA(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 JA(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 ZN="@firebase/storage";function eR(e,t,n){return e=le(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new jN(e,new oN(t),n)}function tR(e){return function(e){e._throwIfRoot("getMetadata");var t=SN(e.storage,e._location,pN());return e.storage.makeRequestWithTokens(t,qN)}(e=le(e))}function nR(e,t){return YN(e=le(e),t)}function rR(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 iR(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new XN(n,r,i,t,it)}Je(new ue("storage",iR,"PUBLIC").setMultipleInstances(!0)),ct(ZN,"0.13.3",""),ct(ZN,"0.13.3","esm2017");class sR{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 aR{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 sR(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new sR(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new sR(e,this,this._ref)):{next:t.next?e=>t.next(new sR(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 oR{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new cR(e,this._service))}get items(){return this._delegate.items.map(e=>new cR(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class cR{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=HN(this._delegate,e);return new cR(t,this.storage)}get root(){return new cR(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new cR(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new aR(eR(this._delegate,e,t),this)}putString(e,t=tN.RAW,n){this._throwIfRoot("putString");var r=rN(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new aR(new jN(this._delegate,new oN(r.data,!0),i),this)}listAll(){return zN(le(this._delegate)).then(e=>new oR(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,KN(t=le(t),e).then(e=>new oR(e,this.storage));var t}getMetadata(){return tR(this._delegate)}updateMetadata(e){return $N(le(this._delegate),e)}getDownloadURL(){return WN(le(this._delegate))}delete(){return this._throwIfRoot("delete"),GN(le(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw VA(e)}}class lR{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(uR(e))throw FA("ref() expected a child path but got a URL, use refFromURL instead.");return new cR(nR(this._delegate,e),this)}refFromURL(e){if(!uR(e))throw FA("refFromURL() expected a full URL but got a child path, use ref() instead.");try{BA.makeFromUrl(e,this._delegate.host)}catch(e){throw FA("refFromUrl() expected a valid full URL but got an invalid one.")}return new cR(nR(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){rR(this._delegate,e,t,n)}}function uR(e){return/^[A-Za-z]+:\/\//.test(e)}function hR(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new lR(n,r)}EA=Nt,CA={TaskState:LN,TaskEvent:ON,StringFormat:tN,Storage:lR,Reference:cR},EA.INTERNAL.registerComponent(new ue("storage-compat",hR,"PUBLIC").setServiceProps(CA).setMultipleInstances(!0)),EA.registerVersion("@firebase/storage-compat","0.3.13");const dR="@firebase/performance",pR="0.6.10",fR=pR,gR="FB-PERF-TRACE-MEASURE",mR="@firebase/performance/config",vR="@firebase/performance/configexpire";var _R,yR,wR,bR="Performance";const IR=new O("performance",bR,{"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."}),TR=new ye(bR);TR.logLevel=m.INFO;let ER,CR;class SR{constructor(e){if(!(this.window=e))throw IR.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&&D()?!!R()||(TR.info("IndexedDB is not supported by current browser"),!1):(TR.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===ER&&(ER=new SR(CR)),ER}}let kR;function AR(e,t){var n=e.length-t.length;if(n<0||1<n)throw IR.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 NR;class RR{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=AR("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=AR("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===NR&&(NR=new RR),NR}}(Rt=_R=_R||{})[Rt.UNKNOWN=0]="UNKNOWN",Rt[Rt.VISIBLE=1]="VISIBLE",Rt[Rt.HIDDEN=2]="HIDDEN";const PR=["firebase_","google_","ga_"],DR=new RegExp("^[a-zA-Z]\\w*$");function xR(){switch(SR.getInstance().document.visibilityState){case"visible":return _R.VISIBLE;case"hidden":return _R.HIDDEN;default:return _R.UNKNOWN}}function OR(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw IR.create("no app id");return t}const LR="0.0.1",MR={loggingEnabled:!0},FR="FIREBASE_INSTALLATIONS_AUTH";function UR(e,t){var r,i,n=function(){const e=SR.getInstance().localStorage;if(e){var t=e.getItem(vR);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(mR);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?(qR(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 IR.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 IR.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:`${FR} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:OR(r.app),app_version:fR,sdk_version:LR})});return fetch(n).then(e=>{if(e.ok)return e.json();throw IR.create("RC response not ok")})}).catch(()=>{TR.info(VR)}).then(qR).then(e=>function(e){const t=SR.getInstance().localStorage;e&&t&&(t.setItem(mR,JSON.stringify(e)),t.setItem(vR,String(Date.now()+60*RR.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const VR="Could not fetch config, will use default configs";function qR(e){if(!e)return e;const t=RR.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=MR.loggingEnabled,n.fpr_log_source?t.logSource=Number(n.fpr_log_source):MR.logSource&&(t.logSource=MR.logSource),n.fpr_log_endpoint_url?t.logEndPointUrl=n.fpr_log_endpoint_url:MR.logEndPointUrl&&(t.logEndPointUrl=MR.logEndPointUrl),n.fpr_log_transport_key?t.transportKey=n.fpr_log_transport_key:MR.transportKey&&(t.transportKey=MR.transportKey),void 0!==n.fpr_vc_network_request_sampling_rate?t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate):void 0!==MR.networkRequestsSamplingRate&&(t.networkRequestsSamplingRate=MR.networkRequestsSamplingRate),void 0!==n.fpr_vc_trace_sampling_rate?t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate):void 0!==MR.tracesSamplingRate&&(t.tracesSamplingRate=MR.tracesSamplingRate),t.logTraceAfterSampling=jR(t.tracesSamplingRate),t.logNetworkAfterSampling=jR(t.networkRequestsSamplingRate),e}function jR(e){return Math.random()<=e}let BR=1,zR;function KR(e){var t;return BR=2,zR=zR||(t=e,function(){const n=SR.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=>{kR=e}),t}(t.installations)).then(e=>UR(t,e)).then(()=>$R(),()=>$R())),zR}function $R(){BR=3}const WR=1e4,GR=3,HR=1e3;let QR=GR,YR=[],JR=!1;function XR(e){setTimeout(()=>{if(0!==QR)return YR.length?void function(){const e=YR.splice(0,HR),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:RR.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=RR.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||TR.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=WR;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(YR=[...r,...YR],TR.info("Retry transport request later.")),QR=GR,XR(n)})}(n,e).catch(()=>{YR=[...e,...YR],QR--,TR.info(`Tries left: ${QR}.`),XR(WR)})}():XR(WR)},e)}function ZR(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw IR.create("invalid cc log");YR=[...YR,e]}({message:t(...e),eventTime:Date.now()})}}let eP;function tP(e,t){eP=eP||ZR(iP),eP(e,t)}function nP(e){var t=RR.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&SR.getInstance().requiredApisAvailable()&&(e.isAuto&&xR()!==_R.VISIBLE||(3===BR?rP(e):KR(e.performanceController).then(()=>rP(e),()=>rP(e))))}function rP(e){var t;!kR||(t=RR.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>tP(e,1),0)}function iP(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:sP(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:sP(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function sP(e){return{google_app_id:OR(e),app_instance_id:kR,web_app_info:{sdk_version:fR,page_url:SR.getInstance().getUrl(),service_worker_status:null!=(t=SR.getInstance().navigator)&&t.serviceWorker?t.serviceWorker.controller?2:3:1,visibility_state:xR(),effective_connection_type:function(){var e=SR.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 aP=["_fp","_fcp","_fid"];class oP{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=SR.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||`${gR}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw IR.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw IR.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(),nP(this)}record(e,t,n){if(e<=0)throw IR.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw IR.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])));nP(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<aP.indexOf(r))&&r.startsWith("_"))throw IR.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=null!=t?t:0,(n=Math.floor(t))<t&&TR.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)&&(!PR.some(e=>n.startsWith(e))&&!!n.match(DR)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw IR.create("invalid attribute name",{attributeName:e});if(!s)throw IR.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=SR.getInstance().getUrl();if(i){const s=new oP(e,"_wt_"+i,!0);i=Math.floor(1e3*SR.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))),nP(s)}}static createUserTimingTrace(e,t){nP(new oP(e,t,!1,t))}}function cP(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=SR.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=RR.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(()=>tP(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const lP=5e3;function uP(e){kR&&(setTimeout(()=>function(n){const e=SR.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{oP.createOobTrace(n,r,i),t=void 0},lP);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),oP.createOobTrace(n,r,i,e))})}else oP.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=SR.getInstance(),n=e.getEntriesByType("resource");for(const r of n)cP(t,r);e.setupObserver("resource",e=>cP(t,e))}(e),0),setTimeout(()=>function(t){const e=SR.getInstance(),n=e.getEntriesByType("measure");for(const r of n)hP(t,r);e.setupObserver("measure",e=>hP(t,e))}(e),0))}function hP(e,t){const n=t.name;n.substring(0,gR.length)!==gR&&oP.createUserTimingTrace(e,n)}class dP{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),SR.getInstance().requiredApisAvailable()?P().then(e=>{e&&(JR||(XR(5500),JR=!0),KR(this).then(()=>uP(this),()=>uP(this)),this.initialized=!0)}).catch(e=>{TR.info(`Environment doesn't support IndexedDB: ${e}`)}):TR.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){RR.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return RR.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){RR.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return RR.getInstance().dataCollectionEnabled}}const pP="[DEFAULT]";const fP=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==pP)throw IR.create("FB not default");if("undefined"==typeof window)throw IR.create("no window");e=window,CR=e;const i=new dP(n,r);return i._init(t),i};Je(new ue("performance",fP,"PUBLIC")),ct(dR,pR),ct(dR,pR,"esm2017");class gP{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=le(t),new oP(t,e);var t}}function mP(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new gP(t,n)}(yR=Nt).INTERNAL.registerComponent(new ue("performance-compat",mP,"PUBLIC")),yR.registerVersion("@firebase/performance-compat","0.2.10");const vP="@firebase/remote-config";class _P{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const yP=new O("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 wP=["1","true","t","yes","y","on"];class bP{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=wP.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 IP(e){const t=le(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 TP(e){const t=le(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function EP(t){const n=le(t),e=new _P;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 x&&-1!==t.code.indexOf(i)?"throttle":"failure");throw await n._storageCache.setLastFetchStatus(r),e}var i}function CP(n){const e=le(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=SP(n,t),e),{});var t,r}function SP(e,t){const n=le(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 bP("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new bP("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 bP("static"))}class kP{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 AP{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"),yP.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 yP.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 yP.create("fetch-status",{httpStatus:o});return{status:o,eTag:i,config:c}}}class NP{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(yP.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 x&&e.customData){var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}}(e))throw e;r={throttleEndTimeMillis:Date.now()+ce(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class RP{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 PP(e,t){var n=e.target.error||void 0;return yP.create(t,{originalErrorMessage:n&&(null==n?void 0:n.message)})}const DP="app_namespace_store";class xP{constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n(PP(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(DP,{keyPath:"compositeKey"})}}catch(e){n(yP.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([DP],"readonly"),r=e.objectStore(DP);var i=this.createCompositeKey(a);try{const s=r.get(i);s.onerror=e=>{t(PP(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(yP.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([DP],"readwrite"),r=n.objectStore(DP);var i=this.createCompositeKey(a);try{const s=r.put({compositeKey:i,value:o});s.onerror=e=>{t(PP(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(yP.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([DP],"readwrite"),r=n.objectStore(DP);var i=this.createCompositeKey(a);try{const s=r.delete(i);s.onerror=e=>{t(PP(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(yP.create("storage-delete",{originalErrorMessage:null==e?void 0:e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class OP{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 LP(){if(!R())return!1;try{return await P()}catch(e){return!1}}Je(new ue("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw yP.create("registration-window");if(!R())throw yP.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:a}=n.options;if(!i)throw yP.create("registration-project-id");if(!s)throw yP.create("registration-api-key");if(!a)throw yP.create("registration-app-id");t=t||"firebase";const o=new xP(a,n.name,t),c=new OP(o),l=new ye(vP);l.logLevel=m.ERROR;a=new AP(r,it,t,i,s,a),a=new NP(a,o),a=new kP(a,o,c,l),a=new RP(n,a,c,o,l);return TP(a),a},"PUBLIC").setMultipleInstances(!0)),ct(vP,"0.4.10"),ct(vP,"0.4.10","esm2017");class MP{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 IP(this._delegate)}ensureInitialized(){return TP(this._delegate)}fetch(){return EP(this._delegate)}fetchAndActivate(){return async function(e){return await EP(e=le(e)),IP(e)}(this._delegate)}getAll(){return CP(this._delegate)}getBoolean(e){return SP(le(this._delegate),e).asBoolean()}getNumber(e){return SP(le(this._delegate),e).asNumber()}getString(e){return SP(le(this._delegate),e).asString()}getValue(e){return SP(this._delegate,e)}setLogLevel(e){!function(e,t){const n=le(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 FP(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new MP(n,r)}return(wR=Nt).INTERNAL.registerComponent(new ue("remoteConfig-compat",FP,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:LP})),wR.registerVersion("@firebase/remote-config-compat","0.2.10"),console.warn(`
It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.
For the CDN builds, these are available in the following manner
(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):
https://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js
`),Nt.registerVersion("firebase","11.0.1","compat-cdn"),Nt});
//# sourceMappingURL=firebase-compat.js.map