diff --git a/includes/block-utils/index.php b/includes/block-utils/index.php index 0241eb44..9ee6f7bf 100644 --- a/includes/block-utils/index.php +++ b/includes/block-utils/index.php @@ -1,7 +1,6 @@ get_registered($block_name); + $attributes = null; + $attributes = $block->get_attributes(); + $modified_attributes = []; + foreach($attributes as $attr_name => $attr_data) { + if (array_key_exists($attr_name, $given_attributes)) { + $modified_attributes[$attr_name] = $given_attributes[$attr_name]; + } elseif (array_key_exists('default', $attr_data)) { + $modified_attributes[$attr_name] = $attr_data['default']; + } else { + $modified_attributes[$attr_name] = null; + } + } + return $modified_attributes; +} /** * Port of classNames JS library, modernized with PHP 8 features. diff --git a/includes/facets/blocks/facet-template/facet-template.php b/includes/facets/blocks/facet-template/facet-template.php index be9823d2..455fb9f7 100644 --- a/includes/facets/blocks/facet-template/facet-template.php +++ b/includes/facets/blocks/facet-template/facet-template.php @@ -105,10 +105,10 @@ public function render_dropdown_facet($facet, $inner_blocks) { public function render_checkbox_radio_facet($facet, $inner_blocks) { $facet_choices = $facet['choices']; $selected_choices = $facet['selected']; - $field_template = $inner_blocks[0]; + $field_template = $inner_blocks[0]; // The innerblocks should contain the template for how this block should be repeated for each value, or $fact_choices. $content = ''; $expanded_content = ''; - // make sure $selected_choices are first in the $facet_choices array + // make sure $selected_choices are first in the $facet_choices array, for a better user experience $blocks_to_generate = []; foreach ($facet_choices as $choice) { $field = $field_template; @@ -227,7 +227,6 @@ public function render_date_range_facet($facet, $inner_blocks) { } public function render_search_facet($facet, $inner_blocks) { - do_action('qm/debug', print_r($facet, true)); return '

Search Facet Here

'; } diff --git a/includes/facets/blocks/facets-context-provider/src/view.js b/includes/facets/blocks/facets-context-provider/src/view.js index ae7c5ed1..e8dfd247 100644 --- a/includes/facets/blocks/facets-context-provider/src/view.js +++ b/includes/facets/blocks/facets-context-provider/src/view.js @@ -27,7 +27,8 @@ function constructNewUrl(selected = false) { }); // Remove any query args on the current url. const stableUrl = window.location.href.split('?')[0]; - // If our url has /page/x/ in it, we need to remove that, we're sending the user back to the first page. + // If our url has /page/x/ in it, we need to remove that + // we're sending the user back to the first page. const stableUrlClean = stableUrl.replace(/\/page\/\d+\//, '/'); const newUrl = addQueryArgs(stableUrlClean, tmp); // console.log( diff --git a/includes/facets/cache/WIP.md b/includes/facets/cache/WIP.md deleted file mode 100644 index ebe9342c..00000000 --- a/includes/facets/cache/WIP.md +++ /dev/null @@ -1,3 +0,0 @@ -## Facets Cache - -This needs to be reworked for the multisite collapse diff --git a/includes/firebase/build/module.js b/includes/firebase/build/module.js index 1fd925ba..18bc8101 100644 --- a/includes/firebase/build/module.js +++ b/includes/firebase/build/module.js @@ -38,10 +38,13 @@ var __webpack_exports__ = {}; __webpack_require__.d(__webpack_exports__, { yA: () => (/* binding */ _app), j2: () => (/* binding */ _auth), + R4: () => (/* binding */ _confirmPasswordReset), C3: () => (/* binding */ _db), hg: () => (/* binding */ _onAuthStateChanged), + J1: () => (/* binding */ _sendPasswordResetEmail), x9: () => (/* binding */ _signInWithEmailAndPassword), - CI: () => (/* binding */ _signOut) + CI: () => (/* binding */ _signOut), + RE: () => (/* binding */ _verifyPasswordResetCode) }); ;// CONCATENATED MODULE: ./node_modules/@firebase/util/dist/index.esm2017.js @@ -3144,7 +3147,7 @@ function isVersionServiceProvider(provider) { } const name$p = "@firebase/app"; -const version$1 = "0.10.6"; +const version$1 = "0.10.7"; /** * @license @@ -3213,7 +3216,7 @@ const name$2 = "@firebase/vertexai-preview"; const name$1 = "@firebase/firestore-compat"; const index_esm2017_name = "firebase"; -const version = "10.12.3"; +const version = "10.12.4"; /** * @license @@ -4230,7 +4233,7 @@ registerCoreComponents(''); var index_esm_name = "firebase"; -var index_esm_version = "10.12.3"; +var index_esm_version = "10.12.4"; /** * @license @@ -10422,7 +10425,7 @@ async function sendPasswordResetEmail(auth, email, actionCodeSettings) { * @public */ async function confirmPasswordReset(auth, oobCode, newPassword) { - await resetPassword(getModularInstance(auth), { + await resetPassword(index_esm2017_getModularInstance(auth), { oobCode, newPassword }) @@ -10457,7 +10460,7 @@ async function applyActionCode(auth, oobCode) { * @public */ async function checkActionCode(auth, oobCode) { - const authModular = getModularInstance(auth); + const authModular = index_esm2017_getModularInstance(auth); const response = await resetPassword(authModular, { oobCode }); // Email could be empty only if the request type is EMAIL_SIGNIN or // VERIFY_AND_CHANGE_EMAIL. @@ -10508,7 +10511,7 @@ async function checkActionCode(auth, oobCode) { * @public */ async function verifyPasswordResetCode(auth, code) { - const { data } = await checkActionCode(getModularInstance(auth), code); + const { data } = await checkActionCode(index_esm2017_getModularInstance(auth), code); // Email should always be present since a code was sent to it return data.email; } @@ -29400,12 +29403,18 @@ const _auth = getAuth(); const _signInWithEmailAndPassword = signInWithEmailAndPassword; const _onAuthStateChanged = onAuthStateChanged; const _signOut = signOut; +const _sendPasswordResetEmail = sendPasswordResetEmail; +const _confirmPasswordReset = confirmPasswordReset; +const _verifyPasswordResetCode = verifyPasswordResetCode; const _db = getDatabase(); var __webpack_exports__app = __webpack_exports__.yA; var __webpack_exports__auth = __webpack_exports__.j2; +var __webpack_exports__confirmPasswordReset = __webpack_exports__.R4; var __webpack_exports__getDatabase = __webpack_exports__.C3; var __webpack_exports__onAuthStateChanged = __webpack_exports__.hg; +var __webpack_exports__sendPasswordResetEmail = __webpack_exports__.J1; var __webpack_exports__signInWithEmailAndPassword = __webpack_exports__.x9; var __webpack_exports__signOut = __webpack_exports__.CI; -export { __webpack_exports__app as app, __webpack_exports__auth as auth, __webpack_exports__getDatabase as getDatabase, __webpack_exports__onAuthStateChanged as onAuthStateChanged, __webpack_exports__signInWithEmailAndPassword as signInWithEmailAndPassword, __webpack_exports__signOut as signOut }; +var __webpack_exports__verifyPasswordResetCode = __webpack_exports__.RE; +export { __webpack_exports__app as app, __webpack_exports__auth as auth, __webpack_exports__confirmPasswordReset as confirmPasswordReset, __webpack_exports__getDatabase as getDatabase, __webpack_exports__onAuthStateChanged as onAuthStateChanged, __webpack_exports__sendPasswordResetEmail as sendPasswordResetEmail, __webpack_exports__signInWithEmailAndPassword as signInWithEmailAndPassword, __webpack_exports__signOut as signOut, __webpack_exports__verifyPasswordResetCode as verifyPasswordResetCode }; diff --git a/includes/firebase/build/module.min.asset.php b/includes/firebase/build/module.min.asset.php index a38362d5..3a3afc4e 100644 --- a/includes/firebase/build/module.min.asset.php +++ b/includes/firebase/build/module.min.asset.php @@ -1 +1 @@ - array(), 'version' => '7f705e4fa6a2b94b2bd8', 'type' => 'module'); + array(), 'version' => '5d98a9eb029dbeca56fb', 'type' => 'module'); diff --git a/includes/firebase/build/module.min.js b/includes/firebase/build/module.min.js index 3f5b4f2e..7c1607d3 100644 --- a/includes/firebase/build/module.min.js +++ b/includes/firebase/build/module.min.js @@ -1,2 +1,2 @@ -var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})}};e.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),e.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var t={};e.d(t,{yA:()=>Dc,j2:()=>Lc,C3:()=>Uc,hg:()=>xc,x9:()=>Mc,CI:()=>Fc});const n=function(e,t){if(!e)throw i(t)},i=function(e){return new Error("Firebase Database (${JSCORE_VERSION}) INTERNAL ASSERT FAILED: "+e)},s=function(e){const t=[];let n=0;for(let i=0;i>6|192,t[n++]=63&s|128):55296==(64512&s)&&i+1>18|240,t[n++]=s>>12&63|128,t[n++]=s>>6&63|128,t[n++]=63&s|128):(t[n++]=s>>12|224,t[n++]=s>>6&63|128,t[n++]=63&s|128)}return t},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(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let t=0;t>2,h=(3&s)<<4|o>>4;let u=(15&o)<<2|c>>6,d=63&c;a||(d=64,r||(u=64)),i.push(n[l],n[h],n[u],n[d])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(s(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,i=0;for(;n191&&s<224){const r=e[n++];t[i++]=String.fromCharCode((31&s)<<6|63&r)}else if(s>239&&s<365){const r=((7&s)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[i++]=String.fromCharCode(55296+(r>>10)),t[i++]=String.fromCharCode(56320+(1023&r))}else{const r=e[n++],o=e[n++];t[i++]=String.fromCharCode((15&s)<<12|(63&r)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,i=[];for(let t=0;t>4;if(i.push(l),64!==a){const e=r<<4&240|a>>2;if(i.push(e),64!==c){const e=a<<6&192|c;i.push(e)}}}return i},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class o extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const a=function(e){const t=s(e);return r.encodeByteArray(t,!0)},c=function(e){return a(e).replace(/\./g,"")},l=function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function h(e){return u(void 0,e)}function u(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=u(e[n],t[n]));return e}const d=()=>{try{return function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==e.g)return e.g;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&l(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},p=e=>{var t,n;return null===(n=null===(t=d())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]},f=()=>{var e;return null===(e=d())||void 0===e?void 0:e.config},_=e=>{var t;return null===(t=d())||void 0===t?void 0:t[`_${e}`]};class m{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function g(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function v(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(g())}function y(){return"object"==typeof navigator&&"ReactNative"===navigator.product}class w extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,w.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,I.prototype.create)}}class I{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],r=s?function(e,t){return e.replace(b,((e,n)=>{const i=t[n];return null!=i?String(i):`<${n}?>`}))}(s,n):"Error",o=`${this.serviceName}: ${r} (${i}).`;return new w(i,o,n)}}const b=/\{\$([^}]+)}/g;function C(e){return JSON.parse(e)}function T(e){return JSON.stringify(e)}const E=function(e){let t={},n={},i={},s="";try{const r=e.split(".");t=C(l(r[0])||""),n=C(l(r[1])||""),s=r[2],i=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:i,signature:s}};function S(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function k(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function R(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function N(e,t,n){const i={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=t.call(n,e[s],s,e));return i}function P(e,t){if(e===t)return!0;const n=Object.keys(e),i=Object.keys(t);for(const s of n){if(!i.includes(s))return!1;const n=e[s],r=t[s];if(O(n)&&O(r)){if(!P(n,r))return!1}else if(n!==r)return!1}for(const e of i)if(!n.includes(e))return!1;return!0}function O(e){return null!==e&&"object"==typeof e}function A(e){const t=[];for(const[n,i]of Object.entries(e))Array.isArray(i)?i.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(i));return t.length?"&"+t.join("&"):""}function D(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,i]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(i)}})),t}function L(e){const t=e.indexOf("?");if(!t)return"";const n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)}class M{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>>31)}let i,s,r=this.chain_[0],o=this.chain_[1],a=this.chain_[2],c=this.chain_[3],l=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(i=c^o&(a^c),s=1518500249):(i=o^a^c,s=1859775393):e<60?(i=o&a|c&(o|a),s=2400959708):(i=o^a^c,s=3395469782);const t=(r<<5|r>>>27)+i+l+s+n[e]&4294967295;l=c,c=a,a=4294967295&(o<<30|o>>>2),o=r,r=t}this.chain_[0]=this.chain_[0]+r&4294967295,this.chain_[1]=this.chain_[1]+o&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+c&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let i=0;const s=this.buf_;let r=this.inbuf_;for(;i=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let i=24;i>=0;i-=8)e[n]=this.chain_[t]>>i&255,++n;return e}}class x{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,n){let i;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");i=function(e,t){if("object"!=typeof e||null===e)return!1;for(const t of["next","error","complete"])if(t in e&&"function"==typeof e[t])return!0;return!1}(e)?e:{next:e,error:t,complete:n},void 0===i.next&&(i.next=F),void 0===i.error&&(i.error=F),void 0===i.complete&&(i.complete=F);const s=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch(e){}})),this.observers.push(i),s}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t{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 F(){}const U=function(e){let t=0;for(let n=0;n=55296&&i<=56319?(t+=4,n++):t+=3}return t};function j(e){return e&&e._delegate?e._delegate:e}class W{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 q="[DEFAULT]";class V{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new m;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),i=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(i)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(i)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(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:q})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=q){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=q){return this.instances.has(e)}getOptions(e=q){return this.instancesOptions.get(e)||{}}initialize(e={}){const{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`);const i=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(i);return i}onInit(e,t){var n;const i=this.normalizeInstanceIdentifier(t),s=null!==(n=this.onInitCallbacks.get(i))&&void 0!==n?n:new Set;s.add(e),this.onInitCallbacks.set(i,s);const r=this.instances.get(i);return r&&e(r,i),()=>{s.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const i of n)try{i(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:(i=e,i===q?void 0:i),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 i;return n||null}normalizeInstanceIdentifier(e=q){return this.component?this.component.multipleInstances?e:q:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class H{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){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new V(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const z=[];var B;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(B||(B={}));const $={debug:B.DEBUG,verbose:B.VERBOSE,info:B.INFO,warn:B.WARN,error:B.ERROR,silent:B.SILENT},K=B.INFO,G={[B.DEBUG]:"log",[B.VERBOSE]:"log",[B.INFO]:"info",[B.WARN]:"warn",[B.ERROR]:"error"},Y=(e,t,...n)=>{if(tt.some((t=>e instanceof t));let X,Z;const ee=new WeakMap,te=new WeakMap,ne=new WeakMap,ie=new WeakMap,se=new WeakMap;let re={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return te.get(e);if("objectStoreNames"===t)return e.objectStoreNames||ne.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return ae(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function oe(e){return"function"==typeof e?(t=e)!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Z||(Z=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(ce(this),e),ae(ee.get(this))}:function(...e){return ae(t.apply(ce(this),e))}:function(e,...n){const i=t.call(ce(this),e,...n);return ne.set(i,e.sort?e.sort():[e]),ae(i)}:(e instanceof IDBTransaction&&function(e){if(te.has(e))return;const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",r),e.removeEventListener("abort",r)},s=()=>{t(),i()},r=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",s),e.addEventListener("error",r),e.addEventListener("abort",r)}));te.set(e,t)}(e),Q(e,X||(X=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,re):e);var t}function ae(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("success",s),e.removeEventListener("error",r)},s=()=>{t(ae(e.result)),i()},r=()=>{n(e.error),i()};e.addEventListener("success",s),e.addEventListener("error",r)}));return t.then((t=>{t instanceof IDBCursor&&ee.set(t,e)})).catch((()=>{})),se.set(t,e),t}(e);if(ie.has(e))return ie.get(e);const t=oe(e);return t!==e&&(ie.set(e,t),se.set(t,e)),t}const ce=e=>se.get(e),le=["get","getKey","getAll","getAllKeys","count"],he=["put","add","delete","clear"],ue=new Map;function de(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(ue.get(t))return ue.get(t);const n=t.replace(/FromIndex$/,""),i=t!==n,s=he.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!s&&!le.includes(n))return;const r=async function(e,...t){const r=this.transaction(e,s?"readwrite":"readonly");let o=r.store;return i&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),s&&r.done]))[0]};return ue.set(t,r),r}var pe;pe=re,re={...pe,get:(e,t,n)=>de(e,t)||pe.get(e,t,n),has:(e,t)=>!!de(e,t)||pe.has(e,t)};class fe{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null})).filter((e=>e)).join(" ")}}const _e="@firebase/app",me="0.10.6",ge=new J("@firebase/app"),ve="@firebase/app-compat",ye="@firebase/analytics-compat",we="@firebase/analytics",Ie="@firebase/app-check-compat",be="@firebase/app-check",Ce="@firebase/auth",Te="@firebase/auth-compat",Ee="@firebase/database",Se="@firebase/database-compat",ke="@firebase/functions",Re="@firebase/functions-compat",Ne="@firebase/installations",Pe="@firebase/installations-compat",Oe="@firebase/messaging",Ae="@firebase/messaging-compat",De="@firebase/performance",Le="@firebase/performance-compat",Me="@firebase/remote-config",xe="@firebase/remote-config-compat",Fe="@firebase/storage",Ue="@firebase/storage-compat",je="@firebase/firestore",We="@firebase/vertexai-preview",qe="@firebase/firestore-compat",Ve="firebase",He="[DEFAULT]",ze={[_e]:"fire-core",[ve]:"fire-core-compat",[we]:"fire-analytics",[ye]:"fire-analytics-compat",[be]:"fire-app-check",[Ie]:"fire-app-check-compat",[Ce]:"fire-auth",[Te]:"fire-auth-compat",[Ee]:"fire-rtdb",[Se]:"fire-rtdb-compat",[ke]:"fire-fn",[Re]:"fire-fn-compat",[Ne]:"fire-iid",[Pe]:"fire-iid-compat",[Oe]:"fire-fcm",[Ae]:"fire-fcm-compat",[De]:"fire-perf",[Le]:"fire-perf-compat",[Me]:"fire-rc",[xe]:"fire-rc-compat",[Fe]:"fire-gcs",[Ue]:"fire-gcs-compat",[je]:"fire-fst",[qe]:"fire-fst-compat",[We]:"fire-vertex","fire-js":"fire-js",[Ve]:"fire-js-all"},Be=new Map,$e=new Map,Ke=new Map;function Ge(e,t){try{e.container.addComponent(t)}catch(n){ge.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function Ye(e){const t=e.name;if(Ke.has(t))return ge.debug(`There were multiple attempts to register component ${t}.`),!1;Ke.set(t,e);for(const t of Be.values())Ge(t,e);for(const t of $e.values())Ge(t,e);return!0}function Je(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function Qe(e){return void 0!==e.settings}const Xe=new I("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 Ze{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 W("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 Xe.create("app-deleted",{appName:this._name})}}const et="10.12.3";function tt(e,t={}){let n=e;"object"!=typeof t&&(t={name:t});const i=Object.assign({name:He,automaticDataCollectionEnabled:!1},t),s=i.name;if("string"!=typeof s||!s)throw Xe.create("bad-app-name",{appName:String(s)});if(n||(n=f()),!n)throw Xe.create("no-options");const r=Be.get(s);if(r){if(P(n,r.options)&&P(i,r.config))return r;throw Xe.create("duplicate-app",{appName:s})}const o=new H(s);for(const e of Ke.values())o.addComponent(e);const a=new Ze(n,i,o);return Be.set(s,a),a}function nt(e=He){const t=Be.get(e);if(!t&&e===He&&f())return tt();if(!t)throw Xe.create("no-app",{appName:e});return t}function it(e,t,n){var i;let s=null!==(i=ze[e])&&void 0!==i?i:e;n&&(s+=`-${n}`);const r=s.match(/\s|\//),o=t.match(/\s|\//);if(r||o){const e=[`Unable to register library "${s}" with version "${t}":`];return r&&e.push(`library name "${s}" contains illegal characters (whitespace or "/")`),r&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void ge.warn(e.join(" "))}Ye(new W(`${s}-version`,(()=>({library:s,version:t})),"VERSION"))}const st="firebase-heartbeat-database",rt=1,ot="firebase-heartbeat-store";let at=null;function ct(){return at||(at=function(e,t,{blocked:n,upgrade:i,blocking:s,terminated:r}={}){const o=indexedDB.open(e,t),a=ae(o);return i&&o.addEventListener("upgradeneeded",(e=>{i(ae(o.result),e.oldVersion,e.newVersion,ae(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),a.then((e=>{r&&e.addEventListener("close",(()=>r())),s&&e.addEventListener("versionchange",(e=>s(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}(st,rt,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(ot)}catch(e){console.warn(e)}}}).catch((e=>{throw Xe.create("idb-open",{originalErrorMessage:e.message})}))),at}async function lt(e,t){try{const n=(await ct()).transaction(ot,"readwrite"),i=n.objectStore(ot);await i.put(t,ht(e)),await n.done}catch(e){if(e instanceof w)ge.warn(e.message);else{const t=Xe.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});ge.warn(t.message)}}}function ht(e){return`${e.name}!${e.options.appId}`}class ut{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new pt(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){var e,t;const n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=dt();if((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)))&&this._heartbeatsCache.lastSentHeartbeatDate!==i&&!this._heartbeatsCache.heartbeats.some((e=>e.date===i)))return this._heartbeatsCache.heartbeats.push({date:i,agent:n}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){var e;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"";const t=dt(),{heartbeatsToSend:n,unsentEntries:i}=function(e,t=1024){const n=[];let i=e.slice();for(const s of e){const e=n.find((e=>e.agent===s.agent));if(e){if(e.dates.push(s.date),ft(n)>t){e.dates.pop();break}}else if(n.push({agent:s.agent,dates:[s.date]}),ft(n)>t){n.pop();break}i=i.slice(1)}return{heartbeatsToSend:n,unsentEntries:i}}(this._heartbeatsCache.heartbeats),s=c(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}}function dt(){return(new Date).toISOString().substring(0,10)}class pt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!function(){try{return"object"==typeof indexedDB}catch(e){return!1}}()&&new Promise(((e,t)=>{try{let n=!0;const i="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(i);s.onsuccess=()=>{s.result.close(),n||self.indexedDB.deleteDatabase(i),e(!0)},s.onupgradeneeded=()=>{n=!1},s.onerror=()=>{var e;t((null===(e=s.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}})).then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=(await ct()).transaction(ot),n=await t.objectStore(ot).get(ht(e));return await t.done,n}catch(e){if(e instanceof w)ge.warn(e.message);else{const t=Xe.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});ge.warn(t.message)}}}(this.app);return(null==e?void 0:e.heartbeats)?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return lt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return lt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function ft(e){return c(JSON.stringify({version:2,heartbeats:e})).length}function _t(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);snew fe(e)),"PRIVATE")),Ye(new W("heartbeat",(e=>new ut(e)),"PRIVATE")),it(_e,me,""),it(_e,me,"esm2017"),it("fire-js",""),it("firebase","10.12.3","app"),Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const mt=function(){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."}},gt=new I("auth","Firebase",{"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."}),vt=new J("@firebase/auth");function yt(e,...t){vt.logLevel<=B.ERROR&&vt.error(`Auth (${et}): ${e}`,...t)}function wt(e,...t){throw Tt(e,...t)}function It(e,...t){return Tt(e,...t)}function bt(e,t,n){const i=Object.assign(Object.assign({},mt()),{[t]:n});return new I("auth","Firebase",i).create(t,{appName:e.name})}function Ct(e){return bt(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Tt(e,...t){if("string"!=typeof e){const n=t[0],i=[...t.slice(1)];return i[0]&&(i[0].appName=e.name),e._errorFactory.create(n,...i)}return gt.create(e,...t)}function Et(e,t,...n){if(!e)throw Tt(t,...n)}function St(e){const t="INTERNAL ASSERTION FAILED: "+e;throw yt(t),new Error(t)}function kt(e,t){e||St(t)}function Rt(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Nt(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}function Pt(){return!("undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===Nt()||"https:"===Nt()||function(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}()||"connection"in navigator))||navigator.onLine}class Ot{constructor(e,t){this.shortDelay=e,this.longDelay=t,kt(t>e,"Short delay should be less than long delay!"),this.isMobile=v()||y()}get(){return Pt()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function At(e,t){kt(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class Dt{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!=typeof self&&"fetch"in self?self.fetch:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void St("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"undefined"!=typeof self&&"Headers"in self?self.Headers:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void St("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"undefined"!=typeof self&&"Response"in self?self.Response:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void St("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const Lt={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"},Mt=new Ot(3e4,6e4);function xt(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function Ft(e,t,n,i,s={}){return Ut(e,s,(async()=>{let s={},r={};i&&("GET"===t?r=i:s={body:JSON.stringify(i)});const o=A(Object.assign({key:e.config.apiKey},r)).slice(1),a=await e._getAdditionalHeaders();return a["Content-Type"]="application/json",e.languageCode&&(a["X-Firebase-Locale"]=e.languageCode),Dt.fetch()(Wt(e,e.config.apiHost,n,o),Object.assign({method:t,headers:a,referrerPolicy:"no-referrer"},s))}))}async function Ut(e,t,n){e._canInitEmulator=!1;const i=Object.assign(Object.assign({},Lt),t);try{const t=new Vt(e),s=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const r=await s.json();if("needConfirmation"in r)throw Ht(e,"account-exists-with-different-credential",r);if(s.ok&&!("errorMessage"in r))return r;{const t=s.ok?r.errorMessage:r.error.message,[n,o]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw Ht(e,"credential-already-in-use",r);if("EMAIL_EXISTS"===n)throw Ht(e,"email-already-in-use",r);if("USER_DISABLED"===n)throw Ht(e,"user-disabled",r);const a=i[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw bt(e,a,o);wt(e,a)}}catch(t){if(t instanceof w)throw t;wt(e,"network-request-failed",{message:String(t)})}}async function jt(e,t,n,i,s={}){const r=await Ft(e,t,n,i,s);return"mfaPendingCredential"in r&&wt(e,"multi-factor-auth-required",{_serverResponse:r}),r}function Wt(e,t,n,i){const s=`${t}${n}?${i}`;return e.config.emulator?At(e.config,s):`${e.config.apiScheme}://${s}`}function qt(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class Vt{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(It(this.auth,"network-request-failed"))),Mt.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function Ht(e,t,n){const i={appName:e.name};n.email&&(i.email=n.email),n.phoneNumber&&(i.phoneNumber=n.phoneNumber);const s=It(e,t,i);return s.customData._tokenResponse=n,s}function zt(e){return void 0!==e&&void 0!==e.enterprise}class Bt{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 qt(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}}async function $t(e,t){return Ft(e,"POST","/v1/accounts:lookup",t)}function Kt(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Gt(e){return 1e3*Number(e)}function Yt(e){const[t,n,i]=e.split(".");if(void 0===t||void 0===n||void 0===i)return yt("JWT malformed, contained fewer than 3 sections"),null;try{const e=l(n);return e?JSON.parse(e):(yt("Failed to decode base64 JWT payload"),null)}catch(e){return yt("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}function Jt(e){const t=Yt(e);return Et(t,"internal-error"),Et(void 0!==t.exp,"internal-error"),Et(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function Qt(e,t,n=!1){if(n)return t;try{return await t}catch(t){throw t instanceof w&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class Xt{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;const 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 Zt{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Kt(this.lastLoginAt),this.creationTime=Kt(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function en(e){var t;const n=e.auth,i=await e.getIdToken(),s=await Qt(e,$t(n,{idToken:i}));Et(null==s?void 0:s.users.length,n,"internal-error");const r=s.users[0];e._notifyReloadListener(r);const o=(null===(t=r.providerUserInfo)||void 0===t?void 0:t.length)?tn(r.providerUserInfo):[],a=(c=e.providerData,l=o,[...c.filter((e=>!l.some((t=>t.providerId===e.providerId)))),...l]);var c,l;const h=e.isAnonymous,u=!(e.email&&r.passwordHash||(null==a?void 0:a.length)),d=!!h&&u,p={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:a,metadata:new Zt(r.createdAt,r.lastLoginAt),isAnonymous:d};Object.assign(e,p)}function tn(e){return e.map((e=>{var{providerId:t}=e,n=_t(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 nn{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){Et(e.idToken,"internal-error"),Et(void 0!==e.idToken,"internal-error"),Et(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):Jt(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){Et(0!==e.length,"internal-error");const t=Jt(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(Et(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){const{accessToken:n,refreshToken:i,expiresIn:s}=await async function(e,t){const n=await Ut(e,{},(async()=>{const n=A({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:i,apiKey:s}=e.config,r=Wt(e,i,"/v1/token",`key=${s}`),o=await e._getAdditionalHeaders();return o["Content-Type"]="application/x-www-form-urlencoded",Dt.fetch()(r,{method:"POST",headers:o,body:n})}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}(e,t);this.updateTokensAndExpiration(n,i,Number(s))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){const{refreshToken:n,accessToken:i,expirationTime:s}=t,r=new nn;return n&&(Et("string"==typeof n,"internal-error",{appName:e}),r.refreshToken=n),i&&(Et("string"==typeof i,"internal-error",{appName:e}),r.accessToken=i),s&&(Et("number"==typeof s,"internal-error",{appName:e}),r.expirationTime=s),r}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 nn,this.toJSON())}_performRefresh(){return St("not implemented")}}function sn(e,t){Et("string"==typeof e||void 0===e,"internal-error",{appName:t})}class rn{constructor(e){var{uid:t,auth:n,stsTokenManager:i}=e,s=_t(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new Xt(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=i,this.accessToken=i.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new Zt(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const t=await Qt(this,this.stsTokenManager.getToken(this.auth,e));return Et(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=j(e),i=await n.getIdToken(t),s=Yt(i);Et(s&&s.exp&&s.auth_time&&s.iat,n.auth,"internal-error");const r="object"==typeof s.firebase?s.firebase:void 0,o=null==r?void 0:r.sign_in_provider;return{claims:s,token:i,authTime:Kt(Gt(s.auth_time)),issuedAtTime:Kt(Gt(s.iat)),expirationTime:Kt(Gt(s.exp)),signInProvider:o||null,signInSecondFactor:(null==r?void 0:r.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=j(e);await en(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(Et(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 rn(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){Et(!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 en(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Qe(this.auth.app))return Promise.reject(Ct(this.auth));const e=await this.getIdToken();return await Qt(this,async function(e,t){return Ft(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,i,s,r,o,a,c,l;const h=null!==(n=t.displayName)&&void 0!==n?n:void 0,u=null!==(i=t.email)&&void 0!==i?i:void 0,d=null!==(s=t.phoneNumber)&&void 0!==s?s:void 0,p=null!==(r=t.photoURL)&&void 0!==r?r:void 0,f=null!==(o=t.tenantId)&&void 0!==o?o:void 0,_=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,m=null!==(c=t.createdAt)&&void 0!==c?c:void 0,g=null!==(l=t.lastLoginAt)&&void 0!==l?l:void 0,{uid:v,emailVerified:y,isAnonymous:w,providerData:I,stsTokenManager:b}=t;Et(v&&b,e,"internal-error");const C=nn.fromJSON(this.name,b);Et("string"==typeof v,e,"internal-error"),sn(h,e.name),sn(u,e.name),Et("boolean"==typeof y,e,"internal-error"),Et("boolean"==typeof w,e,"internal-error"),sn(d,e.name),sn(p,e.name),sn(f,e.name),sn(_,e.name),sn(m,e.name),sn(g,e.name);const T=new rn({uid:v,auth:e,email:u,emailVerified:y,displayName:h,isAnonymous:w,photoURL:p,phoneNumber:d,tenantId:f,stsTokenManager:C,createdAt:m,lastLoginAt:g});return I&&Array.isArray(I)&&(T.providerData=I.map((e=>Object.assign({},e)))),_&&(T._redirectEventId=_),T}static async _fromIdTokenResponse(e,t,n=!1){const i=new nn;i.updateFromServerResponse(t);const s=new rn({uid:t.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await en(s),s}static async _fromGetAccountInfoResponse(e,t,n){const i=t.users[0];Et(void 0!==i.localId,"internal-error");const s=void 0!==i.providerUserInfo?tn(i.providerUserInfo):[],r=!(i.email&&i.passwordHash||(null==s?void 0:s.length)),o=new nn;o.updateFromIdToken(n);const a=new rn({uid:i.localId,auth:e,stsTokenManager:o,isAnonymous:r}),c={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:s,metadata:new Zt(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash||(null==s?void 0:s.length))};return Object.assign(a,c),a}}const on=new Map;function an(e){kt(e instanceof Function,"Expected a class definition");let t=on.get(e);return t?(kt(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,on.set(e,t),t)}class cn{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}cn.type="NONE";const ln=cn;function hn(e,t,n){return`firebase:${e}:${t}:${n}`}class un{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:i,name:s}=this.auth;this.fullUserKey=hn(this.userKey,i.apiKey,s),this.fullPersistenceKey=hn("persistence",i.apiKey,s),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?rn._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const 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 un(an(ln),e,n);const i=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let s=i[0]||an(ln);const r=hn(n,e.config.apiKey,e.name);let o=null;for(const n of t)try{const t=await n._get(r);if(t){const i=rn._fromJSON(e,t);n!==s&&(o=i),s=n;break}}catch(e){}const a=i.filter((e=>e._shouldAllowMigration));return s._shouldAllowMigration&&a.length?(s=a[0],o&&await s._set(r,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==s)try{await e._remove(r)}catch(e){}}))),new un(s,e,n)):new un(s,e,n)}}function dn(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(gn(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(pn(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(yn(t))return"Blackberry";if(wn(t))return"Webos";if(fn(t))return"Safari";if((t.includes("chrome/")||mn(t))&&!t.includes("edge/"))return"Chrome";if(vn(t))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=e.match(t);if(2===(null==n?void 0:n.length))return n[1]}return"Other"}function pn(e=g()){return/firefox\//i.test(e)}function fn(e=g()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function mn(e=g()){return/crios\//i.test(e)}function gn(e=g()){return/iemobile/i.test(e)}function vn(e=g()){return/android/i.test(e)}function yn(e=g()){return/blackberry/i.test(e)}function wn(e=g()){return/webos/i.test(e)}function In(e=g()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function bn(e=g()){return In(e)||vn(e)||wn(e)||yn(e)||/windows phone/i.test(e)||gn(e)}function Cn(e,t=[]){let n;switch(e){case"Browser":n=dn(g());break;case"Worker":n=`${dn(g())}-${e}`;break;default:n=e}const i=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${et}/${i}`}class Tn{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const n=t=>new Promise(((n,i)=>{try{n(e(t))}catch(e){i(e)}}));n.onAbort=t,this.queue.push(n);const i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){t.reverse();for(const e of t)try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==e?void 0:e.message})}}}class En{constructor(e){var t,n,i,s;const r=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(t=r.minPasswordLength)&&void 0!==t?t:6,r.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=r.maxPasswordLength),void 0!==r.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=r.containsLowercaseCharacter),void 0!==r.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=r.containsUppercaseCharacter),void 0!==r.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=r.containsNumericCharacter),void 0!==r.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=r.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!==(i=null===(n=e.allowedNonAlphanumericCharacters)||void 0===n?void 0:n.join(""))&&void 0!==i?i:"",this.forceUpgradeOnSignin=null!==(s=e.forceUpgradeOnSignin)&&void 0!==s&&s,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,n,i,s,r,o;const a={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,a),this.validatePasswordCharacterOptions(e,a),a.isValid&&(a.isValid=null===(t=a.meetsMinPasswordLength)||void 0===t||t),a.isValid&&(a.isValid=null===(n=a.meetsMaxPasswordLength)||void 0===n||n),a.isValid&&(a.isValid=null===(i=a.containsLowercaseLetter)||void 0===i||i),a.isValid&&(a.isValid=null===(s=a.containsUppercaseLetter)||void 0===s||s),a.isValid&&(a.isValid=null===(r=a.containsNumericCharacter)||void 0===r||r),a.isValid&&(a.isValid=null===(o=a.containsNonAlphanumericCharacter)||void 0===o||o),a}validatePasswordLengthOptions(e,t){const n=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),i&&(t.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,t){let n;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let i=0;i="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,i,s){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=s))}}class Sn{constructor(e,t,n,i){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Rn(this),this.idTokenSubscription=new Rn(this),this.beforeStateQueue=new Tn(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=gt,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=an(t)),this._initializationPromise=this.queue((async()=>{var n,i;if(!this._deleted&&(this.persistenceManager=await un.create(this,e),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(i=this.currentUser)||void 0===i?void 0:i.uid)||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUserFromIdToken(e){try{const t=await $t(this,{idToken:e}),n=await rn._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(n)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){var t;if(Qe(this.app)){const e=this.app.settings.authIdToken;return e?new Promise((t=>{setTimeout((()=>this.initializeCurrentUserFromIdToken(e).then(t,t)))})):this.directlySetCurrentUser(null)}const n=await this.assertedPersistence.getCurrentUser();let i=n,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const n=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,r=null==i?void 0:i._redirectEventId,o=await this.tryRedirectSignIn(e);n&&n!==r||!(null==o?void 0:o.user)||(i=o.user,s=!0)}if(!i)return this.directlySetCurrentUser(null);if(!i._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(i)}catch(e){i=n,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return Et(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}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 en(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;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(Qe(this.app))return Promise.reject(Ct(this));const t=e?j(e):null;return t&&Et(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&&Et(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 Qe(this.app)?Promise.reject(Ct(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Qe(this.app)?Promise.reject(Ct(this)):this.queue((async()=>{await this.assertedPersistence.setPersistence(an(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(){const e=await async function(e,t={}){return Ft(e,"GET","/v2/passwordPolicy",xt(e,t))}(this),t=new En(e);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new I("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser)e();else{const n=this.onAuthStateChanged((()=>{n(),e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await async function(e,t){return Ft(e,"POST","/v2/accounts:revokeToken",xt(e,t))}(this,t)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?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){if(!this.redirectPersistenceManager){const t=e&&an(e)||this._popupRedirectResolver;Et(t,this,"argument-error"),this.redirectPersistenceManager=await un.create(this,[an(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return this._isInitialized&&await this.queue((async()=>{})),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,i){if(this._deleted)return()=>{};const s="function"==typeof t?t:t.next.bind(t);let r=!1;const o=this._isInitialized?Promise.resolve():this._initializationPromise;if(Et(o,this,"internal-error"),o.then((()=>{r||s(this.currentUser)})),"function"==typeof t){const s=e.addObserver(t,n,i);return()=>{r=!0,s()}}{const n=e.addObserver(t);return()=>{r=!0,n()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return Et(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Cn(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);const n=await(null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());n&&(t["X-Firebase-Client"]=n);const i=await this._getAppCheckToken();return i&&(t["X-Firebase-AppCheck"]=i),t}async _getAppCheckToken(){var e;const t=await(null===(e=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getToken());return(null==t?void 0:t.error)&&function(e,...t){vt.logLevel<=B.WARN&&vt.warn(`Auth (${et}): ${e}`,...t)}(`Error while retrieving App Check token: ${t.error}`),null==t?void 0:t.token}}function kn(e){return j(e)}class Rn{constructor(e){this.auth=e,this.observer=null,this.addObserver=function(e,t){const n=new x(e,void 0);return n.subscribe.bind(n)}((e=>this.observer=e))}get next(){return Et(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let Nn={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function Pn(e){return Nn.loadJS(e)}function On(e){return`__${e}${Math.floor(1e6*Math.random())}`}class An{constructor(e){this.type="recaptcha-enterprise",this.auth=kn(e)}async verify(e="verify",t=!1){function n(t,n,i){const s=window.grecaptcha;zt(s)?s.enterprise.ready((()=>{s.enterprise.execute(t,{action:e}).then((e=>{n(e)})).catch((()=>{n("NO_RECAPTCHA")}))})):i(Error("No reCAPTCHA enterprise script loaded."))}return new Promise(((e,i)=>{(async function(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,n)=>{(async function(e,t){return Ft(e,"GET","/v2/recaptchaConfig",xt(e,t))})(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((i=>{if(void 0!==i.recaptchaKey){const n=new Bt(i);return null==e.tenantId?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,t(n.siteKey)}n(new Error("recaptcha Enterprise site key undefined"))})).catch((e=>{n(e)}))}))})(this.auth).then((s=>{if(!t&&zt(window.grecaptcha))n(s,e,i);else{if("undefined"==typeof window)return void i(new Error("RecaptchaVerifier is only supported in browser"));let t=Nn.recaptchaEnterpriseScript;0!==t.length&&(t+=s),Pn(t).then((()=>{n(s,e,i)})).catch((e=>{i(e)}))}})).catch((e=>{i(e)}))}))}}async function Dn(e,t,n,i=!1){const s=new An(e);let r;try{r=await s.verify(n)}catch(e){r=await s.verify(n,!0)}const o=Object.assign({},t);return i?Object.assign(o,{captchaResp:r}):Object.assign(o,{captchaResponse:r}),Object.assign(o,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(o,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),o}async function Ln(e,t,n,i){var s;if(null===(s=e._getRecaptchaConfig())||void 0===s?void 0:s.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const s=await Dn(e,t,n,"getOobCode"===n);return i(e,s)}return i(e,t).catch((async s=>{if("auth/missing-recaptcha-token"===s.code){console.log(`${n} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const s=await Dn(e,t,n,"getOobCode"===n);return i(e,s)}return Promise.reject(s)}))}function Mn(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function xn(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}class Fn{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return St("not implemented")}_getIdTokenResponse(e){return St("not implemented")}_linkToIdToken(e,t){return St("not implemented")}_getReauthenticationResolver(e){return St("not implemented")}}async function Un(e,t){return Ft(e,"POST","/v1/accounts:signUp",t)}async function jn(e,t){return jt(e,"POST","/v1/accounts:signInWithPassword",xt(e,t))}class Wn extends Fn{constructor(e,t,n,i=null){super("password",n),this._email=e,this._password=t,this._tenantId=i}static _fromEmailAndPassword(e,t){return new Wn(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new Wn(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e;if((null==t?void 0:t.email)&&(null==t?void 0:t.password)){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return Ln(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",jn);case"emailLink":return async function(e,t){return jt(e,"POST","/v1/accounts:signInWithEmailLink",xt(e,t))}(e,{email:this._email,oobCode:this._password});default:wt(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Ln(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",Un);case"emailLink":return async function(e,t){return jt(e,"POST","/v1/accounts:signInWithEmailLink",xt(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:wt(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function qn(e,t){return jt(e,"POST","/v1/accounts:signInWithIdp",xt(e,t))}class Vn extends Fn{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new Vn(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):wt("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){const t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:i}=t,s=_t(t,["providerId","signInMethod"]);if(!n||!i)return null;const r=new Vn(n,i);return r.idToken=s.idToken||void 0,r.accessToken=s.accessToken||void 0,r.secret=s.secret,r.nonce=s.nonce,r.pendingToken=s.pendingToken||null,r}_getIdTokenResponse(e){return qn(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,qn(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,qn(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=A(t)}return e}}const Hn={USER_NOT_FOUND:"user-not-found"};class zn extends Fn{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new zn({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new zn({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return jt(e,"POST","/v1/accounts:signInWithPhoneNumber",xt(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){const n=await jt(e,"POST","/v1/accounts:signInWithPhoneNumber",xt(e,t));if(n.temporaryProof)throw Ht(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return jt(e,"POST","/v1/accounts:signInWithPhoneNumber",xt(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Hn)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:i}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:i}}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){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:s}=e;return n||t||i||s?new zn({verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:s}):null}}class Bn{constructor(e){var t,n,i,s,r,o;const a=D(L(e)),c=null!==(t=a.apiKey)&&void 0!==t?t:null,l=null!==(n=a.oobCode)&&void 0!==n?n:null,h=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=a.mode)&&void 0!==i?i:null);Et(c&&l&&h,"argument-error"),this.apiKey=c,this.operation=h,this.code=l,this.continueUrl=null!==(s=a.continueUrl)&&void 0!==s?s:null,this.languageCode=null!==(r=a.languageCode)&&void 0!==r?r:null,this.tenantId=null!==(o=a.tenantId)&&void 0!==o?o:null}static parseLink(e){const t=function(e){const t=D(L(e)).link,n=t?D(L(t)).deep_link_id:null,i=D(L(e)).deep_link_id;return(i?D(L(i)).link:null)||i||n||t||e}(e);try{return new Bn(t)}catch(e){return null}}}class $n{constructor(){this.providerId=$n.PROVIDER_ID}static credential(e,t){return Wn._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=Bn.parseLink(t);return Et(n,"argument-error"),Wn._fromEmailAndCode(e,n.code,n.tenantId)}}$n.PROVIDER_ID="password",$n.EMAIL_PASSWORD_SIGN_IN_METHOD="password",$n.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Kn{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 Gn extends Kn{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Yn extends Gn{constructor(){super("facebook.com")}static credential(e){return Vn._fromParams({providerId:Yn.PROVIDER_ID,signInMethod:Yn.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Yn.credentialFromTaggedObject(e)}static credentialFromError(e){return Yn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Yn.credential(e.oauthAccessToken)}catch(e){return null}}}Yn.FACEBOOK_SIGN_IN_METHOD="facebook.com",Yn.PROVIDER_ID="facebook.com";class Jn extends Gn{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Vn._fromParams({providerId:Jn.PROVIDER_ID,signInMethod:Jn.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Jn.credentialFromTaggedObject(e)}static credentialFromError(e){return Jn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return Jn.credential(t,n)}catch(e){return null}}}Jn.GOOGLE_SIGN_IN_METHOD="google.com",Jn.PROVIDER_ID="google.com";class Qn extends Gn{constructor(){super("github.com")}static credential(e){return Vn._fromParams({providerId:Qn.PROVIDER_ID,signInMethod:Qn.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Qn.credentialFromTaggedObject(e)}static credentialFromError(e){return Qn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Qn.credential(e.oauthAccessToken)}catch(e){return null}}}Qn.GITHUB_SIGN_IN_METHOD="github.com",Qn.PROVIDER_ID="github.com";class Xn extends Gn{constructor(){super("twitter.com")}static credential(e,t){return Vn._fromParams({providerId:Xn.PROVIDER_ID,signInMethod:Xn.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Xn.credentialFromTaggedObject(e)}static credentialFromError(e){return Xn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return Xn.credential(t,n)}catch(e){return null}}}Xn.TWITTER_SIGN_IN_METHOD="twitter.com",Xn.PROVIDER_ID="twitter.com";class Zn{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,i=!1){const s=await rn._fromIdTokenResponse(e,n,i),r=ei(n);return new Zn({user:s,providerId:r,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const i=ei(n);return new Zn({user:e,providerId:i,_tokenResponse:n,operationType:t})}}function ei(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class ti extends w{constructor(e,t,n,i){var s;super(t.code,t.message),this.operationType=n,this.user=i,Object.setPrototypeOf(this,ti.prototype),this.customData={appName:e.name,tenantId:null!==(s=e.tenantId)&&void 0!==s?s:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,i){return new ti(e,t,n,i)}}function ni(e,t,n,i){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch((n=>{if("auth/multi-factor-auth-required"===n.code)throw ti._fromErrorAndOperation(e,n,t,i);throw n}))}async function ii(e,t,n=!1){if(Qe(e.app))return Promise.reject(Ct(e));const i="signIn",s=await ni(e,i,t),r=await Zn._fromIdTokenResponse(e,i,s);return n||await e._updateCurrentUser(r.user),r}new WeakMap;const si="__sak";class ri{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(si,"1"),this.storage.removeItem(si),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){const 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 oi extends ri{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=function(){const e=g();return fn(e)||In(e)}()&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=bn(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),i=this.localCache[t];n!==i&&e(t,i,n)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys(((e,t,n)=>{this.notifyListeners(e,n)}));const n=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(n);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const i=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},s=this.storage.getItem(n);!function(){const e=g();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}()||10!==document.documentMode||s===e.newValue||e.newValue===e.oldValue?i():setTimeout(i,10)}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const e of Array.from(n))e(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!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){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}oi.type="LOCAL";const ai=oi;class ci extends ri{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}ci.type="SESSION";const li=ci;class hi{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const n=new hi(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:i,data:s}=t.data,r=this.handlersMap[i];if(!(null==r?void 0:r.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:i});const o=Array.from(r).map((async e=>e(t.origin,s))),a=await function(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})))}(o);t.ports[0].postMessage({status:"done",eventId:n,eventType:i,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function ui(e="",t=10){let n="";for(let e=0;e{const c=ui("",20);i.port1.start();const l=setTimeout((()=>{a(new Error("unsupported_event"))}),n);r={messageChannel:i,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(l),s=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(s),o(t.data.response);break;default:clearTimeout(l),clearTimeout(s),a(new Error("invalid_response"))}}},this.handlers.add(r),i.port1.addEventListener("message",r.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[i.port2])})).finally((()=>{r&&this.removeMessageHandler(r)}))}}function pi(){return window}function fi(){return void 0!==pi().WorkerGlobalScope&&"function"==typeof pi().importScripts}const _i="firebaseLocalStorageDb",mi="firebaseLocalStorage",gi="fbase_key";class vi{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 yi(e,t){return e.transaction([mi],t?"readwrite":"readonly").objectStore(mi)}function wi(){const e=indexedDB.open(_i,1);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(mi,{keyPath:gi})}catch(e){n(e)}})),e.addEventListener("success",(async()=>{const n=e.result;n.objectStoreNames.contains(mi)?t(n):(n.close(),await function(){const e=indexedDB.deleteDatabase(_i);return new vi(e).toPromise()}(),t(await wi()))}))}))}async function Ii(e,t,n){const i=yi(e,!0).put({[gi]:t,value:n});return new vi(i).toPromise()}function bi(e,t){const n=yi(e,!0).delete(t);return new vi(n).toPromise()}class Ci{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 wi()),this.db}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return fi()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=hi._getInstance(fi()?self:null),this.receiver._subscribe("keyChanged",(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){var e,t;if(this.activeServiceWorker=await async function(){if(!(null===navigator||void 0===navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),!this.activeServiceWorker)return;this.sender=new di(this.activeServiceWorker);const n=await this.sender._send("ping",{},800);n&&(null===(e=n[0])||void 0===e?void 0:e.fulfilled)&&(null===(t=n[0])||void 0===t?void 0:t.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?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(t){}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await wi();return await Ii(e,si,"1"),await bi(e,si),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((n=>Ii(n,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function(e,t){const n=yi(e,!1).get(t),i=await new vi(n).toPromise();return void 0===i?null:i.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>bi(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=yi(e,!1).getAll();return new vi(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;if(0!==e.length)for(const{fbase_key:i,value:s}of e)n.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(s)&&(this.notifyListeners(i,s),t.push(i));for(const e of Object.keys(this.localCache))this.localCache[e]&&!n.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const e of Array.from(n))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),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()}}Ci.type="LOCAL";const Ti=Ci;On("rcb"),new Ot(3e4,6e4);class Ei{constructor(e){this.providerId=Ei.PROVIDER_ID,this.auth=kn(e)}verifyPhoneNumber(e,t){return async function(e,t,n){var i;const s=await n.verify();try{let r;if(Et("string"==typeof s,e,"argument-error"),Et("recaptcha"===n.type,e,"argument-error"),r="string"==typeof t?{phoneNumber:t}:t,"session"in r){const t=r.session;if("phoneNumber"in r){Et("enroll"===t.type,e,"internal-error");const n=await function(e,t){return Ft(e,"POST","/v2/accounts/mfaEnrollment:start",xt(e,t))}(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:r.phoneNumber,recaptchaToken:s}});return n.phoneSessionInfo.sessionInfo}{Et("signin"===t.type,e,"internal-error");const n=(null===(i=r.multiFactorHint)||void 0===i?void 0:i.uid)||r.multiFactorUid;Et(n,e,"missing-multi-factor-info");const o=await function(e,t){return Ft(e,"POST","/v2/accounts/mfaSignIn:start",xt(e,t))}(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:s}});return o.phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await async function(e,t){return Ft(e,"POST","/v1/accounts:sendVerificationCode",xt(e,t))}(e,{phoneNumber:r.phoneNumber,recaptchaToken:s});return t}}finally{n._reset()}}(this.auth,e,j(t))}static credential(e,t){return zn._fromVerification(e,t)}static credentialFromResult(e){const t=e;return Ei.credentialFromTaggedObject(t)}static credentialFromError(e){return Ei.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:n}=e;return t&&n?zn._fromTokenResponse(t,n):null}}Ei.PROVIDER_ID="phone",Ei.PHONE_SIGN_IN_METHOD="phone";class Si extends Fn{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return qn(e,this._buildIdpRequest())}_linkToIdToken(e,t){return qn(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return qn(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 ki(e){return ii(e.auth,new Si(e),e.bypassAuthState)}function Ri(e){const{auth:t,user:n}=e;return Et(n,t,"internal-error"),async function(e,t,n=!1){const{auth:i}=e;if(Qe(i.app))return Promise.reject(Ct(i));const s="reauthenticate";try{const r=await Qt(e,ni(i,s,t,e),n);Et(r.idToken,i,"internal-error");const o=Yt(r.idToken);Et(o,i,"internal-error");const{sub:a}=o;return Et(e.uid===a,i,"user-mismatch"),Zn._forOperation(e,s,r)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&wt(i,"user-mismatch"),e}}(n,new Si(e),e.bypassAuthState)}async function Ni(e){const{auth:t,user:n}=e;return Et(n,t,"internal-error"),async function(e,t,n=!1){const i=await Qt(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Zn._forOperation(e,"link",i)}(n,new Si(e),e.bypassAuthState)}class Pi{constructor(e,t,n,i,s=!1){this.auth=e,this.resolver=n,this.user=i,this.bypassAuthState=s,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:i,tenantId:s,error:r,type:o}=e;if(r)return void this.reject(r);const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:s||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return ki;case"linkViaPopup":case"linkViaRedirect":return Ni;case"reauthViaPopup":case"reauthViaRedirect":return Ri;default:wt(this.auth,"internal-error")}}resolve(e){kt(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){kt(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 Oi=new Ot(2e3,1e4);class Ai extends Pi{constructor(e,t,n,i,s){super(e,t,i,s),this.provider=n,this.authWindow=null,this.pollId=null,Ai.currentPopupAction&&Ai.currentPopupAction.cancel(),Ai.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return Et(e,this.auth,"internal-error"),e}async onExecution(){kt(1===this.filter.length,"Popup operations only handle one event");const e=ui();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(It(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(It(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Ai.currentPopupAction=null}pollUserCancellation(){const e=()=>{var t,n;(null===(n=null===(t=this.authWindow)||void 0===t?void 0:t.window)||void 0===n?void 0:n.closed)?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(It(this.auth,"popup-closed-by-user"))}),8e3):this.pollId=window.setTimeout(e,Oi.get())};e()}}Ai.currentPopupAction=null;const Di="pendingRedirect",Li=new Map;class Mi extends Pi{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=Li.get(this.auth._key());if(!e){try{const t=await async function(e,t){const n=function(e){return hn(Di,e.config.apiKey,e.name)}(t),i=function(e){return an(e._redirectPersistence)}(e);if(!await i._isAvailable())return!1;const s="true"===await i._get(n);return await i._remove(n),s}(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}Li.set(this.auth._key(),e)}return this.bypassAuthState||Li.set(this.auth._key(),(()=>Promise.resolve(null))),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){const 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(){}}function xi(e,t){Li.set(e._key(),t)}async function Fi(e,t,n=!1){if(Qe(e.app))return Promise.reject(Ct(e));const i=kn(e),s=function(e,t){return t?an(t):(Et(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}(i,t),r=new Mi(i,s,n),o=await r.execute();return o&&!n&&(delete o.user._redirectEventId,await i._persistUserIfCurrent(o.user),await i._setRedirectUser(null,t)),o}class Ui{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach((n=>{this.isEventForConsumer(e,n)&&(t=!0,this.sendToConsumer(e,n),this.saveEventToCache(e))})),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return Wi(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!Wi(e)){const i=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(It(this.auth,i))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(ji(e))}saveEventToCache(e){this.cachedEventUids.add(ji(e)),this.lastProcessedEventTime=Date.now()}}function ji(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function Wi({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}const qi=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Vi=/^https?/;function Hi(e){const t=Rt(),{protocol:n,hostname:i}=new URL(t);if(e.startsWith("chrome-extension://")){const s=new URL(e);return""===s.hostname&&""===i?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&s.hostname===i}if(!Vi.test(n))return!1;if(qi.test(e))return i===e;const s=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+s+"|"+s+")$","i").test(i)}const zi=new Ot(3e4,6e4);function Bi(){const e=pi().___jsl;if(null==e?void 0:e.H)for(const t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t{var i,s,r;function o(){Bi(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{Bi(),n(It(e,"network-request-failed"))},timeout:zi.get()})}if(null===(s=null===(i=pi().gapi)||void 0===i?void 0:i.iframes)||void 0===s?void 0:s.Iframe)t(gapi.iframes.getContext());else{if(!(null===(r=pi().gapi)||void 0===r?void 0:r.load)){const t=On("iframefcb");return pi()[t]=()=>{gapi.load?o():n(It(e,"network-request-failed"))},Pn(`${Nn.gapiScript}?onload=${t}`).catch((e=>n(e)))}o()}})).catch((e=>{throw Ki=null,e}))}let Ki=null;const Gi=new Ot(5e3,15e3),Yi="__/auth/iframe",Ji="emulator/auth/iframe",Qi={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},Xi=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function Zi(e){const t=e.config;Et(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?At(t,Ji):`https://${e.config.authDomain}/${Yi}`,i={apiKey:t.apiKey,appName:e.name,v:et},s=Xi.get(e.config.apiHost);s&&(i.eid=s);const r=e._getFrameworks();return r.length&&(i.fw=r.join(",")),`${n}?${A(i).slice(1)}`}const es={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class ts{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}const ns=encodeURIComponent("fac");async function is(e,t,n,i,s,r){Et(e.config.authDomain,e,"auth-domain-config-required"),Et(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:i,v:et,eventId:s};if(t instanceof Kn){t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",R(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(r||{}))o[e]=t}if(t instanceof Gn){const e=t.getScopes().filter((e=>""!==e));e.length>0&&(o.scopes=e.join(","))}e.tenantId&&(o.tid=e.tenantId);const a=o;for(const e of Object.keys(a))void 0===a[e]&&delete a[e];const c=await e._getAppCheckToken(),l=c?`#${ns}=${encodeURIComponent(c)}`:"";return`${function({config:e}){return e.emulator?At(e,"emulator/auth/handler"):`https://${e.authDomain}/__/auth/handler`}(e)}?${A(a).slice(1)}${l}`}const ss="webStorageSupport",rs=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=li,this._completeRedirectFn=Fi,this._overrideRedirectResult=xi}async _openPopup(e,t,n,i){var s;return kt(null===(s=this.eventManagers[e._key()])||void 0===s?void 0:s.manager,"_initialize() not called before _openPopup()"),function(e,t,n,i=500,s=600){const r=Math.max((window.screen.availHeight-s)/2,0).toString(),o=Math.max((window.screen.availWidth-i)/2,0).toString();let a="";const c=Object.assign(Object.assign({},es),{width:i.toString(),height:s.toString(),top:r,left:o}),l=g().toLowerCase();n&&(a=mn(l)?"_blank":n),pn(l)&&(t=t||"http://localhost",c.scrollbars="yes");const h=Object.entries(c).reduce(((e,[t,n])=>`${e}${t}=${n},`),"");if(function(e=g()){var t;return In(e)&&!!(null===(t=window.navigator)||void 0===t?void 0:t.standalone)}(l)&&"_self"!==a)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const i=document.createEvent("MouseEvent");i.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(i)}(t||"",a),new ts(null);const u=window.open(t||"",a,h);Et(u,e,"popup-blocked");try{u.focus()}catch(e){}return new ts(u)}(e,await is(e,t,n,Rt(),i),ui())}async _openRedirect(e,t,n,i){return await this._originValidation(e),s=await is(e,t,n,Rt(),i),pi().location.href=s,new Promise((()=>{}));var s}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(kt(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(e){const t=await async function(e){const t=await function(e){return Ki=Ki||$i(e),Ki}(e),n=pi().gapi;return Et(n,e,"internal-error"),t.open({where:document.body,url:Zi(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Qi,dontclear:!0},(t=>new Promise((async(n,i)=>{await t.restyle({setHideOnLeave:!1});const s=It(e,"network-request-failed"),r=pi().setTimeout((()=>{i(s)}),Gi.get());function o(){pi().clearTimeout(r),n(t)}t.ping(o).then(o,(()=>{i(s)}))}))))}(e),n=new Ui(e);return t.register("authEvent",(t=>(Et(null==t?void 0:t.authEvent,e,"invalid-auth-event"),{status:n.onEvent(t.authEvent)?"ACK":"ERROR"})),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:n},this.iframes[e._key()]=t,n}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(ss,{type:ss},(n=>{var i;const s=null===(i=null==n?void 0:n[0])||void 0===i?void 0:i[ss];void 0!==s&&t(!!s),wt(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){if(e.config.emulator)return;const{authorizedDomains:t}=await async function(e,t={}){return Ft(e,"GET","/v1/projects",t)}(e);for(const e of t)try{if(Hi(e))return}catch(e){}wt(e,"unauthorized-domain")}(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return bn()||fn()||In()}};var os="@firebase/auth",as="1.7.5";class cs{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(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e((null==t?void 0:t.stsTokenManager.accessToken)||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){Et(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}const ls=_("authIdTokenMaxAge")||300;let hs=null;var us,ds;us={loadJS:e=>new Promise(((t,n)=>{const i=document.createElement("script");var s,r;i.setAttribute("src",e),i.onload=t,i.onerror=e=>{const t=It("internal-error");t.customData=e,n(t)},i.type="text/javascript",i.charset="UTF-8",(null!==(r=null===(s=document.getElementsByTagName("head"))||void 0===s?void 0:s[0])&&void 0!==r?r:document).appendChild(i)})),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="},Nn=us,ds="Browser",Ye(new W("auth",((e,{options:t})=>{const n=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),s=e.getProvider("app-check-internal"),{apiKey:r,authDomain:o}=n.options;Et(r&&!r.includes(":"),"invalid-api-key",{appName:n.name});const a={apiKey:r,authDomain:o,clientPlatform:ds,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Cn(ds)},c=new Sn(n,i,s,a);return function(e,t){const n=(null==t?void 0:t.persistence)||[],i=(Array.isArray(n)?n:[n]).map(an);(null==t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(i,null==t?void 0:t.popupRedirectResolver)}(c,t),c}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{e.getProvider("auth-internal").initialize()}))),Ye(new W("auth-internal",(e=>{return t=kn(e.getProvider("auth").getImmediate()),new cs(t);var t}),"PRIVATE").setInstantiationMode("EXPLICIT")),it(os,as,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}}(ds)),it(os,as,"esm2017");const ps="@firebase/database",fs="1.0.6";let _s="";class ms{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),T(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:C(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class gs{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return S(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const vs=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 ms(t)}}catch(e){}return new gs},ys=vs("localStorage"),ws=vs("sessionStorage"),Is=new J("@firebase/database"),bs=function(){let e=1;return function(){return e++}}(),Cs=function(e){const t=function(e){const t=[];let i=0;for(let s=0;s=55296&&r<=56319){const t=r-55296;s++,n(s>6|192,t[i++]=63&r|128):r<65536?(t[i++]=r>>12|224,t[i++]=r>>6&63|128,t[i++]=63&r|128):(t[i++]=r>>18|240,t[i++]=r>>12&63|128,t[i++]=r>>6&63|128,t[i++]=63&r|128)}return t}(e),i=new M;i.update(t);const s=i.digest();return r.encodeByteArray(s)},Ts=function(...e){let t="";for(let n=0;nn?i.push(e.substring(s,n)):i.push(e.substring(s,s+t));return i};function Ws(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const qs=function(e){n(!As(e),"Invalid JSON number");let t,i,s,r,o;0===e?(i=0,s=0,t=1/e==-1/0?1:0):(t=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(r=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),i=r+1023,s=Math.round(e*Math.pow(2,52-r)-Math.pow(2,52))):(i=0,s=Math.round(e/Math.pow(2,-1074))));const a=[];for(o=52;o;o-=1)a.push(s%2?1:0),s=Math.floor(s/2);for(o=11;o;o-=1)a.push(i%2?1:0),i=Math.floor(i/2);a.push(t?1:0),a.reverse();const c=a.join("");let l="";for(o=0;o<64;o+=8){let e=parseInt(c.substr(o,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()},Vs=new RegExp("^-?(0*)\\d{1,10}$"),Hs=function(e){if(Vs.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},zs=function(e){try{e()}catch(e){setTimeout((()=>{const t=e.stack||"";throw Os("Exception was thrown by user callback.",t),e}),Math.floor(0))}},Bs=function(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};class $s{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then((e=>this.appCheck=e))}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise(((t,n)=>{setTimeout((()=>{this.appCheck?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then((t=>t.addTokenListener(e)))}notifyForInvalidToken(){Os(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}class Ks{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit((e=>this.auth_=e))}getToken(e){return this.auth_?this.auth_.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(ks("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e))):new Promise(((t,n)=>{setTimeout((()=>{this.auth_?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then((t=>t.addAuthTokenListener(e)))}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',Os(e)}}class Gs{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Gs.OWNER="owner";const Ys="5",Js=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Qs="ac",Xs="websocket",Zs="long_polling";class er{constructor(e,t,n,i,s=!1,r="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=i,this.nodeAdmin=s,this.persistenceKey=r,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ys.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()&&ys.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function tr(e,t,i){let s;if(n("string"==typeof t,"typeof type must == string"),n("object"==typeof i,"typeof params must == object"),t===Xs)s=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Zs)throw new Error("Unknown connection type: "+t);s=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}(function(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams})(e)&&(i.ns=e.namespace);const r=[];return Ws(i,((e,t)=>{r.push(e+"="+t)})),s+r.join("&")}class nr{constructor(){this.counters_={}}incrementCounter(e,t=1){S(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return h(this.counters_)}}const ir={},sr={};function rr(e){const t=e.toString();return ir[t]||(ir[t]=new nr),ir[t]}class or{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.onMessage_(e[t])}));if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const ar="start";class cr{constructor(e,t,n,i,s,r,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.transportSessionId=r,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Rs(e),this.stats_=rr(t),this.urlFn=e=>(this.appCheckToken&&(e[Qs]=this.appCheckToken),tr(t,Zs,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new or(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout((()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null}),Math.floor(3e4)),function(e){if("complete"===document.readyState)e();else{let t=!1;const n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",(()=>{"complete"===document.readyState&&n()})),window.attachEvent("onload",n))}}((()=>{if(this.isClosed_)return;this.scriptTagHolder=new lr(((...e)=>{const[t,n,i,s,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===ar)this.id=n,this.password=i;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)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)}),(()=>{this.onClosed_()}),this.urlFn);const e={};e[ar]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v=Ys,this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e[Qs]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&Js.test(location.hostname)&&(e.r="f");const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,(()=>{}))}))}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){cr.forceAllow_=!0}static forceDisallow(){cr.forceDisallow_=!0}static isAvailable(){return!(!cr.forceAllow_&&(cr.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){const t=T(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=a(t),i=js(n,1840);for(let e=0;edocument.domain="'+document.domain+'";<\/script>');const i=""+n+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){ks("frame writing exception"),e.stack&&ks(e.stack),ks(e)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||ks("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout((()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)}),Math.floor(0)));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<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+30+n.length<=1870;){const e=this.pendingSegs.shift();n=n+"&seg"+i+"="+e.seg+"&ts"+i+"="+e.ts+"&d"+i+"="+e.d,i++}return t+=n,this.addLongPollTag_(t,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_()},i=setTimeout(n,Math.floor(25e3));this.addTag(e,(()=>{clearTimeout(i),n()}))}addTag(e,t){setTimeout((()=>{try{if(!this.sendNewPolls)return;const n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){const e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{ks("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}}),Math.floor(1))}}let hr=null;"undefined"!=typeof MozWebSocket?hr=MozWebSocket:"undefined"!=typeof WebSocket&&(hr=WebSocket);class ur{constructor(e,t,n,i,s,r,o){this.connId=e,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Rs(this.connId),this.stats_=rr(t),this.connURL=ur.connectionURL_(t,r,o,i,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,i,s){const r={};return r.v=Ys,"undefined"!=typeof location&&location.hostname&&Js.test(location.hostname)&&(r.r="f"),t&&(r.s=t),n&&(r.ls=n),i&&(r[Qs]=i),s&&(r.p=s),tr(e,Xs,r)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ys.set("previous_websocket_failure",!0);try{let e;0,this.mySock=new hr(this.connURL,[],e)}catch(e){this.log_("Error instantiating WebSocket.");const t=e.message||e.data;return t&&this.log_(t),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.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){ur.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==hr&&!ur.forceDisallow_}static previouslyFailed(){return ys.isInMemoryStorage||!0===ys.get("previous_websocket_failure")}markConnectionHealthy(){ys.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=C(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(n(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=T(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=js(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e{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)}}}ur.responsesRequiredToBeHealthy=2,ur.healthyTimeout=3e4;class dr{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[cr,ur]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const t=ur&&ur.isAvailable();let n=t&&!ur.previouslyFailed();if(e.webSocketOnly&&(t||Os("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[ur];else{const e=this.transports_=[];for(const t of dr.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);dr.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}dr.globalTransportInitialized_=!1;class pr{constructor(e,t,n,i,s,r,o,a,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=s,this.onMessage_=r,this.onReady_=o,this.onDisconnect_=a,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Rs("c:"+this.id+":"),this.transportManager_=new dr(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));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=Bs((()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))}),Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if("t"in e){const t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=Fs("t",e),n=Fs("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){const t=Fs("t",e),n=Fs("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){const t=Fs("t",e);if("d"in e){const n=e.d;if("h"===t){const e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e{this.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):Bs((()=>{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_(){const 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()&&(ys.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 fr{put(e,t,n,i){}merge(e,t,n,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class _r{constructor(e){this.allowedEvents_=e,this.listeners_={},n(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;et===e)),"Unknown event: "+e)}}class mr extends _r{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||v()||(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 mr}getInitialEvent(e){return n("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class gr{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function wr(e){return e.pieces_.length-e.pieceNum_}function Ir(e){let t=e.pieceNum_;return t=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n0&&n.push(e[t])}return new gr(n,0)}function Sr(e){return e.pieceNum_>=e.pieces_.length}function kr(e,t){const n=yr(e),i=yr(t);if(null===n)return t;if(n===i)return kr(Ir(e),Ir(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function Rr(e,t){if(wr(e)!==wr(t))return!1;for(let n=e.pieceNum_,i=t.pieceNum_;n<=e.pieces_.length;n++,i++)if(e.pieces_[n]!==t.pieces_[i])return!1;return!0}function Nr(e,t){let n=e.pieceNum_,i=t.pieceNum_;if(wr(e)>wr(t))return!1;for(;n768)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+Ar(e))}function Ar(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class Dr extends _r{constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}static getInstance(){return new Dr}getInitialEvent(e){return n("visible"===e,"Unknown event type: "+e),[this.visible_]}}const Lr=1e3;class Mr extends fr{constructor(e,t,n,i,s,r,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=i,this.onServerInfoUpdate_=s,this.authTokenProvider_=r,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=Mr.nextPersistentConnectionId_++,this.log_=Rs("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_=Lr,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Dr.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&mr.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,i){const s=++this.requestNumber_,r={r:s,a:e,b:t};this.log_(T(r)),n(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),i&&(this.requestCBHash_[s]=i)}get(e){this.initConnection_();const t=new m,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const i=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(i),t.promise}listen(e,t,i,s){this.initConnection_();const r=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+r),this.listens.has(o)||this.listens.set(o,new Map),n(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),n(!this.listens.get(o).has(r),"listen() called twice for same path/queryId.");const a={onComplete:s,hashFn:t,query:e,tag:i};this.listens.get(o).set(r,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,(n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)}))}sendListen_(e){const t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);const s={p:n};e.tag&&(s.q=t._queryObject,s.t=e.tag),s.h=e.hashFn(),this.sendRequest("q",s,(s=>{const r=s.d,o=s.s;Mr.warnOnListenWarnings_(r,t),(this.listens.get(n)&&this.listens.get(n).get(i))===e&&(this.log_("listen response",s),"ok"!==o&&this.removeListen_(n,i),e.onComplete&&e.onComplete(o,r))}))}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&S(e,"w")){const n=k(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();Os(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},(()=>{})),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||function(e){const t=E(e).claims;return"object"==typeof t&&!0===t.admin}(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},(()=>{}))}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=function(e){const t=E(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")}(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,(t=>{const n=t.s,i=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,i))}))}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},(e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)}))}unlisten(e,t){const i=e._path.toString(),s=e._queryIdentifier;this.log_("Unlisten called for "+i+" "+s),n(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(i,s)&&this.connected_&&this.sendUnlisten_(i,s,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);const s={p:e};i&&(s.q=n,s.t=i),this.sendRequest("n",s)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,i){const s={p:t,d:n};this.log_("onDisconnect "+e,s),this.sendRequest(e,s,(e=>{i&&setTimeout((()=>{i(e.s,e.d)}),Math.floor(0))}))}put(e,t,n,i){this.putInternal("p",e,t,n,i)}merge(e,t,n,i){this.putInternal("m",e,t,n,i)}putInternal(e,t,n,i,s){this.initConnection_();const r={p:t,d:n};void 0!==s&&(r.h=s),this.outstandingPuts_.push({action:e,request:r,onComplete:i}),this.outstandingPutCount_++;const o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,(n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),i&&i(n.s,n.d)}))}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,(e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}}))}}onDataMessage_(e){if("r"in e){this.log_("from server: "+T(e));const t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"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):Ns("Unrecognized action received from server: "+T(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){n(!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_=Lr,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=Lr,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&((new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=Lr),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime());const e=(new Date).getTime()-this.lastConnectionAttemptTime_;let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,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;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),i=this.onRealtimeDisconnect_.bind(this),s=this.id+":"+Mr.nextConnectionId_++,r=this.lastSessionId;let o=!1,a=null;const c=function(){a?a.close():(o=!0,i())},l=function(e){n(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(e)};this.realtime_={close:c,sendRequest:l};const h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[n,c]=await Promise.all([this.authTokenProvider_.getToken(h),this.appCheckTokenProvider_.getToken(h)]);o?ks("getToken() completed but was canceled"):(ks("getToken() completed. Creating connection."),this.authToken_=n&&n.accessToken,this.appCheckToken_=c&&c.token,a=new pr(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,i,(e=>{Os(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")}),r))}catch(e){this.log_("Failed to get token: "+e),o||(this.repoInfo_.nodeAdmin&&Os(e),c())}}}interrupt(e){ks("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){ks("Resuming connection for reason: "+e),delete this.interruptReasons_[e],R(this.interruptReasons_)&&(this.reconnectDelay_=Lr,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;eUs(e))).join("$"):"default";const i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){const n=new gr(e).toString();let i;if(this.listens.has(n)){const e=this.listens.get(n);i=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else i=void 0;return i}onAuthRevoked_(e,t){ks("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){ks("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class Vr{constructor(e,t,n,i,s){this.key=e,this.value=t,this.color=null!=n?n:Vr.RED,this.left=null!=i?i:Hr.EMPTY_NODE,this.right=null!=s?s:Hr.EMPTY_NODE}copy(e,t,n,i,s){return new Vr(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=i?i:this.left,null!=s?s:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let i=this;const s=n(e,i.key);return i=s<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===s?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return Hr.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,i;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 Hr.EMPTY_NODE;i=n.right.min_(),n=n.copy(i.key,i.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.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_(){const e=this.copy(null,null,Vr.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,Vr.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}Vr.RED=!0,Vr.BLACK=!1;class Hr{constructor(e,t=Hr.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Hr(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,Vr.BLACK,null,null))}remove(e){return new Hr(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Vr.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,i=null;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t){if(n.left.isEmpty())return i?i.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(i=n,n=n.right)}throw 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 qr(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new qr(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new qr(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new qr(this.root_,null,this.comparator_,!0,e)}}function zr(e,t){return Ms(e.name,t.name)}function Br(e,t){return Ms(e,t)}let $r;Hr.EMPTY_NODE=new class{copy(e,t,n,i,s){return this}insert(e,t,n){return new Vr(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}};const Kr=function(e){return"number"==typeof e?"number:"+qs(e):"string:"+e},Gr=function(e){if(e.isLeafNode()){const t=e.val();n("string"==typeof t||"number"==typeof t||"object"==typeof t&&S(t,".sv"),"Priority must be a string or number.")}else n(e===$r||e.isEmpty(),"priority of unexpected type.");n(e===$r||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let Yr,Jr,Qr;class Xr{constructor(e,t=Xr.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,n(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Gr(this.priorityNode_)}static set __childrenNodeConstructor(e){Yr=e}static get __childrenNodeConstructor(){return Yr}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Xr(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Xr.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return Sr(e)?this:".priority"===yr(e)?this.priorityNode_:Xr.__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:Xr.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const i=yr(e);return null===i?t:t.isEmpty()&&".priority"!==i?this:(n(".priority"!==i||1===wr(e),".priority must be the last token in a path"),this.updateImmediateChild(i,Xr.__childrenNodeConstructor.EMPTY_NODE.updateChild(Ir(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:"+Kr(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?qs(this.value_):this.value_,this.lazyHash_=Cs(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Xr.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Xr.__childrenNodeConstructor?-1:(n(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,i=typeof this.value_,s=Xr.VALUE_TYPE_ORDER.indexOf(t),r=Xr.VALUE_TYPE_ORDER.indexOf(i);return n(s>=0,"Unknown leaf type: "+t),n(r>=0,"Unknown leaf type: "+i),s===r?"object"===i?0:this.value_{const r=k(this.indexSet_,s);if(n(r,"Missing index implementation for "+s),i===so){if(r.isDefinedOn(e.node)){const n=[],i=t.getIterator(xr.Wrap);let s=i.getNext();for(;s;)s.name!==e.name&&n.push(s),s=i.getNext();return n.push(e),no(n,r.getCompare())}return so}{const n=t.get(e.name);let s=i;return n&&(s=s.remove(new xr(e.name,n))),s.insert(e,e.node)}}));return new ro(i,this.indexSet_)}removeFromIndexes(e,t){const n=N(this.indexes_,(n=>{if(n===so)return n;{const i=t.get(e.name);return i?n.remove(new xr(e.name,i)):n}}));return new ro(n,this.indexSet_)}}let oo;class ao{constructor(e,t,i){this.children_=e,this.priorityNode_=t,this.indexMap_=i,this.lazyHash_=null,this.priorityNode_&&Gr(this.priorityNode_),this.children_.isEmpty()&&n(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return oo||(oo=new ao(new Hr(Br),null,ro.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||oo}updatePriority(e){return this.children_.isEmpty()?this:new ao(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?oo:t}}getChild(e){const t=yr(e);return null===t?this:this.getImmediateChild(t).getChild(Ir(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if(n(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new xr(e,t);let i,s;t.isEmpty()?(i=this.children_.remove(e),s=this.indexMap_.removeFromIndexes(n,this.children_)):(i=this.children_.insert(e,t),s=this.indexMap_.addToIndexes(n,this.children_));const r=i.isEmpty()?oo:this.priorityNode_;return new ao(i,r,s)}}updateChild(e,t){const i=yr(e);if(null===i)return t;{n(".priority"!==yr(e)||1===wr(e),".priority must be the last token in a path");const s=this.getImmediateChild(i).updateChild(Ir(e),t);return this.updateImmediateChild(i,s)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,i=0,s=!0;if(this.forEachChild(Zr,((r,o)=>{t[r]=o.val(e),n++,s&&ao.INTEGER_REGEXP_.test(r)?i=Math.max(i,Number(r)):s=!1})),!e&&s&&i<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+Kr(this.getPriority().val())+":"),this.forEachChild(Zr,((t,n)=>{const i=n.hash();""!==i&&(e+=":"+t+":"+i)})),this.lazyHash_=""===e?"":Cs(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const i=this.resolveIndex_(n);if(i){const n=i.getPredecessorKey(new xr(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new xr(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new xr(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(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,(e=>e));{const n=this.children_.getIteratorFrom(e.name,xr.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)<0;)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,(e=>e));{const n=this.children_.getReverseIteratorFrom(e.name,xr.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)>0;)n.getNext(),i=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===co?-1:0}withIndex(e){if(e===Wr||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new ao(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===Wr||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(Zr),n=t.getIterator(Zr);let i=e.getNext(),s=n.getNext();for(;i&&s;){if(i.name!==s.name||!i.node.equals(s.node))return!1;i=e.getNext(),s=n.getNext()}return null===i&&null===s}return!1}return!1}}resolveIndex_(e){return e===Wr?null:this.indexMap_.get(e.toString())}}ao.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const co=new class extends ao{constructor(){super(new Hr(Br),ao.EMPTY_NODE,ro.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ao.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(xr,{MIN:{value:new xr(Ds,ao.EMPTY_NODE)},MAX:{value:new xr(Ls,co)}}),jr.__EMPTY_NODE=ao.EMPTY_NODE,Xr.__childrenNodeConstructor=ao,$r=co,Qr=co;const lo=!0;function ho(e,t=null){if(null===e)return ao.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),n(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e)return new Xr(e,ho(t));if(e instanceof Array||!lo){let n=ao.EMPTY_NODE;return Ws(e,((t,i)=>{if(S(e,t)&&"."!==t.substring(0,1)){const e=ho(i);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}})),n.updatePriority(ho(t))}{const n=[];let i=!1;if(Ws(e,((e,t)=>{if("."!==e.substring(0,1)){const s=ho(t);s.isEmpty()||(i=i||!s.getPriority().isEmpty(),n.push(new xr(e,s)))}})),0===n.length)return ao.EMPTY_NODE;const s=no(n,zr,(e=>e.name),Br);if(i){const e=no(n,Zr.getCompare());return new ao(s,ho(t),new ro({".priority":e},{".priority":Zr}))}return new ao(s,ho(t),ro.Default)}}Jr=ho;class uo extends Fr{constructor(e){super(),this.indexPath_=e,n(!Sr(e)&&".priority"!==yr(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),i=this.extractChild(t.node),s=n.compareTo(i);return 0===s?Ms(e.name,t.name):s}makePost(e,t){const n=ho(e),i=ao.EMPTY_NODE.updateChild(this.indexPath_,n);return new xr(t,i)}maxPost(){const e=ao.EMPTY_NODE.updateChild(this.indexPath_,co);return new xr(Ls,e)}toString(){return Cr(this.indexPath_,0).join("/")}}const po=new class extends Fr{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?Ms(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return xr.MIN}maxPost(){return xr.MAX}makePost(e,t){const n=ho(e);return new xr(t,n)}toString(){return".value"}};function fo(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class _o{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_=Zr}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return n(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return n(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Ds}hasEnd(){return this.endSet_}getIndexEndValue(){return n(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return n(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Ls}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return n(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_===Zr}copy(){const e=new _o;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 mo(e){const t={};if(e.isDefault())return t;let i;if(e.index_===Zr?i="$priority":e.index_===po?i="$value":e.index_===Wr?i="$key":(n(e.index_ instanceof uo,"Unrecognized index type!"),i=e.index_.toString()),t.orderBy=T(i),e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=T(e.indexStartValue_),e.startNameSet_&&(t[n]+=","+T(e.indexStartName_))}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=T(e.indexEndValue_),e.endNameSet_&&(t[n]+=","+T(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function go(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==Zr&&(t.i=e.index_.toString()),t}class vo extends fr{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=Rs("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(n(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const r=vo.getListenId_(e,n),o={};this.listens_[r]=o;const a=mo(e._queryParams);this.restRequest_(s+".json",a,((e,t)=>{let a=t;if(404===e&&(a=null,e=null),null===e&&this.onDataUpdate_(s,a,!1,n),k(this.listens_,r)===o){let t;t=e?401===e?"permission_denied":"rest_error:"+e:"ok",i(t,null)}}))}unlisten(e,t){const n=vo.getListenId_(e,t);delete this.listens_[n]}get(e){const t=mo(e._queryParams),n=e._path.toString(),i=new m;return this.restRequest_(n+".json",t,((e,t)=>{let s=t;404===e&&(s=null,e=null),null===e?(this.onDataUpdate_(n,s,!1,null),i.resolve(s)):i.reject(new Error(s))})),i.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then((([i,s])=>{i&&i.accessToken&&(t.auth=i.accessToken),s&&s.token&&(t.ac=s.token);const r=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+A(t);this.log_("Sending REST request for "+r);const o=new XMLHttpRequest;o.onreadystatechange=()=>{if(n&&4===o.readyState){this.log_("REST Response for "+r+" received. status:",o.status,"response:",o.responseText);let e=null;if(o.status>=200&&o.status<300){try{e=C(o.responseText)}catch(e){Os("Failed to parse JSON response for "+r+": "+o.responseText)}n(null,e)}else 401!==o.status&&404!==o.status&&Os("Got unsuccessful REST response for "+r+" Status: "+o.status),n(o.status);n=null}},o.open("GET",r,!0),o.send()}))}}class yo{constructor(){this.rootNode_=ao.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function wo(){return{value:null,children:new Map}}function Io(e,t,n){if(Sr(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const i=yr(t);e.children.has(i)||e.children.set(i,wo()),Io(e.children.get(i),t=Ir(t),n)}}function bo(e,t,n){null!==e.value?n(t,e.value):function(e,t){e.children.forEach(((e,n)=>{t(n,e)}))}(e,((e,i)=>{bo(i,new gr(t.toString()+"/"+e),n)}))}class Co{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&Ws(this.last_,((e,n)=>{t[e]=t[e]-n})),this.last_=e,t}}class To{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Co(e);const n=1e4+2e4*Math.random();Bs(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;Ws(e,((e,i)=>{i>0&&S(this.statsToReport_,e)&&(t[e]=i,n=!0)})),n&&this.server_.reportStats(t),Bs(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}var Eo,So;function ko(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(So=Eo||(Eo={}))[So.OVERWRITE=0]="OVERWRITE",So[So.MERGE=1]="MERGE",So[So.ACK_USER_WRITE=2]="ACK_USER_WRITE",So[So.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class Ro{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=Eo.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(e){if(Sr(this.path)){if(null!=this.affectedTree.value)return n(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new gr(e));return new Ro(vr(),t,this.revert)}}return n(yr(this.path)===e,"operationForChild called for unrelated child."),new Ro(Ir(this.path),this.affectedTree,this.revert)}}class No{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=Eo.OVERWRITE}operationForChild(e){return Sr(this.path)?new No(this.source,vr(),this.snap.getImmediateChild(e)):new No(this.source,Ir(this.path),this.snap)}}class Po{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=Eo.MERGE}operationForChild(e){if(Sr(this.path)){const t=this.children.subtree(new gr(e));return t.isEmpty()?null:t.value?new No(this.source,vr(),t.value):new Po(this.source,vr(),t)}return n(yr(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new Po(this.source,Ir(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Oo{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(Sr(e))return this.isFullyInitialized()&&!this.filtered_;const t=yr(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}function Ao(e,t,n,s,r,o){const a=s.filter((e=>e.type===n));a.sort(((t,n)=>function(e,t,n){if(null==t.childName||null==n.childName)throw i("Should only compare child_ events.");const s=new xr(t.childName,t.snapshotNode),r=new xr(n.childName,n.snapshotNode);return e.index_.compare(s,r)}(e,t,n))),a.forEach((n=>{const i=function(e,t,n){return"value"===t.type||"child_removed"===t.type||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}(e,n,o);r.forEach((s=>{s.respondsTo(n.type)&&t.push(s.createEvent(i,e.query_))}))}))}function Do(e,t){return{eventCache:e,serverCache:t}}function Lo(e,t,n,i){return Do(new Oo(t,n,i),e.serverCache)}function Mo(e,t,n,i){return Do(e.eventCache,new Oo(t,n,i))}function xo(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function Fo(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Uo;class jo{constructor(e,t=(()=>(Uo||(Uo=new Hr(xs)),Uo))()){this.value=e,this.children=t}static fromObject(e){let t=new jo(null);return Ws(e,((e,n)=>{t=t.set(new gr(e),n)})),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:vr(),value:this.value};if(Sr(e))return null;{const n=yr(e),i=this.children.get(n);if(null!==i){const s=i.findRootMostMatchingPathAndValue(Ir(e),t);return null!=s?{path:Er(new gr(n),s.path),value:s.value}:null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,(()=>!0))}subtree(e){if(Sr(e))return this;{const t=yr(e),n=this.children.get(t);return null!==n?n.subtree(Ir(e)):new jo(null)}}set(e,t){if(Sr(e))return new jo(t,this.children);{const n=yr(e),i=(this.children.get(n)||new jo(null)).set(Ir(e),t),s=this.children.insert(n,i);return new jo(this.value,s)}}remove(e){if(Sr(e))return this.children.isEmpty()?new jo(null):new jo(null,this.children);{const t=yr(e),n=this.children.get(t);if(n){const i=n.remove(Ir(e));let s;return s=i.isEmpty()?this.children.remove(t):this.children.insert(t,i),null===this.value&&s.isEmpty()?new jo(null):new jo(this.value,s)}return this}}get(e){if(Sr(e))return this.value;{const t=yr(e),n=this.children.get(t);return n?n.get(Ir(e)):null}}setTree(e,t){if(Sr(e))return t;{const n=yr(e),i=(this.children.get(n)||new jo(null)).setTree(Ir(e),t);let s;return s=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new jo(this.value,s)}}fold(e){return this.fold_(vr(),e)}fold_(e,t){const n={};return this.children.inorderTraversal(((i,s)=>{n[i]=s.fold_(Er(e,i),t)})),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,vr(),t)}findOnPath_(e,t,n){const i=!!this.value&&n(t,this.value);if(i)return i;if(Sr(e))return null;{const i=yr(e),s=this.children.get(i);return s?s.findOnPath_(Ir(e),Er(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,vr(),t)}foreachOnPath_(e,t,n){if(Sr(e))return this;{this.value&&n(t,this.value);const i=yr(e),s=this.children.get(i);return s?s.foreachOnPath_(Ir(e),Er(t,i),n):new jo(null)}}foreach(e){this.foreach_(vr(),e)}foreach_(e,t){this.children.inorderTraversal(((n,i)=>{i.foreach_(Er(e,n),t)})),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal(((t,n)=>{n.value&&e(t,n.value)}))}}class Wo{constructor(e){this.writeTree_=e}static empty(){return new Wo(new jo(null))}}function qo(e,t,n){if(Sr(t))return new Wo(new jo(n));{const i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){const s=i.path;let r=i.value;const o=kr(s,t);return r=r.updateChild(o,n),new Wo(e.writeTree_.set(s,r))}{const i=new jo(n),s=e.writeTree_.setTree(t,i);return new Wo(s)}}}function Vo(e,t,n){let i=e;return Ws(n,((e,n)=>{i=qo(i,Er(t,e),n)})),i}function Ho(e,t){if(Sr(t))return Wo.empty();{const n=e.writeTree_.setTree(t,new jo(null));return new Wo(n)}}function zo(e,t){return null!=Bo(e,t)}function Bo(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(kr(n.path,t)):null}function $o(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(Zr,((e,n)=>{t.push(new xr(e,n))})):e.writeTree_.children.inorderTraversal(((e,n)=>{null!=n.value&&t.push(new xr(e,n.value))})),t}function Ko(e,t){if(Sr(t))return e;{const n=Bo(e,t);return new Wo(null!=n?new jo(n):e.writeTree_.subtree(t))}}function Go(e){return e.writeTree_.isEmpty()}function Yo(e,t){return Jo(vr(),e.writeTree_,t)}function Jo(e,t,i){if(null!=t.value)return i.updateChild(e,t.value);{let s=null;return t.children.inorderTraversal(((t,r)=>{".priority"===t?(n(null!==r.value,"Priority writes must always be leaf nodes"),s=r.value):i=Jo(Er(e,t),r,i)})),i.getChild(e).isEmpty()||null===s||(i=i.updateChild(Er(e,".priority"),s)),i}}function Qo(e,t){return ca(t,e)}function Xo(e,t){if(e.snap)return Nr(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&Nr(Er(e.path,n),t))return!0;return!1}function Zo(e){return e.visible}function ea(e,t,n){let s=Wo.empty();for(let r=0;r{i=i.updateImmediateChild(e,t)})),i;if(n){const s=Ko(e.visibleWrites,t);return n.forEachChild(Zr,((e,t)=>{const n=Yo(Ko(s,new gr(e)),t);i=i.updateImmediateChild(e,n)})),$o(s).forEach((e=>{i=i.updateImmediateChild(e.name,e.node)})),i}return $o(Ko(e.visibleWrites,t)).forEach((e=>{i=i.updateImmediateChild(e.name,e.node)})),i}(e.writeTree,e.treePath,t)}function sa(e,t,i,s){return function(e,t,i,s,r){n(s||r,"Either existingEventSnap or existingServerSnap must exist");const o=Er(t,i);if(zo(e.visibleWrites,o))return null;{const t=Ko(e.visibleWrites,o);return Go(t)?r.getChild(i):Yo(t,r.getChild(i))}}(e.writeTree,e.treePath,t,i,s)}function ra(e,t){return function(e,t){return Bo(e.visibleWrites,t)}(e.writeTree,Er(e.treePath,t))}function oa(e,t,n){return function(e,t,n,i){const s=Er(t,n),r=Bo(e.visibleWrites,s);return null!=r?r:i.isCompleteForChild(n)?Yo(Ko(e.visibleWrites,s),i.getNode().getImmediateChild(n)):null}(e.writeTree,e.treePath,t,n)}function aa(e,t){return ca(Er(e.treePath,t),e.writeTree)}function ca(e,t){return{treePath:e,writeTree:t}}class la{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,s=e.childName;n("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),n(".priority"!==s,"Only non-priority child changes can be tracked.");const r=this.changeMap.get(s);if(r){const n=r.type;if("child_added"===t&&"child_removed"===n)this.changeMap.set(s,fo(s,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===n)this.changeMap.delete(s);else if("child_removed"===t&&"child_changed"===n)this.changeMap.set(s,(o=s,{type:"child_removed",snapshotNode:r.oldSnap,childName:o}));else if("child_changed"===t&&"child_added"===n)this.changeMap.set(s,function(e,t){return{type:"child_added",snapshotNode:t,childName:e}}(s,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==n)throw i("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(s,fo(s,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(s,e);var o}getChanges(){return Array.from(this.changeMap.values())}}const ha=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class ua{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);{const t=null!=this.optCompleteServerCache_?new Oo(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return oa(this.writes_,e,t)}}getChildAfterChild(e,t,n){const i=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:Fo(this.viewCache_),s=function(e,t,n,i,s,r){return function(e,t,n,i,s,r,o){let a;const c=Ko(e.visibleWrites,t),l=Bo(c,vr());if(null!=l)a=l;else{if(null==n)return[];a=Yo(c,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const e=[],t=o.getCompare(),n=r?a.getReverseIteratorFrom(i,o):a.getIteratorFrom(i,o);let c=n.getNext();for(;c&&e.length1)return t;const s=Ir(n),r=c.getNode().getImmediateChild(e).updateChild(s,i);l=".priority"===e?h.updatePriority(c.getNode(),r):h.updateChild(c.getNode(),e,r,s,ha,null)}const u=Mo(t,l,c.isFullyInitialized()||Sr(n),h.filtersNodes());return da(e,u,n,s,new ua(s,u,r),a)}function fa(e,t,n,i,s,r,o){const a=t.eventCache;let c,l;const h=new ua(s,t,r);if(Sr(n))l=e.filter.updateFullNode(t.eventCache.getNode(),i,o),c=Lo(t,l,!0,e.filter.filtersNodes());else{const s=yr(n);if(".priority"===s)l=e.filter.updatePriority(t.eventCache.getNode(),i),c=Lo(t,l,a.isFullyInitialized(),a.isFiltered());else{const r=Ir(n),l=a.getNode().getImmediateChild(s);let u;if(Sr(r))u=i;else{const e=h.getCompleteChild(s);u=null!=e?".priority"===br(r)&&e.getChild(Tr(r)).isEmpty()?e:e.updateChild(r,i):ao.EMPTY_NODE}c=l.equals(u)?t:Lo(t,e.filter.updateChild(a.getNode(),s,u,r,h,o),a.isFullyInitialized(),e.filter.filtersNodes())}}return c}function _a(e,t){return e.eventCache.isCompleteForChild(t)}function ma(e,t,n){return n.foreach(((e,n)=>{t=t.updateChild(e,n)})),t}function ga(e,t,n,i,s,r,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let c,l=t;c=Sr(n)?i:new jo(null).setTree(n,i);const h=t.serverCache.getNode();return c.children.inorderTraversal(((n,i)=>{if(h.hasChild(n)){const c=ma(0,t.serverCache.getNode().getImmediateChild(n),i);l=pa(e,l,new gr(n),c,s,r,o,a)}})),c.children.inorderTraversal(((n,i)=>{const c=!t.serverCache.isCompleteForChild(n)&&null===i.value;if(!h.hasChild(n)&&!c){const c=ma(0,t.serverCache.getNode().getImmediateChild(n),i);l=pa(e,l,new gr(n),c,s,r,o,a)}})),l}function va(e,t){const n=Fo(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!Sr(t)&&!n.getImmediateChild(yr(t)).isEmpty())?n.getChild(t):null}function ya(e,t,s,r){t.type===Eo.MERGE&&null!==t.source.queryId&&(n(Fo(e.viewCache_),"We should always have a full cache before handling merges"),n(xo(e.viewCache_),"Missing event cache, even though we have a server cache"));const o=e.viewCache_,a=function(e,t,s,r,o){const a=new la;let c,l;if(s.type===Eo.OVERWRITE){const i=s;i.source.fromUser?c=fa(e,t,i.path,i.snap,r,o,a):(n(i.source.fromServer,"Unknown source."),l=i.source.tagged||t.serverCache.isFiltered()&&!Sr(i.path),c=pa(e,t,i.path,i.snap,r,o,l,a))}else if(s.type===Eo.MERGE){const i=s;i.source.fromUser?c=function(e,t,n,i,s,r,o){let a=t;return i.foreach(((i,c)=>{const l=Er(n,i);_a(t,yr(l))&&(a=fa(e,a,l,c,s,r,o))})),i.foreach(((i,c)=>{const l=Er(n,i);_a(t,yr(l))||(a=fa(e,a,l,c,s,r,o))})),a}(e,t,i.path,i.children,r,o,a):(n(i.source.fromServer,"Unknown source."),l=i.source.tagged||t.serverCache.isFiltered(),c=ga(e,t,i.path,i.children,r,o,l,a))}else if(s.type===Eo.ACK_USER_WRITE){const i=s;c=i.revert?function(e,t,i,s,r,o){let a;if(null!=ra(s,i))return t;{const c=new ua(s,t,r),l=t.eventCache.getNode();let h;if(Sr(i)||".priority"===yr(i)){let i;if(t.serverCache.isFullyInitialized())i=na(s,Fo(t));else{const e=t.serverCache.getNode();n(e instanceof ao,"serverChildren would be complete if leaf node"),i=ia(s,e)}h=e.filter.updateFullNode(l,i,o)}else{const n=yr(i);let r=oa(s,n,t.serverCache);null==r&&t.serverCache.isCompleteForChild(n)&&(r=l.getImmediateChild(n)),h=null!=r?e.filter.updateChild(l,n,r,Ir(i),c,o):t.eventCache.getNode().hasChild(n)?e.filter.updateChild(l,n,ao.EMPTY_NODE,Ir(i),c,o):l,h.isEmpty()&&t.serverCache.isFullyInitialized()&&(a=na(s,Fo(t)),a.isLeafNode()&&(h=e.filter.updateFullNode(h,a,o)))}return a=t.serverCache.isFullyInitialized()||null!=ra(s,vr()),Lo(t,h,a,e.filter.filtersNodes())}}(e,t,i.path,r,o,a):function(e,t,n,i,s,r,o){if(null!=ra(s,n))return t;const a=t.serverCache.isFiltered(),c=t.serverCache;if(null!=i.value){if(Sr(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return pa(e,t,n,c.getNode().getChild(n),s,r,a,o);if(Sr(n)){let i=new jo(null);return c.getNode().forEachChild(Wr,((e,t)=>{i=i.set(new gr(e),t)})),ga(e,t,n,i,s,r,a,o)}return t}{let l=new jo(null);return i.foreach(((e,t)=>{const i=Er(n,e);c.isCompleteForPath(i)&&(l=l.set(e,c.getNode().getChild(i)))})),ga(e,t,n,l,s,r,a,o)}}(e,t,i.path,i.affectedTree,r,o,a)}else{if(s.type!==Eo.LISTEN_COMPLETE)throw i("Unknown operation type: "+s.type);c=function(e,t,n,i,s){const r=t.serverCache;return da(e,Mo(t,r.getNode(),r.isFullyInitialized()||Sr(n),r.isFiltered()),n,i,ha,s)}(e,t,s.path,r,a)}const h=a.getChanges();return function(e,t,n){const i=t.eventCache;if(i.isFullyInitialized()){const s=i.getNode().isLeafNode()||i.getNode().isEmpty(),r=xo(e);(n.length>0||!e.eventCache.isFullyInitialized()||s&&!i.getNode().equals(r)||!i.getNode().getPriority().equals(r.getPriority()))&&n.push({type:"value",snapshotNode:xo(t)})}}(t,c,h),{viewCache:c,changes:h}}(e.processor_,o,t,s,r);var c,l;return c=e.processor_,l=a.viewCache,n(l.eventCache.getNode().isIndexed(c.filter.getIndex()),"Event snap not indexed"),n(l.serverCache.getNode().isIndexed(c.filter.getIndex()),"Server snap not indexed"),n(a.viewCache.serverCache.isFullyInitialized()||!o.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=a.viewCache,function(e,t,n,i){const s=i?[i]:e.eventRegistrations_;return function(e,t,n,i){const s=[],r=[];return t.forEach((t=>{var n;"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&r.push((n=t.childName,{type:"child_moved",snapshotNode:t.snapshotNode,childName:n}))})),Ao(e,s,"child_removed",t,i,n),Ao(e,s,"child_added",t,i,n),Ao(e,s,"child_moved",r,i,n),Ao(e,s,"child_changed",t,i,n),Ao(e,s,"value",t,i,n),s}(e.eventGenerator_,t,n,s)}(e,a.changes,a.viewCache.eventCache.getNode(),null)}let wa,Ia;function ba(e,t,i,s){const r=t.source.queryId;if(null!==r){const o=e.views.get(r);return n(null!=o,"SyncTree gave us an op for an invalid query."),ya(o,t,i,s)}{let n=[];for(const r of e.views.values())n=n.concat(ya(r,t,i,s));return n}}function Ca(e,t){let n=null;for(const i of e.views.values())n=n||va(i,t);return n}class Ta{constructor(e){this.listenProvider_=e,this.syncPointTree_=new jo(null),this.pendingWriteTree_={visibleWrites:Wo.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Ea(e,t,i,s,r){return function(e,t,i,s,r){n(s>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),e.allWrites.push({path:t,snap:i,writeId:s,visible:r}),r&&(e.visibleWrites=qo(e.visibleWrites,t,i)),e.lastWriteId=s}(e.pendingWriteTree_,t,i,s,r),r?Na(e,new No({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,i)):[]}function Sa(e,t,i=!1){const s=function(e,t){for(let n=0;ne.writeId===t));n(i>=0,"removeWrite called with nonexistent writeId.");const s=e.allWrites[i];e.allWrites.splice(i,1);let r=s.visible,o=!1,a=e.allWrites.length-1;for(;r&&a>=0;){const t=e.allWrites[a];t.visible&&(a>=i&&Xo(t,s.path)?r=!1:Nr(s.path,t.path)&&(o=!0)),a--}return!!r&&(o?(function(e){e.visibleWrites=ea(e.allWrites,Zo,vr()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}(e),!0):(s.snap?e.visibleWrites=Ho(e.visibleWrites,s.path):Ws(s.children,(t=>{e.visibleWrites=Ho(e.visibleWrites,Er(s.path,t))})),!0))}(e.pendingWriteTree_,t)){let t=new jo(null);return null!=s.snap?t=t.set(vr(),!0):Ws(s.children,(e=>{t=t.set(new gr(e),!0)})),Na(e,new Ro(s.path,t,i))}return[]}function ka(e,t,n){return Na(e,new No({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,n))}function Ra(e,t,n){const i=e.pendingWriteTree_,s=e.syncPointTree_.findOnPath(t,((e,n)=>{const i=Ca(n,kr(e,t));if(i)return i}));return ta(i,t,s,n,!0)}function Na(e,t){return Pa(t,e.syncPointTree_,null,Qo(e.pendingWriteTree_,vr()))}function Pa(e,t,n,i){if(Sr(e.path))return Oa(e,t,n,i);{const s=t.get(vr());null==n&&null!=s&&(n=Ca(s,vr()));let r=[];const o=yr(e.path),a=e.operationForChild(o),c=t.children.get(o);if(c&&a){const e=n?n.getImmediateChild(o):null,t=aa(i,o);r=r.concat(Pa(a,c,e,t))}return s&&(r=r.concat(ba(s,e,i,n))),r}}function Oa(e,t,n,i){const s=t.get(vr());null==n&&null!=s&&(n=Ca(s,vr()));let r=[];return t.children.inorderTraversal(((t,s)=>{const o=n?n.getImmediateChild(t):null,a=aa(i,t),c=e.operationForChild(t);c&&(r=r.concat(Oa(c,s,o,a)))})),s&&(r=r.concat(ba(s,e,i,n))),r}function Aa(e,t){return e.tagToQueryMap.get(t)}function Da(e){const t=e.indexOf("$");return n(-1!==t&&t{const s=Ha(i,t.getImmediateChild(e),n);s!==i&&(r=r.updateImmediateChild(e,s))})),r}}class za{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function Ba(e,t){let n=t instanceof gr?t:new gr(t),i=e,s=yr(n);for(;null!==s;){const e=k(i.node.children,s)||{children:{},childCount:0};i=new za(s,i,e),n=Ir(n),s=yr(n)}return i}function $a(e){return e.node.value}function Ka(e,t){e.node.value=t,Xa(e)}function Ga(e){return e.node.childCount>0}function Ya(e,t){Ws(e.node.children,((n,i)=>{t(new za(n,e,i))}))}function Ja(e,t,n,i){n&&!i&&t(e),Ya(e,(e=>{Ja(e,t,!0,i)})),n&&i&&t(e)}function Qa(e){return new gr(null===e.parent?e.name:Qa(e.parent)+"/"+e.name)}function Xa(e){null!==e.parent&&function(e,t,n){const i=function(e){return void 0===$a(e)&&!Ga(e)}(n),s=S(e.node.children,t);i&&s?(delete e.node.children[t],e.node.childCount--,Xa(e)):i||s||(e.node.children[t]=n.node,e.node.childCount++,Xa(e))}(e.parent,e.name,e)}const Za=/[\[\].#$\/\u0000-\u001F\u007F]/,ec=/[\[\].#$\u0000-\u001F\u007F]/,tc=10485760,nc=function(e){return"string"==typeof e&&0!==e.length&&!Za.test(e)},ic=function(e,t,n){const i=n instanceof gr?new Pr(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+Ar(i));if("function"==typeof t)throw new Error(e+"contains a function "+Ar(i)+" with contents = "+t.toString());if(As(t))throw new Error(e+"contains "+t.toString()+" "+Ar(i));if("string"==typeof t&&t.length>tc/3&&U(t)>tc)throw new Error(e+"contains a string greater than "+tc+" utf8 bytes "+Ar(i)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,s=!1;if(Ws(t,((t,r)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(s=!0,!nc(t)))throw new Error(e+" contains an invalid key ("+t+") "+Ar(i)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var o,a;a=t,(o=i).parts_.length>0&&(o.byteLength_+=1),o.parts_.push(a),o.byteLength_+=U(a),Or(o),ic(e,r,i),function(e){const t=e.parts_.pop();e.byteLength_-=U(t),e.parts_.length>0&&(e.byteLength_-=1)}(i)})),n&&s)throw new Error(e+' contains ".value" child '+Ar(i)+" in addition to actual children.")}},sc=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!nc(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),function(e){return"string"==typeof e&&0!==e.length&&!ec.test(e)}(e)}(n))throw new Error(function(e,t){return`${e} failed: ${t} argument `}(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class rc{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function oc(e,t,n){(function(e,t){let n=null;for(let i=0;iNr(e,t)||Nr(t,e)))}function ac(e){for(let t=0;t=0)e.server_=new vo(e.repoInfo_,((t,n,i,s)=>{pc(e,t,n,i,s)}),e.authTokenProvider_,e.appCheckProvider_),setTimeout((()=>fc(e,!0)),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{T(n)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new Mr(e.repoInfo_,t,((t,n,i,s)=>{pc(e,t,n,i,s)}),(t=>{fc(e,t)}),(t=>{!function(e,t){Ws(t,((t,n)=>{_c(e,t,n)}))}(e,t)}),e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener((t=>{e.server_.refreshAuthToken(t)})),e.appCheckProvider_.addTokenChangeListener((t=>{e.server_.refreshAppCheckToken(t.token)})),e.statsReporter_=function(t,n){const i=t.toString();return sr[i]||(sr[i]=new To(e.stats_,e.server_)),sr[i]}(e.repoInfo_),e.infoData_=new yo,e.infoSyncTree_=new Ta({startListening:(t,n,i,s)=>{let r=[];const o=e.infoData_.getNode(t._path);return o.isEmpty()||(r=ka(e.infoSyncTree_,t._path,o),setTimeout((()=>{s("ok")}),0)),r},stopListening:()=>{}}),_c(e,"connected",!1),e.serverSyncTree_=new Ta({startListening:(t,n,i,s)=>(e.server_.listen(t,i,n,((n,i)=>{const r=s(n,i);oc(e.eventQueue_,t._path,r)})),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function uc(e){const t=e.infoData_.getNode(new gr(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function dc(e){return Fa({timestamp:uc(e)})}function pc(e,t,n,i,s){e.dataUpdateCount++;const r=new gr(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(s)if(i){const t=N(n,(e=>ho(e)));o=function(e,t,n,i){const s=Aa(e,i);if(s){const i=Da(s),r=i.path,o=i.queryId,a=kr(r,t),c=jo.fromObject(n);return La(e,r,new Po(ko(o),a,c))}return[]}(e.serverSyncTree_,r,t,s)}else{const t=ho(n);o=function(e,t,n,i){const s=Aa(e,i);if(null!=s){const i=Da(s),r=i.path,o=i.queryId,a=kr(r,t);return La(e,r,new No(ko(o),a,n))}return[]}(e.serverSyncTree_,r,t,s)}else if(i){const t=N(n,(e=>ho(e)));o=function(e,t,n){const i=jo.fromObject(n);return Na(e,new Po({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,i))}(e.serverSyncTree_,r,t)}else{const t=ho(n);o=ka(e.serverSyncTree_,r,t)}let a=r;o.length>0&&(a=wc(e,r)),oc(e.eventQueue_,a,o)}function fc(e,t){_c(e,"connected",t),!1===t&&function(e){gc(e,"onDisconnectEvents");const t=dc(e),n=wo();bo(e.onDisconnect_,vr(),((i,s)=>{const r=qa(i,s,e.serverSyncTree_,t);Io(n,i,r)}));let i=[];bo(n,vr(),((t,n)=>{i=i.concat(ka(e.serverSyncTree_,t,n));const s=function(e,t){const n=Qa(Ic(e,t)),i=Ba(e.transactionQueueTree_,t);return function(e,t,n){let i=void 0?e:e.parent;for(;null!==i;){if(t(i))return!0;i=i.parent}}(i,(t=>{Ec(e,t)})),Ec(e,i),Ja(i,(t=>{Ec(e,t)})),n}(e,t);wc(e,s)})),e.onDisconnect_=wo(),oc(e.eventQueue_,vr(),i)}(e)}function _c(e,t,n){const i=new gr("/.info/"+t),s=ho(n);e.infoData_.updateSnapshot(i,s);const r=ka(e.infoSyncTree_,i,s);oc(e.eventQueue_,i,r)}function mc(e){return e.nextWriteId_++}function gc(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),ks(n,...t)}function vc(e,t,n){return Ra(e.serverSyncTree_,t,n)||ao.EMPTY_NODE}function yc(e,t=e.transactionQueueTree_){if(t||Tc(e,t),$a(t)){const i=bc(e,t);n(i.length>0,"Sending zero length transaction queue"),i.every((e=>0===e.status))&&function(e,t,i){const s=i.map((e=>e.currentWriteId)),r=vc(e,t,s);let o=r;const a=r.hash();for(let e=0;e{gc(e,"transaction put response",{path:l.toString(),status:n});let s=[];if("ok"===n){const n=[];for(let t=0;ti[t].onComplete(null,!0,i[t].currentOutputSnapshotResolved))),i[t].unwatcher();Tc(e,Ba(e.transactionQueueTree_,t)),yc(e,e.transactionQueueTree_),oc(e.eventQueue_,t,s);for(let e=0;e{yc(e,t)}))}function wc(e,t){const i=Ic(e,t),s=Qa(i);return function(e,t,i){if(0===t.length)return;const s=[];let r=[];const o=t.filter((e=>0===e.status)).map((e=>e.currentWriteId));for(let c=0;c=cc)d=!0,u="maxretry",r=r.concat(Sa(e.serverSyncTree_,l.currentWriteId,!0));else{const n=vc(e,l.path,o);l.currentInputSnapshot=n;const i=t[c].update(n.val());if(void 0!==i){ic("transaction failed: Data returned ",i,l.path);let t=ho(i);"object"==typeof i&&null!=i&&S(i,".priority")||(t=t.updatePriority(n.getPriority()));const s=l.currentWriteId,a=dc(e),c=Va(t,n,a);l.currentOutputSnapshotRaw=t,l.currentOutputSnapshotResolved=c,l.currentWriteId=mc(e),o.splice(o.indexOf(s),1),r=r.concat(Ea(e.serverSyncTree_,l.path,c,l.currentWriteId,l.applyLocally)),r=r.concat(Sa(e.serverSyncTree_,s,!0))}else d=!0,u="nodata",r=r.concat(Sa(e.serverSyncTree_,l.currentWriteId,!0))}oc(e.eventQueue_,i,r),r=[],d&&(t[c].status=2,a=t[c].unwatcher,setTimeout(a,Math.floor(0)),t[c].onComplete&&("nodata"===u?s.push((()=>t[c].onComplete(null,!1,t[c].currentInputSnapshot))):s.push((()=>t[c].onComplete(new Error(u),!1,null)))))}var a;Tc(e,e.transactionQueueTree_);for(let e=0;ee.order-t.order)),n}function Cc(e,t,n){const i=$a(t);if(i)for(let e=0;e{Cc(e,t,n)}))}function Tc(e,t){const n=$a(t);if(n){let e=0;for(let t=0;t0?n:void 0)}Ya(t,(t=>{Tc(e,t)}))}function Ec(e,t){const i=$a(t);if(i){const s=[];let r=[],o=-1;for(let t=0;t.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||Ps("Cannot parse Firebase url. Please use https://.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Os("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const s="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new er(n.host,n.secure,i,s,t,"",i!==n.subdomain),path:new gr(n.pathString)}},kc=function(e){let t="",n="",i="",s="",r="",o=!0,a="https",c=443;if("string"==typeof e){let l=e.indexOf("//");l>=0&&(a=e.substring(0,l-1),e=e.substring(l+2));let h=e.indexOf("/");-1===h&&(h=e.length);let u=e.indexOf("?");-1===u&&(u=e.length),t=e.substring(0,Math.min(h,u)),h0){let i=n[e];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}(e.substring(h,u)));const d=function(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const i=n.split("=");2===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):Os(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,u)));l=t.indexOf(":"),l>=0?(o="https"===a||"wss"===a,c=parseInt(t.substring(l+1),10)):l=t.length;const p=t.slice(0,l);if("localhost"===p.toLowerCase())n="localhost";else if(p.split(".").length<=2)n=p;else{const e=t.indexOf(".");i=t.substring(0,e).toLowerCase(),n=t.substring(e+1),r=i}"ns"in d&&(r=d.ns)}return{host:t,port:c,domain:n,subdomain:i,secure:o,scheme:a,pathString:s,namespace:r}};class Rc{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return Sr(this._path)?null:br(this._path)}get ref(){return new Nc(this._repo,this._path)}get _queryIdentifier(){const e=go(this._queryParams),t=Us(e);return"{}"===t?"default":t}get _queryObject(){return go(this._queryParams)}isEqual(e){if(!((e=j(e))instanceof Rc))return!1;const t=this._repo===e._repo,n=Rr(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return t&&n&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;nfunction(e,t,n,i,s){let r=i||e.options.databaseURL;void 0===r&&(e.options.projectId||Ps("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),ks("Using default host for project ",e.options.projectId),r=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o,a,c=Sc(r,s),l=c.repoInfo;"undefined"!=typeof process&&process.env&&(a=process.env.FIREBASE_DATABASE_EMULATOR_HOST),a?(o=!0,r=`http://${a}?ns=${l.namespace}`,c=Sc(r,s),l=c.repoInfo):o=!c.repoInfo.secure;const h=s&&o?new Gs(Gs.OWNER):new Ks(e.name,e.options,t);sc("Invalid Firebase Database URL",c),Sr(c.path)||Ps("Database URL must point to the root of a Firebase Database (not including a child path).");const u=function(e,t,n,i){let s=Oc[t.name];s||(s={},Oc[t.name]=s);let r=s[e.toURLString()];return r&&Ps("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new lc(e,!1,n,i),s[e.toURLString()]=r,r}(l,e,h,new $s(e.name,n));return new Ac(u,e)}(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)),"PUBLIC").setMultipleInstances(!0)),it(ps,fs,void 0),it(ps,fs,"esm2017");const Dc=tt(function(){const e=document.getElementById("wp-script-module-data-@prc/firebase");try{return JSON.parse(e.textContent)}catch(e){return console.error(e),{}}}()),Lc=function(e=nt()){const t=Je(e,"auth");if(t.isInitialized())return t.getImmediate();const n=function(e,t){const n=Je(e,"auth");if(n.isInitialized()){const e=n.getImmediate();if(P(n.getOptions(),null!=t?t:{}))return e;wt(e,"already-initialized")}return n.initialize({options:t})}(e,{popupRedirectResolver:rs,persistence:[Ti,ai,li]}),i=_("authTokenSyncURL");if(i&&"boolean"==typeof isSecureContext&&isSecureContext){const e=new URL(i,location.origin);if(location.origin===e.origin){const t=(s=e.toString(),async e=>{const t=e&&await e.getIdTokenResult(),n=t&&((new Date).getTime()-Date.parse(t.issuedAtTime))/1e3;if(n&&n>ls)return;const i=null==t?void 0:t.token;hs!==i&&(hs=i,await fetch(s,{method:i?"POST":"DELETE",headers:i?{Authorization:`Bearer ${i}`}:{}}))});!function(e,t,n){j(e).beforeAuthStateChanged(t,n)}(n,t,(()=>t(n.currentUser))),function(e,n,i,s){j(e).onIdTokenChanged((e=>t(e)),void 0,void 0)}(n)}}var s;const r=p("auth");return r&&function(e,t,n){const i=kn(e);Et(i._canInitEmulator,i,"emulator-config-failed"),Et(/^https?:\/\//.test(t),i,"invalid-emulator-scheme");const s=!!(null==n?void 0:n.disableWarnings),r=Mn(t),{host:o,port:a}=function(e){const t=Mn(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const i=n[2].split("@").pop()||"",s=/^(\[[^\]]+\])(:|$)/.exec(i);if(s){const e=s[1];return{host:e,port:xn(i.substr(e.length+1))}}{const[e,t]=i.split(":");return{host:e,port:xn(t)}}}(t),c=null===a?"":`:${a}`;i.config.emulator={url:`${r}//${o}${c}/`},i.settings.appVerificationDisabledForTesting=!0,i.emulatorConfig=Object.freeze({host:o,port:a,protocol:r.replace(":",""),options:Object.freeze({disableWarnings:s})}),s||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())}()}(n,`http://${r}`),n}(),Mc=function(e,t,n){return Qe(e.app)?Promise.reject(Ct(e)):async function(e,t){return ii(kn(e),t)}(j(e),$n.credential(t,n)).catch((async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&async function(e){const t=kn(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}(e),t}))},xc=function(e,t,n,i){return j(e).onAuthStateChanged(t,n,i)},Fc=function(e){return j(e).signOut()},Uc=function(e=nt(),t){const n=Je(e,"database").getImmediate({identifier:t});if(!n._instanceStarted){const e=(e=>{const t=p("database");if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const i=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),i]:[t.substring(0,n),i]})();e&&function(e,t,n,i={}){(e=j(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&Ps("Cannot call useEmulator() after instance has already been initialized.");const s=e._repoInternal;let r;if(s.repoInfo_.nodeAdmin)i.mockUserToken&&Ps('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),r=new Gs(Gs.OWNER);else if(i.mockUserToken){const t="string"==typeof i.mockUserToken?i.mockUserToken:function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",i=e.iat||0,s=e.sub||e.user_id;if(!s)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const r=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:i,exp:i+3600,auth_time:i,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}}},e);return[c(JSON.stringify({alg:"none",type:"JWT"})),c(JSON.stringify(r)),""].join(".")}(i.mockUserToken,e.app.options.projectId);r=new Gs(t)}!function(e,t,n,i){e.repoInfo_=new er(`${t}:${n}`,!1,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0),i&&(e.authTokenProvider_=i)}(s,t,n,r)}(n,...e)}return n}();var jc=t.yA,Wc=t.j2,qc=t.C3,Vc=t.hg,Hc=t.x9,zc=t.CI;export{jc as app,Wc as auth,qc as getDatabase,Vc as onAuthStateChanged,Hc as signInWithEmailAndPassword,zc as signOut}; +var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})}};e.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),e.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var t={};e.d(t,{yA:()=>jc,j2:()=>Wc,R4:()=>Bc,C3:()=>Kc,hg:()=>Vc,J1:()=>zc,x9:()=>qc,CI:()=>Hc,RE:()=>$c});const n=function(e,t){if(!e)throw i(t)},i=function(e){return new Error("Firebase Database (${JSCORE_VERSION}) INTERNAL ASSERT FAILED: "+e)},s=function(e){const t=[];let n=0;for(let i=0;i>6|192,t[n++]=63&s|128):55296==(64512&s)&&i+1>18|240,t[n++]=s>>12&63|128,t[n++]=s>>6&63|128,t[n++]=63&s|128):(t[n++]=s>>12|224,t[n++]=s>>6&63|128,t[n++]=63&s|128)}return t},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(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let t=0;t>2,h=(3&s)<<4|o>>4;let u=(15&o)<<2|c>>6,d=63&c;a||(d=64,r||(u=64)),i.push(n[l],n[h],n[u],n[d])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(s(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,i=0;for(;n191&&s<224){const r=e[n++];t[i++]=String.fromCharCode((31&s)<<6|63&r)}else if(s>239&&s<365){const r=((7&s)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[i++]=String.fromCharCode(55296+(r>>10)),t[i++]=String.fromCharCode(56320+(1023&r))}else{const r=e[n++],o=e[n++];t[i++]=String.fromCharCode((15&s)<<12|(63&r)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,i=[];for(let t=0;t>4;if(i.push(l),64!==a){const e=r<<4&240|a>>2;if(i.push(e),64!==c){const e=a<<6&192|c;i.push(e)}}}return i},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class o extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const a=function(e){const t=s(e);return r.encodeByteArray(t,!0)},c=function(e){return a(e).replace(/\./g,"")},l=function(e){try{return r.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function h(e){return u(void 0,e)}function u(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=u(e[n],t[n]));return e}const d=()=>{try{return function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==e.g)return e.g;throw new Error("Unable to locate global object.")}().__FIREBASE_DEFAULTS__||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&l(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},p=e=>{var t,n;return null===(n=null===(t=d())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]},f=()=>{var e;return null===(e=d())||void 0===e?void 0:e.config},_=e=>{var t;return null===(t=d())||void 0===t?void 0:t[`_${e}`]};class m{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function g(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function v(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(g())}function y(){return"object"==typeof navigator&&"ReactNative"===navigator.product}class w extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,w.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,I.prototype.create)}}class I{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],r=s?function(e,t){return e.replace(b,((e,n)=>{const i=t[n];return null!=i?String(i):`<${n}?>`}))}(s,n):"Error",o=`${this.serviceName}: ${r} (${i}).`;return new w(i,o,n)}}const b=/\{\$([^}]+)}/g;function C(e){return JSON.parse(e)}function T(e){return JSON.stringify(e)}const E=function(e){let t={},n={},i={},s="";try{const r=e.split(".");t=C(l(r[0])||""),n=C(l(r[1])||""),s=r[2],i=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:i,signature:s}};function S(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function k(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function R(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function N(e,t,n){const i={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=t.call(n,e[s],s,e));return i}function P(e,t){if(e===t)return!0;const n=Object.keys(e),i=Object.keys(t);for(const s of n){if(!i.includes(s))return!1;const n=e[s],r=t[s];if(O(n)&&O(r)){if(!P(n,r))return!1}else if(n!==r)return!1}for(const e of i)if(!n.includes(e))return!1;return!0}function O(e){return null!==e&&"object"==typeof e}function A(e){const t=[];for(const[n,i]of Object.entries(e))Array.isArray(i)?i.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(i));return t.length?"&"+t.join("&"):""}function D(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,i]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(i)}})),t}function L(e){const t=e.indexOf("?");if(!t)return"";const n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)}class M{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>>31)}let i,s,r=this.chain_[0],o=this.chain_[1],a=this.chain_[2],c=this.chain_[3],l=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(i=c^o&(a^c),s=1518500249):(i=o^a^c,s=1859775393):e<60?(i=o&a|c&(o|a),s=2400959708):(i=o^a^c,s=3395469782);const t=(r<<5|r>>>27)+i+l+s+n[e]&4294967295;l=c,c=a,a=4294967295&(o<<30|o>>>2),o=r,r=t}this.chain_[0]=this.chain_[0]+r&4294967295,this.chain_[1]=this.chain_[1]+o&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+c&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let i=0;const s=this.buf_;let r=this.inbuf_;for(;i=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let i=24;i>=0;i-=8)e[n]=this.chain_[t]>>i&255,++n;return e}}class x{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,n){let i;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");i=function(e,t){if("object"!=typeof e||null===e)return!1;for(const t of["next","error","complete"])if(t in e&&"function"==typeof e[t])return!0;return!1}(e)?e:{next:e,error:t,complete:n},void 0===i.next&&(i.next=F),void 0===i.error&&(i.error=F),void 0===i.complete&&(i.complete=F);const s=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch(e){}})),this.observers.push(i),s}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t{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 F(){}const U=function(e){let t=0;for(let n=0;n=55296&&i<=56319?(t+=4,n++):t+=3}return t};function j(e){return e&&e._delegate?e._delegate:e}class W{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 q="[DEFAULT]";class V{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new m;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),i=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(i)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(i)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(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:q})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=q){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=q){return this.instances.has(e)}getOptions(e=q){return this.instancesOptions.get(e)||{}}initialize(e={}){const{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`);const i=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(i);return i}onInit(e,t){var n;const i=this.normalizeInstanceIdentifier(t),s=null!==(n=this.onInitCallbacks.get(i))&&void 0!==n?n:new Set;s.add(e),this.onInitCallbacks.set(i,s);const r=this.instances.get(i);return r&&e(r,i),()=>{s.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const i of n)try{i(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:(i=e,i===q?void 0:i),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 i;return n||null}normalizeInstanceIdentifier(e=q){return this.component?this.component.multipleInstances?e:q:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class H{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){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new V(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const z=[];var B;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(B||(B={}));const $={debug:B.DEBUG,verbose:B.VERBOSE,info:B.INFO,warn:B.WARN,error:B.ERROR,silent:B.SILENT},K=B.INFO,G={[B.DEBUG]:"log",[B.VERBOSE]:"log",[B.INFO]:"info",[B.WARN]:"warn",[B.ERROR]:"error"},Y=(e,t,...n)=>{if(tt.some((t=>e instanceof t));let X,Z;const ee=new WeakMap,te=new WeakMap,ne=new WeakMap,ie=new WeakMap,se=new WeakMap;let re={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return te.get(e);if("objectStoreNames"===t)return e.objectStoreNames||ne.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return ae(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function oe(e){return"function"==typeof e?(t=e)!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(Z||(Z=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(ce(this),e),ae(ee.get(this))}:function(...e){return ae(t.apply(ce(this),e))}:function(e,...n){const i=t.call(ce(this),e,...n);return ne.set(i,e.sort?e.sort():[e]),ae(i)}:(e instanceof IDBTransaction&&function(e){if(te.has(e))return;const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",r),e.removeEventListener("abort",r)},s=()=>{t(),i()},r=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",s),e.addEventListener("error",r),e.addEventListener("abort",r)}));te.set(e,t)}(e),Q(e,X||(X=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,re):e);var t}function ae(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("success",s),e.removeEventListener("error",r)},s=()=>{t(ae(e.result)),i()},r=()=>{n(e.error),i()};e.addEventListener("success",s),e.addEventListener("error",r)}));return t.then((t=>{t instanceof IDBCursor&&ee.set(t,e)})).catch((()=>{})),se.set(t,e),t}(e);if(ie.has(e))return ie.get(e);const t=oe(e);return t!==e&&(ie.set(e,t),se.set(t,e)),t}const ce=e=>se.get(e),le=["get","getKey","getAll","getAllKeys","count"],he=["put","add","delete","clear"],ue=new Map;function de(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(ue.get(t))return ue.get(t);const n=t.replace(/FromIndex$/,""),i=t!==n,s=he.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!s&&!le.includes(n))return;const r=async function(e,...t){const r=this.transaction(e,s?"readwrite":"readonly");let o=r.store;return i&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),s&&r.done]))[0]};return ue.set(t,r),r}var pe;pe=re,re={...pe,get:(e,t,n)=>de(e,t)||pe.get(e,t,n),has:(e,t)=>!!de(e,t)||pe.has(e,t)};class fe{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null})).filter((e=>e)).join(" ")}}const _e="@firebase/app",me="0.10.7",ge=new J("@firebase/app"),ve="@firebase/app-compat",ye="@firebase/analytics-compat",we="@firebase/analytics",Ie="@firebase/app-check-compat",be="@firebase/app-check",Ce="@firebase/auth",Te="@firebase/auth-compat",Ee="@firebase/database",Se="@firebase/database-compat",ke="@firebase/functions",Re="@firebase/functions-compat",Ne="@firebase/installations",Pe="@firebase/installations-compat",Oe="@firebase/messaging",Ae="@firebase/messaging-compat",De="@firebase/performance",Le="@firebase/performance-compat",Me="@firebase/remote-config",xe="@firebase/remote-config-compat",Fe="@firebase/storage",Ue="@firebase/storage-compat",je="@firebase/firestore",We="@firebase/vertexai-preview",qe="@firebase/firestore-compat",Ve="firebase",He="[DEFAULT]",ze={[_e]:"fire-core",[ve]:"fire-core-compat",[we]:"fire-analytics",[ye]:"fire-analytics-compat",[be]:"fire-app-check",[Ie]:"fire-app-check-compat",[Ce]:"fire-auth",[Te]:"fire-auth-compat",[Ee]:"fire-rtdb",[Se]:"fire-rtdb-compat",[ke]:"fire-fn",[Re]:"fire-fn-compat",[Ne]:"fire-iid",[Pe]:"fire-iid-compat",[Oe]:"fire-fcm",[Ae]:"fire-fcm-compat",[De]:"fire-perf",[Le]:"fire-perf-compat",[Me]:"fire-rc",[xe]:"fire-rc-compat",[Fe]:"fire-gcs",[Ue]:"fire-gcs-compat",[je]:"fire-fst",[qe]:"fire-fst-compat",[We]:"fire-vertex","fire-js":"fire-js",[Ve]:"fire-js-all"},Be=new Map,$e=new Map,Ke=new Map;function Ge(e,t){try{e.container.addComponent(t)}catch(n){ge.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function Ye(e){const t=e.name;if(Ke.has(t))return ge.debug(`There were multiple attempts to register component ${t}.`),!1;Ke.set(t,e);for(const t of Be.values())Ge(t,e);for(const t of $e.values())Ge(t,e);return!0}function Je(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function Qe(e){return void 0!==e.settings}const Xe=new I("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 Ze{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 W("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 Xe.create("app-deleted",{appName:this._name})}}const et="10.12.4";function tt(e,t={}){let n=e;"object"!=typeof t&&(t={name:t});const i=Object.assign({name:He,automaticDataCollectionEnabled:!1},t),s=i.name;if("string"!=typeof s||!s)throw Xe.create("bad-app-name",{appName:String(s)});if(n||(n=f()),!n)throw Xe.create("no-options");const r=Be.get(s);if(r){if(P(n,r.options)&&P(i,r.config))return r;throw Xe.create("duplicate-app",{appName:s})}const o=new H(s);for(const e of Ke.values())o.addComponent(e);const a=new Ze(n,i,o);return Be.set(s,a),a}function nt(e=He){const t=Be.get(e);if(!t&&e===He&&f())return tt();if(!t)throw Xe.create("no-app",{appName:e});return t}function it(e,t,n){var i;let s=null!==(i=ze[e])&&void 0!==i?i:e;n&&(s+=`-${n}`);const r=s.match(/\s|\//),o=t.match(/\s|\//);if(r||o){const e=[`Unable to register library "${s}" with version "${t}":`];return r&&e.push(`library name "${s}" contains illegal characters (whitespace or "/")`),r&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void ge.warn(e.join(" "))}Ye(new W(`${s}-version`,(()=>({library:s,version:t})),"VERSION"))}const st="firebase-heartbeat-database",rt=1,ot="firebase-heartbeat-store";let at=null;function ct(){return at||(at=function(e,t,{blocked:n,upgrade:i,blocking:s,terminated:r}={}){const o=indexedDB.open(e,t),a=ae(o);return i&&o.addEventListener("upgradeneeded",(e=>{i(ae(o.result),e.oldVersion,e.newVersion,ae(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),a.then((e=>{r&&e.addEventListener("close",(()=>r())),s&&e.addEventListener("versionchange",(e=>s(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}(st,rt,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(ot)}catch(e){console.warn(e)}}}).catch((e=>{throw Xe.create("idb-open",{originalErrorMessage:e.message})}))),at}async function lt(e,t){try{const n=(await ct()).transaction(ot,"readwrite"),i=n.objectStore(ot);await i.put(t,ht(e)),await n.done}catch(e){if(e instanceof w)ge.warn(e.message);else{const t=Xe.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});ge.warn(t.message)}}}function ht(e){return`${e.name}!${e.options.appId}`}class ut{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new pt(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){var e,t;const n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=dt();if((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)))&&this._heartbeatsCache.lastSentHeartbeatDate!==i&&!this._heartbeatsCache.heartbeats.some((e=>e.date===i)))return this._heartbeatsCache.heartbeats.push({date:i,agent:n}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){var e;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"";const t=dt(),{heartbeatsToSend:n,unsentEntries:i}=function(e,t=1024){const n=[];let i=e.slice();for(const s of e){const e=n.find((e=>e.agent===s.agent));if(e){if(e.dates.push(s.date),ft(n)>t){e.dates.pop();break}}else if(n.push({agent:s.agent,dates:[s.date]}),ft(n)>t){n.pop();break}i=i.slice(1)}return{heartbeatsToSend:n,unsentEntries:i}}(this._heartbeatsCache.heartbeats),s=c(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}}function dt(){return(new Date).toISOString().substring(0,10)}class pt{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!function(){try{return"object"==typeof indexedDB}catch(e){return!1}}()&&new Promise(((e,t)=>{try{let n=!0;const i="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(i);s.onsuccess=()=>{s.result.close(),n||self.indexedDB.deleteDatabase(i),e(!0)},s.onupgradeneeded=()=>{n=!1},s.onerror=()=>{var e;t((null===(e=s.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}})).then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=(await ct()).transaction(ot),n=await t.objectStore(ot).get(ht(e));return await t.done,n}catch(e){if(e instanceof w)ge.warn(e.message);else{const t=Xe.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});ge.warn(t.message)}}}(this.app);return(null==e?void 0:e.heartbeats)?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return lt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return lt(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function ft(e){return c(JSON.stringify({version:2,heartbeats:e})).length}function _t(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);snew fe(e)),"PRIVATE")),Ye(new W("heartbeat",(e=>new ut(e)),"PRIVATE")),it(_e,me,""),it(_e,me,"esm2017"),it("fire-js",""),it("firebase","10.12.4","app"),Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;const mt=function(){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."}},gt=new I("auth","Firebase",{"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."}),vt=new J("@firebase/auth");function yt(e,...t){vt.logLevel<=B.ERROR&&vt.error(`Auth (${et}): ${e}`,...t)}function wt(e,...t){throw Tt(e,...t)}function It(e,...t){return Tt(e,...t)}function bt(e,t,n){const i=Object.assign(Object.assign({},mt()),{[t]:n});return new I("auth","Firebase",i).create(t,{appName:e.name})}function Ct(e){return bt(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function Tt(e,...t){if("string"!=typeof e){const n=t[0],i=[...t.slice(1)];return i[0]&&(i[0].appName=e.name),e._errorFactory.create(n,...i)}return gt.create(e,...t)}function Et(e,t,...n){if(!e)throw Tt(t,...n)}function St(e){const t="INTERNAL ASSERTION FAILED: "+e;throw yt(t),new Error(t)}function kt(e,t){e||St(t)}function Rt(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Nt(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}function Pt(){return!("undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===Nt()||"https:"===Nt()||function(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}()||"connection"in navigator))||navigator.onLine}class Ot{constructor(e,t){this.shortDelay=e,this.longDelay=t,kt(t>e,"Short delay should be less than long delay!"),this.isMobile=v()||y()}get(){return Pt()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function At(e,t){kt(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class Dt{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"undefined"!=typeof self&&"fetch"in self?self.fetch:"undefined"!=typeof globalThis&&globalThis.fetch?globalThis.fetch:"undefined"!=typeof fetch?fetch:void St("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"undefined"!=typeof self&&"Headers"in self?self.Headers:"undefined"!=typeof globalThis&&globalThis.Headers?globalThis.Headers:"undefined"!=typeof Headers?Headers:void St("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"undefined"!=typeof self&&"Response"in self?self.Response:"undefined"!=typeof globalThis&&globalThis.Response?globalThis.Response:"undefined"!=typeof Response?Response:void St("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const Lt={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"},Mt=new Ot(3e4,6e4);function xt(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function Ft(e,t,n,i,s={}){return Ut(e,s,(async()=>{let s={},r={};i&&("GET"===t?r=i:s={body:JSON.stringify(i)});const o=A(Object.assign({key:e.config.apiKey},r)).slice(1),a=await e._getAdditionalHeaders();return a["Content-Type"]="application/json",e.languageCode&&(a["X-Firebase-Locale"]=e.languageCode),Dt.fetch()(Wt(e,e.config.apiHost,n,o),Object.assign({method:t,headers:a,referrerPolicy:"no-referrer"},s))}))}async function Ut(e,t,n){e._canInitEmulator=!1;const i=Object.assign(Object.assign({},Lt),t);try{const t=new Vt(e),s=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const r=await s.json();if("needConfirmation"in r)throw Ht(e,"account-exists-with-different-credential",r);if(s.ok&&!("errorMessage"in r))return r;{const t=s.ok?r.errorMessage:r.error.message,[n,o]=t.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===n)throw Ht(e,"credential-already-in-use",r);if("EMAIL_EXISTS"===n)throw Ht(e,"email-already-in-use",r);if("USER_DISABLED"===n)throw Ht(e,"user-disabled",r);const a=i[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o)throw bt(e,a,o);wt(e,a)}}catch(t){if(t instanceof w)throw t;wt(e,"network-request-failed",{message:String(t)})}}async function jt(e,t,n,i,s={}){const r=await Ft(e,t,n,i,s);return"mfaPendingCredential"in r&&wt(e,"multi-factor-auth-required",{_serverResponse:r}),r}function Wt(e,t,n,i){const s=`${t}${n}?${i}`;return e.config.emulator?At(e.config,s):`${e.config.apiScheme}://${s}`}function qt(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class Vt{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(It(this.auth,"network-request-failed"))),Mt.get())}))}clearNetworkTimeout(){clearTimeout(this.timer)}}function Ht(e,t,n){const i={appName:e.name};n.email&&(i.email=n.email),n.phoneNumber&&(i.phoneNumber=n.phoneNumber);const s=It(e,t,i);return s.customData._tokenResponse=n,s}function zt(e){return void 0!==e&&void 0!==e.enterprise}class Bt{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 qt(t.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}}async function $t(e,t){return Ft(e,"POST","/v1/accounts:lookup",t)}function Kt(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Gt(e){return 1e3*Number(e)}function Yt(e){const[t,n,i]=e.split(".");if(void 0===t||void 0===n||void 0===i)return yt("JWT malformed, contained fewer than 3 sections"),null;try{const e=l(n);return e?JSON.parse(e):(yt("Failed to decode base64 JWT payload"),null)}catch(e){return yt("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}function Jt(e){const t=Yt(e);return Et(t,"internal-error"),Et(void 0!==t.exp,"internal-error"),Et(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function Qt(e,t,n=!1){if(n)return t;try{return await t}catch(t){throw t instanceof w&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class Xt{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;const 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 Zt{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Kt(this.lastLoginAt),this.creationTime=Kt(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function en(e){var t;const n=e.auth,i=await e.getIdToken(),s=await Qt(e,$t(n,{idToken:i}));Et(null==s?void 0:s.users.length,n,"internal-error");const r=s.users[0];e._notifyReloadListener(r);const o=(null===(t=r.providerUserInfo)||void 0===t?void 0:t.length)?tn(r.providerUserInfo):[],a=(c=e.providerData,l=o,[...c.filter((e=>!l.some((t=>t.providerId===e.providerId)))),...l]);var c,l;const h=e.isAnonymous,u=!(e.email&&r.passwordHash||(null==a?void 0:a.length)),d=!!h&&u,p={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:a,metadata:new Zt(r.createdAt,r.lastLoginAt),isAnonymous:d};Object.assign(e,p)}function tn(e){return e.map((e=>{var{providerId:t}=e,n=_t(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 nn{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){Et(e.idToken,"internal-error"),Et(void 0!==e.idToken,"internal-error"),Et(void 0!==e.refreshToken,"internal-error");const t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):Jt(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){Et(0!==e.length,"internal-error");const t=Jt(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(Et(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){const{accessToken:n,refreshToken:i,expiresIn:s}=await async function(e,t){const n=await Ut(e,{},(async()=>{const n=A({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:i,apiKey:s}=e.config,r=Wt(e,i,"/v1/token",`key=${s}`),o=await e._getAdditionalHeaders();return o["Content-Type"]="application/x-www-form-urlencoded",Dt.fetch()(r,{method:"POST",headers:o,body:n})}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}(e,t);this.updateTokensAndExpiration(n,i,Number(s))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){const{refreshToken:n,accessToken:i,expirationTime:s}=t,r=new nn;return n&&(Et("string"==typeof n,"internal-error",{appName:e}),r.refreshToken=n),i&&(Et("string"==typeof i,"internal-error",{appName:e}),r.accessToken=i),s&&(Et("number"==typeof s,"internal-error",{appName:e}),r.expirationTime=s),r}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 nn,this.toJSON())}_performRefresh(){return St("not implemented")}}function sn(e,t){Et("string"==typeof e||void 0===e,"internal-error",{appName:t})}class rn{constructor(e){var{uid:t,auth:n,stsTokenManager:i}=e,s=_t(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new Xt(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=i,this.accessToken=i.accessToken,this.displayName=s.displayName||null,this.email=s.email||null,this.emailVerified=s.emailVerified||!1,this.phoneNumber=s.phoneNumber||null,this.photoURL=s.photoURL||null,this.isAnonymous=s.isAnonymous||!1,this.tenantId=s.tenantId||null,this.providerData=s.providerData?[...s.providerData]:[],this.metadata=new Zt(s.createdAt||void 0,s.lastLoginAt||void 0)}async getIdToken(e){const t=await Qt(this,this.stsTokenManager.getToken(this.auth,e));return Et(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=j(e),i=await n.getIdToken(t),s=Yt(i);Et(s&&s.exp&&s.auth_time&&s.iat,n.auth,"internal-error");const r="object"==typeof s.firebase?s.firebase:void 0,o=null==r?void 0:r.sign_in_provider;return{claims:s,token:i,authTime:Kt(Gt(s.auth_time)),issuedAtTime:Kt(Gt(s.iat)),expirationTime:Kt(Gt(s.exp)),signInProvider:o||null,signInSecondFactor:(null==r?void 0:r.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=j(e);await en(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(Et(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 rn(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){Et(!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 en(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(Qe(this.auth.app))return Promise.reject(Ct(this.auth));const e=await this.getIdToken();return await Qt(this,async function(e,t){return Ft(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,i,s,r,o,a,c,l;const h=null!==(n=t.displayName)&&void 0!==n?n:void 0,u=null!==(i=t.email)&&void 0!==i?i:void 0,d=null!==(s=t.phoneNumber)&&void 0!==s?s:void 0,p=null!==(r=t.photoURL)&&void 0!==r?r:void 0,f=null!==(o=t.tenantId)&&void 0!==o?o:void 0,_=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,m=null!==(c=t.createdAt)&&void 0!==c?c:void 0,g=null!==(l=t.lastLoginAt)&&void 0!==l?l:void 0,{uid:v,emailVerified:y,isAnonymous:w,providerData:I,stsTokenManager:b}=t;Et(v&&b,e,"internal-error");const C=nn.fromJSON(this.name,b);Et("string"==typeof v,e,"internal-error"),sn(h,e.name),sn(u,e.name),Et("boolean"==typeof y,e,"internal-error"),Et("boolean"==typeof w,e,"internal-error"),sn(d,e.name),sn(p,e.name),sn(f,e.name),sn(_,e.name),sn(m,e.name),sn(g,e.name);const T=new rn({uid:v,auth:e,email:u,emailVerified:y,displayName:h,isAnonymous:w,photoURL:p,phoneNumber:d,tenantId:f,stsTokenManager:C,createdAt:m,lastLoginAt:g});return I&&Array.isArray(I)&&(T.providerData=I.map((e=>Object.assign({},e)))),_&&(T._redirectEventId=_),T}static async _fromIdTokenResponse(e,t,n=!1){const i=new nn;i.updateFromServerResponse(t);const s=new rn({uid:t.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await en(s),s}static async _fromGetAccountInfoResponse(e,t,n){const i=t.users[0];Et(void 0!==i.localId,"internal-error");const s=void 0!==i.providerUserInfo?tn(i.providerUserInfo):[],r=!(i.email&&i.passwordHash||(null==s?void 0:s.length)),o=new nn;o.updateFromIdToken(n);const a=new rn({uid:i.localId,auth:e,stsTokenManager:o,isAnonymous:r}),c={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:s,metadata:new Zt(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash||(null==s?void 0:s.length))};return Object.assign(a,c),a}}const on=new Map;function an(e){kt(e instanceof Function,"Expected a class definition");let t=on.get(e);return t?(kt(t instanceof e,"Instance stored in cache mismatched with class"),t):(t=new e,on.set(e,t),t)}class cn{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}cn.type="NONE";const ln=cn;function hn(e,t,n){return`firebase:${e}:${t}:${n}`}class un{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:i,name:s}=this.auth;this.fullUserKey=hn(this.userKey,i.apiKey,s),this.fullPersistenceKey=hn("persistence",i.apiKey,s),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);return e?rn._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const 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 un(an(ln),e,n);const i=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let s=i[0]||an(ln);const r=hn(n,e.config.apiKey,e.name);let o=null;for(const n of t)try{const t=await n._get(r);if(t){const i=rn._fromJSON(e,t);n!==s&&(o=i),s=n;break}}catch(e){}const a=i.filter((e=>e._shouldAllowMigration));return s._shouldAllowMigration&&a.length?(s=a[0],o&&await s._set(r,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==s)try{await e._remove(r)}catch(e){}}))),new un(s,e,n)):new un(s,e,n)}}function dn(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(gn(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(pn(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(yn(t))return"Blackberry";if(wn(t))return"Webos";if(fn(t))return"Safari";if((t.includes("chrome/")||mn(t))&&!t.includes("edge/"))return"Chrome";if(vn(t))return"Android";{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,n=e.match(t);if(2===(null==n?void 0:n.length))return n[1]}return"Other"}function pn(e=g()){return/firefox\//i.test(e)}function fn(e=g()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function mn(e=g()){return/crios\//i.test(e)}function gn(e=g()){return/iemobile/i.test(e)}function vn(e=g()){return/android/i.test(e)}function yn(e=g()){return/blackberry/i.test(e)}function wn(e=g()){return/webos/i.test(e)}function In(e=g()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function bn(e=g()){return In(e)||vn(e)||wn(e)||yn(e)||/windows phone/i.test(e)||gn(e)}function Cn(e,t=[]){let n;switch(e){case"Browser":n=dn(g());break;case"Worker":n=`${dn(g())}-${e}`;break;default:n=e}const i=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${et}/${i}`}class Tn{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const n=t=>new Promise(((n,i)=>{try{n(e(t))}catch(e){i(e)}}));n.onAbort=t,this.queue.push(n);const i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){t.reverse();for(const e of t)try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==e?void 0:e.message})}}}class En{constructor(e){var t,n,i,s;const r=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(t=r.minPasswordLength)&&void 0!==t?t:6,r.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=r.maxPasswordLength),void 0!==r.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=r.containsLowercaseCharacter),void 0!==r.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=r.containsUppercaseCharacter),void 0!==r.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=r.containsNumericCharacter),void 0!==r.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=r.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!==(i=null===(n=e.allowedNonAlphanumericCharacters)||void 0===n?void 0:n.join(""))&&void 0!==i?i:"",this.forceUpgradeOnSignin=null!==(s=e.forceUpgradeOnSignin)&&void 0!==s&&s,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,n,i,s,r,o;const a={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,a),this.validatePasswordCharacterOptions(e,a),a.isValid&&(a.isValid=null===(t=a.meetsMinPasswordLength)||void 0===t||t),a.isValid&&(a.isValid=null===(n=a.meetsMaxPasswordLength)||void 0===n||n),a.isValid&&(a.isValid=null===(i=a.containsLowercaseLetter)||void 0===i||i),a.isValid&&(a.isValid=null===(s=a.containsUppercaseLetter)||void 0===s||s),a.isValid&&(a.isValid=null===(r=a.containsNumericCharacter)||void 0===r||r),a.isValid&&(a.isValid=null===(o=a.containsNonAlphanumericCharacter)||void 0===o||o),a}validatePasswordLengthOptions(e,t){const n=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),i&&(t.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,t){let n;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let i=0;i="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,i,s){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=s))}}class Sn{constructor(e,t,n,i){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Rn(this),this.idTokenSubscription=new Rn(this),this.beforeStateQueue=new Tn(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=gt,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=an(t)),this._initializationPromise=this.queue((async()=>{var n,i;if(!this._deleted&&(this.persistenceManager=await un.create(this,e),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(i=this.currentUser)||void 0===i?void 0:i.uid)||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUserFromIdToken(e){try{const t=await $t(this,{idToken:e}),n=await rn._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(n)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){var t;if(Qe(this.app)){const e=this.app.settings.authIdToken;return e?new Promise((t=>{setTimeout((()=>this.initializeCurrentUserFromIdToken(e).then(t,t)))})):this.directlySetCurrentUser(null)}const n=await this.assertedPersistence.getCurrentUser();let i=n,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const n=null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId,r=null==i?void 0:i._redirectEventId,o=await this.tryRedirectSignIn(e);n&&n!==r||!(null==o?void 0:o.user)||(i=o.user,s=!0)}if(!i)return this.directlySetCurrentUser(null);if(!i._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(i)}catch(e){i=n,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return Et(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}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 en(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;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if(Qe(this.app))return Promise.reject(Ct(this));const t=e?j(e):null;return t&&Et(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&&Et(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 Qe(this.app)?Promise.reject(Ct(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return Qe(this.app)?Promise.reject(Ct(this)):this.queue((async()=>{await this.assertedPersistence.setPersistence(an(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(){const e=await async function(e,t={}){return Ft(e,"GET","/v2/passwordPolicy",xt(e,t))}(this),t=new En(e);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new I("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser)e();else{const n=this.onAuthStateChanged((()=>{n(),e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await async function(e,t){return Ft(e,"POST","/v2/accounts:revokeToken",xt(e,t))}(this,t)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?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){if(!this.redirectPersistenceManager){const t=e&&an(e)||this._popupRedirectResolver;Et(t,this,"argument-error"),this.redirectPersistenceManager=await un.create(this,[an(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return this._isInitialized&&await this.queue((async()=>{})),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(n=this.redirectUser)||void 0===n?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const n=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,i){if(this._deleted)return()=>{};const s="function"==typeof t?t:t.next.bind(t);let r=!1;const o=this._isInitialized?Promise.resolve():this._initializationPromise;if(Et(o,this,"internal-error"),o.then((()=>{r||s(this.currentUser)})),"function"==typeof t){const s=e.addObserver(t,n,i);return()=>{r=!0,s()}}{const n=e.addObserver(t);return()=>{r=!0,n()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return Et(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=Cn(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);const n=await(null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());n&&(t["X-Firebase-Client"]=n);const i=await this._getAppCheckToken();return i&&(t["X-Firebase-AppCheck"]=i),t}async _getAppCheckToken(){var e;const t=await(null===(e=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getToken());return(null==t?void 0:t.error)&&function(e,...t){vt.logLevel<=B.WARN&&vt.warn(`Auth (${et}): ${e}`,...t)}(`Error while retrieving App Check token: ${t.error}`),null==t?void 0:t.token}}function kn(e){return j(e)}class Rn{constructor(e){this.auth=e,this.observer=null,this.addObserver=function(e,t){const n=new x(e,void 0);return n.subscribe.bind(n)}((e=>this.observer=e))}get next(){return Et(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let Nn={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function Pn(e){return Nn.loadJS(e)}function On(e){return`__${e}${Math.floor(1e6*Math.random())}`}class An{constructor(e){this.type="recaptcha-enterprise",this.auth=kn(e)}async verify(e="verify",t=!1){function n(t,n,i){const s=window.grecaptcha;zt(s)?s.enterprise.ready((()=>{s.enterprise.execute(t,{action:e}).then((e=>{n(e)})).catch((()=>{n("NO_RECAPTCHA")}))})):i(Error("No reCAPTCHA enterprise script loaded."))}return new Promise(((e,i)=>{(async function(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,n)=>{(async function(e,t){return Ft(e,"GET","/v2/recaptchaConfig",xt(e,t))})(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((i=>{if(void 0!==i.recaptchaKey){const n=new Bt(i);return null==e.tenantId?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,t(n.siteKey)}n(new Error("recaptcha Enterprise site key undefined"))})).catch((e=>{n(e)}))}))})(this.auth).then((s=>{if(!t&&zt(window.grecaptcha))n(s,e,i);else{if("undefined"==typeof window)return void i(new Error("RecaptchaVerifier is only supported in browser"));let t=Nn.recaptchaEnterpriseScript;0!==t.length&&(t+=s),Pn(t).then((()=>{n(s,e,i)})).catch((e=>{i(e)}))}})).catch((e=>{i(e)}))}))}}async function Dn(e,t,n,i=!1){const s=new An(e);let r;try{r=await s.verify(n)}catch(e){r=await s.verify(n,!0)}const o=Object.assign({},t);return i?Object.assign(o,{captchaResp:r}):Object.assign(o,{captchaResponse:r}),Object.assign(o,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(o,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),o}async function Ln(e,t,n,i){var s;if(null===(s=e._getRecaptchaConfig())||void 0===s?void 0:s.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const s=await Dn(e,t,n,"getOobCode"===n);return i(e,s)}return i(e,t).catch((async s=>{if("auth/missing-recaptcha-token"===s.code){console.log(`${n} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const s=await Dn(e,t,n,"getOobCode"===n);return i(e,s)}return Promise.reject(s)}))}function Mn(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function xn(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}class Fn{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return St("not implemented")}_getIdTokenResponse(e){return St("not implemented")}_linkToIdToken(e,t){return St("not implemented")}_getReauthenticationResolver(e){return St("not implemented")}}async function Un(e,t){return Ft(e,"POST","/v1/accounts:resetPassword",xt(e,t))}async function jn(e,t){return Ft(e,"POST","/v1/accounts:signUp",t)}async function Wn(e,t){return jt(e,"POST","/v1/accounts:signInWithPassword",xt(e,t))}async function qn(e,t){return async function(e,t){return Ft(e,"POST","/v1/accounts:sendOobCode",xt(e,t))}(e,t)}class Vn extends Fn{constructor(e,t,n,i=null){super("password",n),this._email=e,this._password=t,this._tenantId=i}static _fromEmailAndPassword(e,t){return new Vn(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new Vn(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e;if((null==t?void 0:t.email)&&(null==t?void 0:t.password)){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return Ln(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",Wn);case"emailLink":return async function(e,t){return jt(e,"POST","/v1/accounts:signInWithEmailLink",xt(e,t))}(e,{email:this._email,oobCode:this._password});default:wt(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Ln(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",jn);case"emailLink":return async function(e,t){return jt(e,"POST","/v1/accounts:signInWithEmailLink",xt(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:wt(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Hn(e,t){return jt(e,"POST","/v1/accounts:signInWithIdp",xt(e,t))}class zn extends Fn{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new zn(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):wt("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){const t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:i}=t,s=_t(t,["providerId","signInMethod"]);if(!n||!i)return null;const r=new zn(n,i);return r.idToken=s.idToken||void 0,r.accessToken=s.accessToken||void 0,r.secret=s.secret,r.nonce=s.nonce,r.pendingToken=s.pendingToken||null,r}_getIdTokenResponse(e){return Hn(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Hn(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Hn(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=A(t)}return e}}const Bn={USER_NOT_FOUND:"user-not-found"};class $n extends Fn{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new $n({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new $n({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return jt(e,"POST","/v1/accounts:signInWithPhoneNumber",xt(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){const n=await jt(e,"POST","/v1/accounts:signInWithPhoneNumber",xt(e,t));if(n.temporaryProof)throw Ht(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return jt(e,"POST","/v1/accounts:signInWithPhoneNumber",xt(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Bn)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:i}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:i}}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){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:s}=e;return n||t||i||s?new $n({verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:s}):null}}class Kn{constructor(e){var t,n,i,s,r,o;const a=D(L(e)),c=null!==(t=a.apiKey)&&void 0!==t?t:null,l=null!==(n=a.oobCode)&&void 0!==n?n:null,h=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=a.mode)&&void 0!==i?i:null);Et(c&&l&&h,"argument-error"),this.apiKey=c,this.operation=h,this.code=l,this.continueUrl=null!==(s=a.continueUrl)&&void 0!==s?s:null,this.languageCode=null!==(r=a.languageCode)&&void 0!==r?r:null,this.tenantId=null!==(o=a.tenantId)&&void 0!==o?o:null}static parseLink(e){const t=function(e){const t=D(L(e)).link,n=t?D(L(t)).deep_link_id:null,i=D(L(e)).deep_link_id;return(i?D(L(i)).link:null)||i||n||t||e}(e);try{return new Kn(t)}catch(e){return null}}}class Gn{constructor(){this.providerId=Gn.PROVIDER_ID}static credential(e,t){return Vn._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=Kn.parseLink(t);return Et(n,"argument-error"),Vn._fromEmailAndCode(e,n.code,n.tenantId)}}Gn.PROVIDER_ID="password",Gn.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Gn.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Yn{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 Jn extends Yn{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Qn extends Jn{constructor(){super("facebook.com")}static credential(e){return zn._fromParams({providerId:Qn.PROVIDER_ID,signInMethod:Qn.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Qn.credentialFromTaggedObject(e)}static credentialFromError(e){return Qn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Qn.credential(e.oauthAccessToken)}catch(e){return null}}}Qn.FACEBOOK_SIGN_IN_METHOD="facebook.com",Qn.PROVIDER_ID="facebook.com";class Xn extends Jn{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return zn._fromParams({providerId:Xn.PROVIDER_ID,signInMethod:Xn.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Xn.credentialFromTaggedObject(e)}static credentialFromError(e){return Xn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return Xn.credential(t,n)}catch(e){return null}}}Xn.GOOGLE_SIGN_IN_METHOD="google.com",Xn.PROVIDER_ID="google.com";class Zn extends Jn{constructor(){super("github.com")}static credential(e){return zn._fromParams({providerId:Zn.PROVIDER_ID,signInMethod:Zn.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Zn.credentialFromTaggedObject(e)}static credentialFromError(e){return Zn.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Zn.credential(e.oauthAccessToken)}catch(e){return null}}}Zn.GITHUB_SIGN_IN_METHOD="github.com",Zn.PROVIDER_ID="github.com";class ei extends Jn{constructor(){super("twitter.com")}static credential(e,t){return zn._fromParams({providerId:ei.PROVIDER_ID,signInMethod:ei.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return ei.credentialFromTaggedObject(e)}static credentialFromError(e){return ei.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return ei.credential(t,n)}catch(e){return null}}}ei.TWITTER_SIGN_IN_METHOD="twitter.com",ei.PROVIDER_ID="twitter.com";class ti{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,i=!1){const s=await rn._fromIdTokenResponse(e,n,i),r=ni(n);return new ti({user:s,providerId:r,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);const i=ni(n);return new ti({user:e,providerId:i,_tokenResponse:n,operationType:t})}}function ni(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class ii extends w{constructor(e,t,n,i){var s;super(t.code,t.message),this.operationType=n,this.user=i,Object.setPrototypeOf(this,ii.prototype),this.customData={appName:e.name,tenantId:null!==(s=e.tenantId)&&void 0!==s?s:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,i){return new ii(e,t,n,i)}}function si(e,t,n,i){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch((n=>{if("auth/multi-factor-auth-required"===n.code)throw ii._fromErrorAndOperation(e,n,t,i);throw n}))}async function ri(e,t,n=!1){if(Qe(e.app))return Promise.reject(Ct(e));const i="signIn",s=await si(e,i,t),r=await ti._fromIdTokenResponse(e,i,s);return n||await e._updateCurrentUser(r.user),r}class oi{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?ai._fromServerResponse(e,t):"totpInfo"in t?ci._fromServerResponse(e,t):wt(e,"internal-error")}}class ai extends oi{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new ai(t)}}class ci extends oi{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new ci(t)}}async function li(e){const t=kn(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}new WeakMap;const hi="__sak";class ui{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(hi,"1"),this.storage.removeItem(hi),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){const 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 di extends ui{constructor(){super((()=>window.localStorage),"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=function(){const e=g();return fn(e)||In(e)}()&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=bn(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t),i=this.localCache[t];n!==i&&e(t,i,n)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys(((e,t,n)=>{this.notifyListeners(e,n)}));const n=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(n);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(n,e.newValue):this.storage.removeItem(n);else if(this.localCache[n]===e.newValue&&!t)return}const i=()=>{const e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},s=this.storage.getItem(n);!function(){const e=g();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}()||10!==document.documentMode||s===e.newValue||e.newValue===e.oldValue?i():setTimeout(i,10)}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const e of Array.from(n))e(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!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){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}di.type="LOCAL";const pi=di;class fi extends ui{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){}_removeListener(e,t){}}fi.type="SESSION";const _i=fi;class mi{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const n=new mi(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:i,data:s}=t.data,r=this.handlersMap[i];if(!(null==r?void 0:r.size))return;t.ports[0].postMessage({status:"ack",eventId:n,eventType:i});const o=Array.from(r).map((async e=>e(t.origin,s))),a=await function(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})))}(o);t.ports[0].postMessage({status:"done",eventId:n,eventType:i,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function gi(e="",t=10){let n="";for(let e=0;e{const c=gi("",20);i.port1.start();const l=setTimeout((()=>{a(new Error("unsupported_event"))}),n);r={messageChannel:i,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case"ack":clearTimeout(l),s=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(s),o(t.data.response);break;default:clearTimeout(l),clearTimeout(s),a(new Error("invalid_response"))}}},this.handlers.add(r),i.port1.addEventListener("message",r.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[i.port2])})).finally((()=>{r&&this.removeMessageHandler(r)}))}}function yi(){return window}function wi(){return void 0!==yi().WorkerGlobalScope&&"function"==typeof yi().importScripts}const Ii="firebaseLocalStorageDb",bi="firebaseLocalStorage",Ci="fbase_key";class Ti{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 Ei(e,t){return e.transaction([bi],t?"readwrite":"readonly").objectStore(bi)}function Si(){const e=indexedDB.open(Ii,1);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)})),e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(bi,{keyPath:Ci})}catch(e){n(e)}})),e.addEventListener("success",(async()=>{const n=e.result;n.objectStoreNames.contains(bi)?t(n):(n.close(),await function(){const e=indexedDB.deleteDatabase(Ii);return new Ti(e).toPromise()}(),t(await Si()))}))}))}async function ki(e,t,n){const i=Ei(e,!0).put({[Ci]:t,value:n});return new Ti(i).toPromise()}function Ri(e,t){const n=Ei(e,!0).delete(t);return new Ti(n).toPromise()}class Ni{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 Si()),this.db}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return wi()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=mi._getInstance(wi()?self:null),this.receiver._subscribe("keyChanged",(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){var e,t;if(this.activeServiceWorker=await async function(){if(!(null===navigator||void 0===navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),!this.activeServiceWorker)return;this.sender=new vi(this.activeServiceWorker);const n=await this.sender._send("ping",{},800);n&&(null===(e=n[0])||void 0===e?void 0:e.fulfilled)&&(null===(t=n[0])||void 0===t?void 0:t.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?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(t){}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await Si();return await ki(e,hi,"1"),await Ri(e,hi),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((n=>ki(n,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function(e,t){const n=Ei(e,!1).get(t),i=await new Ti(n).toPromise();return void 0===i?null:i.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>Ri(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=Ei(e,!1).getAll();return new Ti(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],n=new Set;if(0!==e.length)for(const{fbase_key:i,value:s}of e)n.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(s)&&(this.notifyListeners(i,s),t.push(i));for(const e of Object.keys(this.localCache))this.localCache[e]&&!n.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n)for(const e of Array.from(n))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),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()}}Ni.type="LOCAL";const Pi=Ni;On("rcb"),new Ot(3e4,6e4);class Oi{constructor(e){this.providerId=Oi.PROVIDER_ID,this.auth=kn(e)}verifyPhoneNumber(e,t){return async function(e,t,n){var i;const s=await n.verify();try{let r;if(Et("string"==typeof s,e,"argument-error"),Et("recaptcha"===n.type,e,"argument-error"),r="string"==typeof t?{phoneNumber:t}:t,"session"in r){const t=r.session;if("phoneNumber"in r){Et("enroll"===t.type,e,"internal-error");const n=await function(e,t){return Ft(e,"POST","/v2/accounts/mfaEnrollment:start",xt(e,t))}(e,{idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:r.phoneNumber,recaptchaToken:s}});return n.phoneSessionInfo.sessionInfo}{Et("signin"===t.type,e,"internal-error");const n=(null===(i=r.multiFactorHint)||void 0===i?void 0:i.uid)||r.multiFactorUid;Et(n,e,"missing-multi-factor-info");const o=await function(e,t){return Ft(e,"POST","/v2/accounts/mfaSignIn:start",xt(e,t))}(e,{mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:s}});return o.phoneResponseInfo.sessionInfo}}{const{sessionInfo:t}=await async function(e,t){return Ft(e,"POST","/v1/accounts:sendVerificationCode",xt(e,t))}(e,{phoneNumber:r.phoneNumber,recaptchaToken:s});return t}}finally{n._reset()}}(this.auth,e,j(t))}static credential(e,t){return $n._fromVerification(e,t)}static credentialFromResult(e){const t=e;return Oi.credentialFromTaggedObject(t)}static credentialFromError(e){return Oi.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:n}=e;return t&&n?$n._fromTokenResponse(t,n):null}}Oi.PROVIDER_ID="phone",Oi.PHONE_SIGN_IN_METHOD="phone";class Ai extends Fn{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Hn(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Hn(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Hn(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 Di(e){return ri(e.auth,new Ai(e),e.bypassAuthState)}function Li(e){const{auth:t,user:n}=e;return Et(n,t,"internal-error"),async function(e,t,n=!1){const{auth:i}=e;if(Qe(i.app))return Promise.reject(Ct(i));const s="reauthenticate";try{const r=await Qt(e,si(i,s,t,e),n);Et(r.idToken,i,"internal-error");const o=Yt(r.idToken);Et(o,i,"internal-error");const{sub:a}=o;return Et(e.uid===a,i,"user-mismatch"),ti._forOperation(e,s,r)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&wt(i,"user-mismatch"),e}}(n,new Ai(e),e.bypassAuthState)}async function Mi(e){const{auth:t,user:n}=e;return Et(n,t,"internal-error"),async function(e,t,n=!1){const i=await Qt(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return ti._forOperation(e,"link",i)}(n,new Ai(e),e.bypassAuthState)}class xi{constructor(e,t,n,i,s=!1){this.auth=e,this.resolver=n,this.user=i,this.bypassAuthState=s,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:n,postBody:i,tenantId:s,error:r,type:o}=e;if(r)return void this.reject(r);const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:s||void 0,postBody:i||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return Di;case"linkViaPopup":case"linkViaRedirect":return Mi;case"reauthViaPopup":case"reauthViaRedirect":return Li;default:wt(this.auth,"internal-error")}}resolve(e){kt(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){kt(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 Fi=new Ot(2e3,1e4);class Ui extends xi{constructor(e,t,n,i,s){super(e,t,i,s),this.provider=n,this.authWindow=null,this.pollId=null,Ui.currentPopupAction&&Ui.currentPopupAction.cancel(),Ui.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return Et(e,this.auth,"internal-error"),e}async onExecution(){kt(1===this.filter.length,"Popup operations only handle one event");const e=gi();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(It(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(It(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,Ui.currentPopupAction=null}pollUserCancellation(){const e=()=>{var t,n;(null===(n=null===(t=this.authWindow)||void 0===t?void 0:t.window)||void 0===n?void 0:n.closed)?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(It(this.auth,"popup-closed-by-user"))}),8e3):this.pollId=window.setTimeout(e,Fi.get())};e()}}Ui.currentPopupAction=null;const ji="pendingRedirect",Wi=new Map;class qi extends xi{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=Wi.get(this.auth._key());if(!e){try{const t=await async function(e,t){const n=function(e){return hn(ji,e.config.apiKey,e.name)}(t),i=function(e){return an(e._redirectPersistence)}(e);if(!await i._isAvailable())return!1;const s="true"===await i._get(n);return await i._remove(n),s}(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}Wi.set(this.auth._key(),e)}return this.bypassAuthState||Wi.set(this.auth._key(),(()=>Promise.resolve(null))),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){const 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(){}}function Vi(e,t){Wi.set(e._key(),t)}async function Hi(e,t,n=!1){if(Qe(e.app))return Promise.reject(Ct(e));const i=kn(e),s=function(e,t){return t?an(t):(Et(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}(i,t),r=new qi(i,s,n),o=await r.execute();return o&&!n&&(delete o.user._redirectEventId,await i._persistUserIfCurrent(o.user),await i._setRedirectUser(null,t)),o}class zi{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach((n=>{this.isEventForConsumer(e,n)&&(t=!0,this.sendToConsumer(e,n),this.saveEventToCache(e))})),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return $i(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!$i(e)){const i=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error";t.onError(It(this.auth,i))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(Bi(e))}saveEventToCache(e){this.cachedEventUids.add(Bi(e)),this.lastProcessedEventTime=Date.now()}}function Bi(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function $i({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}const Ki=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,Gi=/^https?/;function Yi(e){const t=Rt(),{protocol:n,hostname:i}=new URL(t);if(e.startsWith("chrome-extension://")){const s=new URL(e);return""===s.hostname&&""===i?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&s.hostname===i}if(!Gi.test(n))return!1;if(Ki.test(e))return i===e;const s=e.replace(/\./g,"\\.");return new RegExp("^(.+\\."+s+"|"+s+")$","i").test(i)}const Ji=new Ot(3e4,6e4);function Qi(){const e=yi().___jsl;if(null==e?void 0:e.H)for(const t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t{var i,s,r;function o(){Qi(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{Qi(),n(It(e,"network-request-failed"))},timeout:Ji.get()})}if(null===(s=null===(i=yi().gapi)||void 0===i?void 0:i.iframes)||void 0===s?void 0:s.Iframe)t(gapi.iframes.getContext());else{if(!(null===(r=yi().gapi)||void 0===r?void 0:r.load)){const t=On("iframefcb");return yi()[t]=()=>{gapi.load?o():n(It(e,"network-request-failed"))},Pn(`${Nn.gapiScript}?onload=${t}`).catch((e=>n(e)))}o()}})).catch((e=>{throw Zi=null,e}))}let Zi=null;const es=new Ot(5e3,15e3),ts="__/auth/iframe",ns="emulator/auth/iframe",is={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},ss=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function rs(e){const t=e.config;Et(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?At(t,ns):`https://${e.config.authDomain}/${ts}`,i={apiKey:t.apiKey,appName:e.name,v:et},s=ss.get(e.config.apiHost);s&&(i.eid=s);const r=e._getFrameworks();return r.length&&(i.fw=r.join(",")),`${n}?${A(i).slice(1)}`}const os={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class as{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}const cs=encodeURIComponent("fac");async function ls(e,t,n,i,s,r){Et(e.config.authDomain,e,"auth-domain-config-required"),Et(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:i,v:et,eventId:s};if(t instanceof Yn){t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",R(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(r||{}))o[e]=t}if(t instanceof Jn){const e=t.getScopes().filter((e=>""!==e));e.length>0&&(o.scopes=e.join(","))}e.tenantId&&(o.tid=e.tenantId);const a=o;for(const e of Object.keys(a))void 0===a[e]&&delete a[e];const c=await e._getAppCheckToken(),l=c?`#${cs}=${encodeURIComponent(c)}`:"";return`${function({config:e}){return e.emulator?At(e,"emulator/auth/handler"):`https://${e.authDomain}/__/auth/handler`}(e)}?${A(a).slice(1)}${l}`}const hs="webStorageSupport",us=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=_i,this._completeRedirectFn=Hi,this._overrideRedirectResult=Vi}async _openPopup(e,t,n,i){var s;return kt(null===(s=this.eventManagers[e._key()])||void 0===s?void 0:s.manager,"_initialize() not called before _openPopup()"),function(e,t,n,i=500,s=600){const r=Math.max((window.screen.availHeight-s)/2,0).toString(),o=Math.max((window.screen.availWidth-i)/2,0).toString();let a="";const c=Object.assign(Object.assign({},os),{width:i.toString(),height:s.toString(),top:r,left:o}),l=g().toLowerCase();n&&(a=mn(l)?"_blank":n),pn(l)&&(t=t||"http://localhost",c.scrollbars="yes");const h=Object.entries(c).reduce(((e,[t,n])=>`${e}${t}=${n},`),"");if(function(e=g()){var t;return In(e)&&!!(null===(t=window.navigator)||void 0===t?void 0:t.standalone)}(l)&&"_self"!==a)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const i=document.createEvent("MouseEvent");i.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(i)}(t||"",a),new as(null);const u=window.open(t||"",a,h);Et(u,e,"popup-blocked");try{u.focus()}catch(e){}return new as(u)}(e,await ls(e,t,n,Rt(),i),gi())}async _openRedirect(e,t,n,i){return await this._originValidation(e),s=await ls(e,t,n,Rt(),i),yi().location.href=s,new Promise((()=>{}));var s}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(kt(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(e){const t=await async function(e){const t=await function(e){return Zi=Zi||Xi(e),Zi}(e),n=yi().gapi;return Et(n,e,"internal-error"),t.open({where:document.body,url:rs(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:is,dontclear:!0},(t=>new Promise((async(n,i)=>{await t.restyle({setHideOnLeave:!1});const s=It(e,"network-request-failed"),r=yi().setTimeout((()=>{i(s)}),es.get());function o(){yi().clearTimeout(r),n(t)}t.ping(o).then(o,(()=>{i(s)}))}))))}(e),n=new zi(e);return t.register("authEvent",(t=>(Et(null==t?void 0:t.authEvent,e,"invalid-auth-event"),{status:n.onEvent(t.authEvent)?"ACK":"ERROR"})),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:n},this.iframes[e._key()]=t,n}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(hs,{type:hs},(n=>{var i;const s=null===(i=null==n?void 0:n[0])||void 0===i?void 0:i[hs];void 0!==s&&t(!!s),wt(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){if(e.config.emulator)return;const{authorizedDomains:t}=await async function(e,t={}){return Ft(e,"GET","/v1/projects",t)}(e);for(const e of t)try{if(Yi(e))return}catch(e){}wt(e,"unauthorized-domain")}(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return bn()||fn()||In()}};var ds="@firebase/auth",ps="1.7.5";class fs{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(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e((null==t?void 0:t.stsTokenManager.accessToken)||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){Et(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}const _s=_("authIdTokenMaxAge")||300;let ms=null;var gs,vs;gs={loadJS:e=>new Promise(((t,n)=>{const i=document.createElement("script");var s,r;i.setAttribute("src",e),i.onload=t,i.onerror=e=>{const t=It("internal-error");t.customData=e,n(t)},i.type="text/javascript",i.charset="UTF-8",(null!==(r=null===(s=document.getElementsByTagName("head"))||void 0===s?void 0:s[0])&&void 0!==r?r:document).appendChild(i)})),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="},Nn=gs,vs="Browser",Ye(new W("auth",((e,{options:t})=>{const n=e.getProvider("app").getImmediate(),i=e.getProvider("heartbeat"),s=e.getProvider("app-check-internal"),{apiKey:r,authDomain:o}=n.options;Et(r&&!r.includes(":"),"invalid-api-key",{appName:n.name});const a={apiKey:r,authDomain:o,clientPlatform:vs,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:Cn(vs)},c=new Sn(n,i,s,a);return function(e,t){const n=(null==t?void 0:t.persistence)||[],i=(Array.isArray(n)?n:[n]).map(an);(null==t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(i,null==t?void 0:t.popupRedirectResolver)}(c,t),c}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{e.getProvider("auth-internal").initialize()}))),Ye(new W("auth-internal",(e=>{return t=kn(e.getProvider("auth").getImmediate()),new fs(t);var t}),"PRIVATE").setInstantiationMode("EXPLICIT")),it(ds,ps,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}}(vs)),it(ds,ps,"esm2017");const ys="@firebase/database",ws="1.0.6";let Is="";class bs{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),T(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:C(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Cs{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return S(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const Ts=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 bs(t)}}catch(e){}return new Cs},Es=Ts("localStorage"),Ss=Ts("sessionStorage"),ks=new J("@firebase/database"),Rs=function(){let e=1;return function(){return e++}}(),Ns=function(e){const t=function(e){const t=[];let i=0;for(let s=0;s=55296&&r<=56319){const t=r-55296;s++,n(s>6|192,t[i++]=63&r|128):r<65536?(t[i++]=r>>12|224,t[i++]=r>>6&63|128,t[i++]=63&r|128):(t[i++]=r>>18|240,t[i++]=r>>12&63|128,t[i++]=r>>6&63|128,t[i++]=63&r|128)}return t}(e),i=new M;i.update(t);const s=i.digest();return r.encodeByteArray(s)},Ps=function(...e){let t="";for(let n=0;nn?i.push(e.substring(s,n)):i.push(e.substring(s,s+t));return i};function $s(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const Ks=function(e){n(!Us(e),"Invalid JSON number");let t,i,s,r,o;0===e?(i=0,s=0,t=1/e==-1/0?1:0):(t=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(r=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),i=r+1023,s=Math.round(e*Math.pow(2,52-r)-Math.pow(2,52))):(i=0,s=Math.round(e/Math.pow(2,-1074))));const a=[];for(o=52;o;o-=1)a.push(s%2?1:0),s=Math.floor(s/2);for(o=11;o;o-=1)a.push(i%2?1:0),i=Math.floor(i/2);a.push(t?1:0),a.reverse();const c=a.join("");let l="";for(o=0;o<64;o+=8){let e=parseInt(c.substr(o,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()},Gs=new RegExp("^-?(0*)\\d{1,10}$"),Ys=function(e){if(Gs.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},Js=function(e){try{e()}catch(e){setTimeout((()=>{const t=e.stack||"";throw Fs("Exception was thrown by user callback.",t),e}),Math.floor(0))}},Qs=function(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};class Xs{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then((e=>this.appCheck=e))}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise(((t,n)=>{setTimeout((()=>{this.appCheck?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then((t=>t.addTokenListener(e)))}notifyForInvalidToken(){Fs(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}class Zs{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit((e=>this.auth_=e))}getToken(e){return this.auth_?this.auth_.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(Ds("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e))):new Promise(((t,n)=>{setTimeout((()=>{this.auth_?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then((t=>t.addAuthTokenListener(e)))}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',Fs(e)}}class er{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}er.OWNER="owner";const tr="5",nr=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,ir="ac",sr="websocket",rr="long_polling";class or{constructor(e,t,n,i,s=!1,r="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=i,this.nodeAdmin=s,this.persistenceKey=r,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=Es.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()&&Es.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function ar(e,t,i){let s;if(n("string"==typeof t,"typeof type must == string"),n("object"==typeof i,"typeof params must == object"),t===sr)s=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==rr)throw new Error("Unknown connection type: "+t);s=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}(function(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams})(e)&&(i.ns=e.namespace);const r=[];return $s(i,((e,t)=>{r.push(e+"="+t)})),s+r.join("&")}class cr{constructor(){this.counters_={}}incrementCounter(e,t=1){S(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return h(this.counters_)}}const lr={},hr={};function ur(e){const t=e.toString();return lr[t]||(lr[t]=new cr),lr[t]}class dr{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.onMessage_(e[t])}));if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const pr="start";class fr{constructor(e,t,n,i,s,r,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.transportSessionId=r,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Ls(e),this.stats_=ur(t),this.urlFn=e=>(this.appCheckToken&&(e[ir]=this.appCheckToken),ar(t,rr,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new dr(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout((()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null}),Math.floor(3e4)),function(e){if("complete"===document.readyState)e();else{let t=!1;const n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",(()=>{"complete"===document.readyState&&n()})),window.attachEvent("onload",n))}}((()=>{if(this.isClosed_)return;this.scriptTagHolder=new _r(((...e)=>{const[t,n,i,s,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===pr)this.id=n,this.password=i;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)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)}),(()=>{this.onClosed_()}),this.urlFn);const e={};e[pr]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v=tr,this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e[ir]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&nr.test(location.hostname)&&(e.r="f");const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,(()=>{}))}))}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){fr.forceAllow_=!0}static forceDisallow(){fr.forceDisallow_=!0}static isAvailable(){return!(!fr.forceAllow_&&(fr.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){const t=T(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=a(t),i=Bs(n,1840);for(let e=0;edocument.domain="'+document.domain+'";<\/script>');const i=""+n+"";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){Ds("frame writing exception"),e.stack&&Ds(e.stack),Ds(e)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||Ds("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout((()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)}),Math.floor(0)));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<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+30+n.length<=1870;){const e=this.pendingSegs.shift();n=n+"&seg"+i+"="+e.seg+"&ts"+i+"="+e.ts+"&d"+i+"="+e.d,i++}return t+=n,this.addLongPollTag_(t,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_()},i=setTimeout(n,Math.floor(25e3));this.addTag(e,(()=>{clearTimeout(i),n()}))}addTag(e,t){setTimeout((()=>{try{if(!this.sendNewPolls)return;const n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){const e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{Ds("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}}),Math.floor(1))}}let mr=null;"undefined"!=typeof MozWebSocket?mr=MozWebSocket:"undefined"!=typeof WebSocket&&(mr=WebSocket);class gr{constructor(e,t,n,i,s,r,o){this.connId=e,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Ls(this.connId),this.stats_=ur(t),this.connURL=gr.connectionURL_(t,r,o,i,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,i,s){const r={};return r.v=tr,"undefined"!=typeof location&&location.hostname&&nr.test(location.hostname)&&(r.r="f"),t&&(r.s=t),n&&(r.ls=n),i&&(r[ir]=i),s&&(r.p=s),ar(e,sr,r)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Es.set("previous_websocket_failure",!0);try{let e;0,this.mySock=new mr(this.connURL,[],e)}catch(e){this.log_("Error instantiating WebSocket.");const t=e.message||e.data;return t&&this.log_(t),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.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){gr.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==mr&&!gr.forceDisallow_}static previouslyFailed(){return Es.isInMemoryStorage||!0===Es.get("previous_websocket_failure")}markConnectionHealthy(){Es.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=C(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(n(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=T(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=Bs(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e{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)}}}gr.responsesRequiredToBeHealthy=2,gr.healthyTimeout=3e4;class vr{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[fr,gr]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const t=gr&&gr.isAvailable();let n=t&&!gr.previouslyFailed();if(e.webSocketOnly&&(t||Fs("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[gr];else{const e=this.transports_=[];for(const t of vr.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);vr.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}vr.globalTransportInitialized_=!1;class yr{constructor(e,t,n,i,s,r,o,a,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=s,this.onMessage_=r,this.onReady_=o,this.onDisconnect_=a,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Ls("c:"+this.id+":"),this.transportManager_=new vr(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));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=Qs((()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))}),Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if("t"in e){const t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=Hs("t",e),n=Hs("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){const t=Hs("t",e),n=Hs("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){const t=Hs("t",e);if("d"in e){const n=e.d;if("h"===t){const e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e{this.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):Qs((()=>{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_(){const 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()&&(Es.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 wr{put(e,t,n,i){}merge(e,t,n,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class Ir{constructor(e){this.allowedEvents_=e,this.listeners_={},n(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;et===e)),"Unknown event: "+e)}}class br extends Ir{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||v()||(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 br}getInitialEvent(e){return n("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class Cr{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function Sr(e){return e.pieces_.length-e.pieceNum_}function kr(e){let t=e.pieceNum_;return t=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n0&&n.push(e[t])}return new Cr(n,0)}function Ar(e){return e.pieceNum_>=e.pieces_.length}function Dr(e,t){const n=Er(e),i=Er(t);if(null===n)return t;if(n===i)return Dr(kr(e),kr(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function Lr(e,t){if(Sr(e)!==Sr(t))return!1;for(let n=e.pieceNum_,i=t.pieceNum_;n<=e.pieces_.length;n++,i++)if(e.pieces_[n]!==t.pieces_[i])return!1;return!0}function Mr(e,t){let n=e.pieceNum_,i=t.pieceNum_;if(Sr(e)>Sr(t))return!1;for(;n768)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+Ur(e))}function Ur(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class jr extends Ir{constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}static getInstance(){return new jr}getInitialEvent(e){return n("visible"===e,"Unknown event type: "+e),[this.visible_]}}const Wr=1e3;class qr extends wr{constructor(e,t,n,i,s,r,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=i,this.onServerInfoUpdate_=s,this.authTokenProvider_=r,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=qr.nextPersistentConnectionId_++,this.log_=Ls("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_=Wr,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");jr.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&br.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,i){const s=++this.requestNumber_,r={r:s,a:e,b:t};this.log_(T(r)),n(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),i&&(this.requestCBHash_[s]=i)}get(e){this.initConnection_();const t=new m,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const i=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(i),t.promise}listen(e,t,i,s){this.initConnection_();const r=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+r),this.listens.has(o)||this.listens.set(o,new Map),n(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),n(!this.listens.get(o).has(r),"listen() called twice for same path/queryId.");const a={onComplete:s,hashFn:t,query:e,tag:i};this.listens.get(o).set(r,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,(n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)}))}sendListen_(e){const t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);const s={p:n};e.tag&&(s.q=t._queryObject,s.t=e.tag),s.h=e.hashFn(),this.sendRequest("q",s,(s=>{const r=s.d,o=s.s;qr.warnOnListenWarnings_(r,t),(this.listens.get(n)&&this.listens.get(n).get(i))===e&&(this.log_("listen response",s),"ok"!==o&&this.removeListen_(n,i),e.onComplete&&e.onComplete(o,r))}))}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&S(e,"w")){const n=k(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();Fs(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},(()=>{})),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||function(e){const t=E(e).claims;return"object"==typeof t&&!0===t.admin}(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},(()=>{}))}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=function(e){const t=E(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")}(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,(t=>{const n=t.s,i=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,i))}))}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},(e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)}))}unlisten(e,t){const i=e._path.toString(),s=e._queryIdentifier;this.log_("Unlisten called for "+i+" "+s),n(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(i,s)&&this.connected_&&this.sendUnlisten_(i,s,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);const s={p:e};i&&(s.q=n,s.t=i),this.sendRequest("n",s)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,i){const s={p:t,d:n};this.log_("onDisconnect "+e,s),this.sendRequest(e,s,(e=>{i&&setTimeout((()=>{i(e.s,e.d)}),Math.floor(0))}))}put(e,t,n,i){this.putInternal("p",e,t,n,i)}merge(e,t,n,i){this.putInternal("m",e,t,n,i)}putInternal(e,t,n,i,s){this.initConnection_();const r={p:t,d:n};void 0!==s&&(r.h=s),this.outstandingPuts_.push({action:e,request:r,onComplete:i}),this.outstandingPutCount_++;const o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,(n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),i&&i(n.s,n.d)}))}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,(e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}}))}}onDataMessage_(e){if("r"in e){this.log_("from server: "+T(e));const t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"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):Ms("Unrecognized action received from server: "+T(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){n(!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_=Wr,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=Wr,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&((new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=Wr),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime());const e=(new Date).getTime()-this.lastConnectionAttemptTime_;let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,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;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),i=this.onRealtimeDisconnect_.bind(this),s=this.id+":"+qr.nextConnectionId_++,r=this.lastSessionId;let o=!1,a=null;const c=function(){a?a.close():(o=!0,i())},l=function(e){n(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(e)};this.realtime_={close:c,sendRequest:l};const h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[n,c]=await Promise.all([this.authTokenProvider_.getToken(h),this.appCheckTokenProvider_.getToken(h)]);o?Ds("getToken() completed but was canceled"):(Ds("getToken() completed. Creating connection."),this.authToken_=n&&n.accessToken,this.appCheckToken_=c&&c.token,a=new yr(s,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,i,(e=>{Fs(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")}),r))}catch(e){this.log_("Failed to get token: "+e),o||(this.repoInfo_.nodeAdmin&&Fs(e),c())}}}interrupt(e){Ds("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){Ds("Resuming connection for reason: "+e),delete this.interruptReasons_[e],R(this.interruptReasons_)&&(this.reconnectDelay_=Wr,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;ezs(e))).join("$"):"default";const i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){const n=new Cr(e).toString();let i;if(this.listens.has(n)){const e=this.listens.get(n);i=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else i=void 0;return i}onAuthRevoked_(e,t){Ds("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){Ds("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class Gr{constructor(e,t,n,i,s){this.key=e,this.value=t,this.color=null!=n?n:Gr.RED,this.left=null!=i?i:Yr.EMPTY_NODE,this.right=null!=s?s:Yr.EMPTY_NODE}copy(e,t,n,i,s){return new Gr(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=i?i:this.left,null!=s?s:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let i=this;const s=n(e,i.key);return i=s<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===s?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return Yr.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,i;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 Yr.EMPTY_NODE;i=n.right.min_(),n=n.copy(i.key,i.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.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_(){const e=this.copy(null,null,Gr.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,Gr.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}Gr.RED=!0,Gr.BLACK=!1;class Yr{constructor(e,t=Yr.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Yr(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,Gr.BLACK,null,null))}remove(e){return new Yr(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,Gr.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,i=null;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t){if(n.left.isEmpty())return i?i.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(i=n,n=n.right)}throw 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 Kr(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Kr(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Kr(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Kr(this.root_,null,this.comparator_,!0,e)}}function Jr(e,t){return qs(e.name,t.name)}function Qr(e,t){return qs(e,t)}let Xr;Yr.EMPTY_NODE=new class{copy(e,t,n,i,s){return this}insert(e,t,n){return new Gr(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}};const Zr=function(e){return"number"==typeof e?"number:"+Ks(e):"string:"+e},eo=function(e){if(e.isLeafNode()){const t=e.val();n("string"==typeof t||"number"==typeof t||"object"==typeof t&&S(t,".sv"),"Priority must be a string or number.")}else n(e===Xr||e.isEmpty(),"priority of unexpected type.");n(e===Xr||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let to,no,io;class so{constructor(e,t=so.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,n(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),eo(this.priorityNode_)}static set __childrenNodeConstructor(e){to=e}static get __childrenNodeConstructor(){return to}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new so(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:so.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return Ar(e)?this:".priority"===Er(e)?this.priorityNode_:so.__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:so.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const i=Er(e);return null===i?t:t.isEmpty()&&".priority"!==i?this:(n(".priority"!==i||1===Sr(e),".priority must be the last token in a path"),this.updateImmediateChild(i,so.__childrenNodeConstructor.EMPTY_NODE.updateChild(kr(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:"+Zr(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?Ks(this.value_):this.value_,this.lazyHash_=Ns(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===so.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof so.__childrenNodeConstructor?-1:(n(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,i=typeof this.value_,s=so.VALUE_TYPE_ORDER.indexOf(t),r=so.VALUE_TYPE_ORDER.indexOf(i);return n(s>=0,"Unknown leaf type: "+t),n(r>=0,"Unknown leaf type: "+i),s===r?"object"===i?0:this.value_{const r=k(this.indexSet_,s);if(n(r,"Missing index implementation for "+s),i===ho){if(r.isDefinedOn(e.node)){const n=[],i=t.getIterator(Vr.Wrap);let s=i.getNext();for(;s;)s.name!==e.name&&n.push(s),s=i.getNext();return n.push(e),co(n,r.getCompare())}return ho}{const n=t.get(e.name);let s=i;return n&&(s=s.remove(new Vr(e.name,n))),s.insert(e,e.node)}}));return new uo(i,this.indexSet_)}removeFromIndexes(e,t){const n=N(this.indexes_,(n=>{if(n===ho)return n;{const i=t.get(e.name);return i?n.remove(new Vr(e.name,i)):n}}));return new uo(n,this.indexSet_)}}let po;class fo{constructor(e,t,i){this.children_=e,this.priorityNode_=t,this.indexMap_=i,this.lazyHash_=null,this.priorityNode_&&eo(this.priorityNode_),this.children_.isEmpty()&&n(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return po||(po=new fo(new Yr(Qr),null,uo.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||po}updatePriority(e){return this.children_.isEmpty()?this:new fo(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?po:t}}getChild(e){const t=Er(e);return null===t?this:this.getImmediateChild(t).getChild(kr(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if(n(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new Vr(e,t);let i,s;t.isEmpty()?(i=this.children_.remove(e),s=this.indexMap_.removeFromIndexes(n,this.children_)):(i=this.children_.insert(e,t),s=this.indexMap_.addToIndexes(n,this.children_));const r=i.isEmpty()?po:this.priorityNode_;return new fo(i,r,s)}}updateChild(e,t){const i=Er(e);if(null===i)return t;{n(".priority"!==Er(e)||1===Sr(e),".priority must be the last token in a path");const s=this.getImmediateChild(i).updateChild(kr(e),t);return this.updateImmediateChild(i,s)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,i=0,s=!0;if(this.forEachChild(ro,((r,o)=>{t[r]=o.val(e),n++,s&&fo.INTEGER_REGEXP_.test(r)?i=Math.max(i,Number(r)):s=!1})),!e&&s&&i<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+Zr(this.getPriority().val())+":"),this.forEachChild(ro,((t,n)=>{const i=n.hash();""!==i&&(e+=":"+t+":"+i)})),this.lazyHash_=""===e?"":Ns(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const i=this.resolveIndex_(n);if(i){const n=i.getPredecessorKey(new Vr(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new Vr(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new Vr(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(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,(e=>e));{const n=this.children_.getIteratorFrom(e.name,Vr.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)<0;)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,(e=>e));{const n=this.children_.getReverseIteratorFrom(e.name,Vr.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)>0;)n.getNext(),i=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===_o?-1:0}withIndex(e){if(e===$r||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new fo(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===$r||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(ro),n=t.getIterator(ro);let i=e.getNext(),s=n.getNext();for(;i&&s;){if(i.name!==s.name||!i.node.equals(s.node))return!1;i=e.getNext(),s=n.getNext()}return null===i&&null===s}return!1}return!1}}resolveIndex_(e){return e===$r?null:this.indexMap_.get(e.toString())}}fo.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const _o=new class extends fo{constructor(){super(new Yr(Qr),fo.EMPTY_NODE,uo.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return fo.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(Vr,{MIN:{value:new Vr(js,fo.EMPTY_NODE)},MAX:{value:new Vr(Ws,_o)}}),Br.__EMPTY_NODE=fo.EMPTY_NODE,so.__childrenNodeConstructor=fo,Xr=_o,io=_o;const mo=!0;function go(e,t=null){if(null===e)return fo.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),n(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e)return new so(e,go(t));if(e instanceof Array||!mo){let n=fo.EMPTY_NODE;return $s(e,((t,i)=>{if(S(e,t)&&"."!==t.substring(0,1)){const e=go(i);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}})),n.updatePriority(go(t))}{const n=[];let i=!1;if($s(e,((e,t)=>{if("."!==e.substring(0,1)){const s=go(t);s.isEmpty()||(i=i||!s.getPriority().isEmpty(),n.push(new Vr(e,s)))}})),0===n.length)return fo.EMPTY_NODE;const s=co(n,Jr,(e=>e.name),Qr);if(i){const e=co(n,ro.getCompare());return new fo(s,go(t),new uo({".priority":e},{".priority":ro}))}return new fo(s,go(t),uo.Default)}}no=go;class vo extends Hr{constructor(e){super(),this.indexPath_=e,n(!Ar(e)&&".priority"!==Er(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),i=this.extractChild(t.node),s=n.compareTo(i);return 0===s?qs(e.name,t.name):s}makePost(e,t){const n=go(e),i=fo.EMPTY_NODE.updateChild(this.indexPath_,n);return new Vr(t,i)}maxPost(){const e=fo.EMPTY_NODE.updateChild(this.indexPath_,_o);return new Vr(Ws,e)}toString(){return Nr(this.indexPath_,0).join("/")}}const yo=new class extends Hr{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?qs(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return Vr.MIN}maxPost(){return Vr.MAX}makePost(e,t){const n=go(e);return new Vr(t,n)}toString(){return".value"}};function wo(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class Io{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_=ro}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return n(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return n(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:js}hasEnd(){return this.endSet_}getIndexEndValue(){return n(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return n(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Ws}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return n(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_===ro}copy(){const e=new Io;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 bo(e){const t={};if(e.isDefault())return t;let i;if(e.index_===ro?i="$priority":e.index_===yo?i="$value":e.index_===$r?i="$key":(n(e.index_ instanceof vo,"Unrecognized index type!"),i=e.index_.toString()),t.orderBy=T(i),e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=T(e.indexStartValue_),e.startNameSet_&&(t[n]+=","+T(e.indexStartName_))}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=T(e.indexEndValue_),e.endNameSet_&&(t[n]+=","+T(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function Co(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==ro&&(t.i=e.index_.toString()),t}class To extends wr{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=Ls("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(n(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const r=To.getListenId_(e,n),o={};this.listens_[r]=o;const a=bo(e._queryParams);this.restRequest_(s+".json",a,((e,t)=>{let a=t;if(404===e&&(a=null,e=null),null===e&&this.onDataUpdate_(s,a,!1,n),k(this.listens_,r)===o){let t;t=e?401===e?"permission_denied":"rest_error:"+e:"ok",i(t,null)}}))}unlisten(e,t){const n=To.getListenId_(e,t);delete this.listens_[n]}get(e){const t=bo(e._queryParams),n=e._path.toString(),i=new m;return this.restRequest_(n+".json",t,((e,t)=>{let s=t;404===e&&(s=null,e=null),null===e?(this.onDataUpdate_(n,s,!1,null),i.resolve(s)):i.reject(new Error(s))})),i.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then((([i,s])=>{i&&i.accessToken&&(t.auth=i.accessToken),s&&s.token&&(t.ac=s.token);const r=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+A(t);this.log_("Sending REST request for "+r);const o=new XMLHttpRequest;o.onreadystatechange=()=>{if(n&&4===o.readyState){this.log_("REST Response for "+r+" received. status:",o.status,"response:",o.responseText);let e=null;if(o.status>=200&&o.status<300){try{e=C(o.responseText)}catch(e){Fs("Failed to parse JSON response for "+r+": "+o.responseText)}n(null,e)}else 401!==o.status&&404!==o.status&&Fs("Got unsuccessful REST response for "+r+" Status: "+o.status),n(o.status);n=null}},o.open("GET",r,!0),o.send()}))}}class Eo{constructor(){this.rootNode_=fo.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function So(){return{value:null,children:new Map}}function ko(e,t,n){if(Ar(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const i=Er(t);e.children.has(i)||e.children.set(i,So()),ko(e.children.get(i),t=kr(t),n)}}function Ro(e,t,n){null!==e.value?n(t,e.value):function(e,t){e.children.forEach(((e,n)=>{t(n,e)}))}(e,((e,i)=>{Ro(i,new Cr(t.toString()+"/"+e),n)}))}class No{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&$s(this.last_,((e,n)=>{t[e]=t[e]-n})),this.last_=e,t}}class Po{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new No(e);const n=1e4+2e4*Math.random();Qs(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;$s(e,((e,i)=>{i>0&&S(this.statsToReport_,e)&&(t[e]=i,n=!0)})),n&&this.server_.reportStats(t),Qs(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}var Oo,Ao;function Do(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(Ao=Oo||(Oo={}))[Ao.OVERWRITE=0]="OVERWRITE",Ao[Ao.MERGE=1]="MERGE",Ao[Ao.ACK_USER_WRITE=2]="ACK_USER_WRITE",Ao[Ao.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class Lo{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=Oo.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(e){if(Ar(this.path)){if(null!=this.affectedTree.value)return n(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new Cr(e));return new Lo(Tr(),t,this.revert)}}return n(Er(this.path)===e,"operationForChild called for unrelated child."),new Lo(kr(this.path),this.affectedTree,this.revert)}}class Mo{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=Oo.OVERWRITE}operationForChild(e){return Ar(this.path)?new Mo(this.source,Tr(),this.snap.getImmediateChild(e)):new Mo(this.source,kr(this.path),this.snap)}}class xo{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=Oo.MERGE}operationForChild(e){if(Ar(this.path)){const t=this.children.subtree(new Cr(e));return t.isEmpty()?null:t.value?new Mo(this.source,Tr(),t.value):new xo(this.source,Tr(),t)}return n(Er(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new xo(this.source,kr(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Fo{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(Ar(e))return this.isFullyInitialized()&&!this.filtered_;const t=Er(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}function Uo(e,t,n,s,r,o){const a=s.filter((e=>e.type===n));a.sort(((t,n)=>function(e,t,n){if(null==t.childName||null==n.childName)throw i("Should only compare child_ events.");const s=new Vr(t.childName,t.snapshotNode),r=new Vr(n.childName,n.snapshotNode);return e.index_.compare(s,r)}(e,t,n))),a.forEach((n=>{const i=function(e,t,n){return"value"===t.type||"child_removed"===t.type||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}(e,n,o);r.forEach((s=>{s.respondsTo(n.type)&&t.push(s.createEvent(i,e.query_))}))}))}function jo(e,t){return{eventCache:e,serverCache:t}}function Wo(e,t,n,i){return jo(new Fo(t,n,i),e.serverCache)}function qo(e,t,n,i){return jo(e.eventCache,new Fo(t,n,i))}function Vo(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function Ho(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let zo;class Bo{constructor(e,t=(()=>(zo||(zo=new Yr(Vs)),zo))()){this.value=e,this.children=t}static fromObject(e){let t=new Bo(null);return $s(e,((e,n)=>{t=t.set(new Cr(e),n)})),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:Tr(),value:this.value};if(Ar(e))return null;{const n=Er(e),i=this.children.get(n);if(null!==i){const s=i.findRootMostMatchingPathAndValue(kr(e),t);return null!=s?{path:Or(new Cr(n),s.path),value:s.value}:null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,(()=>!0))}subtree(e){if(Ar(e))return this;{const t=Er(e),n=this.children.get(t);return null!==n?n.subtree(kr(e)):new Bo(null)}}set(e,t){if(Ar(e))return new Bo(t,this.children);{const n=Er(e),i=(this.children.get(n)||new Bo(null)).set(kr(e),t),s=this.children.insert(n,i);return new Bo(this.value,s)}}remove(e){if(Ar(e))return this.children.isEmpty()?new Bo(null):new Bo(null,this.children);{const t=Er(e),n=this.children.get(t);if(n){const i=n.remove(kr(e));let s;return s=i.isEmpty()?this.children.remove(t):this.children.insert(t,i),null===this.value&&s.isEmpty()?new Bo(null):new Bo(this.value,s)}return this}}get(e){if(Ar(e))return this.value;{const t=Er(e),n=this.children.get(t);return n?n.get(kr(e)):null}}setTree(e,t){if(Ar(e))return t;{const n=Er(e),i=(this.children.get(n)||new Bo(null)).setTree(kr(e),t);let s;return s=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new Bo(this.value,s)}}fold(e){return this.fold_(Tr(),e)}fold_(e,t){const n={};return this.children.inorderTraversal(((i,s)=>{n[i]=s.fold_(Or(e,i),t)})),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,Tr(),t)}findOnPath_(e,t,n){const i=!!this.value&&n(t,this.value);if(i)return i;if(Ar(e))return null;{const i=Er(e),s=this.children.get(i);return s?s.findOnPath_(kr(e),Or(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,Tr(),t)}foreachOnPath_(e,t,n){if(Ar(e))return this;{this.value&&n(t,this.value);const i=Er(e),s=this.children.get(i);return s?s.foreachOnPath_(kr(e),Or(t,i),n):new Bo(null)}}foreach(e){this.foreach_(Tr(),e)}foreach_(e,t){this.children.inorderTraversal(((n,i)=>{i.foreach_(Or(e,n),t)})),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal(((t,n)=>{n.value&&e(t,n.value)}))}}class $o{constructor(e){this.writeTree_=e}static empty(){return new $o(new Bo(null))}}function Ko(e,t,n){if(Ar(t))return new $o(new Bo(n));{const i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){const s=i.path;let r=i.value;const o=Dr(s,t);return r=r.updateChild(o,n),new $o(e.writeTree_.set(s,r))}{const i=new Bo(n),s=e.writeTree_.setTree(t,i);return new $o(s)}}}function Go(e,t,n){let i=e;return $s(n,((e,n)=>{i=Ko(i,Or(t,e),n)})),i}function Yo(e,t){if(Ar(t))return $o.empty();{const n=e.writeTree_.setTree(t,new Bo(null));return new $o(n)}}function Jo(e,t){return null!=Qo(e,t)}function Qo(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(Dr(n.path,t)):null}function Xo(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(ro,((e,n)=>{t.push(new Vr(e,n))})):e.writeTree_.children.inorderTraversal(((e,n)=>{null!=n.value&&t.push(new Vr(e,n.value))})),t}function Zo(e,t){if(Ar(t))return e;{const n=Qo(e,t);return new $o(null!=n?new Bo(n):e.writeTree_.subtree(t))}}function ea(e){return e.writeTree_.isEmpty()}function ta(e,t){return na(Tr(),e.writeTree_,t)}function na(e,t,i){if(null!=t.value)return i.updateChild(e,t.value);{let s=null;return t.children.inorderTraversal(((t,r)=>{".priority"===t?(n(null!==r.value,"Priority writes must always be leaf nodes"),s=r.value):i=na(Or(e,t),r,i)})),i.getChild(e).isEmpty()||null===s||(i=i.updateChild(Or(e,".priority"),s)),i}}function ia(e,t){return fa(t,e)}function sa(e,t){if(e.snap)return Mr(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&Mr(Or(e.path,n),t))return!0;return!1}function ra(e){return e.visible}function oa(e,t,n){let s=$o.empty();for(let r=0;r{i=i.updateImmediateChild(e,t)})),i;if(n){const s=Zo(e.visibleWrites,t);return n.forEachChild(ro,((e,t)=>{const n=ta(Zo(s,new Cr(e)),t);i=i.updateImmediateChild(e,n)})),Xo(s).forEach((e=>{i=i.updateImmediateChild(e.name,e.node)})),i}return Xo(Zo(e.visibleWrites,t)).forEach((e=>{i=i.updateImmediateChild(e.name,e.node)})),i}(e.writeTree,e.treePath,t)}function ha(e,t,i,s){return function(e,t,i,s,r){n(s||r,"Either existingEventSnap or existingServerSnap must exist");const o=Or(t,i);if(Jo(e.visibleWrites,o))return null;{const t=Zo(e.visibleWrites,o);return ea(t)?r.getChild(i):ta(t,r.getChild(i))}}(e.writeTree,e.treePath,t,i,s)}function ua(e,t){return function(e,t){return Qo(e.visibleWrites,t)}(e.writeTree,Or(e.treePath,t))}function da(e,t,n){return function(e,t,n,i){const s=Or(t,n),r=Qo(e.visibleWrites,s);return null!=r?r:i.isCompleteForChild(n)?ta(Zo(e.visibleWrites,s),i.getNode().getImmediateChild(n)):null}(e.writeTree,e.treePath,t,n)}function pa(e,t){return fa(Or(e.treePath,t),e.writeTree)}function fa(e,t){return{treePath:e,writeTree:t}}class _a{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,s=e.childName;n("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),n(".priority"!==s,"Only non-priority child changes can be tracked.");const r=this.changeMap.get(s);if(r){const n=r.type;if("child_added"===t&&"child_removed"===n)this.changeMap.set(s,wo(s,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===n)this.changeMap.delete(s);else if("child_removed"===t&&"child_changed"===n)this.changeMap.set(s,(o=s,{type:"child_removed",snapshotNode:r.oldSnap,childName:o}));else if("child_changed"===t&&"child_added"===n)this.changeMap.set(s,function(e,t){return{type:"child_added",snapshotNode:t,childName:e}}(s,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==n)throw i("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(s,wo(s,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(s,e);var o}getChanges(){return Array.from(this.changeMap.values())}}const ma=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class ga{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);{const t=null!=this.optCompleteServerCache_?new Fo(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return da(this.writes_,e,t)}}getChildAfterChild(e,t,n){const i=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:Ho(this.viewCache_),s=function(e,t,n,i,s,r){return function(e,t,n,i,s,r,o){let a;const c=Zo(e.visibleWrites,t),l=Qo(c,Tr());if(null!=l)a=l;else{if(null==n)return[];a=ta(c,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const e=[],t=o.getCompare(),n=r?a.getReverseIteratorFrom(i,o):a.getIteratorFrom(i,o);let c=n.getNext();for(;c&&e.length1)return t;const s=kr(n),r=c.getNode().getImmediateChild(e).updateChild(s,i);l=".priority"===e?h.updatePriority(c.getNode(),r):h.updateChild(c.getNode(),e,r,s,ma,null)}const u=qo(t,l,c.isFullyInitialized()||Ar(n),h.filtersNodes());return va(e,u,n,s,new ga(s,u,r),a)}function wa(e,t,n,i,s,r,o){const a=t.eventCache;let c,l;const h=new ga(s,t,r);if(Ar(n))l=e.filter.updateFullNode(t.eventCache.getNode(),i,o),c=Wo(t,l,!0,e.filter.filtersNodes());else{const s=Er(n);if(".priority"===s)l=e.filter.updatePriority(t.eventCache.getNode(),i),c=Wo(t,l,a.isFullyInitialized(),a.isFiltered());else{const r=kr(n),l=a.getNode().getImmediateChild(s);let u;if(Ar(r))u=i;else{const e=h.getCompleteChild(s);u=null!=e?".priority"===Rr(r)&&e.getChild(Pr(r)).isEmpty()?e:e.updateChild(r,i):fo.EMPTY_NODE}c=l.equals(u)?t:Wo(t,e.filter.updateChild(a.getNode(),s,u,r,h,o),a.isFullyInitialized(),e.filter.filtersNodes())}}return c}function Ia(e,t){return e.eventCache.isCompleteForChild(t)}function ba(e,t,n){return n.foreach(((e,n)=>{t=t.updateChild(e,n)})),t}function Ca(e,t,n,i,s,r,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let c,l=t;c=Ar(n)?i:new Bo(null).setTree(n,i);const h=t.serverCache.getNode();return c.children.inorderTraversal(((n,i)=>{if(h.hasChild(n)){const c=ba(0,t.serverCache.getNode().getImmediateChild(n),i);l=ya(e,l,new Cr(n),c,s,r,o,a)}})),c.children.inorderTraversal(((n,i)=>{const c=!t.serverCache.isCompleteForChild(n)&&null===i.value;if(!h.hasChild(n)&&!c){const c=ba(0,t.serverCache.getNode().getImmediateChild(n),i);l=ya(e,l,new Cr(n),c,s,r,o,a)}})),l}function Ta(e,t){const n=Ho(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!Ar(t)&&!n.getImmediateChild(Er(t)).isEmpty())?n.getChild(t):null}function Ea(e,t,s,r){t.type===Oo.MERGE&&null!==t.source.queryId&&(n(Ho(e.viewCache_),"We should always have a full cache before handling merges"),n(Vo(e.viewCache_),"Missing event cache, even though we have a server cache"));const o=e.viewCache_,a=function(e,t,s,r,o){const a=new _a;let c,l;if(s.type===Oo.OVERWRITE){const i=s;i.source.fromUser?c=wa(e,t,i.path,i.snap,r,o,a):(n(i.source.fromServer,"Unknown source."),l=i.source.tagged||t.serverCache.isFiltered()&&!Ar(i.path),c=ya(e,t,i.path,i.snap,r,o,l,a))}else if(s.type===Oo.MERGE){const i=s;i.source.fromUser?c=function(e,t,n,i,s,r,o){let a=t;return i.foreach(((i,c)=>{const l=Or(n,i);Ia(t,Er(l))&&(a=wa(e,a,l,c,s,r,o))})),i.foreach(((i,c)=>{const l=Or(n,i);Ia(t,Er(l))||(a=wa(e,a,l,c,s,r,o))})),a}(e,t,i.path,i.children,r,o,a):(n(i.source.fromServer,"Unknown source."),l=i.source.tagged||t.serverCache.isFiltered(),c=Ca(e,t,i.path,i.children,r,o,l,a))}else if(s.type===Oo.ACK_USER_WRITE){const i=s;c=i.revert?function(e,t,i,s,r,o){let a;if(null!=ua(s,i))return t;{const c=new ga(s,t,r),l=t.eventCache.getNode();let h;if(Ar(i)||".priority"===Er(i)){let i;if(t.serverCache.isFullyInitialized())i=ca(s,Ho(t));else{const e=t.serverCache.getNode();n(e instanceof fo,"serverChildren would be complete if leaf node"),i=la(s,e)}h=e.filter.updateFullNode(l,i,o)}else{const n=Er(i);let r=da(s,n,t.serverCache);null==r&&t.serverCache.isCompleteForChild(n)&&(r=l.getImmediateChild(n)),h=null!=r?e.filter.updateChild(l,n,r,kr(i),c,o):t.eventCache.getNode().hasChild(n)?e.filter.updateChild(l,n,fo.EMPTY_NODE,kr(i),c,o):l,h.isEmpty()&&t.serverCache.isFullyInitialized()&&(a=ca(s,Ho(t)),a.isLeafNode()&&(h=e.filter.updateFullNode(h,a,o)))}return a=t.serverCache.isFullyInitialized()||null!=ua(s,Tr()),Wo(t,h,a,e.filter.filtersNodes())}}(e,t,i.path,r,o,a):function(e,t,n,i,s,r,o){if(null!=ua(s,n))return t;const a=t.serverCache.isFiltered(),c=t.serverCache;if(null!=i.value){if(Ar(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return ya(e,t,n,c.getNode().getChild(n),s,r,a,o);if(Ar(n)){let i=new Bo(null);return c.getNode().forEachChild($r,((e,t)=>{i=i.set(new Cr(e),t)})),Ca(e,t,n,i,s,r,a,o)}return t}{let l=new Bo(null);return i.foreach(((e,t)=>{const i=Or(n,e);c.isCompleteForPath(i)&&(l=l.set(e,c.getNode().getChild(i)))})),Ca(e,t,n,l,s,r,a,o)}}(e,t,i.path,i.affectedTree,r,o,a)}else{if(s.type!==Oo.LISTEN_COMPLETE)throw i("Unknown operation type: "+s.type);c=function(e,t,n,i,s){const r=t.serverCache;return va(e,qo(t,r.getNode(),r.isFullyInitialized()||Ar(n),r.isFiltered()),n,i,ma,s)}(e,t,s.path,r,a)}const h=a.getChanges();return function(e,t,n){const i=t.eventCache;if(i.isFullyInitialized()){const s=i.getNode().isLeafNode()||i.getNode().isEmpty(),r=Vo(e);(n.length>0||!e.eventCache.isFullyInitialized()||s&&!i.getNode().equals(r)||!i.getNode().getPriority().equals(r.getPriority()))&&n.push({type:"value",snapshotNode:Vo(t)})}}(t,c,h),{viewCache:c,changes:h}}(e.processor_,o,t,s,r);var c,l;return c=e.processor_,l=a.viewCache,n(l.eventCache.getNode().isIndexed(c.filter.getIndex()),"Event snap not indexed"),n(l.serverCache.getNode().isIndexed(c.filter.getIndex()),"Server snap not indexed"),n(a.viewCache.serverCache.isFullyInitialized()||!o.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=a.viewCache,function(e,t,n,i){const s=i?[i]:e.eventRegistrations_;return function(e,t,n,i){const s=[],r=[];return t.forEach((t=>{var n;"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&r.push((n=t.childName,{type:"child_moved",snapshotNode:t.snapshotNode,childName:n}))})),Uo(e,s,"child_removed",t,i,n),Uo(e,s,"child_added",t,i,n),Uo(e,s,"child_moved",r,i,n),Uo(e,s,"child_changed",t,i,n),Uo(e,s,"value",t,i,n),s}(e.eventGenerator_,t,n,s)}(e,a.changes,a.viewCache.eventCache.getNode(),null)}let Sa,ka;function Ra(e,t,i,s){const r=t.source.queryId;if(null!==r){const o=e.views.get(r);return n(null!=o,"SyncTree gave us an op for an invalid query."),Ea(o,t,i,s)}{let n=[];for(const r of e.views.values())n=n.concat(Ea(r,t,i,s));return n}}function Na(e,t){let n=null;for(const i of e.views.values())n=n||Ta(i,t);return n}class Pa{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Bo(null),this.pendingWriteTree_={visibleWrites:$o.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Oa(e,t,i,s,r){return function(e,t,i,s,r){n(s>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===r&&(r=!0),e.allWrites.push({path:t,snap:i,writeId:s,visible:r}),r&&(e.visibleWrites=Ko(e.visibleWrites,t,i)),e.lastWriteId=s}(e.pendingWriteTree_,t,i,s,r),r?Ma(e,new Mo({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,i)):[]}function Aa(e,t,i=!1){const s=function(e,t){for(let n=0;ne.writeId===t));n(i>=0,"removeWrite called with nonexistent writeId.");const s=e.allWrites[i];e.allWrites.splice(i,1);let r=s.visible,o=!1,a=e.allWrites.length-1;for(;r&&a>=0;){const t=e.allWrites[a];t.visible&&(a>=i&&sa(t,s.path)?r=!1:Mr(s.path,t.path)&&(o=!0)),a--}return!!r&&(o?(function(e){e.visibleWrites=oa(e.allWrites,ra,Tr()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}(e),!0):(s.snap?e.visibleWrites=Yo(e.visibleWrites,s.path):$s(s.children,(t=>{e.visibleWrites=Yo(e.visibleWrites,Or(s.path,t))})),!0))}(e.pendingWriteTree_,t)){let t=new Bo(null);return null!=s.snap?t=t.set(Tr(),!0):$s(s.children,(e=>{t=t.set(new Cr(e),!0)})),Ma(e,new Lo(s.path,t,i))}return[]}function Da(e,t,n){return Ma(e,new Mo({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,n))}function La(e,t,n){const i=e.pendingWriteTree_,s=e.syncPointTree_.findOnPath(t,((e,n)=>{const i=Na(n,Dr(e,t));if(i)return i}));return aa(i,t,s,n,!0)}function Ma(e,t){return xa(t,e.syncPointTree_,null,ia(e.pendingWriteTree_,Tr()))}function xa(e,t,n,i){if(Ar(e.path))return Fa(e,t,n,i);{const s=t.get(Tr());null==n&&null!=s&&(n=Na(s,Tr()));let r=[];const o=Er(e.path),a=e.operationForChild(o),c=t.children.get(o);if(c&&a){const e=n?n.getImmediateChild(o):null,t=pa(i,o);r=r.concat(xa(a,c,e,t))}return s&&(r=r.concat(Ra(s,e,i,n))),r}}function Fa(e,t,n,i){const s=t.get(Tr());null==n&&null!=s&&(n=Na(s,Tr()));let r=[];return t.children.inorderTraversal(((t,s)=>{const o=n?n.getImmediateChild(t):null,a=pa(i,t),c=e.operationForChild(t);c&&(r=r.concat(Fa(c,s,o,a)))})),s&&(r=r.concat(Ra(s,e,i,n))),r}function Ua(e,t){return e.tagToQueryMap.get(t)}function ja(e){const t=e.indexOf("$");return n(-1!==t&&t{const s=Ya(i,t.getImmediateChild(e),n);s!==i&&(r=r.updateImmediateChild(e,s))})),r}}class Ja{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function Qa(e,t){let n=t instanceof Cr?t:new Cr(t),i=e,s=Er(n);for(;null!==s;){const e=k(i.node.children,s)||{children:{},childCount:0};i=new Ja(s,i,e),n=kr(n),s=Er(n)}return i}function Xa(e){return e.node.value}function Za(e,t){e.node.value=t,sc(e)}function ec(e){return e.node.childCount>0}function tc(e,t){$s(e.node.children,((n,i)=>{t(new Ja(n,e,i))}))}function nc(e,t,n,i){n&&!i&&t(e),tc(e,(e=>{nc(e,t,!0,i)})),n&&i&&t(e)}function ic(e){return new Cr(null===e.parent?e.name:ic(e.parent)+"/"+e.name)}function sc(e){null!==e.parent&&function(e,t,n){const i=function(e){return void 0===Xa(e)&&!ec(e)}(n),s=S(e.node.children,t);i&&s?(delete e.node.children[t],e.node.childCount--,sc(e)):i||s||(e.node.children[t]=n.node,e.node.childCount++,sc(e))}(e.parent,e.name,e)}const rc=/[\[\].#$\/\u0000-\u001F\u007F]/,oc=/[\[\].#$\u0000-\u001F\u007F]/,ac=10485760,cc=function(e){return"string"==typeof e&&0!==e.length&&!rc.test(e)},lc=function(e,t,n){const i=n instanceof Cr?new xr(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+Ur(i));if("function"==typeof t)throw new Error(e+"contains a function "+Ur(i)+" with contents = "+t.toString());if(Us(t))throw new Error(e+"contains "+t.toString()+" "+Ur(i));if("string"==typeof t&&t.length>ac/3&&U(t)>ac)throw new Error(e+"contains a string greater than "+ac+" utf8 bytes "+Ur(i)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,s=!1;if($s(t,((t,r)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(s=!0,!cc(t)))throw new Error(e+" contains an invalid key ("+t+") "+Ur(i)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var o,a;a=t,(o=i).parts_.length>0&&(o.byteLength_+=1),o.parts_.push(a),o.byteLength_+=U(a),Fr(o),lc(e,r,i),function(e){const t=e.parts_.pop();e.byteLength_-=U(t),e.parts_.length>0&&(e.byteLength_-=1)}(i)})),n&&s)throw new Error(e+' contains ".value" child '+Ur(i)+" in addition to actual children.")}},hc=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!cc(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),function(e){return"string"==typeof e&&0!==e.length&&!oc.test(e)}(e)}(n))throw new Error(function(e,t){return`${e} failed: ${t} argument `}(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class uc{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function dc(e,t,n){(function(e,t){let n=null;for(let i=0;iMr(e,t)||Mr(t,e)))}function pc(e){for(let t=0;t=0)e.server_=new To(e.repoInfo_,((t,n,i,s)=>{yc(e,t,n,i,s)}),e.authTokenProvider_,e.appCheckProvider_),setTimeout((()=>wc(e,!0)),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{T(n)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new qr(e.repoInfo_,t,((t,n,i,s)=>{yc(e,t,n,i,s)}),(t=>{wc(e,t)}),(t=>{!function(e,t){$s(t,((t,n)=>{Ic(e,t,n)}))}(e,t)}),e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener((t=>{e.server_.refreshAuthToken(t)})),e.appCheckProvider_.addTokenChangeListener((t=>{e.server_.refreshAppCheckToken(t.token)})),e.statsReporter_=function(t,n){const i=t.toString();return hr[i]||(hr[i]=new Po(e.stats_,e.server_)),hr[i]}(e.repoInfo_),e.infoData_=new Eo,e.infoSyncTree_=new Pa({startListening:(t,n,i,s)=>{let r=[];const o=e.infoData_.getNode(t._path);return o.isEmpty()||(r=Da(e.infoSyncTree_,t._path,o),setTimeout((()=>{s("ok")}),0)),r},stopListening:()=>{}}),Ic(e,"connected",!1),e.serverSyncTree_=new Pa({startListening:(t,n,i,s)=>(e.server_.listen(t,i,n,((n,i)=>{const r=s(n,i);dc(e.eventQueue_,t._path,r)})),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function gc(e){const t=e.infoData_.getNode(new Cr(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function vc(e){return Ha({timestamp:gc(e)})}function yc(e,t,n,i,s){e.dataUpdateCount++;const r=new Cr(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(s)if(i){const t=N(n,(e=>go(e)));o=function(e,t,n,i){const s=Ua(e,i);if(s){const i=ja(s),r=i.path,o=i.queryId,a=Dr(r,t),c=Bo.fromObject(n);return Wa(e,r,new xo(Do(o),a,c))}return[]}(e.serverSyncTree_,r,t,s)}else{const t=go(n);o=function(e,t,n,i){const s=Ua(e,i);if(null!=s){const i=ja(s),r=i.path,o=i.queryId,a=Dr(r,t);return Wa(e,r,new Mo(Do(o),a,n))}return[]}(e.serverSyncTree_,r,t,s)}else if(i){const t=N(n,(e=>go(e)));o=function(e,t,n){const i=Bo.fromObject(n);return Ma(e,new xo({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,i))}(e.serverSyncTree_,r,t)}else{const t=go(n);o=Da(e.serverSyncTree_,r,t)}let a=r;o.length>0&&(a=Sc(e,r)),dc(e.eventQueue_,a,o)}function wc(e,t){Ic(e,"connected",t),!1===t&&function(e){Cc(e,"onDisconnectEvents");const t=vc(e),n=So();Ro(e.onDisconnect_,Tr(),((i,s)=>{const r=Ka(i,s,e.serverSyncTree_,t);ko(n,i,r)}));let i=[];Ro(n,Tr(),((t,n)=>{i=i.concat(Da(e.serverSyncTree_,t,n));const s=function(e,t){const n=ic(kc(e,t)),i=Qa(e.transactionQueueTree_,t);return function(e,t,n){let i=void 0?e:e.parent;for(;null!==i;){if(t(i))return!0;i=i.parent}}(i,(t=>{Oc(e,t)})),Oc(e,i),nc(i,(t=>{Oc(e,t)})),n}(e,t);Sc(e,s)})),e.onDisconnect_=So(),dc(e.eventQueue_,Tr(),i)}(e)}function Ic(e,t,n){const i=new Cr("/.info/"+t),s=go(n);e.infoData_.updateSnapshot(i,s);const r=Da(e.infoSyncTree_,i,s);dc(e.eventQueue_,i,r)}function bc(e){return e.nextWriteId_++}function Cc(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),Ds(n,...t)}function Tc(e,t,n){return La(e.serverSyncTree_,t,n)||fo.EMPTY_NODE}function Ec(e,t=e.transactionQueueTree_){if(t||Pc(e,t),Xa(t)){const i=Rc(e,t);n(i.length>0,"Sending zero length transaction queue"),i.every((e=>0===e.status))&&function(e,t,i){const s=i.map((e=>e.currentWriteId)),r=Tc(e,t,s);let o=r;const a=r.hash();for(let e=0;e{Cc(e,"transaction put response",{path:l.toString(),status:n});let s=[];if("ok"===n){const n=[];for(let t=0;ti[t].onComplete(null,!0,i[t].currentOutputSnapshotResolved))),i[t].unwatcher();Pc(e,Qa(e.transactionQueueTree_,t)),Ec(e,e.transactionQueueTree_),dc(e.eventQueue_,t,s);for(let e=0;e{Ec(e,t)}))}function Sc(e,t){const i=kc(e,t),s=ic(i);return function(e,t,i){if(0===t.length)return;const s=[];let r=[];const o=t.filter((e=>0===e.status)).map((e=>e.currentWriteId));for(let c=0;c=fc)d=!0,u="maxretry",r=r.concat(Aa(e.serverSyncTree_,l.currentWriteId,!0));else{const n=Tc(e,l.path,o);l.currentInputSnapshot=n;const i=t[c].update(n.val());if(void 0!==i){lc("transaction failed: Data returned ",i,l.path);let t=go(i);"object"==typeof i&&null!=i&&S(i,".priority")||(t=t.updatePriority(n.getPriority()));const s=l.currentWriteId,a=vc(e),c=Ga(t,n,a);l.currentOutputSnapshotRaw=t,l.currentOutputSnapshotResolved=c,l.currentWriteId=bc(e),o.splice(o.indexOf(s),1),r=r.concat(Oa(e.serverSyncTree_,l.path,c,l.currentWriteId,l.applyLocally)),r=r.concat(Aa(e.serverSyncTree_,s,!0))}else d=!0,u="nodata",r=r.concat(Aa(e.serverSyncTree_,l.currentWriteId,!0))}dc(e.eventQueue_,i,r),r=[],d&&(t[c].status=2,a=t[c].unwatcher,setTimeout(a,Math.floor(0)),t[c].onComplete&&("nodata"===u?s.push((()=>t[c].onComplete(null,!1,t[c].currentInputSnapshot))):s.push((()=>t[c].onComplete(new Error(u),!1,null)))))}var a;Pc(e,e.transactionQueueTree_);for(let e=0;ee.order-t.order)),n}function Nc(e,t,n){const i=Xa(t);if(i)for(let e=0;e{Nc(e,t,n)}))}function Pc(e,t){const n=Xa(t);if(n){let e=0;for(let t=0;t0?n:void 0)}tc(t,(t=>{Pc(e,t)}))}function Oc(e,t){const i=Xa(t);if(i){const s=[];let r=[],o=-1;for(let t=0;t.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||xs("Cannot parse Firebase url. Please use https://.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Fs("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const s="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new or(n.host,n.secure,i,s,t,"",i!==n.subdomain),path:new Cr(n.pathString)}},Dc=function(e){let t="",n="",i="",s="",r="",o=!0,a="https",c=443;if("string"==typeof e){let l=e.indexOf("//");l>=0&&(a=e.substring(0,l-1),e=e.substring(l+2));let h=e.indexOf("/");-1===h&&(h=e.length);let u=e.indexOf("?");-1===u&&(u=e.length),t=e.substring(0,Math.min(h,u)),h0){let i=n[e];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}(e.substring(h,u)));const d=function(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const i=n.split("=");2===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):Fs(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,u)));l=t.indexOf(":"),l>=0?(o="https"===a||"wss"===a,c=parseInt(t.substring(l+1),10)):l=t.length;const p=t.slice(0,l);if("localhost"===p.toLowerCase())n="localhost";else if(p.split(".").length<=2)n=p;else{const e=t.indexOf(".");i=t.substring(0,e).toLowerCase(),n=t.substring(e+1),r=i}"ns"in d&&(r=d.ns)}return{host:t,port:c,domain:n,subdomain:i,secure:o,scheme:a,pathString:s,namespace:r}};class Lc{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return Ar(this._path)?null:Rr(this._path)}get ref(){return new Mc(this._repo,this._path)}get _queryIdentifier(){const e=Co(this._queryParams),t=zs(e);return"{}"===t?"default":t}get _queryObject(){return Co(this._queryParams)}isEqual(e){if(!((e=j(e))instanceof Lc))return!1;const t=this._repo===e._repo,n=Lr(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return t&&n&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;nfunction(e,t,n,i,s){let r=i||e.options.databaseURL;void 0===r&&(e.options.projectId||xs("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),Ds("Using default host for project ",e.options.projectId),r=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o,a,c=Ac(r,s),l=c.repoInfo;"undefined"!=typeof process&&process.env&&(a=process.env.FIREBASE_DATABASE_EMULATOR_HOST),a?(o=!0,r=`http://${a}?ns=${l.namespace}`,c=Ac(r,s),l=c.repoInfo):o=!c.repoInfo.secure;const h=s&&o?new er(er.OWNER):new Zs(e.name,e.options,t);hc("Invalid Firebase Database URL",c),Ar(c.path)||xs("Database URL must point to the root of a Firebase Database (not including a child path).");const u=function(e,t,n,i){let s=Fc[t.name];s||(s={},Fc[t.name]=s);let r=s[e.toURLString()];return r&&xs("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new _c(e,!1,n,i),s[e.toURLString()]=r,r}(l,e,h,new Xs(e.name,n));return new Uc(u,e)}(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)),"PUBLIC").setMultipleInstances(!0)),it(ys,ws,void 0),it(ys,ws,"esm2017");const jc=tt(function(){const e=document.getElementById("wp-script-module-data-@prc/firebase");try{return JSON.parse(e.textContent)}catch(e){return console.error(e),{}}}()),Wc=function(e=nt()){const t=Je(e,"auth");if(t.isInitialized())return t.getImmediate();const n=function(e,t){const n=Je(e,"auth");if(n.isInitialized()){const e=n.getImmediate();if(P(n.getOptions(),null!=t?t:{}))return e;wt(e,"already-initialized")}return n.initialize({options:t})}(e,{popupRedirectResolver:us,persistence:[Pi,pi,_i]}),i=_("authTokenSyncURL");if(i&&"boolean"==typeof isSecureContext&&isSecureContext){const e=new URL(i,location.origin);if(location.origin===e.origin){const t=(s=e.toString(),async e=>{const t=e&&await e.getIdTokenResult(),n=t&&((new Date).getTime()-Date.parse(t.issuedAtTime))/1e3;if(n&&n>_s)return;const i=null==t?void 0:t.token;ms!==i&&(ms=i,await fetch(s,{method:i?"POST":"DELETE",headers:i?{Authorization:`Bearer ${i}`}:{}}))});!function(e,t,n){j(e).beforeAuthStateChanged(t,n)}(n,t,(()=>t(n.currentUser))),function(e,n,i,s){j(e).onIdTokenChanged((e=>t(e)),void 0,void 0)}(n)}}var s;const r=p("auth");return r&&function(e,t,n){const i=kn(e);Et(i._canInitEmulator,i,"emulator-config-failed"),Et(/^https?:\/\//.test(t),i,"invalid-emulator-scheme");const s=!!(null==n?void 0:n.disableWarnings),r=Mn(t),{host:o,port:a}=function(e){const t=Mn(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const i=n[2].split("@").pop()||"",s=/^(\[[^\]]+\])(:|$)/.exec(i);if(s){const e=s[1];return{host:e,port:xn(i.substr(e.length+1))}}{const[e,t]=i.split(":");return{host:e,port:xn(t)}}}(t),c=null===a?"":`:${a}`;i.config.emulator={url:`${r}//${o}${c}/`},i.settings.appVerificationDisabledForTesting=!0,i.emulatorConfig=Object.freeze({host:o,port:a,protocol:r.replace(":",""),options:Object.freeze({disableWarnings:s})}),s||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())}()}(n,`http://${r}`),n}(),qc=function(e,t,n){return Qe(e.app)?Promise.reject(Ct(e)):async function(e,t){return ri(kn(e),t)}(j(e),Gn.credential(t,n)).catch((async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&li(e),t}))},Vc=function(e,t,n,i){return j(e).onAuthStateChanged(t,n,i)},Hc=function(e){return j(e).signOut()},zc=async function(e,t,n){const i=kn(e),s={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};n&&function(e,t,n){var i;Et((null===(i=n.url)||void 0===i?void 0:i.length)>0,e,"invalid-continue-uri"),Et(void 0===n.dynamicLinkDomain||n.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(Et(n.iOS.bundleId.length>0,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(Et(n.android.packageName.length>0,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}(i,s,n),await Ln(i,s,"getOobCode",qn)},Bc=async function(e,t,n){await Un(j(e),{oobCode:t,newPassword:n}).catch((async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&li(e),t}))},$c=async function(e,t){const{data:n}=await async function(e,t){const n=j(e),i=await Un(n,{oobCode:t}),s=i.requestType;switch(Et(s,n,"internal-error"),s){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":Et(i.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":Et(i.mfaInfo,n,"internal-error");default:Et(i.email,n,"internal-error")}let r=null;return i.mfaInfo&&(r=oi._fromServerResponse(kn(n),i.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===i.requestType?i.newEmail:i.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===i.requestType?i.email:i.newEmail)||null,multiFactorInfo:r},operation:s}}(j(e),t);return n.email},Kc=function(e=nt(),t){const n=Je(e,"database").getImmediate({identifier:t});if(!n._instanceStarted){const e=(e=>{const t=p("database");if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const i=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),i]:[t.substring(0,n),i]})();e&&function(e,t,n,i={}){(e=j(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&xs("Cannot call useEmulator() after instance has already been initialized.");const s=e._repoInternal;let r;if(s.repoInfo_.nodeAdmin)i.mockUserToken&&xs('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),r=new er(er.OWNER);else if(i.mockUserToken){const t="string"==typeof i.mockUserToken?i.mockUserToken:function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",i=e.iat||0,s=e.sub||e.user_id;if(!s)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const r=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:i,exp:i+3600,auth_time:i,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}}},e);return[c(JSON.stringify({alg:"none",type:"JWT"})),c(JSON.stringify(r)),""].join(".")}(i.mockUserToken,e.app.options.projectId);r=new er(t)}!function(e,t,n,i){e.repoInfo_=new or(`${t}:${n}`,!1,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0),i&&(e.authTokenProvider_=i)}(s,t,n,r)}(n,...e)}return n}();var Gc=t.yA,Yc=t.j2,Jc=t.R4,Qc=t.C3,Xc=t.hg,Zc=t.J1,el=t.x9,tl=t.CI,nl=t.RE;export{Gc as app,Yc as auth,Jc as confirmPasswordReset,Qc as getDatabase,Xc as onAuthStateChanged,Zc as sendPasswordResetEmail,el as signInWithEmailAndPassword,tl as signOut,nl as verifyPasswordResetCode}; //# sourceMappingURL=module.min.js.map \ No newline at end of file diff --git a/includes/firebase/build/module.min.js.map b/includes/firebase/build/module.min.js.map index 1d7b20d5..cc3edd80 100644 --- a/includes/firebase/build/module.min.js.map +++ b/includes/firebase/build/module.min.js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E,G","sources":["webpack://@pewresearch/prc-platform-firebase/webpack/bootstrap","webpack://@pewresearch/prc-platform-firebase/webpack/runtime/define property getters","webpack://@pewresearch/prc-platform-firebase/webpack/runtime/global","webpack://@pewresearch/prc-platform-firebase/webpack/runtime/hasOwnProperty shorthand","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/util/dist/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/component/dist/esm/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/logger/dist/esm/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/idb/build/wrap-idb-value.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/idb/build/index.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/app/dist/esm/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/tslib/tslib.es6.mjs","webpack://@pewresearch/prc-platform-firebase/./node_modules/firebase/app/dist/esm/index.esm.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/firebase/node_modules/@firebase/auth/dist/esm2017/index-54738136.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/database/dist/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./src/index.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\r\n */\r\nconst CONSTANTS = {\r\n /**\r\n * @define {boolean} Whether this is the client Node.js SDK.\r\n */\r\n NODE_CLIENT: false,\r\n /**\r\n * @define {boolean} Whether this is the Admin Node.js SDK.\r\n */\r\n NODE_ADMIN: false,\r\n /**\r\n * Firebase SDK Version\r\n */\r\n SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n */\r\nconst assert = function (assertion, message) {\r\n if (!assertion) {\r\n throw assertionError(message);\r\n }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n */\r\nconst assertionError = function (message) {\r\n return new Error('Firebase Database (' +\r\n CONSTANTS.SDK_VERSION +\r\n ') INTERNAL ASSERT FAILED: ' +\r\n message);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst stringToByteArray$1 = function (str) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) === 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nconst byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n const c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n const c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n const c4 = bytes[pos++];\r\n const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nconst base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeByteArray(input, webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n const byteToCharMap = webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length; i += 3) {\r\n const byte1 = input[i];\r\n const haveByte2 = i + 1 < input.length;\r\n const byte2 = haveByte2 ? input[i + 1] : 0;\r\n const haveByte3 = i + 2 < input.length;\r\n const byte3 = haveByte3 ? input[i + 2] : 0;\r\n const outByte1 = byte1 >> 2;\r\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n let outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param input A string to encode.\r\n * @param webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param input to decode.\r\n * @param webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return string representing the decoded value.\r\n */\r\n decodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param input Input to decode.\r\n * @param webSafe True if we should use the web-safe alphabet.\r\n * @return bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray(input, webSafe) {\r\n this.init_();\r\n const charToByteMap = webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length;) {\r\n const byte1 = charToByteMap[input.charAt(i++)];\r\n const haveByte2 = i < input.length;\r\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n const haveByte3 = i < input.length;\r\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n const haveByte4 = i < input.length;\r\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw new DecodeBase64StringError();\r\n }\r\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 !== 64) {\r\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 !== 64) {\r\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_() {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * An error encountered while decoding base64 string.\r\n */\r\nclass DecodeBase64StringError extends Error {\r\n constructor() {\r\n super(...arguments);\r\n this.name = 'DecodeBase64StringError';\r\n }\r\n}\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nconst base64Encode = function (str) {\r\n const utf8Bytes = stringToByteArray$1(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nconst base64urlEncodeWithoutPadding = function (str) {\r\n // Use base64url encoding and remove padding in the end (dot characters).\r\n return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nconst base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n const dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (const prop in source) {\r\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\nfunction isValidKey(key) {\r\n return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n * @public\r\n */\r\nfunction getGlobal() {\r\n if (typeof self !== 'undefined') {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined') {\r\n return window;\r\n }\r\n if (typeof global !== 'undefined') {\r\n return global;\r\n }\r\n throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\r\n/**\r\n * Attempt to read defaults from a JSON string provided to\r\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\r\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\r\n * The dots are in parens because certain compilers (Vite?) cannot\r\n * handle seeing that variable in comments.\r\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\r\n */\r\nconst getDefaultsFromEnvVariable = () => {\r\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\r\n return;\r\n }\r\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\r\n if (defaultsJsonString) {\r\n return JSON.parse(defaultsJsonString);\r\n }\r\n};\r\nconst getDefaultsFromCookie = () => {\r\n if (typeof document === 'undefined') {\r\n return;\r\n }\r\n let match;\r\n try {\r\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\r\n }\r\n catch (e) {\r\n // Some environments such as Angular Universal SSR have a\r\n // `document` object but error on accessing `document.cookie`.\r\n return;\r\n }\r\n const decoded = match && base64Decode(match[1]);\r\n return decoded && JSON.parse(decoded);\r\n};\r\n/**\r\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\r\n * (1) if such an object exists as a property of `globalThis`\r\n * (2) if such an object was provided on a shell environment variable\r\n * (3) if such an object exists in a cookie\r\n * @public\r\n */\r\nconst getDefaults = () => {\r\n try {\r\n return (getDefaultsFromGlobal() ||\r\n getDefaultsFromEnvVariable() ||\r\n getDefaultsFromCookie());\r\n }\r\n catch (e) {\r\n /**\r\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\r\n * to any environment case we have not accounted for. Log to\r\n * info instead of swallowing so we can find these unknown cases\r\n * and add paths for them if needed.\r\n */\r\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\r\n return;\r\n }\r\n};\r\n/**\r\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };\r\n/**\r\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\r\n const host = getDefaultEmulatorHost(productName);\r\n if (!host) {\r\n return undefined;\r\n }\r\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\r\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\r\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\r\n }\r\n // eslint-disable-next-line no-restricted-globals\r\n const port = parseInt(host.substring(separatorIndex + 1), 10);\r\n if (host[0] === '[') {\r\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\r\n return [host.substring(1, separatorIndex - 1), port];\r\n }\r\n else {\r\n return [host.substring(0, separatorIndex), port];\r\n }\r\n};\r\n/**\r\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\r\n * @public\r\n */\r\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\r\n/**\r\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\r\n * prefixed by \"_\")\r\n * @public\r\n */\r\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Deferred {\r\n constructor() {\r\n this.reject = () => { };\r\n this.resolve = () => { };\r\n this.promise = new Promise((resolve, reject) => {\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n */\r\n wrapCallback(callback) {\r\n return (error, value) => {\r\n if (error) {\r\n this.reject(error);\r\n }\r\n else {\r\n this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n this.promise.catch(() => { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n if (token.uid) {\r\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n }\r\n // Unsecured JWTs use \"none\" as the algorithm.\r\n const header = {\r\n alg: 'none',\r\n type: 'JWT'\r\n };\r\n const project = projectId || 'demo-project';\r\n const iat = token.iat || 0;\r\n const sub = token.sub || token.user_id;\r\n if (!sub) {\r\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n }\r\n const payload = Object.assign({ \r\n // Set all required fields to decent defaults\r\n iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\r\n sign_in_provider: 'custom',\r\n identities: {}\r\n } }, token);\r\n // Unsecured JWTs use the empty string as a signature.\r\n const signature = '';\r\n return [\r\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n signature\r\n ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n return (typeof window !== 'undefined' &&\r\n // @ts-ignore Setting up an broadly applicable index signature for Window\r\n // just to deal with this case would probably be a bad idea.\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected or specified.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n var _a;\r\n const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;\r\n if (forceEnvironment === 'node') {\r\n return true;\r\n }\r\n else if (forceEnvironment === 'browser') {\r\n return false;\r\n }\r\n try {\r\n return (Object.prototype.toString.call(global.process) === '[object process]');\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n return typeof window !== 'undefined' || isWebWorker();\r\n}\r\n/**\r\n * Detect Web Worker context\r\n */\r\nfunction isWebWorker() {\r\n return (typeof WorkerGlobalScope !== 'undefined' &&\r\n typeof self !== 'undefined' &&\r\n self instanceof WorkerGlobalScope);\r\n}\r\nfunction isBrowserExtension() {\r\n const runtime = typeof chrome === 'object'\r\n ? chrome.runtime\r\n : typeof browser === 'object'\r\n ? browser.runtime\r\n : undefined;\r\n return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n const ua = getUA();\r\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n return (!isNode() &&\r\n !!navigator.userAgent &&\r\n navigator.userAgent.includes('Safari') &&\r\n !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n try {\r\n return typeof indexedDB === 'object';\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n return new Promise((resolve, reject) => {\r\n try {\r\n let preExist = true;\r\n const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\r\n const request = self.indexedDB.open(DB_CHECK_NAME);\r\n request.onsuccess = () => {\r\n request.result.close();\r\n // delete database only when it doesn't pre-exist\r\n if (!preExist) {\r\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\r\n }\r\n resolve(true);\r\n };\r\n request.onupgradeneeded = () => {\r\n preExist = false;\r\n };\r\n request.onerror = () => {\r\n var _a;\r\n reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n };\r\n }\r\n catch (error) {\r\n reject(error);\r\n }\r\n });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\r\n return false;\r\n }\r\n return true;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Standardized Firebase Error.\r\n *\r\n * Usage:\r\n *\r\n * // Typescript string literals for type-safe codes\r\n * type Err =\r\n * 'unknown' |\r\n * 'object-not-found'\r\n * ;\r\n *\r\n * // Closure enum for type-safe error codes\r\n * // at-enum {string}\r\n * var Err = {\r\n * UNKNOWN: 'unknown',\r\n * OBJECT_NOT_FOUND: 'object-not-found',\r\n * }\r\n *\r\n * let errors: Map = {\r\n * 'generic-error': \"Unknown error\",\r\n * 'file-not-found': \"Could not find file: {$file}\",\r\n * };\r\n *\r\n * // Type-safe function - must pass a valid error code as param.\r\n * let error = new ErrorFactory('service', 'Service', errors);\r\n *\r\n * ...\r\n * throw error.create(Err.GENERIC);\r\n * ...\r\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n * ...\r\n * // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n * catch (e) {\r\n * assert(e.message === \"Could not find file: foo.txt.\");\r\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n * console.log(\"Could not read file: \" + e['file']);\r\n * }\r\n * }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n constructor(\r\n /** The error code for this error. */\r\n code, message, \r\n /** Custom data for this error. */\r\n customData) {\r\n super(message);\r\n this.code = code;\r\n this.customData = customData;\r\n /** The custom name for all FirebaseErrors. */\r\n this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n }\r\n}\r\nclass ErrorFactory {\r\n constructor(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n create(code, ...data) {\r\n const customData = data[0] || {};\r\n const fullCode = `${this.service}/${code}`;\r\n const template = this.errors[code];\r\n const message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n const error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, (_, key) => {\r\n const value = data[key];\r\n return value != null ? String(value) : `<${key}?>`;\r\n });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n let header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n const parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header,\r\n claims,\r\n data,\r\n signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n const claims = decode(token).claims;\r\n const now = Math.floor(new Date().getTime() / 1000);\r\n let validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n const claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n const decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n const claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n const res = {};\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n const aKeys = Object.keys(a);\r\n const bKeys = Object.keys(b);\r\n for (const k of aKeys) {\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n const aProp = a[k];\r\n const bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (const k of bKeys) {\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n const deferredPromise = new Deferred();\r\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n const params = [];\r\n for (const [key, value] of Object.entries(querystringParams)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(arrayVal => {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n const obj = {};\r\n const tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(token => {\r\n if (token) {\r\n const [key, value] = token.split('=');\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n const queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n const fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n constructor() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (let i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n reset() {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n }\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n compress_(buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n const W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (let i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (let i = 16; i < 80; i++) {\r\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n let a = this.chain_[0];\r\n let b = this.chain_[1];\r\n let c = this.chain_[2];\r\n let d = this.chain_[3];\r\n let e = this.chain_[4];\r\n let f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (let i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n }\r\n update(bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n const lengthMinusBlock = length - this.blockSize;\r\n let n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n const buf = this.buf_;\r\n let inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n }\r\n /** @override */\r\n digest() {\r\n const digest = [];\r\n let totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (let i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n let n = 0;\r\n for (let i = 0; i < 5; i++) {\r\n for (let j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n const proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n constructor(executor, onNoObservers) {\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(() => {\r\n executor(this);\r\n })\r\n .catch(e => {\r\n this.error(e);\r\n });\r\n }\r\n next(value) {\r\n this.forEachObserver((observer) => {\r\n observer.next(value);\r\n });\r\n }\r\n error(error) {\r\n this.forEachObserver((observer) => {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n }\r\n complete() {\r\n this.forEachObserver((observer) => {\r\n observer.complete();\r\n });\r\n this.close();\r\n }\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n subscribe(nextOrObserver, error, complete) {\r\n let observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error,\r\n complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n try {\r\n if (this.finalError) {\r\n observer.error(this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n }\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n unsubscribeOne(i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n }\r\n forEachObserver(fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (let i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n }\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n sendOne(i, fn) {\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n try {\r\n fn(this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n close(err) {\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n this.observers = undefined;\r\n this.onNoObservers = undefined;\r\n });\r\n }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return (...args) => {\r\n Promise.resolve(true)\r\n .then(() => {\r\n fn(...args);\r\n })\r\n .catch((error) => {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (const method of methods) {\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n let argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n const error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n const high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n const c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n return v.toString(16);\r\n });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n *

Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n *

Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, isWebWorker, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n constructor(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n setInstantiationMode(mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n }\r\n setMultipleInstances(multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n }\r\n setServiceProps(props) {\r\n this.serviceProps = props;\r\n return this;\r\n }\r\n setInstanceCreatedCallback(callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n constructor(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n get(identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n const deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n }\r\n getImmediate(options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(`Service ${this.name} is not available`);\r\n }\r\n }\r\n }\r\n getComponent() {\r\n return this.component;\r\n }\r\n setComponent(component) {\r\n if (component.name !== this.name) {\r\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n }\r\n if (this.component) {\r\n throw Error(`Component for ${this.name} has already been provided`);\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n }\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n async delete() {\r\n const services = Array.from(this.instances.values());\r\n await Promise.all([\r\n ...services\r\n .filter(service => 'INTERNAL' in service) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service.INTERNAL.delete()),\r\n ...services\r\n .filter(service => '_delete' in service) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service._delete())\r\n ]);\r\n }\r\n isComponentSet() {\r\n return this.component != null;\r\n }\r\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instances.has(identifier);\r\n }\r\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instancesOptions.get(identifier) || {};\r\n }\r\n initialize(opts = {}) {\r\n const { options = {} } = opts;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(`Component ${this.name} has not been registered yet`);\r\n }\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options\r\n });\r\n // resolve any pending promise waiting for the service instance\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n return instance;\r\n }\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n onInit(callback, identifier) {\r\n var _a;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n const existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return () => {\r\n existingCallbacks.delete(callback);\r\n };\r\n }\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n invokeOnInitCallbacks(instance, identifier) {\r\n const callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n let instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n }\r\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n }\r\n shouldAutoInitialize() {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\r\n }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n constructor(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n addComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n }\r\n provider.setComponent(component);\r\n }\r\n addOrOverwriteComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n }\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n getProvider(name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n const provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n }\r\n getProviders() {\r\n return Array.from(this.providers.values());\r\n }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n [LogLevel.DEBUG]: 'log',\r\n [LogLevel.VERBOSE]: 'log',\r\n [LogLevel.INFO]: 'info',\r\n [LogLevel.WARN]: 'warn',\r\n [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n const now = new Date().toISOString();\r\n const method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method](`[${now}] ${instance.name}:`, ...args);\r\n }\r\n else {\r\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n }\r\n};\r\nclass Logger {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n constructor(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n get logLevel() {\r\n return this._logLevel;\r\n }\r\n set logLevel(val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n }\r\n this._logLevel = val;\r\n }\r\n // Workaround for setter/getter having to be the same type.\r\n setLogLevel(val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n }\r\n get logHandler() {\r\n return this._logHandler;\r\n }\r\n set logHandler(val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n }\r\n get userLogHandler() {\r\n return this._userLogHandler;\r\n }\r\n set userLogHandler(val) {\r\n this._userLogHandler = val;\r\n }\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n debug(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n this._logHandler(this, LogLevel.DEBUG, ...args);\r\n }\r\n log(...args) {\r\n this._userLogHandler &&\r\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n }\r\n info(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n this._logHandler(this, LogLevel.INFO, ...args);\r\n }\r\n warn(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n this._logHandler(this, LogLevel.WARN, ...args);\r\n }\r\n error(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n this._logHandler(this, LogLevel.ERROR, ...args);\r\n }\r\n}\r\nfunction setLogLevel(level) {\r\n instances.forEach(inst => {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n for (const instance of instances) {\r\n let customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = (instance, level, ...args) => {\r\n const message = args\r\n .map(arg => {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(arg => arg)\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message,\r\n args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, isBrowser, isWebWorker, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PlatformLoggerServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n }\r\n // In initial implementation, this will be called by installations on\r\n // auth token refresh, and installations will send this string.\r\n getPlatformInfoString() {\r\n const providers = this.container.getProviders();\r\n // Loop through providers and get library/version pairs from any that are\r\n // version components.\r\n return providers\r\n .map(provider => {\r\n if (isVersionServiceProvider(provider)) {\r\n const service = provider.getImmediate();\r\n return `${service.library}/${service.version}`;\r\n }\r\n else {\r\n return null;\r\n }\r\n })\r\n .filter(logString => logString)\r\n .join(' ');\r\n }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n const component = provider.getComponent();\r\n return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* ComponentType.VERSION */;\r\n}\n\nconst name$p = \"@firebase/app\";\nconst version$1 = \"0.10.6\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/app');\n\nconst name$o = \"@firebase/app-compat\";\n\nconst name$n = \"@firebase/analytics-compat\";\n\nconst name$m = \"@firebase/analytics\";\n\nconst name$l = \"@firebase/app-check-compat\";\n\nconst name$k = \"@firebase/app-check\";\n\nconst name$j = \"@firebase/auth\";\n\nconst name$i = \"@firebase/auth-compat\";\n\nconst name$h = \"@firebase/database\";\n\nconst name$g = \"@firebase/database-compat\";\n\nconst name$f = \"@firebase/functions\";\n\nconst name$e = \"@firebase/functions-compat\";\n\nconst name$d = \"@firebase/installations\";\n\nconst name$c = \"@firebase/installations-compat\";\n\nconst name$b = \"@firebase/messaging\";\n\nconst name$a = \"@firebase/messaging-compat\";\n\nconst name$9 = \"@firebase/performance\";\n\nconst name$8 = \"@firebase/performance-compat\";\n\nconst name$7 = \"@firebase/remote-config\";\n\nconst name$6 = \"@firebase/remote-config-compat\";\n\nconst name$5 = \"@firebase/storage\";\n\nconst name$4 = \"@firebase/storage-compat\";\n\nconst name$3 = \"@firebase/firestore\";\n\nconst name$2 = \"@firebase/vertexai-preview\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"10.12.3\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n [name$p]: 'fire-core',\r\n [name$o]: 'fire-core-compat',\r\n [name$m]: 'fire-analytics',\r\n [name$n]: 'fire-analytics-compat',\r\n [name$k]: 'fire-app-check',\r\n [name$l]: 'fire-app-check-compat',\r\n [name$j]: 'fire-auth',\r\n [name$i]: 'fire-auth-compat',\r\n [name$h]: 'fire-rtdb',\r\n [name$g]: 'fire-rtdb-compat',\r\n [name$f]: 'fire-fn',\r\n [name$e]: 'fire-fn-compat',\r\n [name$d]: 'fire-iid',\r\n [name$c]: 'fire-iid-compat',\r\n [name$b]: 'fire-fcm',\r\n [name$a]: 'fire-fcm-compat',\r\n [name$9]: 'fire-perf',\r\n [name$8]: 'fire-perf-compat',\r\n [name$7]: 'fire-rc',\r\n [name$6]: 'fire-rc-compat',\r\n [name$5]: 'fire-gcs',\r\n [name$4]: 'fire-gcs-compat',\r\n [name$3]: 'fire-fst',\r\n [name$1]: 'fire-fst-compat',\r\n [name$2]: 'fire-vertex',\r\n 'fire-js': 'fire-js',\r\n [name]: 'fire-js-all'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * @internal\r\n */\r\nconst _serverApps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n try {\r\n app.container.addComponent(component);\r\n }\r\n catch (e) {\r\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n const componentName = component.name;\r\n if (_components.has(componentName)) {\r\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n return false;\r\n }\r\n _components.set(componentName, component);\r\n // add the component to existing app instances\r\n for (const app of _apps.values()) {\r\n _addComponent(app, component);\r\n }\r\n for (const serverApp of _serverApps.values()) {\r\n _addComponent(serverApp, component);\r\n }\r\n return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n const heartbeatController = app.container\r\n .getProvider('heartbeat')\r\n .getImmediate({ optional: true });\r\n if (heartbeatController) {\r\n void heartbeatController.triggerHeartbeat();\r\n }\r\n return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n *\r\n * @param obj - an object of type FirebaseApp or FirebaseOptions.\r\n *\r\n * @returns true if the provide object is of type FirebaseApp.\r\n *\r\n * @internal\r\n */\r\nfunction _isFirebaseApp(obj) {\r\n return obj.options !== undefined;\r\n}\r\n/**\r\n *\r\n * @param obj - an object of type FirebaseApp.\r\n *\r\n * @returns true if the provided object is of type FirebaseServerAppImpl.\r\n *\r\n * @internal\r\n */\r\nfunction _isFirebaseServerApp(obj) {\r\n return obj.settings !== undefined;\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n _components.clear();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n 'call initializeApp() first',\r\n [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}'\",\r\n [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n [\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',\r\n [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n 'Firebase App instance.',\r\n [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\r\n [\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseAppImpl {\r\n constructor(options, config, container) {\r\n this._isDeleted = false;\r\n this._options = Object.assign({}, options);\r\n this._config = Object.assign({}, config);\r\n this._name = config.name;\r\n this._automaticDataCollectionEnabled =\r\n config.automaticDataCollectionEnabled;\r\n this._container = container;\r\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n }\r\n get automaticDataCollectionEnabled() {\r\n this.checkDestroyed();\r\n return this._automaticDataCollectionEnabled;\r\n }\r\n set automaticDataCollectionEnabled(val) {\r\n this.checkDestroyed();\r\n this._automaticDataCollectionEnabled = val;\r\n }\r\n get name() {\r\n this.checkDestroyed();\r\n return this._name;\r\n }\r\n get options() {\r\n this.checkDestroyed();\r\n return this._options;\r\n }\r\n get config() {\r\n this.checkDestroyed();\r\n return this._config;\r\n }\r\n get container() {\r\n return this._container;\r\n }\r\n get isDeleted() {\r\n return this._isDeleted;\r\n }\r\n set isDeleted(val) {\r\n this._isDeleted = val;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseServerAppImpl extends FirebaseAppImpl {\r\n constructor(options, serverConfig, name, container) {\r\n // Build configuration parameters for the FirebaseAppImpl base class.\r\n const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined\r\n ? serverConfig.automaticDataCollectionEnabled\r\n : false;\r\n // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\r\n const config = {\r\n name,\r\n automaticDataCollectionEnabled\r\n };\r\n if (options.apiKey !== undefined) {\r\n // Construct the parent FirebaseAppImp object.\r\n super(options, config, container);\r\n }\r\n else {\r\n const appImpl = options;\r\n super(appImpl.options, config, container);\r\n }\r\n // Now construct the data for the FirebaseServerAppImpl.\r\n this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig);\r\n this._finalizationRegistry = null;\r\n if (typeof FinalizationRegistry !== 'undefined') {\r\n this._finalizationRegistry = new FinalizationRegistry(() => {\r\n this.automaticCleanup();\r\n });\r\n }\r\n this._refCount = 0;\r\n this.incRefCount(this._serverConfig.releaseOnDeref);\r\n // Do not retain a hard reference to the dref object, otherwise the FinalizationRegisry\r\n // will never trigger.\r\n this._serverConfig.releaseOnDeref = undefined;\r\n serverConfig.releaseOnDeref = undefined;\r\n registerVersion(name$p, version$1, 'serverapp');\r\n }\r\n toJSON() {\r\n return undefined;\r\n }\r\n get refCount() {\r\n return this._refCount;\r\n }\r\n // Increment the reference count of this server app. If an object is provided, register it\r\n // with the finalization registry.\r\n incRefCount(obj) {\r\n if (this.isDeleted) {\r\n return;\r\n }\r\n this._refCount++;\r\n if (obj !== undefined && this._finalizationRegistry !== null) {\r\n this._finalizationRegistry.register(obj, this);\r\n }\r\n }\r\n // Decrement the reference count.\r\n decRefCount() {\r\n if (this.isDeleted) {\r\n return 0;\r\n }\r\n return --this._refCount;\r\n }\r\n // Invoked by the FinalizationRegistry callback to note that this app should go through its\r\n // reference counts and delete itself if no reference count remain. The coordinating logic that\r\n // handles this is in deleteApp(...).\r\n automaticCleanup() {\r\n void deleteApp(this);\r\n }\r\n get settings() {\r\n this.checkDestroyed();\r\n return this._serverConfig;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n let options = _options;\r\n if (typeof rawConfig !== 'object') {\r\n const name = rawConfig;\r\n rawConfig = { name };\r\n }\r\n const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n const name = config.name;\r\n if (typeof name !== 'string' || !name) {\r\n throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\r\n appName: String(name)\r\n });\r\n }\r\n options || (options = getDefaultAppConfig());\r\n if (!options) {\r\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\r\n }\r\n const existingApp = _apps.get(name);\r\n if (existingApp) {\r\n // return the existing app if options and config deep equal the ones in the existing app.\r\n if (deepEqual(options, existingApp.options) &&\r\n deepEqual(config, existingApp.config)) {\r\n return existingApp;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\r\n }\r\n }\r\n const container = new ComponentContainer(name);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseAppImpl(options, config, container);\r\n _apps.set(name, newApp);\r\n return newApp;\r\n}\r\nfunction initializeServerApp(_options, _serverAppConfig) {\r\n if (isBrowser() && !isWebWorker()) {\r\n // FirebaseServerApp isn't designed to be run in browsers.\r\n throw ERROR_FACTORY.create(\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);\r\n }\r\n if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {\r\n _serverAppConfig.automaticDataCollectionEnabled = false;\r\n }\r\n let appOptions;\r\n if (_isFirebaseApp(_options)) {\r\n appOptions = _options.options;\r\n }\r\n else {\r\n appOptions = _options;\r\n }\r\n // Build an app name based on a hash of the configuration options.\r\n const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions);\r\n // However, Do not mangle the name based on releaseOnDeref, since it will vary between the\r\n // construction of FirebaseServerApp instances. For example, if the object is the request headers.\r\n if (nameObj.releaseOnDeref !== undefined) {\r\n delete nameObj.releaseOnDeref;\r\n }\r\n const hashCode = (s) => {\r\n return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);\r\n };\r\n if (_serverAppConfig.releaseOnDeref !== undefined) {\r\n if (typeof FinalizationRegistry === 'undefined') {\r\n throw ERROR_FACTORY.create(\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});\r\n }\r\n }\r\n const nameString = '' + hashCode(JSON.stringify(nameObj));\r\n const existingApp = _serverApps.get(nameString);\r\n if (existingApp) {\r\n existingApp.incRefCount(_serverAppConfig.releaseOnDeref);\r\n return existingApp;\r\n }\r\n const container = new ComponentContainer(nameString);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container);\r\n _serverApps.set(nameString, newApp);\r\n return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n * provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n * If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n const app = _apps.get(name);\r\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\r\n return initializeApp();\r\n }\r\n if (!app) {\r\n throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\r\n }\r\n return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n * .then(function() {\r\n * console.log(\"App deleted successfully\");\r\n * })\r\n * .catch(function(error) {\r\n * console.log(\"Error deleting app:\", error);\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n let cleanupProviders = false;\r\n const name = app.name;\r\n if (_apps.has(name)) {\r\n cleanupProviders = true;\r\n _apps.delete(name);\r\n }\r\n else if (_serverApps.has(name)) {\r\n const firebaseServerApp = app;\r\n if (firebaseServerApp.decRefCount() <= 0) {\r\n _serverApps.delete(name);\r\n cleanupProviders = true;\r\n }\r\n }\r\n if (cleanupProviders) {\r\n await Promise.all(app.container\r\n .getProviders()\r\n .map(provider => provider.delete()));\r\n app.isDeleted = true;\r\n }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n var _a;\r\n // TODO: We can use this check to whitelist strings when/if we set up\r\n // a good whitelist system.\r\n let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n if (variant) {\r\n library += `-${variant}`;\r\n }\r\n const libraryMismatch = library.match(/\\s|\\//);\r\n const versionMismatch = version.match(/\\s|\\//);\r\n if (libraryMismatch || versionMismatch) {\r\n const warning = [\r\n `Unable to register library \"${library}\" with version \"${version}\":`\r\n ];\r\n if (libraryMismatch) {\r\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n if (libraryMismatch && versionMismatch) {\r\n warning.push('and');\r\n }\r\n if (versionMismatch) {\r\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n logger.warn(warning.join(' '));\r\n return;\r\n }\r\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n if (logCallback !== null && typeof logCallback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\r\n }\r\n setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n setLogLevel$1(logLevel);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n try {\r\n db.createObjectStore(STORE_NAME);\r\n }\r\n catch (e) {\r\n // Safari/iOS browsers throw occasional exceptions on\r\n // db.createObjectStore() that may be a bug. Avoid blocking\r\n // the rest of the app functionality.\r\n console.warn(e);\r\n }\r\n }\r\n }\r\n }).catch(e => {\r\n throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\r\n originalErrorMessage: e.message\r\n });\r\n });\r\n }\r\n return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME);\r\n const result = await tx.objectStore(STORE_NAME).get(computeKey(app));\r\n // We already have the value but tx.done can throw,\r\n // so we need to await it here to catch errors\r\n await tx.done;\r\n return result;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(STORE_NAME);\r\n await objectStore.put(heartbeatObject, computeKey(app));\r\n await tx.done;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nfunction computeKey(app) {\r\n return `${app.name}!${app.options.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n /**\r\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n * the header string.\r\n * Stores one record per date. This will be consolidated into the standard\r\n * format of one record per user agent string before being sent as a header.\r\n * Populated from indexedDB when the controller is instantiated and should\r\n * be kept in sync with indexedDB.\r\n * Leave public for easier testing.\r\n */\r\n this._heartbeatsCache = null;\r\n const app = this.container.getProvider('app').getImmediate();\r\n this._storage = new HeartbeatStorageImpl(app);\r\n this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n this._heartbeatsCache = result;\r\n return result;\r\n });\r\n }\r\n /**\r\n * Called to report a heartbeat. The function will generate\r\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n * to IndexedDB.\r\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n * already logged, subsequent calls to this function in the same day will be ignored.\r\n */\r\n async triggerHeartbeat() {\r\n var _a, _b;\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n // If we failed to construct a heartbeats cache, then return immediately.\r\n if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {\r\n return;\r\n }\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n /**\r\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n * It also clears all heartbeats from memory as well as in IndexedDB.\r\n *\r\n * NOTE: Consuming product SDKs should not send the header if this method\r\n * returns an empty string.\r\n */\r\n async getHeartbeatsHeader() {\r\n var _a;\r\n if (this._heartbeatsCache === null) {\r\n await this._heartbeatsCachePromise;\r\n }\r\n // If it's still null or the array is empty, there is no data to send.\r\n if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null ||\r\n this._heartbeatsCache.heartbeats.length === 0) {\r\n return '';\r\n }\r\n const date = getUTCDateString();\r\n // Extract as many heartbeats from the cache as will fit under the size limit.\r\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n // Store last sent date to prevent another being logged/sent for the same day.\r\n this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n if (unsentEntries.length > 0) {\r\n // Store any unsent entries if they exist.\r\n this._heartbeatsCache.heartbeats = unsentEntries;\r\n // This seems more likely than emptying the array (below) to lead to some odd state\r\n // since the cache isn't empty and this will be called again on the next request,\r\n // and is probably safest if we await it.\r\n await this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n else {\r\n this._heartbeatsCache.heartbeats = [];\r\n // Do not wait for this, to reduce latency.\r\n void this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n return headerString;\r\n }\r\n}\r\nfunction getUTCDateString() {\r\n const today = new Date();\r\n // Returns date format 'YYYY-MM-DD'\r\n return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n // Heartbeats grouped by user agent in the standard format to be sent in\r\n // the header.\r\n const heartbeatsToSend = [];\r\n // Single date format heartbeats that are not sent.\r\n let unsentEntries = heartbeatsCache.slice();\r\n for (const singleDateHeartbeat of heartbeatsCache) {\r\n // Look for an existing entry with the same user agent.\r\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n if (!heartbeatEntry) {\r\n // If no entry for this user agent exists, create one.\r\n heartbeatsToSend.push({\r\n agent: singleDateHeartbeat.agent,\r\n dates: [singleDateHeartbeat.date]\r\n });\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n // If the header would exceed max size, remove the added heartbeat\r\n // entry and stop adding to the header.\r\n heartbeatsToSend.pop();\r\n break;\r\n }\r\n }\r\n else {\r\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n // If the header would exceed max size, remove the added date\r\n // and stop adding to the header.\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n heartbeatEntry.dates.pop();\r\n break;\r\n }\r\n }\r\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n // quota and the loop breaks early.)\r\n unsentEntries = unsentEntries.slice(1);\r\n }\r\n return {\r\n heartbeatsToSend,\r\n unsentEntries\r\n };\r\n}\r\nclass HeartbeatStorageImpl {\r\n constructor(app) {\r\n this.app = app;\r\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n }\r\n async runIndexedDBEnvironmentCheck() {\r\n if (!isIndexedDBAvailable()) {\r\n return false;\r\n }\r\n else {\r\n return validateIndexedDBOpenable()\r\n .then(() => true)\r\n .catch(() => false);\r\n }\r\n }\r\n /**\r\n * Read all heartbeats.\r\n */\r\n async read() {\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return { heartbeats: [] };\r\n }\r\n else {\r\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {\r\n return idbHeartbeatObject;\r\n }\r\n else {\r\n return { heartbeats: [] };\r\n }\r\n }\r\n }\r\n // overwrite the storage with the provided heartbeats\r\n async overwrite(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: heartbeatsObject.heartbeats\r\n });\r\n }\r\n }\r\n // add heartbeats\r\n async add(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: [\r\n ...existingHeartbeatsObject.heartbeats,\r\n ...heartbeatsObject.heartbeats\r\n ]\r\n });\r\n }\r\n }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n // base64 has a restricted set of characters, all of which should be 1 byte.\r\n return base64urlEncodeWithoutPadding(\r\n // heartbeatsCache wrapper properties\r\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerCoreComponents(variant) {\r\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n // Register `app` package.\r\n registerVersion(name$p, version$1, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name$p, version$1, 'esm2017');\r\n // Register platform SDK identifier (no version).\r\n registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _isFirebaseApp, _isFirebaseServerApp, _registerComponent, _removeServiceInstance, _serverApps, deleteApp, getApp, getApps, initializeApp, initializeServerApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"10.12.3\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","import { SDK_VERSION, _isFirebaseServerApp, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';\nimport { ErrorFactory, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, deepEqual, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { __rest } from 'tslib';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An enum of factors that may be used for multifactor authentication.\r\n *\r\n * @public\r\n */\r\nconst FactorId = {\r\n /** Phone as second factor */\r\n PHONE: 'phone',\r\n TOTP: 'totp'\r\n};\r\n/**\r\n * Enumeration of supported providers.\r\n *\r\n * @public\r\n */\r\nconst ProviderId = {\r\n /** Facebook provider ID */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub provider ID */\r\n GITHUB: 'github.com',\r\n /** Google provider ID */\r\n GOOGLE: 'google.com',\r\n /** Password provider */\r\n PASSWORD: 'password',\r\n /** Phone provider */\r\n PHONE: 'phone',\r\n /** Twitter provider ID */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported sign-in methods.\r\n *\r\n * @public\r\n */\r\nconst SignInMethod = {\r\n /** Email link sign in method */\r\n EMAIL_LINK: 'emailLink',\r\n /** Email/password sign in method */\r\n EMAIL_PASSWORD: 'password',\r\n /** Facebook sign in method */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub sign in method */\r\n GITHUB: 'github.com',\r\n /** Google sign in method */\r\n GOOGLE: 'google.com',\r\n /** Phone sign in method */\r\n PHONE: 'phone',\r\n /** Twitter sign in method */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported operation types.\r\n *\r\n * @public\r\n */\r\nconst OperationType = {\r\n /** Operation involving linking an additional provider to an already signed-in user. */\r\n LINK: 'link',\r\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\r\n REAUTHENTICATE: 'reauthenticate',\r\n /** Operation involving signing in a user. */\r\n SIGN_IN: 'signIn'\r\n};\r\n/**\r\n * An enumeration of the possible email action types.\r\n *\r\n * @public\r\n */\r\nconst ActionCodeOperation = {\r\n /** The email link sign-in action. */\r\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\r\n /** The password reset action. */\r\n PASSWORD_RESET: 'PASSWORD_RESET',\r\n /** The email revocation action. */\r\n RECOVER_EMAIL: 'RECOVER_EMAIL',\r\n /** The revert second factor addition email action. */\r\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\r\n /** The revert second factor addition email action. */\r\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\r\n /** The email verification action. */\r\n VERIFY_EMAIL: 'VERIFY_EMAIL'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _debugErrorMap() {\r\n return {\r\n [\"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',\r\n [\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */]: '',\r\n [\"app-not-authorized\" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: \"This app, identified by the domain where it's hosted, is not \" +\r\n 'authorized to use Firebase Authentication with the provided API key. ' +\r\n 'Review your key configuration in the Google API console.',\r\n [\"app-not-installed\" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +\r\n 'Android package name or iOS bundle ID) provided is not installed on ' +\r\n 'this device.',\r\n [\"captcha-check-failed\" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +\r\n 'already used or the domain associated with it does not match the list ' +\r\n 'of whitelisted domains.',\r\n [\"code-expired\" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +\r\n 'again.',\r\n [\"cordova-not-ready\" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',\r\n [\"cors-unsupported\" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',\r\n [\"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',\r\n [\"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',\r\n [\"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +\r\n 'again before retrying this request.',\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.',\r\n [\"dynamic-link-not-activated\" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\r\n 'conditions.',\r\n [\"email-change-needs-verification\" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',\r\n [\"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',\r\n [\"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +\r\n 'no longer be configured to use the emulator. Try calling ' +\r\n '\"connectAuthEmulator()\" sooner.',\r\n [\"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',\r\n [\"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',\r\n [\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',\r\n [\"invalid-app-credential\" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +\r\n ' The reCAPTCHA token response is either invalid or expired.',\r\n [\"invalid-app-id\" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',\r\n [\"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */]: \"This user's credential isn't valid for this project. This can happen \" +\r\n \"if the user's token has been tampered with, or if the user isn't for \" +\r\n 'the project associated with this API key.',\r\n [\"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +\r\n 'invalid. Please resend the verification code sms and be sure to use the ' +\r\n 'verification code provided by the user.',\r\n [\"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',\r\n [\"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\r\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\r\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\r\n 'cordova-plugin-customurlscheme.',\r\n [\"invalid-custom-token\" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',\r\n [\"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',\r\n [\"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',\r\n [\"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',\r\n [\"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',\r\n [\"invalid-cert-hash\" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',\r\n [\"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */]: 'The supplied auth credential is incorrect, malformed or has expired.',\r\n [\"invalid-message-payload\" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',\r\n [\"invalid-oauth-provider\" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +\r\n 'only supports OAuth providers.',\r\n [\"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +\r\n 'specified API key.',\r\n [\"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +\r\n 'project. Edit the list of authorized domains from the Firebase console.',\r\n [\"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +\r\n 'expired, or has already been used.',\r\n [\"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',\r\n [\"invalid-persistence-type\" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',\r\n [\"invalid-phone-number\" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +\r\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\r\n 'phone numbers are written in the format [+][country code][subscriber ' +\r\n 'number including area code].',\r\n [\"invalid-provider-id\" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',\r\n [\"invalid-recipient-email\" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +\r\n 'recipient email address is invalid.',\r\n [\"invalid-sender\" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',\r\n [\"invalid-tenant-id\" /* AuthErrorCode.INVALID_TENANT_ID */]: \"The Auth instance's tenant ID is invalid.\",\r\n [\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',\r\n [\"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */]: 'An Android Package Name must be provided if the Android App is required to be installed.',\r\n [\"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\r\n 'by following the instructions in the Firebase console.',\r\n [\"missing-app-credential\" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +\r\n 'assertion. A reCAPTCHA response token needs to be provided.',\r\n [\"missing-verification-code\" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',\r\n [\"missing-continue-uri\" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',\r\n [\"missing-iframe-start\" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',\r\n [\"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',\r\n [\"missing-or-invalid-nonce\" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +\r\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\r\n 'in the ID token payload.',\r\n [\"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */]: 'A non-empty password must be provided',\r\n [\"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',\r\n [\"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',\r\n [\"missing-phone-number\" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',\r\n [\"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',\r\n [\"app-deleted\" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',\r\n [\"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',\r\n [\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',\r\n [\"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +\r\n 'sign-in credentials. Sign in using a provider associated with this ' +\r\n 'email address.',\r\n [\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\r\n [\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',\r\n [\"null-user\" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +\r\n 'requires a non-null user object.',\r\n [\"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +\r\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\r\n 'Auth section.',\r\n [\"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +\r\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\r\n ' and web storage must be enabled.',\r\n [\"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\r\n [\"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',\r\n [\"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',\r\n [\"quota-exceeded\" /* AuthErrorCode.QUOTA_EXCEEDED */]: \"The project's quota for this operation has been exceeded.\",\r\n [\"redirect-cancelled-by-user\" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',\r\n [\"redirect-operation-pending\" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',\r\n [\"rejected-credential\" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',\r\n [\"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',\r\n [\"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',\r\n [\"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */]: \"The provided tenant ID does not match the Auth instance's tenant ID\",\r\n [\"timeout\" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',\r\n [\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */]: \"The user's credential is no longer valid. The user must sign in again.\",\r\n [\"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +\r\n 'Try again later.',\r\n [\"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +\r\n 'the domain in the Firebase console.',\r\n [\"unsupported-first-factor\" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */]: 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\r\n [\"unsupported-persistence-type\" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',\r\n [\"unsupported-tenant-operation\" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',\r\n [\"unverified-email\" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',\r\n [\"user-cancelled\" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',\r\n [\"user-not-found\" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +\r\n 'have been deleted.',\r\n [\"user-disabled\" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',\r\n [\"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',\r\n [\"user-signed-out\" /* AuthErrorCode.USER_SIGNED_OUT */]: '',\r\n [\"weak-password\" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',\r\n [\"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',\r\n [\"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +\r\n 'different options. To avoid this error, call initializeAuth() with the ' +\r\n 'same options as when it was originally called, or call getAuth() to return the' +\r\n ' already initialized instance.',\r\n [\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is missing when sending request to the backend.',\r\n [\"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is invalid when sending request to the backend.',\r\n [\"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */]: 'The reCAPTCHA action is invalid when sending request to the backend.',\r\n [\"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */]: 'reCAPTCHA Enterprise integration is not enabled for this project.',\r\n [\"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */]: 'The reCAPTCHA client type is missing when sending request to the backend.',\r\n [\"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is missing when sending request to the backend.',\r\n [\"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */]: 'Invalid request parameters.',\r\n [\"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is invalid when sending request to the backend.',\r\n [\"unsupported-password-policy-schema-version\" /* AuthErrorCode.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.',\r\n [\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: 'The password does not meet the requirements.'\r\n };\r\n}\r\nfunction _prodErrorMap() {\r\n // We will include this one message in the prod error map since by the very\r\n // nature of this error, developers will never be able to see the message\r\n // using the debugErrorMap (which is installed during auth initialization).\r\n return {\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.'\r\n };\r\n}\r\n/**\r\n * A verbose error map with detailed descriptions for most error codes.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst debugErrorMap = _debugErrorMap;\r\n/**\r\n * A minimal error map with all verbose error messages stripped.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst prodErrorMap = _prodErrorMap;\r\nconst _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());\r\n/**\r\n * A map of potential `Auth` error codes, for easier comparison with errors\r\n * thrown by the SDK.\r\n *\r\n * @remarks\r\n * Note that you can't tree-shake individual keys\r\n * in the map, so by using the map you might substantially increase your\r\n * bundle size.\r\n *\r\n * @public\r\n */\r\nconst AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\r\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\r\n ARGUMENT_ERROR: 'auth/argument-error',\r\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\r\n APP_NOT_INSTALLED: 'auth/app-not-installed',\r\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\r\n CODE_EXPIRED: 'auth/code-expired',\r\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\r\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\r\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\r\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\r\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\r\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\r\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\r\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\r\n EMAIL_EXISTS: 'auth/email-already-in-use',\r\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\r\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\r\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\r\n INTERNAL_ERROR: 'auth/internal-error',\r\n INVALID_API_KEY: 'auth/invalid-api-key',\r\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\r\n INVALID_APP_ID: 'auth/invalid-app-id',\r\n INVALID_AUTH: 'auth/invalid-user-token',\r\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\r\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\r\n INVALID_CODE: 'auth/invalid-verification-code',\r\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\r\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\r\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\r\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\r\n INVALID_EMAIL: 'auth/invalid-email',\r\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\r\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\r\n INVALID_LOGIN_CREDENTIALS: 'auth/invalid-credential',\r\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\r\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\r\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\r\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\r\n INVALID_OOB_CODE: 'auth/invalid-action-code',\r\n INVALID_ORIGIN: 'auth/unauthorized-domain',\r\n INVALID_PASSWORD: 'auth/wrong-password',\r\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\r\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\r\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\r\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\r\n INVALID_SENDER: 'auth/invalid-sender',\r\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\r\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\r\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\r\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\r\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\r\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\r\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\r\n MISSING_CODE: 'auth/missing-verification-code',\r\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\r\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\r\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\r\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\r\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\r\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\r\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\r\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\r\n MODULE_DESTROYED: 'auth/app-deleted',\r\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\r\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\r\n NULL_USER: 'auth/null-user',\r\n NO_AUTH_EVENT: 'auth/no-auth-event',\r\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\r\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\r\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\r\n POPUP_BLOCKED: 'auth/popup-blocked',\r\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\r\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\r\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\r\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\r\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\r\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\r\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\r\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\r\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\r\n TIMEOUT: 'auth/timeout',\r\n TOKEN_EXPIRED: 'auth/user-token-expired',\r\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\r\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\r\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\r\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\r\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\r\n UNVERIFIED_EMAIL: 'auth/unverified-email',\r\n USER_CANCELLED: 'auth/user-cancelled',\r\n USER_DELETED: 'auth/user-not-found',\r\n USER_DISABLED: 'auth/user-disabled',\r\n USER_MISMATCH: 'auth/user-mismatch',\r\n USER_SIGNED_OUT: 'auth/user-signed-out',\r\n WEAK_PASSWORD: 'auth/weak-password',\r\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\r\n ALREADY_INITIALIZED: 'auth/already-initialized',\r\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\r\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\r\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\r\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\r\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\r\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\r\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\r\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logClient = new Logger('@firebase/auth');\r\nfunction _logWarn(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.WARN) {\r\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\r\nfunction _logError(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.ERROR) {\r\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _fail(authOrCode, ...rest) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _createError(authOrCode, ...rest) {\r\n return createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _errorWithCustomMessage(auth, code, message) {\r\n const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });\r\n const factory = new ErrorFactory('auth', 'Firebase', errorMap);\r\n return factory.create(code, {\r\n appName: auth.name\r\n });\r\n}\r\nfunction _serverAppCurrentUserOperationNotSupportedError(auth) {\r\n return _errorWithCustomMessage(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */, 'Operations that alter the current user are not supported in conjunction with FirebaseServerApp');\r\n}\r\nfunction _assertInstanceOf(auth, object, instance) {\r\n const constructorInstance = instance;\r\n if (!(object instanceof constructorInstance)) {\r\n if (constructorInstance.name !== object.constructor.name) {\r\n _fail(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n throw _errorWithCustomMessage(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +\r\n `Did you pass a reference from a different Auth SDK?`);\r\n }\r\n}\r\nfunction createErrorInternal(authOrCode, ...rest) {\r\n if (typeof authOrCode !== 'string') {\r\n const code = rest[0];\r\n const fullParams = [...rest.slice(1)];\r\n if (fullParams[0]) {\r\n fullParams[0].appName = authOrCode.name;\r\n }\r\n return authOrCode._errorFactory.create(code, ...fullParams);\r\n }\r\n return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);\r\n}\r\nfunction _assert(assertion, authOrCode, ...rest) {\r\n if (!assertion) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n }\r\n}\r\n/**\r\n * Unconditionally fails, throwing an internal error with the given message.\r\n *\r\n * @param failure type of failure encountered\r\n * @throws Error\r\n */\r\nfunction debugFail(failure) {\r\n // Log the failure in addition to throw an exception, just in case the\r\n // exception is swallowed.\r\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\r\n _logError(message);\r\n // NOTE: We don't use FirebaseError here because these are internal failures\r\n // that cannot be handled by the user. (Also it would create a circular\r\n // dependency between the error and assert modules which doesn't work.)\r\n throw new Error(message);\r\n}\r\n/**\r\n * Fails if the given assertion condition is false, throwing an Error with the\r\n * given message if it did.\r\n *\r\n * @param assertion\r\n * @param message\r\n */\r\nfunction debugAssert(assertion, message) {\r\n if (!assertion) {\r\n debugFail(message);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _getCurrentUrl() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';\r\n}\r\nfunction _isHttpOrHttps() {\r\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\r\n}\r\nfunction _getCurrentScheme() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine whether the browser is working online\r\n */\r\nfunction _isOnline() {\r\n if (typeof navigator !== 'undefined' &&\r\n navigator &&\r\n 'onLine' in navigator &&\r\n typeof navigator.onLine === 'boolean' &&\r\n // Apply only for traditional web apps and Chrome extensions.\r\n // This is especially true for Cordova apps which have unreliable\r\n // navigator.onLine behavior unless cordova-plugin-network-information is\r\n // installed which overwrites the native navigator.onLine value and\r\n // defines navigator.connection.\r\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {\r\n return navigator.onLine;\r\n }\r\n // If we can't determine the state, assume it is online.\r\n return true;\r\n}\r\nfunction _getUserLanguage() {\r\n if (typeof navigator === 'undefined') {\r\n return null;\r\n }\r\n const navigatorLanguage = navigator;\r\n return (\r\n // Most reliable, but only supported in Chrome/Firefox.\r\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\r\n // Supported in most browsers, but returns the language of the browser\r\n // UI, not the language set in browser settings.\r\n navigatorLanguage.language ||\r\n // Couldn't determine language.\r\n null);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A structure to help pick between a range of long and short delay durations\r\n * depending on the current environment. In general, the long delay is used for\r\n * mobile environments whereas short delays are used for desktop environments.\r\n */\r\nclass Delay {\r\n constructor(shortDelay, longDelay) {\r\n this.shortDelay = shortDelay;\r\n this.longDelay = longDelay;\r\n // Internal error when improperly initialized.\r\n debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');\r\n this.isMobile = isMobileCordova() || isReactNative();\r\n }\r\n get() {\r\n if (!_isOnline()) {\r\n // Pick the shorter timeout.\r\n return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);\r\n }\r\n // If running in a mobile environment, return the long delay, otherwise\r\n // return the short delay.\r\n // This could be improved in the future to dynamically change based on other\r\n // variables instead of just reading the current environment.\r\n return this.isMobile ? this.longDelay : this.shortDelay;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _emulatorUrl(config, path) {\r\n debugAssert(config.emulator, 'Emulator should always be set here');\r\n const { url } = config.emulator;\r\n if (!path) {\r\n return url;\r\n }\r\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FetchProvider {\r\n static initialize(fetchImpl, headersImpl, responseImpl) {\r\n this.fetchImpl = fetchImpl;\r\n if (headersImpl) {\r\n this.headersImpl = headersImpl;\r\n }\r\n if (responseImpl) {\r\n this.responseImpl = responseImpl;\r\n }\r\n }\r\n static fetch() {\r\n if (this.fetchImpl) {\r\n return this.fetchImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'fetch' in self) {\r\n return self.fetch;\r\n }\r\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\r\n return globalThis.fetch;\r\n }\r\n if (typeof fetch !== 'undefined') {\r\n return fetch;\r\n }\r\n debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static headers() {\r\n if (this.headersImpl) {\r\n return this.headersImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Headers' in self) {\r\n return self.Headers;\r\n }\r\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\r\n return globalThis.Headers;\r\n }\r\n if (typeof Headers !== 'undefined') {\r\n return Headers;\r\n }\r\n debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static response() {\r\n if (this.responseImpl) {\r\n return this.responseImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Response' in self) {\r\n return self.Response;\r\n }\r\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\r\n return globalThis.Response;\r\n }\r\n if (typeof Response !== 'undefined') {\r\n return Response;\r\n }\r\n debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Map from errors returned by the server to errors to developer visible errors\r\n */\r\nconst SERVER_ERROR_MAP = {\r\n // Custom token errors.\r\n [\"CREDENTIAL_MISMATCH\" /* ServerError.CREDENTIAL_MISMATCH */]: \"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CUSTOM_TOKEN\" /* ServerError.MISSING_CUSTOM_TOKEN */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Create Auth URI errors.\r\n [\"INVALID_IDENTIFIER\" /* ServerError.INVALID_IDENTIFIER */]: \"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CONTINUE_URI\" /* ServerError.MISSING_CONTINUE_URI */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Sign in with email and password errors (some apply to sign up too).\r\n [\"INVALID_PASSWORD\" /* ServerError.INVALID_PASSWORD */]: \"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_PASSWORD\" /* ServerError.MISSING_PASSWORD */]: \"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */,\r\n // Thrown if Email Enumeration Protection is enabled in the project and the email or password is\r\n // invalid.\r\n [\"INVALID_LOGIN_CREDENTIALS\" /* ServerError.INVALID_LOGIN_CREDENTIALS */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n // Sign up with email and password errors.\r\n [\"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */]: \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */,\r\n [\"PASSWORD_LOGIN_DISABLED\" /* ServerError.PASSWORD_LOGIN_DISABLED */]: \"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,\r\n // Verify assertion for sign in with credential errors:\r\n [\"INVALID_IDP_RESPONSE\" /* ServerError.INVALID_IDP_RESPONSE */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n [\"INVALID_PENDING_TOKEN\" /* ServerError.INVALID_PENDING_TOKEN */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n [\"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_REQ_TYPE\" /* ServerError.MISSING_REQ_TYPE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Send Password reset email errors:\r\n [\"EMAIL_NOT_FOUND\" /* ServerError.EMAIL_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */,\r\n [\"RESET_PASSWORD_EXCEED_LIMIT\" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n [\"EXPIRED_OOB_CODE\" /* ServerError.EXPIRED_OOB_CODE */]: \"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */,\r\n [\"INVALID_OOB_CODE\" /* ServerError.INVALID_OOB_CODE */]: \"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_OOB_CODE\" /* ServerError.MISSING_OOB_CODE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Operations that require ID token in request:\r\n [\"CREDENTIAL_TOO_OLD_LOGIN_AGAIN\" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: \"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,\r\n [\"INVALID_ID_TOKEN\" /* ServerError.INVALID_ID_TOKEN */]: \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */,\r\n [\"TOKEN_EXPIRED\" /* ServerError.TOKEN_EXPIRED */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n // Other errors.\r\n [\"TOO_MANY_ATTEMPTS_TRY_LATER\" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n [\"PASSWORD_DOES_NOT_MEET_REQUIREMENTS\" /* ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: \"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */,\r\n // Phone Auth related errors.\r\n [\"INVALID_CODE\" /* ServerError.INVALID_CODE */]: \"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */,\r\n [\"INVALID_SESSION_INFO\" /* ServerError.INVALID_SESSION_INFO */]: \"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */,\r\n [\"INVALID_TEMPORARY_PROOF\" /* ServerError.INVALID_TEMPORARY_PROOF */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n [\"MISSING_SESSION_INFO\" /* ServerError.MISSING_SESSION_INFO */]: \"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */,\r\n [\"SESSION_EXPIRED\" /* ServerError.SESSION_EXPIRED */]: \"code-expired\" /* AuthErrorCode.CODE_EXPIRED */,\r\n // Other action code errors when additional settings passed.\r\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\r\n // This is OK as this error will be caught by client side validation.\r\n [\"MISSING_ANDROID_PACKAGE_NAME\" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,\r\n [\"UNAUTHORIZED_DOMAIN\" /* ServerError.UNAUTHORIZED_DOMAIN */]: \"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,\r\n // getProjectConfig errors when clientId is passed.\r\n [\"INVALID_OAUTH_CLIENT_ID\" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: \"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,\r\n // User actions (sign-up or deletion) disabled errors.\r\n [\"ADMIN_ONLY_OPERATION\" /* ServerError.ADMIN_ONLY_OPERATION */]: \"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,\r\n // Multi factor related errors.\r\n [\"INVALID_MFA_PENDING_CREDENTIAL\" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: \"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */,\r\n [\"MFA_ENROLLMENT_NOT_FOUND\" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: \"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,\r\n [\"MISSING_MFA_ENROLLMENT_ID\" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */,\r\n [\"MISSING_MFA_PENDING_CREDENTIAL\" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: \"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */,\r\n [\"SECOND_FACTOR_EXISTS\" /* ServerError.SECOND_FACTOR_EXISTS */]: \"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,\r\n [\"SECOND_FACTOR_LIMIT_EXCEEDED\" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: \"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,\r\n // Blocking functions related errors.\r\n [\"BLOCKING_FUNCTION_ERROR_RESPONSE\" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Recaptcha related errors.\r\n [\"RECAPTCHA_NOT_ENABLED\" /* ServerError.RECAPTCHA_NOT_ENABLED */]: \"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,\r\n [\"MISSING_RECAPTCHA_TOKEN\" /* ServerError.MISSING_RECAPTCHA_TOKEN */]: \"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_TOKEN\" /* ServerError.INVALID_RECAPTCHA_TOKEN */]: \"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_ACTION\" /* ServerError.INVALID_RECAPTCHA_ACTION */]: \"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,\r\n [\"MISSING_CLIENT_TYPE\" /* ServerError.MISSING_CLIENT_TYPE */]: \"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */,\r\n [\"MISSING_RECAPTCHA_VERSION\" /* ServerError.MISSING_RECAPTCHA_VERSION */]: \"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,\r\n [\"INVALID_RECAPTCHA_VERSION\" /* ServerError.INVALID_RECAPTCHA_VERSION */]: \"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,\r\n [\"INVALID_REQ_TYPE\" /* ServerError.INVALID_REQ_TYPE */]: \"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);\r\nfunction _addTidIfNecessary(auth, request) {\r\n if (auth.tenantId && !request.tenantId) {\r\n return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });\r\n }\r\n return request;\r\n}\r\nasync function _performApiRequest(auth, method, path, request, customErrorMap = {}) {\r\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\r\n let body = {};\r\n let params = {};\r\n if (request) {\r\n if (method === \"GET\" /* HttpMethod.GET */) {\r\n params = request;\r\n }\r\n else {\r\n body = {\r\n body: JSON.stringify(request)\r\n };\r\n }\r\n }\r\n const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/json';\r\n if (auth.languageCode) {\r\n headers[\"X-Firebase-Locale\" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;\r\n }\r\n return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,\r\n headers, referrerPolicy: 'no-referrer' }, body));\r\n });\r\n}\r\nasync function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {\r\n auth._canInitEmulator = false;\r\n const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);\r\n try {\r\n const networkTimeout = new NetworkTimeout(auth);\r\n const response = await Promise.race([\r\n fetchFn(),\r\n networkTimeout.promise\r\n ]);\r\n // If we've reached this point, the fetch succeeded and the networkTimeout\r\n // didn't throw; clear the network timeout delay so that Node won't hang\r\n networkTimeout.clearNetworkTimeout();\r\n const json = await response.json();\r\n if ('needConfirmation' in json) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, json);\r\n }\r\n if (response.ok && !('errorMessage' in json)) {\r\n return json;\r\n }\r\n else {\r\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\r\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\r\n if (serverErrorCode === \"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {\r\n throw _makeTaggedError(auth, \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);\r\n }\r\n else if (serverErrorCode === \"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */) {\r\n throw _makeTaggedError(auth, \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */, json);\r\n }\r\n else if (serverErrorCode === \"USER_DISABLED\" /* ServerError.USER_DISABLED */) {\r\n throw _makeTaggedError(auth, \"user-disabled\" /* AuthErrorCode.USER_DISABLED */, json);\r\n }\r\n const authError = errorMap[serverErrorCode] ||\r\n serverErrorCode\r\n .toLowerCase()\r\n .replace(/[_\\s]+/g, '-');\r\n if (serverErrorMessage) {\r\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\r\n }\r\n else {\r\n _fail(auth, authError);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n throw e;\r\n }\r\n // Changing this to a different error code will log user out when there is a network error\r\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\r\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\r\n _fail(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e) });\r\n }\r\n}\r\nasync function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {\r\n const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));\r\n if ('mfaPendingCredential' in serverResponse) {\r\n _fail(auth, \"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */, {\r\n _serverResponse: serverResponse\r\n });\r\n }\r\n return serverResponse;\r\n}\r\nfunction _getFinalTarget(auth, host, path, query) {\r\n const base = `${host}${path}?${query}`;\r\n if (!auth.config.emulator) {\r\n return `${auth.config.apiScheme}://${base}`;\r\n }\r\n return _emulatorUrl(auth.config, base);\r\n}\r\nfunction _parseEnforcementState(enforcementStateStr) {\r\n switch (enforcementStateStr) {\r\n case 'ENFORCE':\r\n return \"ENFORCE\" /* EnforcementState.ENFORCE */;\r\n case 'AUDIT':\r\n return \"AUDIT\" /* EnforcementState.AUDIT */;\r\n case 'OFF':\r\n return \"OFF\" /* EnforcementState.OFF */;\r\n default:\r\n return \"ENFORCEMENT_STATE_UNSPECIFIED\" /* EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED */;\r\n }\r\n}\r\nclass NetworkTimeout {\r\n constructor(auth) {\r\n this.auth = auth;\r\n // Node timers and browser timers are fundamentally incompatible, but we\r\n // don't care about the value here\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timer = null;\r\n this.promise = new Promise((_, reject) => {\r\n this.timer = setTimeout(() => {\r\n return reject(_createError(this.auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, DEFAULT_API_TIMEOUT_MS.get());\r\n });\r\n }\r\n clearNetworkTimeout() {\r\n clearTimeout(this.timer);\r\n }\r\n}\r\nfunction _makeTaggedError(auth, code, response) {\r\n const errorParams = {\r\n appName: auth.name\r\n };\r\n if (response.email) {\r\n errorParams.email = response.email;\r\n }\r\n if (response.phoneNumber) {\r\n errorParams.phoneNumber = response.phoneNumber;\r\n }\r\n const error = _createError(auth, code, errorParams);\r\n // We know customData is defined on error because errorParams is defined\r\n error.customData._tokenResponse = response;\r\n return error;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isV2(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.getResponse !== undefined);\r\n}\r\nfunction isEnterprise(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.enterprise !== undefined);\r\n}\r\nclass RecaptchaConfig {\r\n constructor(response) {\r\n /**\r\n * The reCAPTCHA site key.\r\n */\r\n this.siteKey = '';\r\n /**\r\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\r\n */\r\n this.recaptchaEnforcementState = [];\r\n if (response.recaptchaKey === undefined) {\r\n throw new Error('recaptchaKey undefined');\r\n }\r\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\r\n this.siteKey = response.recaptchaKey.split('/')[3];\r\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\r\n }\r\n /**\r\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\r\n *\r\n * @param providerStr - The provider whose enforcement state is to be returned.\r\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\r\n */\r\n getProviderEnforcementState(providerStr) {\r\n if (!this.recaptchaEnforcementState ||\r\n this.recaptchaEnforcementState.length === 0) {\r\n return null;\r\n }\r\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\r\n if (recaptchaEnforcementState.provider &&\r\n recaptchaEnforcementState.provider === providerStr) {\r\n return _parseEnforcementState(recaptchaEnforcementState.enforcementState);\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\r\n *\r\n * @param providerStr - The provider whose enablement state is to be returned.\r\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\r\n */\r\n isProviderEnabled(providerStr) {\r\n return (this.getProviderEnforcementState(providerStr) ===\r\n \"ENFORCE\" /* EnforcementState.ENFORCE */ ||\r\n this.getProviderEnforcementState(providerStr) === \"AUDIT\" /* EnforcementState.AUDIT */);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getRecaptchaParams(auth) {\r\n return ((await _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/recaptchaParams\" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');\r\n}\r\nasync function getRecaptchaConfig(auth, request) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/recaptchaConfig\" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteAccount(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:delete\" /* Endpoint.DELETE_ACCOUNT */, request);\r\n}\r\nasync function deleteLinkedAccounts(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function getAccountInfo(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:lookup\" /* Endpoint.GET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction utcTimestampToDateString(utcTimestamp) {\r\n if (!utcTimestamp) {\r\n return undefined;\r\n }\r\n try {\r\n // Convert to date object.\r\n const date = new Date(Number(utcTimestamp));\r\n // Test date is valid.\r\n if (!isNaN(date.getTime())) {\r\n // Convert to UTC date string.\r\n return date.toUTCString();\r\n }\r\n }\r\n catch (e) {\r\n // Do nothing. undefined will be returned.\r\n }\r\n return undefined;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nfunction getIdToken(user, forceRefresh = false) {\r\n return getModularInstance(user).getIdToken(forceRefresh);\r\n}\r\n/**\r\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getIdTokenResult(user, forceRefresh = false) {\r\n const userInternal = getModularInstance(user);\r\n const token = await userInternal.getIdToken(forceRefresh);\r\n const claims = _parseToken(token);\r\n _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;\r\n const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];\r\n return {\r\n claims,\r\n token,\r\n authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),\r\n issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),\r\n expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),\r\n signInProvider: signInProvider || null,\r\n signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null\r\n };\r\n}\r\nfunction secondsStringToMilliseconds(seconds) {\r\n return Number(seconds) * 1000;\r\n}\r\nfunction _parseToken(token) {\r\n const [algorithm, payload, signature] = token.split('.');\r\n if (algorithm === undefined ||\r\n payload === undefined ||\r\n signature === undefined) {\r\n _logError('JWT malformed, contained fewer than 3 sections');\r\n return null;\r\n }\r\n try {\r\n const decoded = base64Decode(payload);\r\n if (!decoded) {\r\n _logError('Failed to decode base64 JWT payload');\r\n return null;\r\n }\r\n return JSON.parse(decoded);\r\n }\r\n catch (e) {\r\n _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());\r\n return null;\r\n }\r\n}\r\n/**\r\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\r\n */\r\nfunction _tokenExpiresIn(token) {\r\n const parsedToken = _parseToken(token);\r\n _assert(parsedToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return Number(parsedToken.exp) - Number(parsedToken.iat);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _logoutIfInvalidated(user, promise, bypassAuthState = false) {\r\n if (bypassAuthState) {\r\n return promise;\r\n }\r\n try {\r\n return await promise;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\r\n if (user.auth.currentUser === user) {\r\n await user.auth.signOut();\r\n }\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isUserInvalidated({ code }) {\r\n return (code === `auth/${\"user-disabled\" /* AuthErrorCode.USER_DISABLED */}` ||\r\n code === `auth/${\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */}`);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ProactiveRefresh {\r\n constructor(user) {\r\n this.user = user;\r\n this.isRunning = false;\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timerId = null;\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n }\r\n _start() {\r\n if (this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = true;\r\n this.schedule();\r\n }\r\n _stop() {\r\n if (!this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = false;\r\n if (this.timerId !== null) {\r\n clearTimeout(this.timerId);\r\n }\r\n }\r\n getInterval(wasError) {\r\n var _a;\r\n if (wasError) {\r\n const interval = this.errorBackoff;\r\n this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);\r\n return interval;\r\n }\r\n else {\r\n // Reset the error backoff\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;\r\n const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;\r\n return Math.max(0, interval);\r\n }\r\n }\r\n schedule(wasError = false) {\r\n if (!this.isRunning) {\r\n // Just in case...\r\n return;\r\n }\r\n const interval = this.getInterval(wasError);\r\n this.timerId = setTimeout(async () => {\r\n await this.iteration();\r\n }, interval);\r\n }\r\n async iteration() {\r\n try {\r\n await this.user.getIdToken(true);\r\n }\r\n catch (e) {\r\n // Only retry on network errors\r\n if ((e === null || e === void 0 ? void 0 : e.code) ===\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n this.schedule(/* wasError */ true);\r\n }\r\n return;\r\n }\r\n this.schedule();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserMetadata {\r\n constructor(createdAt, lastLoginAt) {\r\n this.createdAt = createdAt;\r\n this.lastLoginAt = lastLoginAt;\r\n this._initializeTime();\r\n }\r\n _initializeTime() {\r\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\r\n this.creationTime = utcTimestampToDateString(this.createdAt);\r\n }\r\n _copy(metadata) {\r\n this.createdAt = metadata.createdAt;\r\n this.lastLoginAt = metadata.lastLoginAt;\r\n this._initializeTime();\r\n }\r\n toJSON() {\r\n return {\r\n createdAt: this.createdAt,\r\n lastLoginAt: this.lastLoginAt\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reloadWithoutSaving(user) {\r\n var _a;\r\n const auth = user.auth;\r\n const idToken = await user.getIdToken();\r\n const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));\r\n _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const coreAccount = response.users[0];\r\n user._notifyReloadListener(coreAccount);\r\n const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const providerData = mergeProviderData(user.providerData, newProviderData);\r\n // Preserves the non-nonymous status of the stored user, even if no more\r\n // credentials (federated or email/password) are linked to the user. If\r\n // the user was previously anonymous, then use provider data to update.\r\n // On the other hand, if it was not anonymous before, it should never be\r\n // considered anonymous now.\r\n const oldIsAnonymous = user.isAnonymous;\r\n const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\r\n const updates = {\r\n uid: coreAccount.localId,\r\n displayName: coreAccount.displayName || null,\r\n photoURL: coreAccount.photoUrl || null,\r\n email: coreAccount.email || null,\r\n emailVerified: coreAccount.emailVerified || false,\r\n phoneNumber: coreAccount.phoneNumber || null,\r\n tenantId: coreAccount.tenantId || null,\r\n providerData,\r\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n isAnonymous\r\n };\r\n Object.assign(user, updates);\r\n}\r\n/**\r\n * Reloads user account data, if signed in.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function reload(user) {\r\n const userInternal = getModularInstance(user);\r\n await _reloadWithoutSaving(userInternal);\r\n // Even though the current user hasn't changed, update\r\n // current user will trigger a persistence update w/ the\r\n // new info.\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n userInternal.auth._notifyListenersIfCurrent(userInternal);\r\n}\r\nfunction mergeProviderData(original, newData) {\r\n const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));\r\n return [...deduped, ...newData];\r\n}\r\nfunction extractProviderData(providers) {\r\n return providers.map((_a) => {\r\n var { providerId } = _a, provider = __rest(_a, [\"providerId\"]);\r\n return {\r\n providerId,\r\n uid: provider.rawId || '',\r\n displayName: provider.displayName || null,\r\n email: provider.email || null,\r\n phoneNumber: provider.phoneNumber || null,\r\n photoURL: provider.photoUrl || null\r\n };\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestStsToken(auth, refreshToken) {\r\n const response = await _performFetchWithErrorHandling(auth, {}, async () => {\r\n const body = querystring({\r\n 'grant_type': 'refresh_token',\r\n 'refresh_token': refreshToken\r\n }).slice(1);\r\n const { tokenApiHost, apiKey } = auth.config;\r\n const url = _getFinalTarget(auth, tokenApiHost, \"/v1/token\" /* Endpoint.TOKEN */, `key=${apiKey}`);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';\r\n return FetchProvider.fetch()(url, {\r\n method: \"POST\" /* HttpMethod.POST */,\r\n headers,\r\n body\r\n });\r\n });\r\n // The response comes back in snake_case. Convert to camel:\r\n return {\r\n accessToken: response.access_token,\r\n expiresIn: response.expires_in,\r\n refreshToken: response.refresh_token\r\n };\r\n}\r\nasync function revokeToken(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts:revokeToken\" /* Endpoint.REVOKE_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\r\n * it references AuthInternal which has a circular dependency with UserInternal.\r\n *\r\n * @internal\r\n */\r\nclass StsTokenManager {\r\n constructor() {\r\n this.refreshToken = null;\r\n this.accessToken = null;\r\n this.expirationTime = null;\r\n }\r\n get isExpired() {\r\n return (!this.expirationTime ||\r\n Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);\r\n }\r\n updateFromServerResponse(response) {\r\n _assert(response.idToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.idToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.refreshToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\r\n ? Number(response.expiresIn)\r\n : _tokenExpiresIn(response.idToken);\r\n this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);\r\n }\r\n updateFromIdToken(idToken) {\r\n _assert(idToken.length !== 0, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const expiresIn = _tokenExpiresIn(idToken);\r\n this.updateTokensAndExpiration(idToken, null, expiresIn);\r\n }\r\n async getToken(auth, forceRefresh = false) {\r\n if (!forceRefresh && this.accessToken && !this.isExpired) {\r\n return this.accessToken;\r\n }\r\n _assert(this.refreshToken, auth, \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */);\r\n if (this.refreshToken) {\r\n await this.refresh(auth, this.refreshToken);\r\n return this.accessToken;\r\n }\r\n return null;\r\n }\r\n clearRefreshToken() {\r\n this.refreshToken = null;\r\n }\r\n async refresh(auth, oldToken) {\r\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);\r\n this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));\r\n }\r\n updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {\r\n this.refreshToken = refreshToken || null;\r\n this.accessToken = accessToken || null;\r\n this.expirationTime = Date.now() + expiresInSec * 1000;\r\n }\r\n static fromJSON(appName, object) {\r\n const { refreshToken, accessToken, expirationTime } = object;\r\n const manager = new StsTokenManager();\r\n if (refreshToken) {\r\n _assert(typeof refreshToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.refreshToken = refreshToken;\r\n }\r\n if (accessToken) {\r\n _assert(typeof accessToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.accessToken = accessToken;\r\n }\r\n if (expirationTime) {\r\n _assert(typeof expirationTime === 'number', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.expirationTime = expirationTime;\r\n }\r\n return manager;\r\n }\r\n toJSON() {\r\n return {\r\n refreshToken: this.refreshToken,\r\n accessToken: this.accessToken,\r\n expirationTime: this.expirationTime\r\n };\r\n }\r\n _assign(stsTokenManager) {\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.refreshToken = stsTokenManager.refreshToken;\r\n this.expirationTime = stsTokenManager.expirationTime;\r\n }\r\n _clone() {\r\n return Object.assign(new StsTokenManager(), this.toJSON());\r\n }\r\n _performRefresh() {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction assertStringOrUndefined(assertion, appName) {\r\n _assert(typeof assertion === 'string' || typeof assertion === 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, { appName });\r\n}\r\nclass UserImpl {\r\n constructor(_a) {\r\n var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, [\"uid\", \"auth\", \"stsTokenManager\"]);\r\n // For the user object, provider is always Firebase.\r\n this.providerId = \"firebase\" /* ProviderId.FIREBASE */;\r\n this.proactiveRefresh = new ProactiveRefresh(this);\r\n this.reloadUserInfo = null;\r\n this.reloadListener = null;\r\n this.uid = uid;\r\n this.auth = auth;\r\n this.stsTokenManager = stsTokenManager;\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.displayName = opt.displayName || null;\r\n this.email = opt.email || null;\r\n this.emailVerified = opt.emailVerified || false;\r\n this.phoneNumber = opt.phoneNumber || null;\r\n this.photoURL = opt.photoURL || null;\r\n this.isAnonymous = opt.isAnonymous || false;\r\n this.tenantId = opt.tenantId || null;\r\n this.providerData = opt.providerData ? [...opt.providerData] : [];\r\n this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);\r\n }\r\n async getIdToken(forceRefresh) {\r\n const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));\r\n _assert(accessToken, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n if (this.accessToken !== accessToken) {\r\n this.accessToken = accessToken;\r\n await this.auth._persistUserIfCurrent(this);\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n return accessToken;\r\n }\r\n getIdTokenResult(forceRefresh) {\r\n return getIdTokenResult(this, forceRefresh);\r\n }\r\n reload() {\r\n return reload(this);\r\n }\r\n _assign(user) {\r\n if (this === user) {\r\n return;\r\n }\r\n _assert(this.uid === user.uid, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.displayName = user.displayName;\r\n this.photoURL = user.photoURL;\r\n this.email = user.email;\r\n this.emailVerified = user.emailVerified;\r\n this.phoneNumber = user.phoneNumber;\r\n this.isAnonymous = user.isAnonymous;\r\n this.tenantId = user.tenantId;\r\n this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n this.metadata._copy(user.metadata);\r\n this.stsTokenManager._assign(user.stsTokenManager);\r\n }\r\n _clone(auth) {\r\n const newUser = new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));\r\n newUser.metadata._copy(this.metadata);\r\n return newUser;\r\n }\r\n _onReload(callback) {\r\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\r\n _assert(!this.reloadListener, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.reloadListener = callback;\r\n if (this.reloadUserInfo) {\r\n this._notifyReloadListener(this.reloadUserInfo);\r\n this.reloadUserInfo = null;\r\n }\r\n }\r\n _notifyReloadListener(userInfo) {\r\n if (this.reloadListener) {\r\n this.reloadListener(userInfo);\r\n }\r\n else {\r\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\r\n this.reloadUserInfo = userInfo;\r\n }\r\n }\r\n _startProactiveRefresh() {\r\n this.proactiveRefresh._start();\r\n }\r\n _stopProactiveRefresh() {\r\n this.proactiveRefresh._stop();\r\n }\r\n async _updateTokensIfNecessary(response, reload = false) {\r\n let tokensRefreshed = false;\r\n if (response.idToken &&\r\n response.idToken !== this.stsTokenManager.accessToken) {\r\n this.stsTokenManager.updateFromServerResponse(response);\r\n tokensRefreshed = true;\r\n }\r\n if (reload) {\r\n await _reloadWithoutSaving(this);\r\n }\r\n await this.auth._persistUserIfCurrent(this);\r\n if (tokensRefreshed) {\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n }\r\n async delete() {\r\n if (_isFirebaseServerApp(this.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));\r\n }\r\n const idToken = await this.getIdToken();\r\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\r\n this.stsTokenManager.clearRefreshToken();\r\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\r\n // cancels pending actions...\r\n return this.auth.signOut();\r\n }\r\n toJSON() {\r\n return Object.assign(Object.assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(userInfo => (Object.assign({}, userInfo))), stsTokenManager: this.stsTokenManager.toJSON(), \r\n // Redirect event ID must be maintained in case there is a pending\r\n // redirect event.\r\n _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), { \r\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\r\n apiKey: this.auth.config.apiKey, appName: this.auth.name });\r\n }\r\n get refreshToken() {\r\n return this.stsTokenManager.refreshToken || '';\r\n }\r\n static _fromJSON(auth, object) {\r\n var _a, _b, _c, _d, _e, _f, _g, _h;\r\n const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;\r\n const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;\r\n const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;\r\n const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;\r\n const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;\r\n const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;\r\n const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;\r\n const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;\r\n const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;\r\n _assert(uid && plainObjectTokenManager, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);\r\n _assert(typeof uid === 'string', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(displayName, auth.name);\r\n assertStringOrUndefined(email, auth.name);\r\n _assert(typeof emailVerified === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof isAnonymous === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(phoneNumber, auth.name);\r\n assertStringOrUndefined(photoURL, auth.name);\r\n assertStringOrUndefined(tenantId, auth.name);\r\n assertStringOrUndefined(_redirectEventId, auth.name);\r\n assertStringOrUndefined(createdAt, auth.name);\r\n assertStringOrUndefined(lastLoginAt, auth.name);\r\n const user = new UserImpl({\r\n uid,\r\n auth,\r\n email,\r\n emailVerified,\r\n displayName,\r\n isAnonymous,\r\n photoURL,\r\n phoneNumber,\r\n tenantId,\r\n stsTokenManager,\r\n createdAt,\r\n lastLoginAt\r\n });\r\n if (providerData && Array.isArray(providerData)) {\r\n user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n }\r\n if (_redirectEventId) {\r\n user._redirectEventId = _redirectEventId;\r\n }\r\n return user;\r\n }\r\n /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromServerResponse(idTokenResponse);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: idTokenResponse.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // Updates the user info and data and resolves with a user instance.\r\n await _reloadWithoutSaving(user);\r\n return user;\r\n }\r\n /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromGetAccountInfoResponse(auth, response, idToken) {\r\n const coreAccount = response.users[0];\r\n _assert(coreAccount.localId !== undefined, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const providerData = coreAccount.providerUserInfo !== undefined\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const isAnonymous = !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromIdToken(idToken);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: coreAccount.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // update the user with data from the GetAccountInfo response.\r\n const updates = {\r\n uid: coreAccount.localId,\r\n displayName: coreAccount.displayName || null,\r\n photoURL: coreAccount.photoUrl || null,\r\n email: coreAccount.email || null,\r\n emailVerified: coreAccount.emailVerified || false,\r\n phoneNumber: coreAccount.phoneNumber || null,\r\n tenantId: coreAccount.tenantId || null,\r\n providerData,\r\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n isAnonymous: !(coreAccount.email && coreAccount.passwordHash) &&\r\n !(providerData === null || providerData === void 0 ? void 0 : providerData.length)\r\n };\r\n Object.assign(user, updates);\r\n return user;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst instanceCache = new Map();\r\nfunction _getInstance(cls) {\r\n debugAssert(cls instanceof Function, 'Expected a class definition');\r\n let instance = instanceCache.get(cls);\r\n if (instance) {\r\n debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');\r\n return instance;\r\n }\r\n instance = new cls();\r\n instanceCache.set(cls, instance);\r\n return instance;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass InMemoryPersistence {\r\n constructor() {\r\n this.type = \"NONE\" /* PersistenceType.NONE */;\r\n this.storage = {};\r\n }\r\n async _isAvailable() {\r\n return true;\r\n }\r\n async _set(key, value) {\r\n this.storage[key] = value;\r\n }\r\n async _get(key) {\r\n const value = this.storage[key];\r\n return value === undefined ? null : value;\r\n }\r\n async _remove(key) {\r\n delete this.storage[key];\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n}\r\nInMemoryPersistence.type = 'NONE';\r\n/**\r\n * An implementation of {@link Persistence} of type 'NONE'.\r\n *\r\n * @public\r\n */\r\nconst inMemoryPersistence = InMemoryPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _persistenceKeyName(key, apiKey, appName) {\r\n return `${\"firebase\" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;\r\n}\r\nclass PersistenceUserManager {\r\n constructor(persistence, auth, userKey) {\r\n this.persistence = persistence;\r\n this.auth = auth;\r\n this.userKey = userKey;\r\n const { config, name } = this.auth;\r\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\r\n this.fullPersistenceKey = _persistenceKeyName(\"persistence\" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);\r\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\r\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n setCurrentUser(user) {\r\n return this.persistence._set(this.fullUserKey, user.toJSON());\r\n }\r\n async getCurrentUser() {\r\n const blob = await this.persistence._get(this.fullUserKey);\r\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\r\n }\r\n removeCurrentUser() {\r\n return this.persistence._remove(this.fullUserKey);\r\n }\r\n savePersistenceForRedirect() {\r\n return this.persistence._set(this.fullPersistenceKey, this.persistence.type);\r\n }\r\n async setPersistence(newPersistence) {\r\n if (this.persistence === newPersistence) {\r\n return;\r\n }\r\n const currentUser = await this.getCurrentUser();\r\n await this.removeCurrentUser();\r\n this.persistence = newPersistence;\r\n if (currentUser) {\r\n return this.setCurrentUser(currentUser);\r\n }\r\n }\r\n delete() {\r\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n static async create(auth, persistenceHierarchy, userKey = \"authUser\" /* KeyName.AUTH_USER */) {\r\n if (!persistenceHierarchy.length) {\r\n return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);\r\n }\r\n // Eliminate any persistences that are not available\r\n const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (await persistence._isAvailable()) {\r\n return persistence;\r\n }\r\n return undefined;\r\n }))).filter(persistence => persistence);\r\n // Fall back to the first persistence listed, or in memory if none available\r\n let selectedPersistence = availablePersistences[0] ||\r\n _getInstance(inMemoryPersistence);\r\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\r\n // Pull out the existing user, setting the chosen persistence to that\r\n // persistence if the user exists.\r\n let userToMigrate = null;\r\n // Note, here we check for a user in _all_ persistences, not just the\r\n // ones deemed available. If we can migrate a user out of a broken\r\n // persistence, we will (but only if that persistence supports migration).\r\n for (const persistence of persistenceHierarchy) {\r\n try {\r\n const blob = await persistence._get(key);\r\n if (blob) {\r\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\r\n if (persistence !== selectedPersistence) {\r\n userToMigrate = user;\r\n }\r\n selectedPersistence = persistence;\r\n break;\r\n }\r\n }\r\n catch (_a) { }\r\n }\r\n // If we find the user in a persistence that does support migration, use\r\n // that migration path (of only persistences that support migration)\r\n const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);\r\n // If the persistence does _not_ allow migration, just finish off here\r\n if (!selectedPersistence._shouldAllowMigration ||\r\n !migrationHierarchy.length) {\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n selectedPersistence = migrationHierarchy[0];\r\n if (userToMigrate) {\r\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\r\n // we'll just let it bubble to surface the error.\r\n await selectedPersistence._set(key, userToMigrate.toJSON());\r\n }\r\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\r\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\r\n await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (persistence !== selectedPersistence) {\r\n try {\r\n await persistence._remove(key);\r\n }\r\n catch (_a) { }\r\n }\r\n }));\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine the browser for the purposes of reporting usage to the API\r\n */\r\nfunction _getBrowserName(userAgent) {\r\n const ua = userAgent.toLowerCase();\r\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\r\n return \"Opera\" /* BrowserName.OPERA */;\r\n }\r\n else if (_isIEMobile(ua)) {\r\n // Windows phone IEMobile browser.\r\n return \"IEMobile\" /* BrowserName.IEMOBILE */;\r\n }\r\n else if (ua.includes('msie') || ua.includes('trident/')) {\r\n return \"IE\" /* BrowserName.IE */;\r\n }\r\n else if (ua.includes('edge/')) {\r\n return \"Edge\" /* BrowserName.EDGE */;\r\n }\r\n else if (_isFirefox(ua)) {\r\n return \"Firefox\" /* BrowserName.FIREFOX */;\r\n }\r\n else if (ua.includes('silk/')) {\r\n return \"Silk\" /* BrowserName.SILK */;\r\n }\r\n else if (_isBlackBerry(ua)) {\r\n // Blackberry browser.\r\n return \"Blackberry\" /* BrowserName.BLACKBERRY */;\r\n }\r\n else if (_isWebOS(ua)) {\r\n // WebOS default browser.\r\n return \"Webos\" /* BrowserName.WEBOS */;\r\n }\r\n else if (_isSafari(ua)) {\r\n return \"Safari\" /* BrowserName.SAFARI */;\r\n }\r\n else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&\r\n !ua.includes('edge/')) {\r\n return \"Chrome\" /* BrowserName.CHROME */;\r\n }\r\n else if (_isAndroid(ua)) {\r\n // Android stock browser.\r\n return \"Android\" /* BrowserName.ANDROID */;\r\n }\r\n else {\r\n // Most modern browsers have name/version at end of user agent string.\r\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\r\n const matches = userAgent.match(re);\r\n if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {\r\n return matches[1];\r\n }\r\n }\r\n return \"Other\" /* BrowserName.OTHER */;\r\n}\r\nfunction _isFirefox(ua = getUA()) {\r\n return /firefox\\//i.test(ua);\r\n}\r\nfunction _isSafari(userAgent = getUA()) {\r\n const ua = userAgent.toLowerCase();\r\n return (ua.includes('safari/') &&\r\n !ua.includes('chrome/') &&\r\n !ua.includes('crios/') &&\r\n !ua.includes('android'));\r\n}\r\nfunction _isChromeIOS(ua = getUA()) {\r\n return /crios\\//i.test(ua);\r\n}\r\nfunction _isIEMobile(ua = getUA()) {\r\n return /iemobile/i.test(ua);\r\n}\r\nfunction _isAndroid(ua = getUA()) {\r\n return /android/i.test(ua);\r\n}\r\nfunction _isBlackBerry(ua = getUA()) {\r\n return /blackberry/i.test(ua);\r\n}\r\nfunction _isWebOS(ua = getUA()) {\r\n return /webos/i.test(ua);\r\n}\r\nfunction _isIOS(ua = getUA()) {\r\n return (/iphone|ipad|ipod/i.test(ua) ||\r\n (/macintosh/i.test(ua) && /mobile/i.test(ua)));\r\n}\r\nfunction _isIOS7Or8(ua = getUA()) {\r\n return (/(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\r\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua));\r\n}\r\nfunction _isIOSStandalone(ua = getUA()) {\r\n var _a;\r\n return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);\r\n}\r\nfunction _isIE10() {\r\n return isIE() && document.documentMode === 10;\r\n}\r\nfunction _isMobileBrowser(ua = getUA()) {\r\n // TODO: implement getBrowserName equivalent for OS.\r\n return (_isIOS(ua) ||\r\n _isAndroid(ua) ||\r\n _isWebOS(ua) ||\r\n _isBlackBerry(ua) ||\r\n /windows phone/i.test(ua) ||\r\n _isIEMobile(ua));\r\n}\r\nfunction _isIframe() {\r\n try {\r\n // Check that the current window is not the top window.\r\n // If so, return true.\r\n return !!(window && window !== window.top);\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/*\r\n * Determine the SDK version string\r\n */\r\nfunction _getClientVersion(clientPlatform, frameworks = []) {\r\n let reportedPlatform;\r\n switch (clientPlatform) {\r\n case \"Browser\" /* ClientPlatform.BROWSER */:\r\n // In a browser environment, report the browser name.\r\n reportedPlatform = _getBrowserName(getUA());\r\n break;\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n // Technically a worker runs from a browser but we need to differentiate a\r\n // worker from a browser.\r\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\r\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\r\n break;\r\n default:\r\n reportedPlatform = clientPlatform;\r\n }\r\n const reportedFrameworks = frameworks.length\r\n ? frameworks.join(',')\r\n : 'FirebaseCore-web'; /* default value if no other framework is used */\r\n return `${reportedPlatform}/${\"JsCore\" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthMiddlewareQueue {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.queue = [];\r\n }\r\n pushCallback(callback, onAbort) {\r\n // The callback could be sync or async. Wrap it into a\r\n // function that is always async.\r\n const wrappedCallback = (user) => new Promise((resolve, reject) => {\r\n try {\r\n const result = callback(user);\r\n // Either resolve with existing promise or wrap a non-promise\r\n // return value into a promise.\r\n resolve(result);\r\n }\r\n catch (e) {\r\n // Sync callback throws.\r\n reject(e);\r\n }\r\n });\r\n // Attach the onAbort if present\r\n wrappedCallback.onAbort = onAbort;\r\n this.queue.push(wrappedCallback);\r\n const index = this.queue.length - 1;\r\n return () => {\r\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\r\n // indexing of other elements.\r\n this.queue[index] = () => Promise.resolve();\r\n };\r\n }\r\n async runMiddleware(nextUser) {\r\n if (this.auth.currentUser === nextUser) {\r\n return;\r\n }\r\n // While running the middleware, build a temporary stack of onAbort\r\n // callbacks to call if one middleware callback rejects.\r\n const onAbortStack = [];\r\n try {\r\n for (const beforeStateCallback of this.queue) {\r\n await beforeStateCallback(nextUser);\r\n // Only push the onAbort if the callback succeeds\r\n if (beforeStateCallback.onAbort) {\r\n onAbortStack.push(beforeStateCallback.onAbort);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // Run all onAbort, with separate try/catch to ignore any errors and\r\n // continue\r\n onAbortStack.reverse();\r\n for (const onAbort of onAbortStack) {\r\n try {\r\n onAbort();\r\n }\r\n catch (_) {\r\n /* swallow error */\r\n }\r\n }\r\n throw this.auth._errorFactory.create(\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */, {\r\n originalMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\r\n *\r\n * @param auth Auth object.\r\n * @param request Password policy request.\r\n * @returns Password policy response.\r\n */\r\nasync function _getPasswordPolicy(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/passwordPolicy\" /* Endpoint.GET_PASSWORD_POLICY */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Minimum min password length enforced by the backend, even if no minimum length is set.\r\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\r\n/**\r\n * Stores password policy requirements and provides password validation against the policy.\r\n *\r\n * @internal\r\n */\r\nclass PasswordPolicyImpl {\r\n constructor(response) {\r\n var _a, _b, _c, _d;\r\n // Only include custom strength options defined in the response.\r\n const responseOptions = response.customStrengthOptions;\r\n this.customStrengthOptions = {};\r\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\r\n this.customStrengthOptions.minPasswordLength =\r\n (_a = responseOptions.minPasswordLength) !== null && _a !== void 0 ? _a : MINIMUM_MIN_PASSWORD_LENGTH;\r\n if (responseOptions.maxPasswordLength) {\r\n this.customStrengthOptions.maxPasswordLength =\r\n responseOptions.maxPasswordLength;\r\n }\r\n if (responseOptions.containsLowercaseCharacter !== undefined) {\r\n this.customStrengthOptions.containsLowercaseLetter =\r\n responseOptions.containsLowercaseCharacter;\r\n }\r\n if (responseOptions.containsUppercaseCharacter !== undefined) {\r\n this.customStrengthOptions.containsUppercaseLetter =\r\n responseOptions.containsUppercaseCharacter;\r\n }\r\n if (responseOptions.containsNumericCharacter !== undefined) {\r\n this.customStrengthOptions.containsNumericCharacter =\r\n responseOptions.containsNumericCharacter;\r\n }\r\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\r\n this.customStrengthOptions.containsNonAlphanumericCharacter =\r\n responseOptions.containsNonAlphanumericCharacter;\r\n }\r\n this.enforcementState = response.enforcementState;\r\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\r\n this.enforcementState = 'OFF';\r\n }\r\n // Use an empty string if no non-alphanumeric characters are specified in the response.\r\n this.allowedNonAlphanumericCharacters =\r\n (_c = (_b = response.allowedNonAlphanumericCharacters) === null || _b === void 0 ? void 0 : _b.join('')) !== null && _c !== void 0 ? _c : '';\r\n this.forceUpgradeOnSignin = (_d = response.forceUpgradeOnSignin) !== null && _d !== void 0 ? _d : false;\r\n this.schemaVersion = response.schemaVersion;\r\n }\r\n validatePassword(password) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const status = {\r\n isValid: true,\r\n passwordPolicy: this\r\n };\r\n // Check the password length and character options.\r\n this.validatePasswordLengthOptions(password, status);\r\n this.validatePasswordCharacterOptions(password, status);\r\n // Combine the status into single isValid property.\r\n status.isValid && (status.isValid = (_a = status.meetsMinPasswordLength) !== null && _a !== void 0 ? _a : true);\r\n status.isValid && (status.isValid = (_b = status.meetsMaxPasswordLength) !== null && _b !== void 0 ? _b : true);\r\n status.isValid && (status.isValid = (_c = status.containsLowercaseLetter) !== null && _c !== void 0 ? _c : true);\r\n status.isValid && (status.isValid = (_d = status.containsUppercaseLetter) !== null && _d !== void 0 ? _d : true);\r\n status.isValid && (status.isValid = (_e = status.containsNumericCharacter) !== null && _e !== void 0 ? _e : true);\r\n status.isValid && (status.isValid = (_f = status.containsNonAlphanumericCharacter) !== null && _f !== void 0 ? _f : true);\r\n return status;\r\n }\r\n /**\r\n * Validates that the password meets the length options for the policy.\r\n *\r\n * @param password Password to validate.\r\n * @param status Validation status.\r\n */\r\n validatePasswordLengthOptions(password, status) {\r\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\r\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\r\n if (minPasswordLength) {\r\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\r\n }\r\n if (maxPasswordLength) {\r\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\r\n }\r\n }\r\n /**\r\n * Validates that the password meets the character options for the policy.\r\n *\r\n * @param password Password to validate.\r\n * @param status Validation status.\r\n */\r\n validatePasswordCharacterOptions(password, status) {\r\n // Assign statuses for requirements even if the password is an empty string.\r\n this.updatePasswordCharacterOptionsStatuses(status, \r\n /* containsLowercaseCharacter= */ false, \r\n /* containsUppercaseCharacter= */ false, \r\n /* containsNumericCharacter= */ false, \r\n /* containsNonAlphanumericCharacter= */ false);\r\n let passwordChar;\r\n for (let i = 0; i < password.length; i++) {\r\n passwordChar = password.charAt(i);\r\n this.updatePasswordCharacterOptionsStatuses(status, \r\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\r\n passwordChar <= 'z', \r\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\r\n passwordChar <= 'Z', \r\n /* containsNumericCharacter= */ passwordChar >= '0' &&\r\n passwordChar <= '9', \r\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(passwordChar));\r\n }\r\n }\r\n /**\r\n * Updates the running validation status with the statuses for the character options.\r\n * Expected to be called each time a character is processed to update each option status\r\n * based on the current character.\r\n *\r\n * @param status Validation status.\r\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\r\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\r\n * @param containsNumericCharacter Whether the character is a numeric character.\r\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\r\n */\r\n updatePasswordCharacterOptionsStatuses(status, containsLowercaseCharacter, containsUppercaseCharacter, containsNumericCharacter, containsNonAlphanumericCharacter) {\r\n if (this.customStrengthOptions.containsLowercaseLetter) {\r\n status.containsLowercaseLetter || (status.containsLowercaseLetter = containsLowercaseCharacter);\r\n }\r\n if (this.customStrengthOptions.containsUppercaseLetter) {\r\n status.containsUppercaseLetter || (status.containsUppercaseLetter = containsUppercaseCharacter);\r\n }\r\n if (this.customStrengthOptions.containsNumericCharacter) {\r\n status.containsNumericCharacter || (status.containsNumericCharacter = containsNumericCharacter);\r\n }\r\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\r\n status.containsNonAlphanumericCharacter || (status.containsNonAlphanumericCharacter = containsNonAlphanumericCharacter);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthImpl {\r\n constructor(app, heartbeatServiceProvider, appCheckServiceProvider, config) {\r\n this.app = app;\r\n this.heartbeatServiceProvider = heartbeatServiceProvider;\r\n this.appCheckServiceProvider = appCheckServiceProvider;\r\n this.config = config;\r\n this.currentUser = null;\r\n this.emulatorConfig = null;\r\n this.operations = Promise.resolve();\r\n this.authStateSubscription = new Subscription(this);\r\n this.idTokenSubscription = new Subscription(this);\r\n this.beforeStateQueue = new AuthMiddlewareQueue(this);\r\n this.redirectUser = null;\r\n this.isProactiveRefreshEnabled = false;\r\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1;\r\n // Any network calls will set this to true and prevent subsequent emulator\r\n // initialization\r\n this._canInitEmulator = true;\r\n this._isInitialized = false;\r\n this._deleted = false;\r\n this._initializationPromise = null;\r\n this._popupRedirectResolver = null;\r\n this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;\r\n this._agentRecaptchaConfig = null;\r\n this._tenantRecaptchaConfigs = {};\r\n this._projectPasswordPolicy = null;\r\n this._tenantPasswordPolicies = {};\r\n // Tracks the last notified UID for state change listeners to prevent\r\n // repeated calls to the callbacks. Undefined means it's never been\r\n // called, whereas null means it's been called with a signed out user\r\n this.lastNotifiedUid = undefined;\r\n this.languageCode = null;\r\n this.tenantId = null;\r\n this.settings = { appVerificationDisabledForTesting: false };\r\n this.frameworks = [];\r\n this.name = app.name;\r\n this.clientVersion = config.sdkClientVersion;\r\n }\r\n _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {\r\n if (popupRedirectResolver) {\r\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\r\n }\r\n // Have to check for app deletion throughout initialization (after each\r\n // promise resolution)\r\n this._initializationPromise = this.queue(async () => {\r\n var _a, _b;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);\r\n if (this._deleted) {\r\n return;\r\n }\r\n // Initialize the resolver early if necessary (only applicable to web:\r\n // this will cause the iframe to load immediately in certain cases)\r\n if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {\r\n // If this fails, don't halt auth loading\r\n try {\r\n await this._popupRedirectResolver._initialize(this);\r\n }\r\n catch (e) {\r\n /* Ignore the error */\r\n }\r\n }\r\n await this.initializeCurrentUser(popupRedirectResolver);\r\n this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this._isInitialized = true;\r\n });\r\n return this._initializationPromise;\r\n }\r\n /**\r\n * If the persistence is changed in another window, the user manager will let us know\r\n */\r\n async _onStorageEvent() {\r\n if (this._deleted) {\r\n return;\r\n }\r\n const user = await this.assertedPersistence.getCurrentUser();\r\n if (!this.currentUser && !user) {\r\n // No change, do nothing (was signed out and remained signed out).\r\n return;\r\n }\r\n // If the same user is to be synchronized.\r\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\r\n // Data update, simply copy data changes.\r\n this._currentUser._assign(user);\r\n // If tokens changed from previous user tokens, this will trigger\r\n // notifyAuthListeners_.\r\n await this.currentUser.getIdToken();\r\n return;\r\n }\r\n // Update current Auth state. Either a new login or logout.\r\n // Skip blocking callbacks, they should not apply to a change in another tab.\r\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\r\n }\r\n async initializeCurrentUserFromIdToken(idToken) {\r\n try {\r\n const response = await getAccountInfo(this, { idToken });\r\n const user = await UserImpl._fromGetAccountInfoResponse(this, response, idToken);\r\n await this.directlySetCurrentUser(user);\r\n }\r\n catch (err) {\r\n console.warn('FirebaseServerApp could not login user with provided authIdToken: ', err);\r\n await this.directlySetCurrentUser(null);\r\n }\r\n }\r\n async initializeCurrentUser(popupRedirectResolver) {\r\n var _a;\r\n if (_isFirebaseServerApp(this.app)) {\r\n const idToken = this.app.settings.authIdToken;\r\n if (idToken) {\r\n // Start the auth operation in the next tick to allow a moment for the customer's app to\r\n // attach an emulator, if desired.\r\n return new Promise(resolve => {\r\n setTimeout(() => this.initializeCurrentUserFromIdToken(idToken).then(resolve, resolve));\r\n });\r\n }\r\n else {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n // First check to see if we have a pending redirect event.\r\n const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());\r\n let futureCurrentUser = previouslyStoredUser;\r\n let needsTocheckMiddleware = false;\r\n if (popupRedirectResolver && this.config.authDomain) {\r\n await this.getOrInitRedirectPersistenceManager();\r\n const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;\r\n const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;\r\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\r\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\r\n // matches the redirect user, then we want to initially sign in with the\r\n // new user object from result.\r\n // TODO(samgho): More thoroughly test all of this\r\n if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\r\n (result === null || result === void 0 ? void 0 : result.user)) {\r\n futureCurrentUser = result.user;\r\n needsTocheckMiddleware = true;\r\n }\r\n }\r\n // If no user in persistence, there is no current user. Set to null.\r\n if (!futureCurrentUser) {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n if (!futureCurrentUser._redirectEventId) {\r\n // This isn't a redirect link operation, we can reload and bail.\r\n // First though, ensure that we check the middleware is happy.\r\n if (needsTocheckMiddleware) {\r\n try {\r\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\r\n }\r\n catch (e) {\r\n futureCurrentUser = previouslyStoredUser;\r\n // We know this is available since the bit is only set when the\r\n // resolver is available\r\n this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));\r\n }\r\n }\r\n if (futureCurrentUser) {\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n else {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n _assert(this._popupRedirectResolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n await this.getOrInitRedirectPersistenceManager();\r\n // If the redirect user's event ID matches the current user's event ID,\r\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\r\n // This is important for the reauthenticateWithRedirect() flow.\r\n if (this.redirectUser &&\r\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {\r\n return this.directlySetCurrentUser(futureCurrentUser);\r\n }\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n async tryRedirectSignIn(redirectResolver) {\r\n // The redirect user needs to be checked (and signed in if available)\r\n // during auth initialization. All of the normal sign in and link/reauth\r\n // flows call back into auth and push things onto the promise queue. We\r\n // need to await the result of the redirect sign in *inside the promise\r\n // queue*. This presents a problem: we run into deadlock. See:\r\n // ┌> [Initialization] ─────┐\r\n // ┌> [] │\r\n // └─ [getRedirectResult] <─┘\r\n // where [] are tasks on the queue and arrows denote awaits\r\n // Initialization will never complete because it's waiting on something\r\n // that's waiting for initialization to complete!\r\n //\r\n // Instead, this method calls getRedirectResult() (stored in\r\n // _completeRedirectFn) with an optional parameter that instructs all of\r\n // the underlying auth operations to skip anything that mutates auth state.\r\n let result = null;\r\n try {\r\n // We know this._popupRedirectResolver is set since redirectResolver\r\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\r\n result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);\r\n }\r\n catch (e) {\r\n // Swallow any errors here; the code can retrieve them in\r\n // getRedirectResult().\r\n await this._setRedirectUser(null);\r\n }\r\n return result;\r\n }\r\n async reloadAndSetCurrentUserOrClear(user) {\r\n try {\r\n await _reloadWithoutSaving(user);\r\n }\r\n catch (e) {\r\n if ((e === null || e === void 0 ? void 0 : e.code) !==\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n // Something's wrong with the user's token. Log them out and remove\r\n // them from storage\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n return this.directlySetCurrentUser(user);\r\n }\r\n useDeviceLanguage() {\r\n this.languageCode = _getUserLanguage();\r\n }\r\n async _delete() {\r\n this._deleted = true;\r\n }\r\n async updateCurrentUser(userExtern) {\r\n if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n // The public updateCurrentUser method needs to make a copy of the user,\r\n // and also check that the project matches\r\n const user = userExtern\r\n ? getModularInstance(userExtern)\r\n : null;\r\n if (user) {\r\n _assert(user.auth.config.apiKey === this.config.apiKey, this, \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */);\r\n }\r\n return this._updateCurrentUser(user && user._clone(this));\r\n }\r\n async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {\r\n if (this._deleted) {\r\n return;\r\n }\r\n if (user) {\r\n _assert(this.tenantId === user.tenantId, this, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n }\r\n if (!skipBeforeStateCallbacks) {\r\n await this.beforeStateQueue.runMiddleware(user);\r\n }\r\n return this.queue(async () => {\r\n await this.directlySetCurrentUser(user);\r\n this.notifyAuthListeners();\r\n });\r\n }\r\n async signOut() {\r\n if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n // Run first, to block _setRedirectUser() if any callbacks fail.\r\n await this.beforeStateQueue.runMiddleware(null);\r\n // Clear the redirect user when signOut is called\r\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\r\n await this._setRedirectUser(null);\r\n }\r\n // Prevent callbacks from being called again in _updateCurrentUser, as\r\n // they were already called in the first line.\r\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\r\n }\r\n setPersistence(persistence) {\r\n if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n return this.queue(async () => {\r\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\r\n });\r\n }\r\n _getRecaptchaConfig() {\r\n if (this.tenantId == null) {\r\n return this._agentRecaptchaConfig;\r\n }\r\n else {\r\n return this._tenantRecaptchaConfigs[this.tenantId];\r\n }\r\n }\r\n async validatePassword(password) {\r\n if (!this._getPasswordPolicyInternal()) {\r\n await this._updatePasswordPolicy();\r\n }\r\n // Password policy will be defined after fetching.\r\n const passwordPolicy = this._getPasswordPolicyInternal();\r\n // Check that the policy schema version is supported by the SDK.\r\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\r\n if (passwordPolicy.schemaVersion !==\r\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION) {\r\n return Promise.reject(this._errorFactory.create(\"unsupported-password-policy-schema-version\" /* AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION */, {}));\r\n }\r\n return passwordPolicy.validatePassword(password);\r\n }\r\n _getPasswordPolicyInternal() {\r\n if (this.tenantId === null) {\r\n return this._projectPasswordPolicy;\r\n }\r\n else {\r\n return this._tenantPasswordPolicies[this.tenantId];\r\n }\r\n }\r\n async _updatePasswordPolicy() {\r\n const response = await _getPasswordPolicy(this);\r\n const passwordPolicy = new PasswordPolicyImpl(response);\r\n if (this.tenantId === null) {\r\n this._projectPasswordPolicy = passwordPolicy;\r\n }\r\n else {\r\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\r\n }\r\n }\r\n _getPersistence() {\r\n return this.assertedPersistence.persistence.type;\r\n }\r\n _updateErrorMap(errorMap) {\r\n this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());\r\n }\r\n onAuthStateChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);\r\n }\r\n beforeAuthStateChanged(callback, onAbort) {\r\n return this.beforeStateQueue.pushCallback(callback, onAbort);\r\n }\r\n onIdTokenChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);\r\n }\r\n authStateReady() {\r\n return new Promise((resolve, reject) => {\r\n if (this.currentUser) {\r\n resolve();\r\n }\r\n else {\r\n const unsubscribe = this.onAuthStateChanged(() => {\r\n unsubscribe();\r\n resolve();\r\n }, reject);\r\n }\r\n });\r\n }\r\n /**\r\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\r\n */\r\n async revokeAccessToken(token) {\r\n if (this.currentUser) {\r\n const idToken = await this.currentUser.getIdToken();\r\n // Generalize this to accept other providers once supported.\r\n const request = {\r\n providerId: 'apple.com',\r\n tokenType: \"ACCESS_TOKEN\" /* TokenType.ACCESS_TOKEN */,\r\n token,\r\n idToken\r\n };\r\n if (this.tenantId != null) {\r\n request.tenantId = this.tenantId;\r\n }\r\n await revokeToken(this, request);\r\n }\r\n }\r\n toJSON() {\r\n var _a;\r\n return {\r\n apiKey: this.config.apiKey,\r\n authDomain: this.config.authDomain,\r\n appName: this.name,\r\n currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()\r\n };\r\n }\r\n async _setRedirectUser(user, popupRedirectResolver) {\r\n const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);\r\n return user === null\r\n ? redirectManager.removeCurrentUser()\r\n : redirectManager.setCurrentUser(user);\r\n }\r\n async getOrInitRedirectPersistenceManager(popupRedirectResolver) {\r\n if (!this.redirectPersistenceManager) {\r\n const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\r\n this._popupRedirectResolver;\r\n _assert(resolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], \"redirectUser\" /* KeyName.REDIRECT_USER */);\r\n this.redirectUser =\r\n await this.redirectPersistenceManager.getCurrentUser();\r\n }\r\n return this.redirectPersistenceManager;\r\n }\r\n async _redirectUserForId(id) {\r\n var _a, _b;\r\n // Make sure we've cleared any pending persistence actions if we're not in\r\n // the initializer\r\n if (this._isInitialized) {\r\n await this.queue(async () => { });\r\n }\r\n if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {\r\n return this._currentUser;\r\n }\r\n if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {\r\n return this.redirectUser;\r\n }\r\n return null;\r\n }\r\n async _persistUserIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n return this.queue(async () => this.directlySetCurrentUser(user));\r\n }\r\n }\r\n /** Notifies listeners only if the user is current */\r\n _notifyListenersIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n this.notifyAuthListeners();\r\n }\r\n }\r\n _key() {\r\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\r\n }\r\n _startProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = true;\r\n if (this.currentUser) {\r\n this._currentUser._startProactiveRefresh();\r\n }\r\n }\r\n _stopProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = false;\r\n if (this.currentUser) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n }\r\n /** Returns the current user cast as the internal type */\r\n get _currentUser() {\r\n return this.currentUser;\r\n }\r\n notifyAuthListeners() {\r\n var _a, _b;\r\n if (!this._isInitialized) {\r\n return;\r\n }\r\n this.idTokenSubscription.next(this.currentUser);\r\n const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;\r\n if (this.lastNotifiedUid !== currentUid) {\r\n this.lastNotifiedUid = currentUid;\r\n this.authStateSubscription.next(this.currentUser);\r\n }\r\n }\r\n registerStateListener(subscription, nextOrObserver, error, completed) {\r\n if (this._deleted) {\r\n return () => { };\r\n }\r\n const cb = typeof nextOrObserver === 'function'\r\n ? nextOrObserver\r\n : nextOrObserver.next.bind(nextOrObserver);\r\n let isUnsubscribed = false;\r\n const promise = this._isInitialized\r\n ? Promise.resolve()\r\n : this._initializationPromise;\r\n _assert(promise, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // The callback needs to be called asynchronously per the spec.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n promise.then(() => {\r\n if (isUnsubscribed) {\r\n return;\r\n }\r\n cb(this.currentUser);\r\n });\r\n if (typeof nextOrObserver === 'function') {\r\n const unsubscribe = subscription.addObserver(nextOrObserver, error, completed);\r\n return () => {\r\n isUnsubscribed = true;\r\n unsubscribe();\r\n };\r\n }\r\n else {\r\n const unsubscribe = subscription.addObserver(nextOrObserver);\r\n return () => {\r\n isUnsubscribed = true;\r\n unsubscribe();\r\n };\r\n }\r\n }\r\n /**\r\n * Unprotected (from race conditions) method to set the current user. This\r\n * should only be called from within a queued callback. This is necessary\r\n * because the queue shouldn't rely on another queued callback.\r\n */\r\n async directlySetCurrentUser(user) {\r\n if (this.currentUser && this.currentUser !== user) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n if (user && this.isProactiveRefreshEnabled) {\r\n user._startProactiveRefresh();\r\n }\r\n this.currentUser = user;\r\n if (user) {\r\n await this.assertedPersistence.setCurrentUser(user);\r\n }\r\n else {\r\n await this.assertedPersistence.removeCurrentUser();\r\n }\r\n }\r\n queue(action) {\r\n // In case something errors, the callback still should be called in order\r\n // to keep the promise chain alive\r\n this.operations = this.operations.then(action, action);\r\n return this.operations;\r\n }\r\n get assertedPersistence() {\r\n _assert(this.persistenceManager, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.persistenceManager;\r\n }\r\n _logFramework(framework) {\r\n if (!framework || this.frameworks.includes(framework)) {\r\n return;\r\n }\r\n this.frameworks.push(framework);\r\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\r\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\r\n this.frameworks.sort();\r\n this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());\r\n }\r\n _getFrameworks() {\r\n return this.frameworks;\r\n }\r\n async _getAdditionalHeaders() {\r\n var _a;\r\n // Additional headers on every request\r\n const headers = {\r\n [\"X-Client-Version\" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion\r\n };\r\n if (this.app.options.appId) {\r\n headers[\"X-Firebase-gmpid\" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;\r\n }\r\n // If the heartbeat service exists, add the heartbeat string\r\n const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider\r\n .getImmediate({\r\n optional: true\r\n })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());\r\n if (heartbeatsHeader) {\r\n headers[\"X-Firebase-Client\" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;\r\n }\r\n // If the App Check service exists, add the App Check token in the headers\r\n const appCheckToken = await this._getAppCheckToken();\r\n if (appCheckToken) {\r\n headers[\"X-Firebase-AppCheck\" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;\r\n }\r\n return headers;\r\n }\r\n async _getAppCheckToken() {\r\n var _a;\r\n const appCheckTokenResult = await ((_a = this.appCheckServiceProvider\r\n .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken());\r\n if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {\r\n // Context: appCheck.getToken() will never throw even if an error happened.\r\n // In the error case, a dummy token will be returned along with an error field describing\r\n // the error. In general, we shouldn't care about the error condition and just use\r\n // the token (actual or dummy) to send requests.\r\n _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);\r\n }\r\n return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token;\r\n }\r\n}\r\n/**\r\n * Method to be used to cast down to our private implmentation of Auth.\r\n * It will also handle unwrapping from the compat type if necessary\r\n *\r\n * @param auth Auth object passed in from developer\r\n */\r\nfunction _castAuth(auth) {\r\n return getModularInstance(auth);\r\n}\r\n/** Helper class to wrap subscriber logic */\r\nclass Subscription {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.observer = null;\r\n this.addObserver = createSubscribe(observer => (this.observer = observer));\r\n }\r\n get next() {\r\n _assert(this.observer, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.observer.next.bind(this.observer);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet externalJSProvider = {\r\n async loadJS() {\r\n throw new Error('Unable to load external scripts');\r\n },\r\n recaptchaV2Script: '',\r\n recaptchaEnterpriseScript: '',\r\n gapiScript: ''\r\n};\r\nfunction _setExternalJSProvider(p) {\r\n externalJSProvider = p;\r\n}\r\nfunction _loadJS(url) {\r\n return externalJSProvider.loadJS(url);\r\n}\r\nfunction _recaptchaV2ScriptUrl() {\r\n return externalJSProvider.recaptchaV2Script;\r\n}\r\nfunction _recaptchaEnterpriseScriptUrl() {\r\n return externalJSProvider.recaptchaEnterpriseScript;\r\n}\r\nfunction _gapiScriptUrl() {\r\n return externalJSProvider.gapiScript;\r\n}\r\nfunction _generateCallbackName(prefix) {\r\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\r\n}\n\n/* eslint-disable @typescript-eslint/no-require-imports */\r\nconst RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\r\nconst FAKE_TOKEN = 'NO_RECAPTCHA';\r\nclass RecaptchaEnterpriseVerifier {\r\n /**\r\n *\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n *\r\n */\r\n constructor(authExtern) {\r\n /**\r\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\r\n */\r\n this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\r\n this.auth = _castAuth(authExtern);\r\n }\r\n /**\r\n * Executes the verification process.\r\n *\r\n * @returns A Promise for a token that can be used to assert the validity of a request.\r\n */\r\n async verify(action = 'verify', forceRefresh = false) {\r\n async function retrieveSiteKey(auth) {\r\n if (!forceRefresh) {\r\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\r\n return auth._agentRecaptchaConfig.siteKey;\r\n }\r\n if (auth.tenantId != null &&\r\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {\r\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\r\n }\r\n }\r\n return new Promise(async (resolve, reject) => {\r\n getRecaptchaConfig(auth, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n })\r\n .then(response => {\r\n if (response.recaptchaKey === undefined) {\r\n reject(new Error('recaptcha Enterprise site key undefined'));\r\n }\r\n else {\r\n const config = new RecaptchaConfig(response);\r\n if (auth.tenantId == null) {\r\n auth._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\r\n }\r\n return resolve(config.siteKey);\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n function retrieveRecaptchaToken(siteKey, resolve, reject) {\r\n const grecaptcha = window.grecaptcha;\r\n if (isEnterprise(grecaptcha)) {\r\n grecaptcha.enterprise.ready(() => {\r\n grecaptcha.enterprise\r\n .execute(siteKey, { action })\r\n .then(token => {\r\n resolve(token);\r\n })\r\n .catch(() => {\r\n resolve(FAKE_TOKEN);\r\n });\r\n });\r\n }\r\n else {\r\n reject(Error('No reCAPTCHA enterprise script loaded.'));\r\n }\r\n }\r\n return new Promise((resolve, reject) => {\r\n retrieveSiteKey(this.auth)\r\n .then(siteKey => {\r\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n }\r\n else {\r\n if (typeof window === 'undefined') {\r\n reject(new Error('RecaptchaVerifier is only supported in browser'));\r\n return;\r\n }\r\n let url = _recaptchaEnterpriseScriptUrl();\r\n if (url.length !== 0) {\r\n url += siteKey;\r\n }\r\n _loadJS(url)\r\n .then(() => {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n}\r\nasync function injectRecaptchaFields(auth, request, action, captchaResp = false) {\r\n const verifier = new RecaptchaEnterpriseVerifier(auth);\r\n let captchaResponse;\r\n try {\r\n captchaResponse = await verifier.verify(action);\r\n }\r\n catch (error) {\r\n captchaResponse = await verifier.verify(action, true);\r\n }\r\n const newRequest = Object.assign({}, request);\r\n if (!captchaResp) {\r\n Object.assign(newRequest, { captchaResponse });\r\n }\r\n else {\r\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\r\n }\r\n Object.assign(newRequest, { 'clientType': \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */ });\r\n Object.assign(newRequest, {\r\n 'recaptchaVersion': \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n return newRequest;\r\n}\r\nasync function handleRecaptchaFlow(authInstance, request, actionName, actionMethod) {\r\n var _a;\r\n if ((_a = authInstance\r\n ._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaProvider.EMAIL_PASSWORD_PROVIDER */)) {\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\r\n return actionMethod(authInstance, requestWithRecaptcha);\r\n }\r\n else {\r\n return actionMethod(authInstance, request).catch(async (error) => {\r\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n console.log(`${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\r\n return actionMethod(authInstance, requestWithRecaptcha);\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n}\r\nasync function _initializeRecaptchaConfig(auth) {\r\n const authInternal = _castAuth(auth);\r\n const response = await getRecaptchaConfig(authInternal, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n const config = new RecaptchaConfig(response);\r\n if (authInternal.tenantId == null) {\r\n authInternal._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\r\n }\r\n if (config.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaProvider.EMAIL_PASSWORD_PROVIDER */)) {\r\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\r\n void verifier.verify();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Initializes an {@link Auth} instance with fine-grained control over\r\n * {@link Dependencies}.\r\n *\r\n * @remarks\r\n *\r\n * This function allows more control over the {@link Auth} instance than\r\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\r\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\r\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\r\n * need control over which persistence layer is used, or to minimize bundle\r\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\r\n *\r\n * For example, if your app only uses anonymous accounts and you only want\r\n * accounts saved for the current session, initialize `Auth` with:\r\n *\r\n * ```js\r\n * const auth = initializeAuth(app, {\r\n * persistence: browserSessionPersistence,\r\n * popupRedirectResolver: undefined,\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nfunction initializeAuth(app, deps) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n const auth = provider.getImmediate();\r\n const initialOptions = provider.getOptions();\r\n if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {\r\n return auth;\r\n }\r\n else {\r\n _fail(auth, \"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */);\r\n }\r\n }\r\n const auth = provider.initialize({ options: deps });\r\n return auth;\r\n}\r\nfunction _initializeAuthInstance(auth, deps) {\r\n const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];\r\n const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);\r\n if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {\r\n auth._updateErrorMap(deps.errorMap);\r\n }\r\n // This promise is intended to float; auth initialization happens in the\r\n // background, meanwhile the auth object may be used by the app.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);\r\n}\n\n/**\r\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\r\n * Firebase Auth services.\r\n *\r\n * @remarks\r\n * This must be called synchronously immediately following the first call to\r\n * {@link initializeAuth}. Do not use with production credentials as emulator\r\n * traffic is not encrypted.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\r\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\r\n * `true` to disable the warning banner attached to the DOM.\r\n *\r\n * @public\r\n */\r\nfunction connectAuthEmulator(auth, url, options) {\r\n const authInternal = _castAuth(auth);\r\n _assert(authInternal._canInitEmulator, authInternal, \"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);\r\n _assert(/^https?:\\/\\//.test(url), authInternal, \"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);\r\n const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);\r\n const protocol = extractProtocol(url);\r\n const { host, port } = extractHostAndPort(url);\r\n const portStr = port === null ? '' : `:${port}`;\r\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\r\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\r\n authInternal.settings.appVerificationDisabledForTesting = true;\r\n authInternal.emulatorConfig = Object.freeze({\r\n host,\r\n port,\r\n protocol: protocol.replace(':', ''),\r\n options: Object.freeze({ disableWarnings })\r\n });\r\n if (!disableWarnings) {\r\n emitEmulatorWarning();\r\n }\r\n}\r\nfunction extractProtocol(url) {\r\n const protocolEnd = url.indexOf(':');\r\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\r\n}\r\nfunction extractHostAndPort(url) {\r\n const protocol = extractProtocol(url);\r\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\r\n if (!authority) {\r\n return { host: '', port: null };\r\n }\r\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\r\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\r\n if (bracketedIPv6) {\r\n const host = bracketedIPv6[1];\r\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\r\n }\r\n else {\r\n const [host, port] = hostAndPort.split(':');\r\n return { host, port: parsePort(port) };\r\n }\r\n}\r\nfunction parsePort(portStr) {\r\n if (!portStr) {\r\n return null;\r\n }\r\n const port = Number(portStr);\r\n if (isNaN(port)) {\r\n return null;\r\n }\r\n return port;\r\n}\r\nfunction emitEmulatorWarning() {\r\n function attachBanner() {\r\n const el = document.createElement('p');\r\n const sty = el.style;\r\n el.innerText =\r\n 'Running in emulator mode. Do not use with production credentials.';\r\n sty.position = 'fixed';\r\n sty.width = '100%';\r\n sty.backgroundColor = '#ffffff';\r\n sty.border = '.1em solid #000000';\r\n sty.color = '#b50000';\r\n sty.bottom = '0px';\r\n sty.left = '0px';\r\n sty.margin = '0px';\r\n sty.zIndex = '10000';\r\n sty.textAlign = 'center';\r\n el.classList.add('firebase-emulator-warning');\r\n document.body.appendChild(el);\r\n }\r\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\r\n console.info('WARNING: You are using the Auth Emulator,' +\r\n ' which is intended for local testing only. Do not use with' +\r\n ' production credentials.');\r\n }\r\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\r\n if (document.readyState === 'loading') {\r\n window.addEventListener('DOMContentLoaded', attachBanner);\r\n }\r\n else {\r\n attachBanner();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by an {@link AuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /**\r\n * The authentication provider ID for the credential.\r\n *\r\n * @remarks\r\n * For example, 'facebook.com', or 'google.com'.\r\n */\r\n providerId, \r\n /**\r\n * The authentication sign in method for the credential.\r\n *\r\n * @remarks\r\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\r\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\r\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\r\n */\r\n signInMethod) {\r\n this.providerId = providerId;\r\n this.signInMethod = signInMethod;\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n *\r\n * @returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _linkToIdToken(_auth, _idToken) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function resetPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:resetPassword\" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function updateEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\r\n// format as updateEmailPassword.\r\nasync function linkEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, request);\r\n}\r\nasync function applyActionCode$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithPassword(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPassword\" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendOobCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendOobCode\" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendEmailVerification$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendPasswordResetEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendSignInLinkToEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function verifyAndChangeEmail(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithEmailLink$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithEmailLinkForLinking(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\r\n * {@link ProviderId}.PASSWORD\r\n *\r\n * @remarks\r\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /** @internal */\r\n _email, \r\n /** @internal */\r\n _password, signInMethod, \r\n /** @internal */\r\n _tenantId = null) {\r\n super(\"password\" /* ProviderId.PASSWORD */, signInMethod);\r\n this._email = _email;\r\n this._password = _password;\r\n this._tenantId = _tenantId;\r\n }\r\n /** @internal */\r\n static _fromEmailAndPassword(email, password) {\r\n return new EmailAuthCredential(email, password, \"password\" /* SignInMethod.EMAIL_PASSWORD */);\r\n }\r\n /** @internal */\r\n static _fromEmailAndCode(email, oobCode, tenantId = null) {\r\n return new EmailAuthCredential(email, oobCode, \"emailLink\" /* SignInMethod.EMAIL_LINK */, tenantId);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n email: this._email,\r\n password: this._password,\r\n signInMethod: this.signInMethod,\r\n tenantId: this._tenantId\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\r\n *\r\n * @param json - Either `object` or the stringified representation of the object. When string is\r\n * provided, `JSON.parse` would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {\r\n if (obj.signInMethod === \"password\" /* SignInMethod.EMAIL_PASSWORD */) {\r\n return this._fromEmailAndPassword(obj.email, obj.password);\r\n }\r\n else if (obj.signInMethod === \"emailLink\" /* SignInMethod.EMAIL_LINK */) {\r\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\r\n }\r\n }\r\n return null;\r\n }\r\n /** @internal */\r\n async _getIdTokenResponse(auth) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n const request = {\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n return handleRecaptchaFlow(auth, request, \"signInWithPassword\" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */, signInWithPassword);\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLink$1(auth, {\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n async _linkToIdToken(auth, idToken) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n const request = {\r\n idToken,\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n return handleRecaptchaFlow(auth, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, linkEmailPassword);\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLinkForLinking(auth, {\r\n idToken,\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return this._getIdTokenResponse(auth);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithIdp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithIdp\" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI$1 = 'http://localhost';\r\n/**\r\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass OAuthCredential extends AuthCredential {\r\n constructor() {\r\n super(...arguments);\r\n this.pendingToken = null;\r\n }\r\n /** @internal */\r\n static _fromParams(params) {\r\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\r\n if (params.idToken || params.accessToken) {\r\n // OAuth 2 and either ID token or access token.\r\n if (params.idToken) {\r\n cred.idToken = params.idToken;\r\n }\r\n if (params.accessToken) {\r\n cred.accessToken = params.accessToken;\r\n }\r\n // Add nonce if available and no pendingToken is present.\r\n if (params.nonce && !params.pendingToken) {\r\n cred.nonce = params.nonce;\r\n }\r\n if (params.pendingToken) {\r\n cred.pendingToken = params.pendingToken;\r\n }\r\n }\r\n else if (params.oauthToken && params.oauthTokenSecret) {\r\n // OAuth 1 and OAuth token with token secret\r\n cred.accessToken = params.oauthToken;\r\n cred.secret = params.oauthTokenSecret;\r\n }\r\n else {\r\n _fail(\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n return cred;\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n idToken: this.idToken,\r\n accessToken: this.accessToken,\r\n secret: this.secret,\r\n nonce: this.nonce,\r\n pendingToken: this.pendingToken,\r\n providerId: this.providerId,\r\n signInMethod: this.signInMethod\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod } = obj, rest = __rest(obj, [\"providerId\", \"signInMethod\"]);\r\n if (!providerId || !signInMethod) {\r\n return null;\r\n }\r\n const cred = new OAuthCredential(providerId, signInMethod);\r\n cred.idToken = rest.idToken || undefined;\r\n cred.accessToken = rest.accessToken || undefined;\r\n cred.secret = rest.secret;\r\n cred.nonce = rest.nonce;\r\n cred.pendingToken = rest.pendingToken || null;\r\n return cred;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n buildRequest() {\r\n const request = {\r\n requestUri: IDP_REQUEST_URI$1,\r\n returnSecureToken: true\r\n };\r\n if (this.pendingToken) {\r\n request.pendingToken = this.pendingToken;\r\n }\r\n else {\r\n const postBody = {};\r\n if (this.idToken) {\r\n postBody['id_token'] = this.idToken;\r\n }\r\n if (this.accessToken) {\r\n postBody['access_token'] = this.accessToken;\r\n }\r\n if (this.secret) {\r\n postBody['oauth_token_secret'] = this.secret;\r\n }\r\n postBody['providerId'] = this.providerId;\r\n if (this.nonce && !this.pendingToken) {\r\n postBody['nonce'] = this.nonce;\r\n }\r\n request.postBody = querystring(postBody);\r\n }\r\n return request;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function sendPhoneVerificationCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendVerificationCode\" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithPhoneNumber$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function linkWithPhoneNumber$1(auth, request) {\r\n const response = await _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n if (response.temporaryProof) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, response);\r\n }\r\n return response;\r\n}\r\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */\r\n};\r\nasync function verifyPhoneNumberForExisting(auth, request) {\r\n const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents the credentials returned by {@link PhoneAuthProvider}.\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"phone\" /* ProviderId.PHONE */, \"phone\" /* SignInMethod.PHONE */);\r\n this.params = params;\r\n }\r\n /** @internal */\r\n static _fromVerification(verificationId, verificationCode) {\r\n return new PhoneAuthCredential({ verificationId, verificationCode });\r\n }\r\n /** @internal */\r\n static _fromTokenResponse(phoneNumber, temporaryProof) {\r\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _makeVerificationRequest() {\r\n const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;\r\n if (temporaryProof && phoneNumber) {\r\n return { temporaryProof, phoneNumber };\r\n }\r\n return {\r\n sessionInfo: verificationId,\r\n code: verificationCode\r\n };\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n const obj = {\r\n providerId: this.providerId\r\n };\r\n if (this.params.phoneNumber) {\r\n obj.phoneNumber = this.params.phoneNumber;\r\n }\r\n if (this.params.temporaryProof) {\r\n obj.temporaryProof = this.params.temporaryProof;\r\n }\r\n if (this.params.verificationCode) {\r\n obj.verificationCode = this.params.verificationCode;\r\n }\r\n if (this.params.verificationId) {\r\n obj.verificationId = this.params.verificationId;\r\n }\r\n return obj;\r\n }\r\n /** Generates a phone credential based on a plain object or a JSON string. */\r\n static fromJSON(json) {\r\n if (typeof json === 'string') {\r\n json = JSON.parse(json);\r\n }\r\n const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;\r\n if (!verificationCode &&\r\n !verificationId &&\r\n !phoneNumber &&\r\n !temporaryProof) {\r\n return null;\r\n }\r\n return new PhoneAuthCredential({\r\n verificationId,\r\n verificationCode,\r\n phoneNumber,\r\n temporaryProof\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Maps the mode string in action code URL to Action Code Info operation.\r\n *\r\n * @param mode\r\n */\r\nfunction parseMode(mode) {\r\n switch (mode) {\r\n case 'recoverEmail':\r\n return \"RECOVER_EMAIL\" /* ActionCodeOperation.RECOVER_EMAIL */;\r\n case 'resetPassword':\r\n return \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */;\r\n case 'signIn':\r\n return \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n case 'verifyEmail':\r\n return \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */;\r\n case 'verifyAndChangeEmail':\r\n return \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;\r\n case 'revertSecondFactorAddition':\r\n return \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;\r\n default:\r\n return null;\r\n }\r\n}\r\n/**\r\n * Helper to parse FDL links\r\n *\r\n * @param url\r\n */\r\nfunction parseDeepLink(url) {\r\n const link = querystringDecode(extractQuerystring(url))['link'];\r\n // Double link case (automatic redirect).\r\n const doubleDeepLink = link\r\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\r\n : null;\r\n // iOS custom scheme links.\r\n const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];\r\n const iOSDoubleDeepLink = iOSDeepLink\r\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\r\n : null;\r\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\r\n}\r\n/**\r\n * A utility class to parse email action URLs such as password reset, email verification,\r\n * email link sign in, etc.\r\n *\r\n * @public\r\n */\r\nclass ActionCodeURL {\r\n /**\r\n * @param actionLink - The link from which to extract the URL.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @internal\r\n */\r\n constructor(actionLink) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const searchParams = querystringDecode(extractQuerystring(actionLink));\r\n const apiKey = (_a = searchParams[\"apiKey\" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;\r\n const code = (_b = searchParams[\"oobCode\" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;\r\n const operation = parseMode((_c = searchParams[\"mode\" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);\r\n // Validate API key, code and mode.\r\n _assert(apiKey && code && operation, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.apiKey = apiKey;\r\n this.operation = operation;\r\n this.code = code;\r\n this.continueUrl = (_d = searchParams[\"continueUrl\" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;\r\n this.languageCode = (_e = searchParams[\"languageCode\" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;\r\n this.tenantId = (_f = searchParams[\"tenantId\" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;\r\n }\r\n /**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\r\n * otherwise returns null.\r\n *\r\n * @param link - The email action link string.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @public\r\n */\r\n static parseLink(link) {\r\n const actionLink = parseDeepLink(link);\r\n try {\r\n return new ActionCodeURL(actionLink);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if\r\n * the link is valid, otherwise returns null.\r\n *\r\n * @public\r\n */\r\nfunction parseActionCodeURL(link) {\r\n return ActionCodeURL.parseLink(link);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating {@link EmailAuthCredential}.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthProvider {\r\n constructor() {\r\n /**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\n this.providerId = EmailAuthProvider.PROVIDER_ID;\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and password.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credential(email, password);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\r\n * ```\r\n *\r\n * @param email - Email address.\r\n * @param password - User account password.\r\n * @returns The auth provider credential.\r\n */\r\n static credential(email, password) {\r\n return EmailAuthCredential._fromEmailAndPassword(email, password);\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\r\n * email link operation.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * await sendSignInLinkToEmail(auth, email);\r\n * // Obtain emailLink from user.\r\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance used to verify the link.\r\n * @param email - Email address.\r\n * @param emailLink - Sign-in email link.\r\n * @returns - The auth provider credential.\r\n */\r\n static credentialWithLink(email, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n _assert(actionCodeUrl, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);\r\n }\r\n}\r\n/**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\nEmailAuthProvider.PROVIDER_ID = \"password\" /* ProviderId.PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\r\n */\r\nEmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = \"password\" /* SignInMethod.EMAIL_PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_LINK.\r\n */\r\nEmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = \"emailLink\" /* SignInMethod.EMAIL_LINK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\r\n *\r\n * This class is not meant to be instantiated directly.\r\n *\r\n * @public\r\n */\r\nclass FederatedAuthProvider {\r\n /**\r\n * Constructor for generic OAuth providers.\r\n *\r\n * @param providerId - Provider for which credentials should be generated.\r\n */\r\n constructor(providerId) {\r\n this.providerId = providerId;\r\n /** @internal */\r\n this.defaultLanguageCode = null;\r\n /** @internal */\r\n this.customParameters = {};\r\n }\r\n /**\r\n * Set the language gode.\r\n *\r\n * @param languageCode - language code\r\n */\r\n setDefaultLanguage(languageCode) {\r\n this.defaultLanguageCode = languageCode;\r\n }\r\n /**\r\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\r\n * operations.\r\n *\r\n * @remarks\r\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\r\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\r\n *\r\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\r\n */\r\n setCustomParameters(customOAuthParameters) {\r\n this.customParameters = customOAuthParameters;\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of {@link CustomParameters}.\r\n */\r\n getCustomParameters() {\r\n return this.customParameters;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Common code to all OAuth providers. This is separate from the\r\n * {@link OAuthProvider} so that child providers (like\r\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\r\n * Instead, they rely on a static `credential` method.\r\n */\r\nclass BaseOAuthProvider extends FederatedAuthProvider {\r\n constructor() {\r\n super(...arguments);\r\n /** @internal */\r\n this.scopes = [];\r\n }\r\n /**\r\n * Add an OAuth scope to the credential.\r\n *\r\n * @param scope - Provider OAuth scope to add.\r\n */\r\n addScope(scope) {\r\n // If not already added, add scope to list.\r\n if (!this.scopes.includes(scope)) {\r\n this.scopes.push(scope);\r\n }\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of OAuth scopes.\r\n */\r\n getScopes() {\r\n return [...this.scopes];\r\n }\r\n}\r\n/**\r\n * Provider for generating generic {@link OAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new OAuthProvider('google.com');\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new OAuthProvider('google.com');\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass OAuthProvider extends BaseOAuthProvider {\r\n /**\r\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n _assert('providerId' in obj && 'signInMethod' in obj, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return OAuthCredential._fromParams(obj);\r\n }\r\n /**\r\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\r\n *\r\n * @remarks\r\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\r\n * the raw nonce must match the nonce field in the ID token.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `googleUser` from the onsuccess Google Sign In callback.\r\n * // Initialize a generate OAuth provider with a `google.com` providerId.\r\n * const provider = new OAuthProvider('google.com');\r\n * const credential = provider.credential({\r\n * idToken: googleUser.getAuthResponse().id_token,\r\n * });\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param params - Either the options object containing the ID token, access token and raw nonce\r\n * or the ID token string.\r\n */\r\n credential(params) {\r\n return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));\r\n }\r\n /** An internal credential method that accepts more permissive options */\r\n _credential(params) {\r\n _assert(params.idToken || params.accessToken, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n // For OAuthCredential, sign in method is same as providerId.\r\n return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;\r\n if (!oauthAccessToken &&\r\n !oauthTokenSecret &&\r\n !oauthIdToken &&\r\n !pendingToken) {\r\n return null;\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n try {\r\n return new OAuthProvider(providerId)._credential({\r\n idToken: oauthIdToken,\r\n accessToken: oauthAccessToken,\r\n nonce,\r\n pendingToken\r\n });\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('user_birthday');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * provider.addScope('user_birthday');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass FacebookAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"facebook.com\" /* ProviderId.FACEBOOK */);\r\n }\r\n /**\r\n * Creates a credential for Facebook.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `event` from the Facebook auth.authResponseChange callback.\r\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param accessToken - Facebook access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: FacebookAuthProvider.PROVIDER_ID,\r\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return FacebookAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.FACEBOOK. */\r\nFacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = \"facebook.com\" /* SignInMethod.FACEBOOK */;\r\n/** Always set to {@link ProviderId}.FACEBOOK. */\r\nFacebookAuthProvider.PROVIDER_ID = \"facebook.com\" /* ProviderId.FACEBOOK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GoogleAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GoogleAuthProvider();\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass GoogleAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"google.com\" /* ProviderId.GOOGLE */);\r\n this.addScope('profile');\r\n }\r\n /**\r\n * Creates a credential for Google. At least one of ID token and access token is required.\r\n *\r\n * @example\r\n * ```javascript\r\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\r\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param idToken - Google ID token.\r\n * @param accessToken - Google access token.\r\n */\r\n static credential(idToken, accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GoogleAuthProvider.PROVIDER_ID,\r\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\r\n idToken,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GoogleAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken } = tokenResponse;\r\n if (!oauthIdToken && !oauthAccessToken) {\r\n // This could be an oauth 1 credential or a phone credential\r\n return null;\r\n }\r\n try {\r\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GOOGLE. */\r\nGoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = \"google.com\" /* SignInMethod.GOOGLE */;\r\n/** Always set to {@link ProviderId}.GOOGLE. */\r\nGoogleAuthProvider.PROVIDER_ID = \"google.com\" /* ProviderId.GOOGLE */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\r\n *\r\n * @remarks\r\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\r\n * the {@link signInWithPopup} handler:\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GithubAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('repo');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GithubAuthProvider();\r\n * provider.addScope('repo');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass GithubAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"github.com\" /* ProviderId.GITHUB */);\r\n }\r\n /**\r\n * Creates a credential for Github.\r\n *\r\n * @param accessToken - Github access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GithubAuthProvider.PROVIDER_ID,\r\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GithubAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GITHUB. */\r\nGithubAuthProvider.GITHUB_SIGN_IN_METHOD = \"github.com\" /* SignInMethod.GITHUB */;\r\n/** Always set to {@link ProviderId}.GITHUB. */\r\nGithubAuthProvider.PROVIDER_ID = \"github.com\" /* ProviderId.GITHUB */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI = 'http://localhost';\r\n/**\r\n * @public\r\n */\r\nclass SAMLAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(providerId, pendingToken) {\r\n super(providerId, providerId);\r\n this.pendingToken = pendingToken;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n signInMethod: this.signInMethod,\r\n providerId: this.providerId,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod, pendingToken } = obj;\r\n if (!providerId ||\r\n !signInMethod ||\r\n !pendingToken ||\r\n providerId !== signInMethod) {\r\n return null;\r\n }\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n /**\r\n * Helper static method to avoid exposing the constructor to end users.\r\n *\r\n * @internal\r\n */\r\n static _create(providerId, pendingToken) {\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n buildRequest() {\r\n return {\r\n requestUri: IDP_REQUEST_URI,\r\n returnSecureToken: true,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SAML_PROVIDER_PREFIX = 'saml.';\r\n/**\r\n * An {@link AuthProvider} for SAML.\r\n *\r\n * @public\r\n */\r\nclass SAMLAuthProvider extends FederatedAuthProvider {\r\n /**\r\n * Constructor. The providerId must start with \"saml.\"\r\n * @param providerId - SAML provider ID.\r\n */\r\n constructor(providerId) {\r\n _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n super(providerId);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\r\n * successful SAML flow completes.\r\n *\r\n * @remarks\r\n *\r\n * For example, to get an {@link AuthCredential}, you could write the\r\n * following code:\r\n *\r\n * ```js\r\n * const userCredential = await signInWithPopup(auth, samlProvider);\r\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\r\n * ```\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n /**\r\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const credential = SAMLAuthCredential.fromJSON(json);\r\n _assert(credential, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return credential;\r\n }\r\n static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { pendingToken, providerId } = tokenResponse;\r\n if (!pendingToken || !providerId) {\r\n return null;\r\n }\r\n try {\r\n return SAMLAuthCredential._create(providerId, pendingToken);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new TwitterAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new TwitterAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass TwitterAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"twitter.com\" /* ProviderId.TWITTER */);\r\n }\r\n /**\r\n * Creates a credential for Twitter.\r\n *\r\n * @param token - Twitter access token.\r\n * @param secret - Twitter secret.\r\n */\r\n static credential(token, secret) {\r\n return OAuthCredential._fromParams({\r\n providerId: TwitterAuthProvider.PROVIDER_ID,\r\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\r\n oauthToken: token,\r\n oauthTokenSecret: secret\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return TwitterAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthAccessToken, oauthTokenSecret } = tokenResponse;\r\n if (!oauthAccessToken || !oauthTokenSecret) {\r\n return null;\r\n }\r\n try {\r\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.TWITTER. */\r\nTwitterAuthProvider.TWITTER_SIGN_IN_METHOD = \"twitter.com\" /* SignInMethod.TWITTER */;\r\n/** Always set to {@link ProviderId}.TWITTER. */\r\nTwitterAuthProvider.PROVIDER_ID = \"twitter.com\" /* ProviderId.TWITTER */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signUp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserCredentialImpl {\r\n constructor(params) {\r\n this.user = params.user;\r\n this.providerId = params.providerId;\r\n this._tokenResponse = params._tokenResponse;\r\n this.operationType = params.operationType;\r\n }\r\n static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {\r\n const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);\r\n const providerId = providerIdForResponse(idTokenResponse);\r\n const userCred = new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: idTokenResponse,\r\n operationType\r\n });\r\n return userCred;\r\n }\r\n static async _forOperation(user, operationType, response) {\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n const providerId = providerIdForResponse(response);\r\n return new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: response,\r\n operationType\r\n });\r\n }\r\n}\r\nfunction providerIdForResponse(response) {\r\n if (response.providerId) {\r\n return response.providerId;\r\n }\r\n if ('phoneNumber' in response) {\r\n return \"phone\" /* ProviderId.PHONE */;\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in as an anonymous user.\r\n *\r\n * @remarks\r\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\r\n * new anonymous user identity will be created and returned.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nasync function signInAnonymously(auth) {\r\n var _a;\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n await authInternal._initializationPromise;\r\n if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {\r\n // If an anonymous user is already signed in, no need to sign them in again.\r\n return new UserCredentialImpl({\r\n user: authInternal.currentUser,\r\n providerId: null,\r\n operationType: \"signIn\" /* OperationType.SIGN_IN */\r\n });\r\n }\r\n const response = await signUp(authInternal, {\r\n returnSecureToken: true\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response, true);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorError extends FirebaseError {\r\n constructor(auth, error, operationType, user) {\r\n var _a;\r\n super(error.code, error.message);\r\n this.operationType = operationType;\r\n this.user = user;\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, MultiFactorError.prototype);\r\n this.customData = {\r\n appName: auth.name,\r\n tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,\r\n _serverResponse: error.customData._serverResponse,\r\n operationType\r\n };\r\n }\r\n static _fromErrorAndOperation(auth, error, operationType, user) {\r\n return new MultiFactorError(auth, error, operationType, user);\r\n }\r\n}\r\nfunction _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {\r\n const idTokenProvider = operationType === \"reauthenticate\" /* OperationType.REAUTHENTICATE */\r\n ? credential._getReauthenticationResolver(auth)\r\n : credential._getIdTokenResponse(auth);\r\n return idTokenProvider.catch(error => {\r\n if (error.code === `auth/${\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */}`) {\r\n throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);\r\n }\r\n throw error;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Takes a set of UserInfo provider data and converts it to a set of names\r\n */\r\nfunction providerDataAsNames(providerData) {\r\n return new Set(providerData\r\n .map(({ providerId }) => providerId)\r\n .filter(pid => !!pid));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Unlinks a provider from a user account.\r\n *\r\n * @param user - The user.\r\n * @param providerId - The provider to unlink.\r\n *\r\n * @public\r\n */\r\nasync function unlink(user, providerId) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(true, userInternal, providerId);\r\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\r\n idToken: await userInternal.getIdToken(),\r\n deleteProvider: [providerId]\r\n });\r\n const providersLeft = providerDataAsNames(providerUserInfo || []);\r\n userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));\r\n if (!providersLeft.has(\"phone\" /* ProviderId.PHONE */)) {\r\n userInternal.phoneNumber = null;\r\n }\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n return userInternal;\r\n}\r\nasync function _link$1(user, credential, bypassAuthState = false) {\r\n const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);\r\n return UserCredentialImpl._forOperation(user, \"link\" /* OperationType.LINK */, response);\r\n}\r\nasync function _assertLinkedStatus(expected, user, provider) {\r\n await _reloadWithoutSaving(user);\r\n const providerIds = providerDataAsNames(user.providerData);\r\n const code = expected === false\r\n ? \"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */\r\n : \"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */;\r\n _assert(providerIds.has(provider) === expected, user.auth, code);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reauthenticate(user, credential, bypassAuthState = false) {\r\n const { auth } = user;\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const operationType = \"reauthenticate\" /* OperationType.REAUTHENTICATE */;\r\n try {\r\n const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);\r\n _assert(response.idToken, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const parsed = _parseToken(response.idToken);\r\n _assert(parsed, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const { sub: localId } = parsed;\r\n _assert(user.uid === localId, auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n return UserCredentialImpl._forOperation(user, operationType, response);\r\n }\r\n catch (e) {\r\n // Convert user deleted error into user mismatch\r\n if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${\"user-not-found\" /* AuthErrorCode.USER_DELETED */}`) {\r\n _fail(auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n }\r\n throw e;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _signInWithCredential(auth, credential, bypassAuthState = false) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const operationType = \"signIn\" /* OperationType.SIGN_IN */;\r\n const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);\r\n if (!bypassAuthState) {\r\n await auth._updateCurrentUser(userCredential.user);\r\n }\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCredential(auth, credential) {\r\n return _signInWithCredential(_castAuth(auth), credential);\r\n}\r\n/**\r\n * Links the user account with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function linkWithCredential(user, credential) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, credential.providerId);\r\n return _link$1(userInternal, credential);\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\r\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\r\n * or a `TOKEN_EXPIRED` error.\r\n *\r\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithCredential(user, credential) {\r\n return _reauthenticate(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithCustomToken$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithCustomToken\" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in using a custom token.\r\n *\r\n * @remarks\r\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\r\n * be generated by an auth backend using the\r\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\r\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\r\n *\r\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param customToken - The custom token to sign in with.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCustomToken(auth, customToken) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const response = await signInWithCustomToken$1(authInternal, {\r\n token: customToken,\r\n returnSecureToken: true\r\n });\r\n const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(cred.user);\r\n return cred;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorInfoImpl {\r\n constructor(factorId, response) {\r\n this.factorId = factorId;\r\n this.uid = response.mfaEnrollmentId;\r\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\r\n this.displayName = response.displayName;\r\n }\r\n static _fromServerResponse(auth, enrollment) {\r\n if ('phoneInfo' in enrollment) {\r\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n else if ('totpInfo' in enrollment) {\r\n return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n return _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n}\r\nclass PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"phone\" /* FactorId.PHONE */, response);\r\n this.phoneNumber = response.phoneInfo;\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new PhoneMultiFactorInfoImpl(enrollment);\r\n }\r\n}\r\nclass TotpMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"totp\" /* FactorId.TOTP */, response);\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new TotpMultiFactorInfoImpl(enrollment);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {\r\n var _a;\r\n _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, \"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */);\r\n _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\r\n actionCodeSettings.dynamicLinkDomain.length > 0, auth, \"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);\r\n request.continueUrl = actionCodeSettings.url;\r\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\r\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\r\n if (actionCodeSettings.iOS) {\r\n _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, \"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);\r\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\r\n }\r\n if (actionCodeSettings.android) {\r\n _assert(actionCodeSettings.android.packageName.length > 0, auth, \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);\r\n request.androidInstallApp = actionCodeSettings.android.installApp;\r\n request.androidMinimumVersionCode =\r\n actionCodeSettings.android.minimumVersion;\r\n request.androidPackageName = actionCodeSettings.android.packageName;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\r\n * cached for the project or tenant.\r\n *\r\n * @remarks\r\n * We only fetch the password policy if the password did not meet policy requirements and\r\n * there is an existing policy cached. A developer must call validatePassword at least\r\n * once for the cache to be automatically updated.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @private\r\n */\r\nasync function recachePasswordPolicy(auth) {\r\n const authInternal = _castAuth(auth);\r\n if (authInternal._getPasswordPolicyInternal()) {\r\n await authInternal._updatePasswordPolicy();\r\n }\r\n}\r\n/**\r\n * Sends a password reset email to the given email address. This method does not throw an error when\r\n * there's no user account with the given email address and\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled.\r\n *\r\n * @remarks\r\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\r\n * the email sent to the user, along with the new password specified by the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain code from user.\r\n * await confirmPasswordReset('user@example.com', code);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendPasswordResetEmail(auth, email, actionCodeSettings) {\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendPasswordResetEmail$1);\r\n}\r\n/**\r\n * Completes the password reset process, given a confirmation code and new password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A confirmation code sent to the user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nasync function confirmPasswordReset(auth, oobCode, newPassword) {\r\n await resetPassword(getModularInstance(auth), {\r\n oobCode,\r\n newPassword\r\n })\r\n .catch(async (error) => {\r\n if (error.code ===\r\n `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\r\n });\r\n // Do not return the email.\r\n}\r\n/**\r\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function applyActionCode(auth, oobCode) {\r\n await applyActionCode$1(getModularInstance(auth), { oobCode });\r\n}\r\n/**\r\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns metadata about the code.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function checkActionCode(auth, oobCode) {\r\n const authModular = getModularInstance(auth);\r\n const response = await resetPassword(authModular, { oobCode });\r\n // Email could be empty only if the request type is EMAIL_SIGNIN or\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // New email should not be empty if the request type is\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // Multi-factor info could not be empty if the request type is\r\n // REVERT_SECOND_FACTOR_ADDITION.\r\n const operation = response.requestType;\r\n _assert(operation, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n switch (operation) {\r\n case \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */:\r\n break;\r\n case \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:\r\n _assert(response.newEmail, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n break;\r\n case \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:\r\n _assert(response.mfaInfo, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // fall through\r\n default:\r\n _assert(response.email, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n // The multi-factor info for revert second factor addition\r\n let multiFactorInfo = null;\r\n if (response.mfaInfo) {\r\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);\r\n }\r\n return {\r\n data: {\r\n email: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.newEmail\r\n : response.email) || null,\r\n previousEmail: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.email\r\n : response.newEmail) || null,\r\n multiFactorInfo\r\n },\r\n operation\r\n };\r\n}\r\n/**\r\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns the user's email address if valid.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param code - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function verifyPasswordResetCode(auth, code) {\r\n const { data } = await checkActionCode(getModularInstance(auth), code);\r\n // Email should always be present since a code was sent to it\r\n return data.email;\r\n}\r\n/**\r\n * Creates a new user account associated with the specified email address and password.\r\n *\r\n * @remarks\r\n * On successful creation of the user account, this user will also be signed in to your application.\r\n *\r\n * User account creation can fail if the account already exists or the password is invalid.\r\n *\r\n * This method is not supported on {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Note: The email address acts as a unique identifier for the user and enables an email-based\r\n * password reset. This function will create a new user account and set the initial user password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param password - The user's chosen password.\r\n *\r\n * @public\r\n */\r\nasync function createUserWithEmailAndPassword(auth, email, password) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n returnSecureToken: true,\r\n email,\r\n password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n const signUpResponse = handleRecaptchaFlow(authInternal, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, signUp);\r\n const response = await signUpResponse.catch(error => {\r\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and password.\r\n *\r\n * @remarks\r\n * Fails with an error if the email address and password do not match. When\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled, this method fails with \"auth/invalid-credential\" in case of an invalid\r\n * email/password.\r\n *\r\n * This method is not supported on {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Note: The user's password is NOT the password used to access the user's email account. The\r\n * email address serves as a unique identifier for the user, and the password is used to access\r\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\r\n *\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The users email address.\r\n * @param password - The users password.\r\n *\r\n * @public\r\n */\r\nfunction signInWithEmailAndPassword(auth, email, password) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password)).catch(async (error) => {\r\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a sign-in email link to the user with the specified email.\r\n *\r\n * @remarks\r\n * The sign-in operation has to always be completed in the app unlike other out of band email\r\n * actions (password reset and email verifications). This is because, at the end of the flow,\r\n * the user is expected to be signed in and their Auth state persisted within the app.\r\n *\r\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\r\n * address and the email link supplied in the email sent to the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param authInternal - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendSignInLinkToEmail(auth, email, actionCodeSettings) {\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n function setActionCodeSettings(request, actionCodeSettings) {\r\n _assert(actionCodeSettings.handleCodeInApp, authInternal, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n }\r\n setActionCodeSettings(request, actionCodeSettings);\r\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendSignInLinkToEmail$1);\r\n}\r\n/**\r\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nfunction isSignInWithEmailLink(auth, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and sign-in email link.\r\n *\r\n * @remarks\r\n * If no link is passed, the link is inferred from the current URL.\r\n *\r\n * Fails with an error if the email address is invalid or OTP in email link expires.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nasync function signInWithEmailLink(auth, email, emailLink) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authModular = getModularInstance(auth);\r\n const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());\r\n // Check if the tenant ID in the email link matches the tenant ID on Auth\r\n // instance.\r\n _assert(credential._tenantId === (authModular.tenantId || null), authModular, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n return signInWithCredential(authModular, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createAuthUri(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:createAuthUri\" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Gets the list of possible sign in methods for the given email address. This method returns an\r\n * empty list when\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled, irrespective of the number of authentication methods available for the given email.\r\n *\r\n * @remarks\r\n * This is useful to differentiate methods of sign-in for the same provider, eg.\r\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\r\n * {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n *\r\n * Deprecated. Migrating off of this method is recommended as a security best-practice.\r\n * Learn more in the Identity Platform documentation for\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}.\r\n * @public\r\n */\r\nasync function fetchSignInMethodsForEmail(auth, email) {\r\n // createAuthUri returns an error if continue URI is not http or https.\r\n // For environments like Cordova, Chrome extensions, native frameworks, file\r\n // systems, etc, use http://localhost as continue URL.\r\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\r\n const request = {\r\n identifier: email,\r\n continueUri\r\n };\r\n const { signinMethods } = await createAuthUri(getModularInstance(auth), request);\r\n return signinMethods || [];\r\n}\r\n/**\r\n * Sends a verification email to a user.\r\n *\r\n * @remarks\r\n * The verification process is completed by calling {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendEmailVerification(user, actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendEmailVerification(user, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */,\r\n idToken\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await sendEmailVerification$1(userInternal.auth, request);\r\n if (email !== user.email) {\r\n await user.reload();\r\n }\r\n}\r\n/**\r\n * Sends a verification email to a new email address.\r\n *\r\n * @remarks\r\n * The user's email will be updated to the new one after being verified.\r\n *\r\n * If you have a custom email action handler, you can complete the verification process by calling\r\n * {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address to be verified before update.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,\r\n idToken,\r\n newEmail\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await verifyAndChangeEmail(userInternal.auth, request);\r\n if (email !== user.email) {\r\n // If the local copy of the email on user is outdated, reload the\r\n // user.\r\n await user.reload();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateProfile$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates a user's profile data.\r\n *\r\n * @param user - The user.\r\n * @param profile - The profile's `displayName` and `photoURL` to update.\r\n *\r\n * @public\r\n */\r\nasync function updateProfile(user, { displayName, photoURL: photoUrl }) {\r\n if (displayName === undefined && photoUrl === undefined) {\r\n return;\r\n }\r\n const userInternal = getModularInstance(user);\r\n const idToken = await userInternal.getIdToken();\r\n const profileRequest = {\r\n idToken,\r\n displayName,\r\n photoUrl,\r\n returnSecureToken: true\r\n };\r\n const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));\r\n userInternal.displayName = response.displayName || null;\r\n userInternal.photoURL = response.photoUrl || null;\r\n // Update the password provider as well\r\n const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === \"password\" /* ProviderId.PASSWORD */);\r\n if (passwordProvider) {\r\n passwordProvider.displayName = userInternal.displayName;\r\n passwordProvider.photoURL = userInternal.photoURL;\r\n }\r\n await userInternal._updateTokensIfNecessary(response);\r\n}\r\n/**\r\n * Updates the user's email address.\r\n *\r\n * @remarks\r\n * An email will be sent to the original email address (if it was set) that allows to revoke the\r\n * email address change, in order to protect them from account hijacking.\r\n *\r\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address.\r\n *\r\n * Throws \"auth/operation-not-allowed\" error when\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled.\r\n * Deprecated - Use {@link verifyBeforeUpdateEmail} instead.\r\n *\r\n * @public\r\n */\r\nfunction updateEmail(user, newEmail) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n return updateEmailOrPassword(userInternal, newEmail, null);\r\n}\r\n/**\r\n * Updates the user's password.\r\n *\r\n * @remarks\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nfunction updatePassword(user, newPassword) {\r\n return updateEmailOrPassword(getModularInstance(user), null, newPassword);\r\n}\r\nasync function updateEmailOrPassword(user, email, password) {\r\n const { auth } = user;\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n idToken,\r\n returnSecureToken: true\r\n };\r\n if (email) {\r\n request.email = email;\r\n }\r\n if (password) {\r\n request.password = password;\r\n }\r\n const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Parse the `AdditionalUserInfo` from the ID token response.\r\n *\r\n */\r\nfunction _fromIdTokenResponse(idTokenResponse) {\r\n var _a, _b;\r\n if (!idTokenResponse) {\r\n return null;\r\n }\r\n const { providerId } = idTokenResponse;\r\n const profile = idTokenResponse.rawUserInfo\r\n ? JSON.parse(idTokenResponse.rawUserInfo)\r\n : {};\r\n const isNewUser = idTokenResponse.isNewUser ||\r\n idTokenResponse.kind === \"identitytoolkit#SignupNewUserResponse\" /* IdTokenResponseKind.SignupNewUser */;\r\n if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {\r\n const signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];\r\n if (signInProvider) {\r\n const filteredProviderId = signInProvider !== \"anonymous\" /* ProviderId.ANONYMOUS */ &&\r\n signInProvider !== \"custom\" /* ProviderId.CUSTOM */\r\n ? signInProvider\r\n : null;\r\n // Uses generic class in accordance with the legacy SDK.\r\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\r\n }\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n switch (providerId) {\r\n case \"facebook.com\" /* ProviderId.FACEBOOK */:\r\n return new FacebookAdditionalUserInfo(isNewUser, profile);\r\n case \"github.com\" /* ProviderId.GITHUB */:\r\n return new GithubAdditionalUserInfo(isNewUser, profile);\r\n case \"google.com\" /* ProviderId.GOOGLE */:\r\n return new GoogleAdditionalUserInfo(isNewUser, profile);\r\n case \"twitter.com\" /* ProviderId.TWITTER */:\r\n return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);\r\n case \"custom\" /* ProviderId.CUSTOM */:\r\n case \"anonymous\" /* ProviderId.ANONYMOUS */:\r\n return new GenericAdditionalUserInfo(isNewUser, null);\r\n default:\r\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\r\n }\r\n}\r\nclass GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile = {}) {\r\n this.isNewUser = isNewUser;\r\n this.providerId = providerId;\r\n this.profile = profile;\r\n }\r\n}\r\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile, username) {\r\n super(isNewUser, providerId, profile);\r\n this.username = username;\r\n }\r\n}\r\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"facebook.com\" /* ProviderId.FACEBOOK */, profile);\r\n }\r\n}\r\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"github.com\" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null);\r\n }\r\n}\r\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"google.com\" /* ProviderId.GOOGLE */, profile);\r\n }\r\n}\r\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile, screenName) {\r\n super(isNewUser, \"twitter.com\" /* ProviderId.TWITTER */, profile, screenName);\r\n }\r\n}\r\n/**\r\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\r\n *\r\n * @param userCredential - The user credential.\r\n *\r\n * @public\r\n */\r\nfunction getAdditionalUserInfo(userCredential) {\r\n const { user, _tokenResponse } = userCredential;\r\n if (user.isAnonymous && !_tokenResponse) {\r\n // Handle the special case where signInAnonymously() gets called twice.\r\n // No network call is made so there's nothing to actually fill this in\r\n return {\r\n providerId: null,\r\n isNewUser: false,\r\n profile: null\r\n };\r\n }\r\n return _fromIdTokenResponse(_tokenResponse);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Non-optional auth methods.\r\n/**\r\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\r\n * `Auth` session and applies this type of persistence for future sign-in requests, including\r\n * sign-in with redirect requests.\r\n *\r\n * @remarks\r\n * This makes it easy for a user signing in to specify whether their session should be\r\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\r\n * that are shared by other users or have sensitive data.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * setPersistence(auth, browserSessionPersistence);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param persistence - The {@link Persistence} to use.\r\n * @returns A `Promise` that resolves once the persistence change has completed\r\n *\r\n * @public\r\n */\r\nfunction setPersistence(auth, persistence) {\r\n return getModularInstance(auth).setPersistence(persistence);\r\n}\r\n/**\r\n * Loads the reCAPTCHA configuration into the `Auth` instance.\r\n *\r\n * @remarks\r\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\r\n * verification flow should be triggered for each auth provider, into the\r\n * current Auth session.\r\n *\r\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\r\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\r\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\r\n * auth flows.\r\n *\r\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\r\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * initializeRecaptchaConfig(auth);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction initializeRecaptchaConfig(auth) {\r\n return _initializeRecaptchaConfig(auth);\r\n}\r\n/**\r\n * Validates the password against the password policy configured for the project or tenant.\r\n *\r\n * @remarks\r\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\r\n * policy configured for the project. Otherwise, this method will use the policy configured\r\n * for the tenant. If a password policy has not been configured, then the default policy\r\n * configured for all projects will be used.\r\n *\r\n * If an auth flow fails because a submitted password does not meet the password policy\r\n * requirements and this method has previously been called, then this method will use the\r\n * most recent policy available when called again.\r\n *\r\n * @example\r\n * ```javascript\r\n * validatePassword(auth, 'some-password');\r\n * ```\r\n *\r\n * @param auth The {@link Auth} instance.\r\n * @param password The password to validate.\r\n *\r\n * @public\r\n */\r\nasync function validatePassword(auth, password) {\r\n const authInternal = _castAuth(auth);\r\n return authInternal.validatePassword(password);\r\n}\r\n/**\r\n * Adds an observer for changes to the signed-in user's ID token.\r\n *\r\n * @remarks\r\n * This includes sign-in, sign-out, and token refresh events.\r\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onIdTokenChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Adds a blocking callback that runs before an auth state change\r\n * sets a new user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param callback - callback triggered before new user value is set.\r\n * If this throws, it blocks the user from being set.\r\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\r\n * callback throws, allowing you to undo any side effects.\r\n */\r\nfunction beforeAuthStateChanged(auth, callback, onAbort) {\r\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\r\n}\r\n/**\r\n * Adds an observer for changes to the user's sign-in state.\r\n *\r\n * @remarks\r\n * To keep the old behavior, see {@link onIdTokenChanged}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onAuthStateChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Sets the current language to the default device/browser preference.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction useDeviceLanguage(auth) {\r\n getModularInstance(auth).useDeviceLanguage();\r\n}\r\n/**\r\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\r\n * {@link Auth} instance.\r\n *\r\n * @remarks\r\n * A new instance copy of the user provided will be made and set as currentUser.\r\n *\r\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\r\n * like other sign in methods.\r\n *\r\n * The operation fails with an error if the user to be updated belongs to a different Firebase\r\n * project.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param user - The new {@link User}.\r\n *\r\n * @public\r\n */\r\nfunction updateCurrentUser(auth, user) {\r\n return getModularInstance(auth).updateCurrentUser(user);\r\n}\r\n/**\r\n * Signs out the current user.\r\n *\r\n * @remarks\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction signOut(auth) {\r\n return getModularInstance(auth).signOut();\r\n}\r\n/**\r\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param token - The Apple OAuth access token.\r\n *\r\n * @public\r\n */\r\nfunction revokeAccessToken(auth, token) {\r\n const authInternal = _castAuth(auth);\r\n return authInternal.revokeAccessToken(token);\r\n}\r\n/**\r\n * Deletes and signs out the user.\r\n *\r\n * @remarks\r\n * Important: this is a security-sensitive operation that requires the user to have recently\r\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function deleteUser(user) {\r\n return getModularInstance(user).delete();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorSessionImpl {\r\n constructor(type, credential, user) {\r\n this.type = type;\r\n this.credential = credential;\r\n this.user = user;\r\n }\r\n static _fromIdtoken(idToken, user) {\r\n return new MultiFactorSessionImpl(\"enroll\" /* MultiFactorSessionType.ENROLL */, idToken, user);\r\n }\r\n static _fromMfaPendingCredential(mfaPendingCredential) {\r\n return new MultiFactorSessionImpl(\"signin\" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);\r\n }\r\n toJSON() {\r\n const key = this.type === \"enroll\" /* MultiFactorSessionType.ENROLL */\r\n ? 'idToken'\r\n : 'pendingCredential';\r\n return {\r\n multiFactorSession: {\r\n [key]: this.credential\r\n }\r\n };\r\n }\r\n static fromJSON(obj) {\r\n var _a, _b;\r\n if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {\r\n if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {\r\n return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);\r\n }\r\n else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {\r\n return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);\r\n }\r\n }\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorResolverImpl {\r\n constructor(session, hints, signInResolver) {\r\n this.session = session;\r\n this.hints = hints;\r\n this.signInResolver = signInResolver;\r\n }\r\n /** @internal */\r\n static _fromError(authExtern, error) {\r\n const auth = _castAuth(authExtern);\r\n const serverResponse = error.customData._serverResponse;\r\n const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));\r\n _assert(serverResponse.mfaPendingCredential, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);\r\n return new MultiFactorResolverImpl(session, hints, async (assertion) => {\r\n const mfaResponse = await assertion._process(auth, session);\r\n // Clear out the unneeded fields from the old login response\r\n delete serverResponse.mfaInfo;\r\n delete serverResponse.mfaPendingCredential;\r\n // Use in the new token & refresh token in the old response\r\n const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });\r\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\r\n switch (error.operationType) {\r\n case \"signIn\" /* OperationType.SIGN_IN */:\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);\r\n await auth._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n case \"reauthenticate\" /* OperationType.REAUTHENTICATE */:\r\n _assert(error.user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n });\r\n }\r\n async resolveSignIn(assertionExtern) {\r\n const assertion = assertionExtern;\r\n return this.signInResolver(assertion);\r\n }\r\n}\r\n/**\r\n * Provides a {@link MultiFactorResolver} suitable for completion of a\r\n * multi-factor flow.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\r\n * reauthentication operation.\r\n *\r\n * @public\r\n */\r\nfunction getMultiFactorResolver(auth, error) {\r\n var _a;\r\n const authModular = getModularInstance(auth);\r\n const errorInternal = error;\r\n _assert(error.customData.operationType, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction startEnrollTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction withdrawMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:withdraw\" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));\r\n}\n\nclass MultiFactorUserImpl {\r\n constructor(user) {\r\n this.user = user;\r\n this.enrolledFactors = [];\r\n user._onReload(userInfo => {\r\n if (userInfo.mfaInfo) {\r\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));\r\n }\r\n });\r\n }\r\n static _fromUser(user) {\r\n return new MultiFactorUserImpl(user);\r\n }\r\n async getSession() {\r\n return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user);\r\n }\r\n async enroll(assertionExtern, displayName) {\r\n const assertion = assertionExtern;\r\n const session = (await this.getSession());\r\n const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));\r\n // New tokens will be issued after enrollment of the new second factors.\r\n // They need to be updated on the user.\r\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\r\n // The user needs to be reloaded to get the new multi-factor information\r\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\r\n // will be updated.\r\n return this.user.reload();\r\n }\r\n async unenroll(infoOrUid) {\r\n const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\r\n const idToken = await this.user.getIdToken();\r\n try {\r\n const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {\r\n idToken,\r\n mfaEnrollmentId\r\n }));\r\n // Remove the second factor from the user's list.\r\n this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);\r\n // Depending on whether the backend decided to revoke the user's session,\r\n // the tokenResponse may be empty. If the tokens were not updated (and they\r\n // are now invalid), reloading the user will discover this and invalidate\r\n // the user's state accordingly.\r\n await this.user._updateTokensIfNecessary(idTokenResponse);\r\n await this.user.reload();\r\n }\r\n catch (e) {\r\n throw e;\r\n }\r\n }\r\n}\r\nconst multiFactorUserCache = new WeakMap();\r\n/**\r\n * The {@link MultiFactorUser} corresponding to the user.\r\n *\r\n * @remarks\r\n * This is used to access all multi-factor properties and operations related to the user.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nfunction multiFactor(user) {\r\n const userModular = getModularInstance(user);\r\n if (!multiFactorUserCache.has(userModular)) {\r\n multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));\r\n }\r\n return multiFactorUserCache.get(userModular);\r\n}\n\nconst STORAGE_AVAILABLE_KEY = '__sak';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// There are two different browser persistence types: local and session.\r\n// Both have the same implementation but use a different underlying storage\r\n// object.\r\nclass BrowserPersistenceClass {\r\n constructor(storageRetriever, type) {\r\n this.storageRetriever = storageRetriever;\r\n this.type = type;\r\n }\r\n _isAvailable() {\r\n try {\r\n if (!this.storage) {\r\n return Promise.resolve(false);\r\n }\r\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\r\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\r\n return Promise.resolve(true);\r\n }\r\n catch (_a) {\r\n return Promise.resolve(false);\r\n }\r\n }\r\n _set(key, value) {\r\n this.storage.setItem(key, JSON.stringify(value));\r\n return Promise.resolve();\r\n }\r\n _get(key) {\r\n const json = this.storage.getItem(key);\r\n return Promise.resolve(json ? JSON.parse(json) : null);\r\n }\r\n _remove(key) {\r\n this.storage.removeItem(key);\r\n return Promise.resolve();\r\n }\r\n get storage() {\r\n return this.storageRetriever();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _iframeCannotSyncWebStorage() {\r\n const ua = getUA();\r\n return _isSafari(ua) || _isIOS(ua);\r\n}\r\n// The polling period in case events are not supported\r\nconst _POLLING_INTERVAL_MS$1 = 1000;\r\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\r\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\r\nclass BrowserLocalPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.localStorage, \"LOCAL\" /* PersistenceType.LOCAL */);\r\n this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n // Safari or iOS browser and embedded in an iframe.\r\n this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();\r\n // Whether to use polling instead of depending on window events\r\n this.fallbackToPolling = _isMobileBrowser();\r\n this._shouldAllowMigration = true;\r\n }\r\n forAllChangedKeys(cb) {\r\n // Check all keys with listeners on them.\r\n for (const key of Object.keys(this.listeners)) {\r\n // Get value from localStorage.\r\n const newValue = this.storage.getItem(key);\r\n const oldValue = this.localCache[key];\r\n // If local map value does not match, trigger listener with storage event.\r\n // Differentiate this simulated event from the real storage event.\r\n if (newValue !== oldValue) {\r\n cb(key, oldValue, newValue);\r\n }\r\n }\r\n }\r\n onStorageEvent(event, poll = false) {\r\n // Key would be null in some situations, like when localStorage is cleared\r\n if (!event.key) {\r\n this.forAllChangedKeys((key, _oldValue, newValue) => {\r\n this.notifyListeners(key, newValue);\r\n });\r\n return;\r\n }\r\n const key = event.key;\r\n // Check the mechanism how this event was detected.\r\n // The first event will dictate the mechanism to be used.\r\n if (poll) {\r\n // Environment detects storage changes via polling.\r\n // Remove storage event listener to prevent possible event duplication.\r\n this.detachListener();\r\n }\r\n else {\r\n // Environment detects storage changes via storage event listener.\r\n // Remove polling listener to prevent possible event duplication.\r\n this.stopPolling();\r\n }\r\n // Safari embedded iframe. Storage event will trigger with the delta\r\n // changes but no changes will be applied to the iframe localStorage.\r\n if (this.safariLocalStorageNotSynced) {\r\n // Get current iframe page value.\r\n const storedValue = this.storage.getItem(key);\r\n // Value not synchronized, synchronize manually.\r\n if (event.newValue !== storedValue) {\r\n if (event.newValue !== null) {\r\n // Value changed from current value.\r\n this.storage.setItem(key, event.newValue);\r\n }\r\n else {\r\n // Current value deleted.\r\n this.storage.removeItem(key);\r\n }\r\n }\r\n else if (this.localCache[key] === event.newValue && !poll) {\r\n // Already detected and processed, do not trigger listeners again.\r\n return;\r\n }\r\n }\r\n const triggerListeners = () => {\r\n // Keep local map up to date in case storage event is triggered before\r\n // poll.\r\n const storedValue = this.storage.getItem(key);\r\n if (!poll && this.localCache[key] === storedValue) {\r\n // Real storage event which has already been detected, do nothing.\r\n // This seems to trigger in some IE browsers for some reason.\r\n return;\r\n }\r\n this.notifyListeners(key, storedValue);\r\n };\r\n const storedValue = this.storage.getItem(key);\r\n if (_isIE10() &&\r\n storedValue !== event.newValue &&\r\n event.newValue !== event.oldValue) {\r\n // IE 10 has this weird bug where a storage event would trigger with the\r\n // correct key, oldValue and newValue but localStorage.getItem(key) does\r\n // not yield the updated value until a few milliseconds. This ensures\r\n // this recovers from that situation.\r\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\r\n }\r\n else {\r\n triggerListeners();\r\n }\r\n }\r\n notifyListeners(key, value) {\r\n this.localCache[key] = value;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(value ? JSON.parse(value) : value);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(() => {\r\n this.forAllChangedKeys((key, oldValue, newValue) => {\r\n this.onStorageEvent(new StorageEvent('storage', {\r\n key,\r\n oldValue,\r\n newValue\r\n }), \r\n /* poll */ true);\r\n });\r\n }, _POLLING_INTERVAL_MS$1);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n attachListener() {\r\n window.addEventListener('storage', this.boundEventHandler);\r\n }\r\n detachListener() {\r\n window.removeEventListener('storage', this.boundEventHandler);\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n // Whether browser can detect storage event when it had already been pushed to the background.\r\n // This may happen in some mobile browsers. A localStorage change in the foreground window\r\n // will not be detected in the background window via the storage event.\r\n // This was detected in iOS 7.x mobile browsers\r\n if (this.fallbackToPolling) {\r\n this.startPolling();\r\n }\r\n else {\r\n this.attachListener();\r\n }\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n this.localCache[key] = this.storage.getItem(key);\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.detachListener();\r\n this.stopPolling();\r\n }\r\n }\r\n // Update local cache on base operations:\r\n async _set(key, value) {\r\n await super._set(key, value);\r\n this.localCache[key] = JSON.stringify(value);\r\n }\r\n async _get(key) {\r\n const value = await super._get(key);\r\n this.localCache[key] = JSON.stringify(value);\r\n return value;\r\n }\r\n async _remove(key) {\r\n await super._remove(key);\r\n delete this.localCache[key];\r\n }\r\n}\r\nBrowserLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserLocalPersistence = BrowserLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass BrowserSessionPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.sessionStorage, \"SESSION\" /* PersistenceType.SESSION */);\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n}\r\nBrowserSessionPersistence.type = 'SESSION';\r\n/**\r\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserSessionPersistence = BrowserSessionPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\r\n *\r\n * @param promises - Array of promises to wait on.\r\n */\r\nfunction _allSettled(promises) {\r\n return Promise.all(promises.map(async (promise) => {\r\n try {\r\n const value = await promise;\r\n return {\r\n fulfilled: true,\r\n value\r\n };\r\n }\r\n catch (reason) {\r\n return {\r\n fulfilled: false,\r\n reason\r\n };\r\n }\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface class for receiving messages.\r\n *\r\n */\r\nclass Receiver {\r\n constructor(eventTarget) {\r\n this.eventTarget = eventTarget;\r\n this.handlersMap = {};\r\n this.boundEventHandler = this.handleEvent.bind(this);\r\n }\r\n /**\r\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\r\n *\r\n * @param eventTarget - An event target (such as window or self) through which the underlying\r\n * messages will be received.\r\n */\r\n static _getInstance(eventTarget) {\r\n // The results are stored in an array since objects can't be keys for other\r\n // objects. In addition, setting a unique property on an event target as a\r\n // hash map key may not be allowed due to CORS restrictions.\r\n const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));\r\n if (existingInstance) {\r\n return existingInstance;\r\n }\r\n const newInstance = new Receiver(eventTarget);\r\n this.receivers.push(newInstance);\r\n return newInstance;\r\n }\r\n isListeningto(eventTarget) {\r\n return this.eventTarget === eventTarget;\r\n }\r\n /**\r\n * Fans out a MessageEvent to the appropriate listeners.\r\n *\r\n * @remarks\r\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\r\n * finished processing.\r\n *\r\n * @param event - The MessageEvent.\r\n *\r\n */\r\n async handleEvent(event) {\r\n const messageEvent = event;\r\n const { eventId, eventType, data } = messageEvent.data;\r\n const handlers = this.handlersMap[eventType];\r\n if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {\r\n return;\r\n }\r\n messageEvent.ports[0].postMessage({\r\n status: \"ack\" /* _Status.ACK */,\r\n eventId,\r\n eventType\r\n });\r\n const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));\r\n const response = await _allSettled(promises);\r\n messageEvent.ports[0].postMessage({\r\n status: \"done\" /* _Status.DONE */,\r\n eventId,\r\n eventType,\r\n response\r\n });\r\n }\r\n /**\r\n * Subscribe an event handler for a particular event.\r\n *\r\n * @param eventType - Event name to subscribe to.\r\n * @param eventHandler - The event handler which should receive the events.\r\n *\r\n */\r\n _subscribe(eventType, eventHandler) {\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.addEventListener('message', this.boundEventHandler);\r\n }\r\n if (!this.handlersMap[eventType]) {\r\n this.handlersMap[eventType] = new Set();\r\n }\r\n this.handlersMap[eventType].add(eventHandler);\r\n }\r\n /**\r\n * Unsubscribe an event handler from a particular event.\r\n *\r\n * @param eventType - Event name to unsubscribe from.\r\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\r\n *\r\n */\r\n _unsubscribe(eventType, eventHandler) {\r\n if (this.handlersMap[eventType] && eventHandler) {\r\n this.handlersMap[eventType].delete(eventHandler);\r\n }\r\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\r\n delete this.handlersMap[eventType];\r\n }\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\r\n }\r\n }\r\n}\r\nReceiver.receivers = [];\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _generateEventId(prefix = '', digits = 10) {\r\n let random = '';\r\n for (let i = 0; i < digits; i++) {\r\n random += Math.floor(Math.random() * 10);\r\n }\r\n return prefix + random;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface for sending messages and waiting for a completion response.\r\n *\r\n */\r\nclass Sender {\r\n constructor(target) {\r\n this.target = target;\r\n this.handlers = new Set();\r\n }\r\n /**\r\n * Unsubscribe the handler and remove it from our tracking Set.\r\n *\r\n * @param handler - The handler to unsubscribe.\r\n */\r\n removeMessageHandler(handler) {\r\n if (handler.messageChannel) {\r\n handler.messageChannel.port1.removeEventListener('message', handler.onMessage);\r\n handler.messageChannel.port1.close();\r\n }\r\n this.handlers.delete(handler);\r\n }\r\n /**\r\n * Send a message to the Receiver located at {@link target}.\r\n *\r\n * @remarks\r\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\r\n * receiver has had a chance to fully process the event.\r\n *\r\n * @param eventType - Type of event to send.\r\n * @param data - The payload of the event.\r\n * @param timeout - Timeout for waiting on an ACK from the receiver.\r\n *\r\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\r\n */\r\n async _send(eventType, data, timeout = 50 /* _TimeoutDuration.ACK */) {\r\n const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\r\n if (!messageChannel) {\r\n throw new Error(\"connection_unavailable\" /* _MessageError.CONNECTION_UNAVAILABLE */);\r\n }\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n let completionTimer;\r\n let handler;\r\n return new Promise((resolve, reject) => {\r\n const eventId = _generateEventId('', 20);\r\n messageChannel.port1.start();\r\n const ackTimer = setTimeout(() => {\r\n reject(new Error(\"unsupported_event\" /* _MessageError.UNSUPPORTED_EVENT */));\r\n }, timeout);\r\n handler = {\r\n messageChannel,\r\n onMessage(event) {\r\n const messageEvent = event;\r\n if (messageEvent.data.eventId !== eventId) {\r\n return;\r\n }\r\n switch (messageEvent.data.status) {\r\n case \"ack\" /* _Status.ACK */:\r\n // The receiver should ACK first.\r\n clearTimeout(ackTimer);\r\n completionTimer = setTimeout(() => {\r\n reject(new Error(\"timeout\" /* _MessageError.TIMEOUT */));\r\n }, 3000 /* _TimeoutDuration.COMPLETION */);\r\n break;\r\n case \"done\" /* _Status.DONE */:\r\n // Once the receiver's handlers are finished we will get the results.\r\n clearTimeout(completionTimer);\r\n resolve(messageEvent.data.response);\r\n break;\r\n default:\r\n clearTimeout(ackTimer);\r\n clearTimeout(completionTimer);\r\n reject(new Error(\"invalid_response\" /* _MessageError.INVALID_RESPONSE */));\r\n break;\r\n }\r\n }\r\n };\r\n this.handlers.add(handler);\r\n messageChannel.port1.addEventListener('message', handler.onMessage);\r\n this.target.postMessage({\r\n eventType,\r\n eventId,\r\n data\r\n }, [messageChannel.port2]);\r\n }).finally(() => {\r\n if (handler) {\r\n this.removeMessageHandler(handler);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Lazy accessor for window, since the compat layer won't tree shake this out,\r\n * we need to make sure not to mess with window unless we have to\r\n */\r\nfunction _window() {\r\n return window;\r\n}\r\nfunction _setWindowLocation(url) {\r\n _window().location.href = url;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _isWorker() {\r\n return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\r\n typeof _window()['importScripts'] === 'function');\r\n}\r\nasync function _getActiveServiceWorker() {\r\n if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {\r\n return null;\r\n }\r\n try {\r\n const registration = await navigator.serviceWorker.ready;\r\n return registration.active;\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n}\r\nfunction _getServiceWorkerController() {\r\n var _a;\r\n return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;\r\n}\r\nfunction _getWorkerGlobalScope() {\r\n return _isWorker() ? self : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebaseLocalStorageDb';\r\nconst DB_VERSION = 1;\r\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\r\nconst DB_DATA_KEYPATH = 'fbase_key';\r\n/**\r\n * Promise wrapper for IDBRequest\r\n *\r\n * Unfortunately we can't cleanly extend Promise since promises are not callable in ES6\r\n *\r\n */\r\nclass DBPromise {\r\n constructor(request) {\r\n this.request = request;\r\n }\r\n toPromise() {\r\n return new Promise((resolve, reject) => {\r\n this.request.addEventListener('success', () => {\r\n resolve(this.request.result);\r\n });\r\n this.request.addEventListener('error', () => {\r\n reject(this.request.error);\r\n });\r\n });\r\n }\r\n}\r\nfunction getObjectStore(db, isReadWrite) {\r\n return db\r\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\r\n .objectStore(DB_OBJECTSTORE_NAME);\r\n}\r\nfunction _deleteDatabase() {\r\n const request = indexedDB.deleteDatabase(DB_NAME);\r\n return new DBPromise(request).toPromise();\r\n}\r\nfunction _openDatabase() {\r\n const request = indexedDB.open(DB_NAME, DB_VERSION);\r\n return new Promise((resolve, reject) => {\r\n request.addEventListener('error', () => {\r\n reject(request.error);\r\n });\r\n request.addEventListener('upgradeneeded', () => {\r\n const db = request.result;\r\n try {\r\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n });\r\n request.addEventListener('success', async () => {\r\n const db = request.result;\r\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\r\n // same time. The only way to recover seems to be deleting the database\r\n // and re-initializing it.\r\n // https://github.com/firebase/firebase-js-sdk/issues/634\r\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\r\n // Need to close the database or else you get a `blocked` event\r\n db.close();\r\n await _deleteDatabase();\r\n resolve(await _openDatabase());\r\n }\r\n else {\r\n resolve(db);\r\n }\r\n });\r\n });\r\n}\r\nasync function _putObject(db, key, value) {\r\n const request = getObjectStore(db, true).put({\r\n [DB_DATA_KEYPATH]: key,\r\n value\r\n });\r\n return new DBPromise(request).toPromise();\r\n}\r\nasync function getObject(db, key) {\r\n const request = getObjectStore(db, false).get(key);\r\n const data = await new DBPromise(request).toPromise();\r\n return data === undefined ? null : data.value;\r\n}\r\nfunction _deleteObject(db, key) {\r\n const request = getObjectStore(db, true).delete(key);\r\n return new DBPromise(request).toPromise();\r\n}\r\nconst _POLLING_INTERVAL_MS = 800;\r\nconst _TRANSACTION_RETRY_COUNT = 3;\r\nclass IndexedDBLocalPersistence {\r\n constructor() {\r\n this.type = \"LOCAL\" /* PersistenceType.LOCAL */;\r\n this._shouldAllowMigration = true;\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n this.pendingWrites = 0;\r\n this.receiver = null;\r\n this.sender = null;\r\n this.serviceWorkerReceiverAvailable = false;\r\n this.activeServiceWorker = null;\r\n // Fire & forget the service worker registration as it may never resolve\r\n this._workerInitializationPromise =\r\n this.initializeServiceWorkerMessaging().then(() => { }, () => { });\r\n }\r\n async _openDb() {\r\n if (this.db) {\r\n return this.db;\r\n }\r\n this.db = await _openDatabase();\r\n return this.db;\r\n }\r\n async _withRetries(op) {\r\n let numAttempts = 0;\r\n while (true) {\r\n try {\r\n const db = await this._openDb();\r\n return await op(db);\r\n }\r\n catch (e) {\r\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\r\n throw e;\r\n }\r\n if (this.db) {\r\n this.db.close();\r\n this.db = undefined;\r\n }\r\n // TODO: consider adding exponential backoff\r\n }\r\n }\r\n }\r\n /**\r\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\r\n * postMessage interface to send these events to the worker ourselves.\r\n */\r\n async initializeServiceWorkerMessaging() {\r\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\r\n }\r\n /**\r\n * As the worker we should listen to events from the main window.\r\n */\r\n async initializeReceiver() {\r\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\r\n // Refresh from persistence if we receive a KeyChanged message.\r\n this.receiver._subscribe(\"keyChanged\" /* _EventType.KEY_CHANGED */, async (_origin, data) => {\r\n const keys = await this._poll();\r\n return {\r\n keyProcessed: keys.includes(data.key)\r\n };\r\n });\r\n // Let the sender know that we are listening so they give us more timeout.\r\n this.receiver._subscribe(\"ping\" /* _EventType.PING */, async (_origin, _data) => {\r\n return [\"keyChanged\" /* _EventType.KEY_CHANGED */];\r\n });\r\n }\r\n /**\r\n * As the main window, we should let the worker know when keys change (set and remove).\r\n *\r\n * @remarks\r\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\r\n * may not resolve.\r\n */\r\n async initializeSender() {\r\n var _a, _b;\r\n // Check to see if there's an active service worker.\r\n this.activeServiceWorker = await _getActiveServiceWorker();\r\n if (!this.activeServiceWorker) {\r\n return;\r\n }\r\n this.sender = new Sender(this.activeServiceWorker);\r\n // Ping the service worker to check what events they can handle.\r\n const results = await this.sender._send(\"ping\" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */);\r\n if (!results) {\r\n return;\r\n }\r\n if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&\r\n ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes(\"keyChanged\" /* _EventType.KEY_CHANGED */))) {\r\n this.serviceWorkerReceiverAvailable = true;\r\n }\r\n }\r\n /**\r\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\r\n * worker will just trigger a full sync anyway.\r\n *\r\n * @remarks\r\n * For now, we only support one service worker per page.\r\n *\r\n * @param key - Storage key which changed.\r\n */\r\n async notifyServiceWorker(key) {\r\n if (!this.sender ||\r\n !this.activeServiceWorker ||\r\n _getServiceWorkerController() !== this.activeServiceWorker) {\r\n return;\r\n }\r\n try {\r\n await this.sender._send(\"keyChanged\" /* _EventType.KEY_CHANGED */, { key }, \r\n // Use long timeout if receiver has previously responded to a ping from us.\r\n this.serviceWorkerReceiverAvailable\r\n ? 800 /* _TimeoutDuration.LONG_ACK */\r\n : 50 /* _TimeoutDuration.ACK */);\r\n }\r\n catch (_a) {\r\n // This is a best effort approach. Ignore errors.\r\n }\r\n }\r\n async _isAvailable() {\r\n try {\r\n if (!indexedDB) {\r\n return false;\r\n }\r\n const db = await _openDatabase();\r\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\r\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\r\n return true;\r\n }\r\n catch (_a) { }\r\n return false;\r\n }\r\n async _withPendingWrite(write) {\r\n this.pendingWrites++;\r\n try {\r\n await write();\r\n }\r\n finally {\r\n this.pendingWrites--;\r\n }\r\n }\r\n async _set(key, value) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _putObject(db, key, value));\r\n this.localCache[key] = value;\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _get(key) {\r\n const obj = (await this._withRetries((db) => getObject(db, key)));\r\n this.localCache[key] = obj;\r\n return obj;\r\n }\r\n async _remove(key) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _deleteObject(db, key));\r\n delete this.localCache[key];\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _poll() {\r\n // TODO: check if we need to fallback if getAll is not supported\r\n const result = await this._withRetries((db) => {\r\n const getAllRequest = getObjectStore(db, false).getAll();\r\n return new DBPromise(getAllRequest).toPromise();\r\n });\r\n if (!result) {\r\n return [];\r\n }\r\n // If we have pending writes in progress abort, we'll get picked up on the next poll\r\n if (this.pendingWrites !== 0) {\r\n return [];\r\n }\r\n const keys = [];\r\n const keysInResult = new Set();\r\n if (result.length !== 0) {\r\n for (const { fbase_key: key, value } of result) {\r\n keysInResult.add(key);\r\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\r\n this.notifyListeners(key, value);\r\n keys.push(key);\r\n }\r\n }\r\n }\r\n for (const localKey of Object.keys(this.localCache)) {\r\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\r\n // Deleted\r\n this.notifyListeners(localKey, null);\r\n keys.push(localKey);\r\n }\r\n }\r\n return keys;\r\n }\r\n notifyListeners(key, newValue) {\r\n this.localCache[key] = newValue;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(newValue);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.startPolling();\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n void this._get(key); // This can happen in the background async and we can return immediately.\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.stopPolling();\r\n }\r\n }\r\n}\r\nIndexedDBLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst indexedDBLocalPersistence = IndexedDBLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:start\" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _SOLVE_TIME_MS = 500;\r\nconst _EXPIRATION_TIME_MS = 60000;\r\nconst _WIDGET_ID_START = 1000000000000;\r\nclass MockReCaptcha {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.counter = _WIDGET_ID_START;\r\n this._widgets = new Map();\r\n }\r\n render(container, parameters) {\r\n const id = this.counter;\r\n this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));\r\n this.counter++;\r\n return id;\r\n }\r\n reset(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());\r\n this._widgets.delete(id);\r\n }\r\n getResponse(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';\r\n }\r\n async execute(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());\r\n return '';\r\n }\r\n}\r\nclass MockWidget {\r\n constructor(containerOrId, appName, params) {\r\n this.params = params;\r\n this.timerId = null;\r\n this.deleted = false;\r\n this.responseToken = null;\r\n this.clickHandler = () => {\r\n this.execute();\r\n };\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, { appName });\r\n this.container = container;\r\n this.isVisible = this.params.size !== 'invisible';\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n else {\r\n this.container.addEventListener('click', this.clickHandler);\r\n }\r\n }\r\n getResponse() {\r\n this.checkIfDeleted();\r\n return this.responseToken;\r\n }\r\n delete() {\r\n this.checkIfDeleted();\r\n this.deleted = true;\r\n if (this.timerId) {\r\n clearTimeout(this.timerId);\r\n this.timerId = null;\r\n }\r\n this.container.removeEventListener('click', this.clickHandler);\r\n }\r\n execute() {\r\n this.checkIfDeleted();\r\n if (this.timerId) {\r\n return;\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.responseToken = generateRandomAlphaNumericString(50);\r\n const { callback, 'expired-callback': expiredCallback } = this.params;\r\n if (callback) {\r\n try {\r\n callback(this.responseToken);\r\n }\r\n catch (e) { }\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.timerId = null;\r\n this.responseToken = null;\r\n if (expiredCallback) {\r\n try {\r\n expiredCallback();\r\n }\r\n catch (e) { }\r\n }\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n }, _EXPIRATION_TIME_MS);\r\n }, _SOLVE_TIME_MS);\r\n }\r\n checkIfDeleted() {\r\n if (this.deleted) {\r\n throw new Error('reCAPTCHA mock was already deleted!');\r\n }\r\n }\r\n}\r\nfunction generateRandomAlphaNumericString(len) {\r\n const chars = [];\r\n const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n for (let i = 0; i < len; i++) {\r\n chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));\r\n }\r\n return chars.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// ReCaptcha will load using the same callback, so the callback function needs\r\n// to be kept around\r\nconst _JSLOAD_CALLBACK = _generateCallbackName('rcb');\r\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\r\n/**\r\n * Loader for the GReCaptcha library. There should only ever be one of this.\r\n */\r\nclass ReCaptchaLoaderImpl {\r\n constructor() {\r\n var _a;\r\n this.hostLanguage = '';\r\n this.counter = 0;\r\n /**\r\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\r\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\r\n * `window.grecaptcha.render()` will not. Another load will add it.\r\n */\r\n this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);\r\n }\r\n load(auth, hl = '') {\r\n _assert(isHostLanguageValid(hl), auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\r\n return Promise.resolve(_window().grecaptcha);\r\n }\r\n return new Promise((resolve, reject) => {\r\n const networkTimeout = _window().setTimeout(() => {\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, NETWORK_TIMEOUT_DELAY.get());\r\n _window()[_JSLOAD_CALLBACK] = () => {\r\n _window().clearTimeout(networkTimeout);\r\n delete _window()[_JSLOAD_CALLBACK];\r\n const recaptcha = _window().grecaptcha;\r\n if (!recaptcha || !isV2(recaptcha)) {\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n return;\r\n }\r\n // Wrap the greptcha render function so that we know if the developer has\r\n // called it separately\r\n const render = recaptcha.render;\r\n recaptcha.render = (container, params) => {\r\n const widgetId = render(container, params);\r\n this.counter++;\r\n return widgetId;\r\n };\r\n this.hostLanguage = hl;\r\n resolve(recaptcha);\r\n };\r\n const url = `${_recaptchaV2ScriptUrl()}?${querystring({\r\n onload: _JSLOAD_CALLBACK,\r\n render: 'explicit',\r\n hl\r\n })}`;\r\n _loadJS(url).catch(() => {\r\n clearTimeout(networkTimeout);\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n });\r\n });\r\n }\r\n clearedOneInstance() {\r\n this.counter--;\r\n }\r\n shouldResolveImmediately(hl) {\r\n var _a;\r\n // We can resolve immediately if:\r\n // • grecaptcha is already defined AND (\r\n // 1. the requested language codes are the same OR\r\n // 2. there exists already a ReCaptcha on the page\r\n // 3. the library was already loaded by the app\r\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\r\n // that are already in the page\r\n return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&\r\n (hl === this.hostLanguage ||\r\n this.counter > 0 ||\r\n this.librarySeparatelyLoaded));\r\n }\r\n}\r\nfunction isHostLanguageValid(hl) {\r\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\r\n}\r\nclass MockReCaptchaLoaderImpl {\r\n async load(auth) {\r\n return new MockReCaptcha(auth);\r\n }\r\n clearedOneInstance() { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\r\nconst DEFAULT_PARAMS = {\r\n theme: 'light',\r\n type: 'image'\r\n};\r\n/**\r\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\r\n *\r\n * @remarks\r\n * `RecaptchaVerifier` does not work in a Node.js environment.\r\n *\r\n * @public\r\n */\r\nclass RecaptchaVerifier {\r\n /**\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n *\r\n * @param containerOrId - The reCAPTCHA container parameter.\r\n *\r\n * @remarks\r\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\r\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\r\n * an element ID. The corresponding element must also must be in the DOM at the time of\r\n * initialization.\r\n *\r\n * @param parameters - The optional reCAPTCHA parameters.\r\n *\r\n * @remarks\r\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\r\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\r\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\r\n * 'invisible'.\r\n */\r\n constructor(authExtern, containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS)) {\r\n this.parameters = parameters;\r\n /**\r\n * The application verifier type.\r\n *\r\n * @remarks\r\n * For a reCAPTCHA verifier, this is 'recaptcha'.\r\n */\r\n this.type = RECAPTCHA_VERIFIER_TYPE;\r\n this.destroyed = false;\r\n this.widgetId = null;\r\n this.tokenChangeListeners = new Set();\r\n this.renderPromise = null;\r\n this.recaptcha = null;\r\n this.auth = _castAuth(authExtern);\r\n this.isInvisible = this.parameters.size === 'invisible';\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.container = container;\r\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\r\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\r\n ? new MockReCaptchaLoaderImpl()\r\n : new ReCaptchaLoaderImpl();\r\n this.validateStartingState();\r\n // TODO: Figure out if sdk version is needed\r\n }\r\n /**\r\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\r\n *\r\n * @returns A Promise for the reCAPTCHA token.\r\n */\r\n async verify() {\r\n this.assertNotDestroyed();\r\n const id = await this.render();\r\n const recaptcha = this.getAssertedRecaptcha();\r\n const response = recaptcha.getResponse(id);\r\n if (response) {\r\n return response;\r\n }\r\n return new Promise(resolve => {\r\n const tokenChange = (token) => {\r\n if (!token) {\r\n return; // Ignore token expirations.\r\n }\r\n this.tokenChangeListeners.delete(tokenChange);\r\n resolve(token);\r\n };\r\n this.tokenChangeListeners.add(tokenChange);\r\n if (this.isInvisible) {\r\n recaptcha.execute(id);\r\n }\r\n });\r\n }\r\n /**\r\n * Renders the reCAPTCHA widget on the page.\r\n *\r\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\r\n */\r\n render() {\r\n try {\r\n this.assertNotDestroyed();\r\n }\r\n catch (e) {\r\n // This method returns a promise. Since it's not async (we want to return the\r\n // _same_ promise if rendering is still occurring), the API surface should\r\n // reject with the error rather than just throw\r\n return Promise.reject(e);\r\n }\r\n if (this.renderPromise) {\r\n return this.renderPromise;\r\n }\r\n this.renderPromise = this.makeRenderPromise().catch(e => {\r\n this.renderPromise = null;\r\n throw e;\r\n });\r\n return this.renderPromise;\r\n }\r\n /** @internal */\r\n _reset() {\r\n this.assertNotDestroyed();\r\n if (this.widgetId !== null) {\r\n this.getAssertedRecaptcha().reset(this.widgetId);\r\n }\r\n }\r\n /**\r\n * Clears the reCAPTCHA widget from the page and destroys the instance.\r\n */\r\n clear() {\r\n this.assertNotDestroyed();\r\n this.destroyed = true;\r\n this._recaptchaLoader.clearedOneInstance();\r\n if (!this.isInvisible) {\r\n this.container.childNodes.forEach(node => {\r\n this.container.removeChild(node);\r\n });\r\n }\r\n }\r\n validateStartingState() {\r\n _assert(!this.parameters.sitekey, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n }\r\n makeTokenCallback(existing) {\r\n return token => {\r\n this.tokenChangeListeners.forEach(listener => listener(token));\r\n if (typeof existing === 'function') {\r\n existing(token);\r\n }\r\n else if (typeof existing === 'string') {\r\n const globalFunc = _window()[existing];\r\n if (typeof globalFunc === 'function') {\r\n globalFunc(token);\r\n }\r\n }\r\n };\r\n }\r\n assertNotDestroyed() {\r\n _assert(!this.destroyed, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n async makeRenderPromise() {\r\n await this.init();\r\n if (!this.widgetId) {\r\n let container = this.container;\r\n if (!this.isInvisible) {\r\n const guaranteedEmpty = document.createElement('div');\r\n container.appendChild(guaranteedEmpty);\r\n container = guaranteedEmpty;\r\n }\r\n this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);\r\n }\r\n return this.widgetId;\r\n }\r\n async init() {\r\n _assert(_isHttpOrHttps() && !_isWorker(), this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n await domReady();\r\n this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);\r\n const siteKey = await getRecaptchaParams(this.auth);\r\n _assert(siteKey, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.parameters.sitekey = siteKey;\r\n }\r\n getAssertedRecaptcha() {\r\n _assert(this.recaptcha, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.recaptcha;\r\n }\r\n}\r\nfunction domReady() {\r\n let resolver = null;\r\n return new Promise(resolve => {\r\n if (document.readyState === 'complete') {\r\n resolve();\r\n return;\r\n }\r\n // Document not ready, wait for load before resolving.\r\n // Save resolver, so we can remove listener in case it was externally\r\n // cancelled.\r\n resolver = () => resolve();\r\n window.addEventListener('load', resolver);\r\n }).catch(e => {\r\n if (resolver) {\r\n window.removeEventListener('load', resolver);\r\n }\r\n throw e;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ConfirmationResultImpl {\r\n constructor(verificationId, onConfirmation) {\r\n this.verificationId = verificationId;\r\n this.onConfirmation = onConfirmation;\r\n }\r\n confirm(verificationCode) {\r\n const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);\r\n return this.onConfirmation(authCredential);\r\n }\r\n}\r\n/**\r\n * Asynchronously signs in using a phone number.\r\n *\r\n * @remarks\r\n * This method sends a code via SMS to the given\r\n * phone number, and returns a {@link ConfirmationResult}. After the user\r\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\r\n * with the code to sign the user in.\r\n *\r\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\r\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\r\n * This function can work on other platforms that do not support the\r\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\r\n * third-party {@link ApplicationVerifier} implementation.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain a verificationCode from the user.\r\n * const credential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));\r\n}\r\n/**\r\n * Links the user account with the given phone number.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, \"phone\" /* ProviderId.PHONE */);\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh phone credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\r\n *\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\r\n *\r\n */\r\nasync function _verifyPhoneNumber(auth, options, verifier) {\r\n var _a;\r\n const recaptchaToken = await verifier.verify();\r\n try {\r\n _assert(typeof recaptchaToken === 'string', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n let phoneInfoOptions;\r\n if (typeof options === 'string') {\r\n phoneInfoOptions = {\r\n phoneNumber: options\r\n };\r\n }\r\n else {\r\n phoneInfoOptions = options;\r\n }\r\n if ('session' in phoneInfoOptions) {\r\n const session = phoneInfoOptions.session;\r\n if ('phoneNumber' in phoneInfoOptions) {\r\n _assert(session.type === \"enroll\" /* MultiFactorSessionType.ENROLL */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollPhoneMfa(auth, {\r\n idToken: session.credential,\r\n phoneEnrollmentInfo: {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneSessionInfo.sessionInfo;\r\n }\r\n else {\r\n _assert(session.type === \"signin\" /* MultiFactorSessionType.SIGN_IN */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||\r\n phoneInfoOptions.multiFactorUid;\r\n _assert(mfaEnrollmentId, auth, \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */);\r\n const response = await startSignInPhoneMfa(auth, {\r\n mfaPendingCredential: session.credential,\r\n mfaEnrollmentId,\r\n phoneSignInInfo: {\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneResponseInfo.sessionInfo;\r\n }\r\n }\r\n else {\r\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n });\r\n return sessionInfo;\r\n }\r\n }\r\n finally {\r\n verifier._reset();\r\n }\r\n}\r\n/**\r\n * Updates the user's phone number.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * await updatePhoneNumber(user, phoneCredential);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param credential - A credential authenticating the new phone number.\r\n *\r\n * @public\r\n */\r\nasync function updatePhoneNumber(user, credential) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n await _link$1(userInternal, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link PhoneAuthCredential}.\r\n *\r\n * @remarks\r\n * `PhoneAuthProvider` does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, phoneCredential);\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthProvider {\r\n /**\r\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\r\n *\r\n */\r\n constructor(auth) {\r\n /** Always set to {@link ProviderId}.PHONE. */\r\n this.providerId = PhoneAuthProvider.PROVIDER_ID;\r\n this.auth = _castAuth(auth);\r\n }\r\n /**\r\n *\r\n * Starts a phone number authentication flow by sending a verification code to the given phone\r\n * number.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\r\n * E.164 format (e.g. +16505550101).\r\n * @param applicationVerifier - For abuse prevention, this method also requires a\r\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\r\n * {@link RecaptchaVerifier}.\r\n *\r\n * @returns A Promise for a verification ID that can be passed to\r\n * {@link PhoneAuthProvider.credential} to identify this flow..\r\n */\r\n verifyPhoneNumber(phoneOptions, applicationVerifier) {\r\n return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));\r\n }\r\n /**\r\n * Creates a phone auth credential, given the verification ID from\r\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\r\n * mobile device.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\r\n * @param verificationCode - The verification code sent to the user's mobile device.\r\n *\r\n * @returns The auth provider credential.\r\n */\r\n static credential(verificationId, verificationCode) {\r\n return PhoneAuthCredential._fromVerification(verificationId, verificationCode);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n const credential = userCredential;\r\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\r\n }\r\n /**\r\n * Returns an {@link AuthCredential} when passed an error.\r\n *\r\n * @remarks\r\n *\r\n * This method works for errors like\r\n * `auth/account-exists-with-different-credentials`. This is useful for\r\n * recovering when attempting to set a user's phone number but the number\r\n * in question is already tied to another account. For example, the following\r\n * code tries to update the current user's phone number, and if that\r\n * fails, links the user with the account associated with that number:\r\n *\r\n * ```js\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\r\n * try {\r\n * const code = ''; // Prompt the user for the verification code\r\n * await updatePhoneNumber(\r\n * auth.currentUser,\r\n * PhoneAuthProvider.credential(verificationId, code));\r\n * } catch (e) {\r\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\r\n * const cred = PhoneAuthProvider.credentialFromError(e);\r\n * await linkWithCredential(auth.currentUser, cred);\r\n * }\r\n * }\r\n *\r\n * // At this point, auth.currentUser.phoneNumber === number.\r\n * ```\r\n *\r\n * @param error - The error to generate a credential from.\r\n */\r\n static credentialFromError(error) {\r\n return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { phoneNumber, temporaryProof } = tokenResponse;\r\n if (phoneNumber && temporaryProof) {\r\n return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);\r\n }\r\n return null;\r\n }\r\n}\r\n/** Always set to {@link ProviderId}.PHONE. */\r\nPhoneAuthProvider.PROVIDER_ID = \"phone\" /* ProviderId.PHONE */;\r\n/** Always set to {@link SignInMethod}.PHONE. */\r\nPhoneAuthProvider.PHONE_SIGN_IN_METHOD = \"phone\" /* SignInMethod.PHONE */;\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Chooses a popup/redirect resolver to use. This prefers the override (which\r\n * is directly passed in), and falls back to the property set on the auth\r\n * object. If neither are available, this function errors w/ an argument error.\r\n */\r\nfunction _withDefaultResolver(auth, resolverOverride) {\r\n if (resolverOverride) {\r\n return _getInstance(resolverOverride);\r\n }\r\n _assert(auth._popupRedirectResolver, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return auth._popupRedirectResolver;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass IdpCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"custom\" /* ProviderId.CUSTOM */, \"custom\" /* ProviderId.CUSTOM */);\r\n this.params = params;\r\n }\r\n _getIdTokenResponse(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _linkToIdToken(auth, idToken) {\r\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\r\n }\r\n _getReauthenticationResolver(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _buildIdpRequest(idToken) {\r\n const request = {\r\n requestUri: this.params.requestUri,\r\n sessionId: this.params.sessionId,\r\n postBody: this.params.postBody,\r\n tenantId: this.params.tenantId,\r\n pendingToken: this.params.pendingToken,\r\n returnSecureToken: true,\r\n returnIdpCredential: true\r\n };\r\n if (idToken) {\r\n request.idToken = idToken;\r\n }\r\n return request;\r\n }\r\n}\r\nfunction _signIn(params) {\r\n return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nfunction _reauth(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nasync function _link(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _link$1(user, new IdpCredential(params), params.bypassAuthState);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n */\r\nclass AbstractPopupRedirectOperation {\r\n constructor(auth, filter, resolver, user, bypassAuthState = false) {\r\n this.auth = auth;\r\n this.resolver = resolver;\r\n this.user = user;\r\n this.bypassAuthState = bypassAuthState;\r\n this.pendingPromise = null;\r\n this.eventManager = null;\r\n this.filter = Array.isArray(filter) ? filter : [filter];\r\n }\r\n execute() {\r\n return new Promise(async (resolve, reject) => {\r\n this.pendingPromise = { resolve, reject };\r\n try {\r\n this.eventManager = await this.resolver._initialize(this.auth);\r\n await this.onExecution();\r\n this.eventManager.registerConsumer(this);\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n });\r\n }\r\n async onAuthEvent(event) {\r\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\r\n if (error) {\r\n this.reject(error);\r\n return;\r\n }\r\n const params = {\r\n auth: this.auth,\r\n requestUri: urlResponse,\r\n sessionId: sessionId,\r\n tenantId: tenantId || undefined,\r\n postBody: postBody || undefined,\r\n user: this.user,\r\n bypassAuthState: this.bypassAuthState\r\n };\r\n try {\r\n this.resolve(await this.getIdpTask(type)(params));\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n }\r\n onError(error) {\r\n this.reject(error);\r\n }\r\n getIdpTask(type) {\r\n switch (type) {\r\n case \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */:\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n return _signIn;\r\n case \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n return _link;\r\n case \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return _reauth;\r\n default:\r\n _fail(this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n resolve(cred) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.resolve(cred);\r\n this.unregisterAndCleanUp();\r\n }\r\n reject(error) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.reject(error);\r\n this.unregisterAndCleanUp();\r\n }\r\n unregisterAndCleanUp() {\r\n if (this.eventManager) {\r\n this.eventManager.unregisterConsumer(this);\r\n }\r\n this.pendingPromise = null;\r\n this.cleanUp();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\r\n/**\r\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\r\n *\r\n * @remarks\r\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\r\n * unsuccessful, returns an error object containing additional information about the error.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPopup(auth, provider, resolver) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_createError(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\r\n }\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n const action = new PopupOperation(authInternal, \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\r\n * OAuth flow.\r\n *\r\n * @remarks\r\n * If the reauthentication is successful, the returned result will contain the user and the\r\n * provider's credential.\r\n *\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n * // Reauthenticate using a popup.\r\n * await reauthenticateWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_createError(userInternal.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\r\n }\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\r\n *\r\n * @remarks\r\n * If the linking is successful, the returned result will contain the user and the provider's credential.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n *\r\n */\r\nclass PopupOperation extends AbstractPopupRedirectOperation {\r\n constructor(auth, filter, provider, resolver, user) {\r\n super(auth, filter, resolver, user);\r\n this.provider = provider;\r\n this.authWindow = null;\r\n this.pollId = null;\r\n if (PopupOperation.currentPopupAction) {\r\n PopupOperation.currentPopupAction.cancel();\r\n }\r\n PopupOperation.currentPopupAction = this;\r\n }\r\n async executeNotNull() {\r\n const result = await this.execute();\r\n _assert(result, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return result;\r\n }\r\n async onExecution() {\r\n debugAssert(this.filter.length === 1, 'Popup operations only handle one event');\r\n const eventId = _generateEventId();\r\n this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor\r\n eventId);\r\n this.authWindow.associatedEvent = eventId;\r\n // Check for web storage support and origin validation _after_ the popup is\r\n // loaded. These operations are slow (~1 second or so) Rather than\r\n // waiting on them before opening the window, optimistically open the popup\r\n // and check for storage support at the same time. If storage support is\r\n // not available, this will cause the whole thing to reject properly. It\r\n // will also close the popup, but since the promise has already rejected,\r\n // the popup closed by user poll will reject into the void.\r\n this.resolver._originValidation(this.auth).catch(e => {\r\n this.reject(e);\r\n });\r\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\r\n if (!isSupported) {\r\n this.reject(_createError(this.auth, \"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));\r\n }\r\n });\r\n // Handle user closure. Notice this does *not* use await\r\n this.pollUserCancellation();\r\n }\r\n get eventId() {\r\n var _a;\r\n return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;\r\n }\r\n cancel() {\r\n this.reject(_createError(this.auth, \"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));\r\n }\r\n cleanUp() {\r\n if (this.authWindow) {\r\n this.authWindow.close();\r\n }\r\n if (this.pollId) {\r\n window.clearTimeout(this.pollId);\r\n }\r\n this.authWindow = null;\r\n this.pollId = null;\r\n PopupOperation.currentPopupAction = null;\r\n }\r\n pollUserCancellation() {\r\n const poll = () => {\r\n var _a, _b;\r\n if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {\r\n // Make sure that there is sufficient time for whatever action to\r\n // complete. The window could have closed but the sign in network\r\n // call could still be in flight. This is specifically true for\r\n // Firefox or if the opener is in an iframe, in which case the oauth\r\n // helper closes the popup.\r\n this.pollId = window.setTimeout(() => {\r\n this.pollId = null;\r\n this.reject(_createError(this.auth, \"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));\r\n }, 8000 /* _Timeout.AUTH_EVENT */);\r\n return;\r\n }\r\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\r\n };\r\n poll();\r\n }\r\n}\r\n// Only one popup is ever shown at once. The lifecycle of the current popup\r\n// can be managed / cancelled by the constructor.\r\nPopupOperation.currentPopupAction = null;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\r\n// We only get one redirect outcome for any one auth, so just store it\r\n// in here.\r\nconst redirectOutcomeMap = new Map();\r\nclass RedirectAction extends AbstractPopupRedirectOperation {\r\n constructor(auth, resolver, bypassAuthState = false) {\r\n super(auth, [\r\n \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,\r\n \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */,\r\n \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */,\r\n \"unknown\" /* AuthEventType.UNKNOWN */\r\n ], resolver, undefined, bypassAuthState);\r\n this.eventId = null;\r\n }\r\n /**\r\n * Override the execute function; if we already have a redirect result, then\r\n * just return it.\r\n */\r\n async execute() {\r\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\r\n if (!readyOutcome) {\r\n try {\r\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);\r\n const result = hasPendingRedirect ? await super.execute() : null;\r\n readyOutcome = () => Promise.resolve(result);\r\n }\r\n catch (e) {\r\n readyOutcome = () => Promise.reject(e);\r\n }\r\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\r\n }\r\n // If we're not bypassing auth state, the ready outcome should be set to\r\n // null.\r\n if (!this.bypassAuthState) {\r\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\r\n }\r\n return readyOutcome();\r\n }\r\n async onAuthEvent(event) {\r\n if (event.type === \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {\r\n return super.onAuthEvent(event);\r\n }\r\n else if (event.type === \"unknown\" /* AuthEventType.UNKNOWN */) {\r\n // This is a sentinel value indicating there's no pending redirect\r\n this.resolve(null);\r\n return;\r\n }\r\n if (event.eventId) {\r\n const user = await this.auth._redirectUserForId(event.eventId);\r\n if (user) {\r\n this.user = user;\r\n return super.onAuthEvent(event);\r\n }\r\n else {\r\n this.resolve(null);\r\n }\r\n }\r\n }\r\n async onExecution() { }\r\n cleanUp() { }\r\n}\r\nasync function _getAndClearPendingRedirectStatus(resolver, auth) {\r\n const key = pendingRedirectKey(auth);\r\n const persistence = resolverPersistence(resolver);\r\n if (!(await persistence._isAvailable())) {\r\n return false;\r\n }\r\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\r\n await persistence._remove(key);\r\n return hasPendingRedirect;\r\n}\r\nasync function _setPendingRedirectStatus(resolver, auth) {\r\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\r\n}\r\nfunction _clearRedirectOutcomes() {\r\n redirectOutcomeMap.clear();\r\n}\r\nfunction _overrideRedirectResult(auth, result) {\r\n redirectOutcomeMap.set(auth._key(), result);\r\n}\r\nfunction resolverPersistence(resolver) {\r\n return _getInstance(resolver._redirectPersistence);\r\n}\r\nfunction pendingRedirectKey(auth) {\r\n return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Authenticates a Firebase client using a full-page redirect flow.\r\n *\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link signInWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction signInWithRedirect(auth, provider, resolver) {\r\n return _signInWithRedirect(auth, provider, resolver);\r\n}\r\nasync function _signInWithRedirect(auth, provider, resolver) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await authInternal._initializationPromise;\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, authInternal);\r\n return resolverInternal._openRedirect(authInternal, provider, \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */);\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link reauthenticateWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * // Reauthenticate using a redirect.\r\n * await reauthenticateWithRedirect(result.user, provider);\r\n * // This will again trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction reauthenticateWithRedirect(user, provider, resolver) {\r\n return _reauthenticateWithRedirect(user, provider, resolver);\r\n}\r\nasync function _reauthenticateWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link linkWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithRedirect(result.user, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction linkWithRedirect(user, provider, resolver) {\r\n return _linkWithRedirect(user, provider, resolver);\r\n}\r\nasync function _linkWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _assertLinkedStatus(false, userInternal, provider.providerId);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\r\n *\r\n * @remarks\r\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\r\n * error. If no redirect operation was called, returns `null`.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function getRedirectResult(auth, resolver) {\r\n await _castAuth(auth)._initializationPromise;\r\n return _getRedirectResult(auth, resolver, false);\r\n}\r\nasync function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\r\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\r\n const result = await action.execute();\r\n if (result && !bypassAuthState) {\r\n delete result.user._redirectEventId;\r\n await authInternal._persistUserIfCurrent(result.user);\r\n await authInternal._setRedirectUser(null, resolverExtern);\r\n }\r\n return result;\r\n}\r\nasync function prepareUserForRedirect(user) {\r\n const eventId = _generateEventId(`${user.uid}:::`);\r\n user._redirectEventId = eventId;\r\n await user.auth._setRedirectUser(user);\r\n await user.auth._persistUserIfCurrent(user);\r\n return eventId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// The amount of time to store the UIDs of seen events; this is\r\n// set to 10 min by default\r\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\r\nclass AuthEventManager {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.cachedEventUids = new Set();\r\n this.consumers = new Set();\r\n this.queuedRedirectEvent = null;\r\n this.hasHandledPotentialRedirect = false;\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n registerConsumer(authEventConsumer) {\r\n this.consumers.add(authEventConsumer);\r\n if (this.queuedRedirectEvent &&\r\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {\r\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\r\n this.saveEventToCache(this.queuedRedirectEvent);\r\n this.queuedRedirectEvent = null;\r\n }\r\n }\r\n unregisterConsumer(authEventConsumer) {\r\n this.consumers.delete(authEventConsumer);\r\n }\r\n onEvent(event) {\r\n // Check if the event has already been handled\r\n if (this.hasEventBeenHandled(event)) {\r\n return false;\r\n }\r\n let handled = false;\r\n this.consumers.forEach(consumer => {\r\n if (this.isEventForConsumer(event, consumer)) {\r\n handled = true;\r\n this.sendToConsumer(event, consumer);\r\n this.saveEventToCache(event);\r\n }\r\n });\r\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\r\n // If we've already seen a redirect before, or this is a popup event,\r\n // bail now\r\n return handled;\r\n }\r\n this.hasHandledPotentialRedirect = true;\r\n // If the redirect wasn't handled, hang on to it\r\n if (!handled) {\r\n this.queuedRedirectEvent = event;\r\n handled = true;\r\n }\r\n return handled;\r\n }\r\n sendToConsumer(event, consumer) {\r\n var _a;\r\n if (event.error && !isNullRedirectEvent(event)) {\r\n const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||\r\n \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */;\r\n consumer.onError(_createError(this.auth, code));\r\n }\r\n else {\r\n consumer.onAuthEvent(event);\r\n }\r\n }\r\n isEventForConsumer(event, consumer) {\r\n const eventIdMatches = consumer.eventId === null ||\r\n (!!event.eventId && event.eventId === consumer.eventId);\r\n return consumer.filter.includes(event.type) && eventIdMatches;\r\n }\r\n hasEventBeenHandled(event) {\r\n if (Date.now() - this.lastProcessedEventTime >=\r\n EVENT_DUPLICATION_CACHE_DURATION_MS) {\r\n this.cachedEventUids.clear();\r\n }\r\n return this.cachedEventUids.has(eventUid(event));\r\n }\r\n saveEventToCache(event) {\r\n this.cachedEventUids.add(eventUid(event));\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n}\r\nfunction eventUid(e) {\r\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\r\n}\r\nfunction isNullRedirectEvent({ type, error }) {\r\n return (type === \"unknown\" /* AuthEventType.UNKNOWN */ &&\r\n (error === null || error === void 0 ? void 0 : error.code) === `auth/${\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */}`);\r\n}\r\nfunction isRedirectEvent(event) {\r\n switch (event.type) {\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return true;\r\n case \"unknown\" /* AuthEventType.UNKNOWN */:\r\n return isNullRedirectEvent(event);\r\n default:\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _getProjectConfig(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/projects\" /* Endpoint.GET_PROJECT_CONFIG */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\r\nconst HTTP_REGEX = /^https?/;\r\nasync function _validateOrigin(auth) {\r\n // Skip origin validation if we are in an emulated environment\r\n if (auth.config.emulator) {\r\n return;\r\n }\r\n const { authorizedDomains } = await _getProjectConfig(auth);\r\n for (const domain of authorizedDomains) {\r\n try {\r\n if (matchDomain(domain)) {\r\n return;\r\n }\r\n }\r\n catch (_a) {\r\n // Do nothing if there's a URL error; just continue searching\r\n }\r\n }\r\n // In the old SDK, this error also provides helpful messages.\r\n _fail(auth, \"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */);\r\n}\r\nfunction matchDomain(expected) {\r\n const currentUrl = _getCurrentUrl();\r\n const { protocol, hostname } = new URL(currentUrl);\r\n if (expected.startsWith('chrome-extension://')) {\r\n const ceUrl = new URL(expected);\r\n if (ceUrl.hostname === '' && hostname === '') {\r\n // For some reason we're not parsing chrome URLs properly\r\n return (protocol === 'chrome-extension:' &&\r\n expected.replace('chrome-extension://', '') ===\r\n currentUrl.replace('chrome-extension://', ''));\r\n }\r\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\r\n }\r\n if (!HTTP_REGEX.test(protocol)) {\r\n return false;\r\n }\r\n if (IP_ADDRESS_REGEX.test(expected)) {\r\n // The domain has to be exactly equal to the pattern, as an IP domain will\r\n // only contain the IP, no extra character.\r\n return hostname === expected;\r\n }\r\n // Dots in pattern should be escaped.\r\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\r\n // Non ip address domains.\r\n // domain.com = *.domain.com OR domain.com\r\n const re = new RegExp('^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');\r\n return re.test(hostname);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\r\n/**\r\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\r\n * it will stop working after a retrial. This is a hack to fix this issue.\r\n */\r\nfunction resetUnloadedGapiModules() {\r\n // Clear last failed gapi.load state to force next gapi.load to first\r\n // load the failed gapi.iframes module.\r\n // Get gapix.beacon context.\r\n const beacon = _window().___jsl;\r\n // Get current hint.\r\n if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {\r\n // Get gapi hint.\r\n for (const hint of Object.keys(beacon.H)) {\r\n // Requested modules.\r\n beacon.H[hint].r = beacon.H[hint].r || [];\r\n // Loaded modules.\r\n beacon.H[hint].L = beacon.H[hint].L || [];\r\n // Set requested modules to a copy of the loaded modules.\r\n beacon.H[hint].r = [...beacon.H[hint].L];\r\n // Clear pending callbacks.\r\n if (beacon.CP) {\r\n for (let i = 0; i < beacon.CP.length; i++) {\r\n // Remove all failed pending callbacks.\r\n beacon.CP[i] = null;\r\n }\r\n }\r\n }\r\n }\r\n}\r\nfunction loadGapi(auth) {\r\n return new Promise((resolve, reject) => {\r\n var _a, _b, _c;\r\n // Function to run when gapi.load is ready.\r\n function loadGapiIframe() {\r\n // The developer may have tried to previously run gapi.load and failed.\r\n // Run this to fix that.\r\n resetUnloadedGapiModules();\r\n gapi.load('gapi.iframes', {\r\n callback: () => {\r\n resolve(gapi.iframes.getContext());\r\n },\r\n ontimeout: () => {\r\n // The above reset may be sufficient, but having this reset after\r\n // failure ensures that if the developer calls gapi.load after the\r\n // connection is re-established and before another attempt to embed\r\n // the iframe, it would work and would not be broken because of our\r\n // failed attempt.\r\n // Timeout when gapi.iframes.Iframe not loaded.\r\n resetUnloadedGapiModules();\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n },\r\n timeout: NETWORK_TIMEOUT.get()\r\n });\r\n }\r\n if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {\r\n // If gapi.iframes.Iframe available, resolve.\r\n resolve(gapi.iframes.getContext());\r\n }\r\n else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {\r\n // Gapi loader ready, load gapi.iframes.\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Create a new iframe callback when this is called so as not to overwrite\r\n // any previous defined callback. This happens if this method is called\r\n // multiple times in parallel and could result in the later callback\r\n // overwriting the previous one. This would end up with a iframe\r\n // timeout.\r\n const cbName = _generateCallbackName('iframefcb');\r\n // GApi loader not available, dynamically load platform.js.\r\n _window()[cbName] = () => {\r\n // GApi loader should be ready.\r\n if (!!gapi.load) {\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Gapi loader failed, throw error.\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }\r\n };\r\n // Load GApi loader.\r\n return _loadJS(`${_gapiScriptUrl()}?onload=${cbName}`)\r\n .catch(e => reject(e));\r\n }\r\n }).catch(error => {\r\n // Reset cached promise to allow for retrial.\r\n cachedGApiLoader = null;\r\n throw error;\r\n });\r\n}\r\nlet cachedGApiLoader = null;\r\nfunction _loadGapi(auth) {\r\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\r\n return cachedGApiLoader;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PING_TIMEOUT = new Delay(5000, 15000);\r\nconst IFRAME_PATH = '__/auth/iframe';\r\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\r\nconst IFRAME_ATTRIBUTES = {\r\n style: {\r\n position: 'absolute',\r\n top: '-100px',\r\n width: '1px',\r\n height: '1px'\r\n },\r\n 'aria-hidden': 'true',\r\n tabindex: '-1'\r\n};\r\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\r\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\r\nconst EID_FROM_APIHOST = new Map([\r\n [\"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */, 'p'],\r\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'],\r\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\r\n]);\r\nfunction getIframeUrl(auth) {\r\n const config = auth.config;\r\n _assert(config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n const url = config.emulator\r\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\r\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\r\n const params = {\r\n apiKey: config.apiKey,\r\n appName: auth.name,\r\n v: SDK_VERSION\r\n };\r\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\r\n if (eid) {\r\n params.eid = eid;\r\n }\r\n const frameworks = auth._getFrameworks();\r\n if (frameworks.length) {\r\n params.fw = frameworks.join(',');\r\n }\r\n return `${url}?${querystring(params).slice(1)}`;\r\n}\r\nasync function _openIframe(auth) {\r\n const context = await _loadGapi(auth);\r\n const gapi = _window().gapi;\r\n _assert(gapi, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return context.open({\r\n where: document.body,\r\n url: getIframeUrl(auth),\r\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\r\n attributes: IFRAME_ATTRIBUTES,\r\n dontclear: true\r\n }, (iframe) => new Promise(async (resolve, reject) => {\r\n await iframe.restyle({\r\n // Prevent iframe from closing on mouse out.\r\n setHideOnLeave: false\r\n });\r\n const networkError = _createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);\r\n // Confirm iframe is correctly loaded.\r\n // To fallback on failure, set a timeout.\r\n const networkErrorTimer = _window().setTimeout(() => {\r\n reject(networkError);\r\n }, PING_TIMEOUT.get());\r\n // Clear timer and resolve pending iframe ready promise.\r\n function clearTimerAndResolve() {\r\n _window().clearTimeout(networkErrorTimer);\r\n resolve(iframe);\r\n }\r\n // This returns an IThenable. However the reject part does not call\r\n // when the iframe is not loaded.\r\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\r\n reject(networkError);\r\n });\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst BASE_POPUP_OPTIONS = {\r\n location: 'yes',\r\n resizable: 'yes',\r\n statusbar: 'yes',\r\n toolbar: 'no'\r\n};\r\nconst DEFAULT_WIDTH = 500;\r\nconst DEFAULT_HEIGHT = 600;\r\nconst TARGET_BLANK = '_blank';\r\nconst FIREFOX_EMPTY_URL = 'http://localhost';\r\nclass AuthPopup {\r\n constructor(window) {\r\n this.window = window;\r\n this.associatedEvent = null;\r\n }\r\n close() {\r\n if (this.window) {\r\n try {\r\n this.window.close();\r\n }\r\n catch (e) { }\r\n }\r\n }\r\n}\r\nfunction _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {\r\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\r\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\r\n let target = '';\r\n const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top,\r\n left });\r\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\r\n // specified, even though the popup is not necessarily blocked.\r\n const ua = getUA().toLowerCase();\r\n if (name) {\r\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\r\n }\r\n if (_isFirefox(ua)) {\r\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\r\n url = url || FIREFOX_EMPTY_URL;\r\n // Firefox disables by default scrolling on popup windows, which can create\r\n // issues when the user has many Google accounts, for instance.\r\n options.scrollbars = 'yes';\r\n }\r\n const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');\r\n if (_isIOSStandalone(ua) && target !== '_self') {\r\n openAsNewWindowIOS(url || '', target);\r\n return new AuthPopup(null);\r\n }\r\n // about:blank getting sanitized causing browsers like IE/Edge to display\r\n // brief error message before redirecting to handler.\r\n const newWin = window.open(url || '', target, optionsString);\r\n _assert(newWin, auth, \"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */);\r\n // Flaky on IE edge, encapsulate with a try and catch.\r\n try {\r\n newWin.focus();\r\n }\r\n catch (e) { }\r\n return new AuthPopup(newWin);\r\n}\r\nfunction openAsNewWindowIOS(url, target) {\r\n const el = document.createElement('a');\r\n el.href = url;\r\n el.target = target;\r\n const click = document.createEvent('MouseEvent');\r\n click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);\r\n el.dispatchEvent(click);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * URL for Authentication widget which will initiate the OAuth handshake\r\n *\r\n * @internal\r\n */\r\nconst WIDGET_PATH = '__/auth/handler';\r\n/**\r\n * URL for emulated environment\r\n *\r\n * @internal\r\n */\r\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\r\n/**\r\n * Fragment name for the App Check token that gets passed to the widget\r\n *\r\n * @internal\r\n */\r\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\r\nasync function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {\r\n _assert(auth.config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n _assert(auth.config.apiKey, auth, \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */);\r\n const params = {\r\n apiKey: auth.config.apiKey,\r\n appName: auth.name,\r\n authType,\r\n redirectUrl,\r\n v: SDK_VERSION,\r\n eventId\r\n };\r\n if (provider instanceof FederatedAuthProvider) {\r\n provider.setDefaultLanguage(auth.languageCode);\r\n params.providerId = provider.providerId || '';\r\n if (!isEmpty(provider.getCustomParameters())) {\r\n params.customParameters = JSON.stringify(provider.getCustomParameters());\r\n }\r\n // TODO set additionalParams from the provider as well?\r\n for (const [key, value] of Object.entries(additionalParams || {})) {\r\n params[key] = value;\r\n }\r\n }\r\n if (provider instanceof BaseOAuthProvider) {\r\n const scopes = provider.getScopes().filter(scope => scope !== '');\r\n if (scopes.length > 0) {\r\n params.scopes = scopes.join(',');\r\n }\r\n }\r\n if (auth.tenantId) {\r\n params.tid = auth.tenantId;\r\n }\r\n // TODO: maybe set eid as endipointId\r\n // TODO: maybe set fw as Frameworks.join(\",\")\r\n const paramsDict = params;\r\n for (const key of Object.keys(paramsDict)) {\r\n if (paramsDict[key] === undefined) {\r\n delete paramsDict[key];\r\n }\r\n }\r\n // Sets the App Check token to pass to the widget\r\n const appCheckToken = await auth._getAppCheckToken();\r\n const appCheckTokenFragment = appCheckToken\r\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\r\n : '';\r\n // Start at index 1 to skip the leading '&' in the query string\r\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;\r\n}\r\nfunction getHandlerBase({ config }) {\r\n if (!config.emulator) {\r\n return `https://${config.authDomain}/${WIDGET_PATH}`;\r\n }\r\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The special web storage event\r\n *\r\n */\r\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\r\nclass BrowserPopupRedirectResolver {\r\n constructor() {\r\n this.eventManagers = {};\r\n this.iframes = {};\r\n this.originValidationPromises = {};\r\n this._redirectPersistence = browserSessionPersistence;\r\n this._completeRedirectFn = _getRedirectResult;\r\n this._overrideRedirectResult = _overrideRedirectResult;\r\n }\r\n // Wrapping in async even though we don't await anywhere in order\r\n // to make sure errors are raised as promise rejections\r\n async _openPopup(auth, provider, authType, eventId) {\r\n var _a;\r\n debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');\r\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n return _open(auth, url, _generateEventId());\r\n }\r\n async _openRedirect(auth, provider, authType, eventId) {\r\n await this._originValidation(auth);\r\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n _setWindowLocation(url);\r\n return new Promise(() => { });\r\n }\r\n _initialize(auth) {\r\n const key = auth._key();\r\n if (this.eventManagers[key]) {\r\n const { manager, promise } = this.eventManagers[key];\r\n if (manager) {\r\n return Promise.resolve(manager);\r\n }\r\n else {\r\n debugAssert(promise, 'If manager is not set, promise should be');\r\n return promise;\r\n }\r\n }\r\n const promise = this.initAndGetManager(auth);\r\n this.eventManagers[key] = { promise };\r\n // If the promise is rejected, the key should be removed so that the\r\n // operation can be retried later.\r\n promise.catch(() => {\r\n delete this.eventManagers[key];\r\n });\r\n return promise;\r\n }\r\n async initAndGetManager(auth) {\r\n const iframe = await _openIframe(auth);\r\n const manager = new AuthEventManager(auth);\r\n iframe.register('authEvent', (iframeEvent) => {\r\n _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, \"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */);\r\n // TODO: Consider splitting redirect and popup events earlier on\r\n const handled = manager.onEvent(iframeEvent.authEvent);\r\n return { status: handled ? \"ACK\" /* GapiOutcome.ACK */ : \"ERROR\" /* GapiOutcome.ERROR */ };\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n this.eventManagers[auth._key()] = { manager };\r\n this.iframes[auth._key()] = iframe;\r\n return manager;\r\n }\r\n _isIframeWebStorageSupported(auth, cb) {\r\n const iframe = this.iframes[auth._key()];\r\n iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {\r\n var _a;\r\n const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];\r\n if (isSupported !== undefined) {\r\n cb(!!isSupported);\r\n }\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n }\r\n _originValidation(auth) {\r\n const key = auth._key();\r\n if (!this.originValidationPromises[key]) {\r\n this.originValidationPromises[key] = _validateOrigin(auth);\r\n }\r\n return this.originValidationPromises[key];\r\n }\r\n get _shouldInitProactively() {\r\n // Mobile browsers and Safari need to optimistically initialize\r\n return _isMobileBrowser() || _isSafari() || _isIOS();\r\n }\r\n}\r\n/**\r\n * An implementation of {@link PopupRedirectResolver} suitable for browser\r\n * based applications.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @public\r\n */\r\nconst browserPopupRedirectResolver = BrowserPopupRedirectResolver;\n\nclass MultiFactorAssertionImpl {\r\n constructor(factorId) {\r\n this.factorId = factorId;\r\n }\r\n _process(auth, session, displayName) {\r\n switch (session.type) {\r\n case \"enroll\" /* MultiFactorSessionType.ENROLL */:\r\n return this._finalizeEnroll(auth, session.credential, displayName);\r\n case \"signin\" /* MultiFactorSessionType.SIGN_IN */:\r\n return this._finalizeSignIn(auth, session.credential);\r\n default:\r\n return debugFail('unexpected MultiFactorSessionType');\r\n }\r\n }\r\n}\n\n/**\r\n * {@inheritdoc PhoneMultiFactorAssertion}\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(credential) {\r\n super(\"phone\" /* FactorId.PHONE */);\r\n this.credential = credential;\r\n }\r\n /** @internal */\r\n static _fromCredential(credential) {\r\n return new PhoneMultiFactorAssertionImpl(credential);\r\n }\r\n /** @internal */\r\n _finalizeEnroll(auth, idToken, displayName) {\r\n return finalizeEnrollPhoneMfa(auth, {\r\n idToken,\r\n displayName,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n /** @internal */\r\n _finalizeSignIn(auth, mfaPendingCredential) {\r\n return finalizeSignInPhoneMfa(auth, {\r\n mfaPendingCredential,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorGenerator {\r\n constructor() { }\r\n /**\r\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\r\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}\r\n */\r\n static assertion(credential) {\r\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\r\n }\r\n}\r\n/**\r\n * The identifier of the phone second factor: `phone`.\r\n */\r\nPhoneMultiFactorGenerator.FACTOR_ID = 'phone';\n\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass TotpMultiFactorGenerator {\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\r\n * the TOTP (time-based one-time password) second factor.\r\n * This assertion is used to complete enrollment in TOTP second factor.\r\n *\r\n * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorUser.enroll}.\r\n */\r\n static assertionForEnrollment(secret, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\r\n }\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\r\n * This assertion is used to complete signIn with TOTP as the second factor.\r\n *\r\n * @param enrollmentId identifies the enrolled TOTP second factor.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}.\r\n */\r\n static assertionForSignIn(enrollmentId, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);\r\n }\r\n /**\r\n * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\r\n * Creates a TOTP secret as part of enrolling a TOTP second factor.\r\n * Used for generating a QR code URL or inputting into a TOTP app.\r\n * This method uses the auth instance corresponding to the user in the multiFactorSession.\r\n *\r\n * @param session The {@link MultiFactorSession} that the user is part of.\r\n * @returns A promise to {@link TotpSecret}.\r\n */\r\n static async generateSecret(session) {\r\n var _a;\r\n const mfaSession = session;\r\n _assert(typeof ((_a = mfaSession.user) === null || _a === void 0 ? void 0 : _a.auth) !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollTotpMfa(mfaSession.user.auth, {\r\n idToken: mfaSession.credential,\r\n totpEnrollmentInfo: {}\r\n });\r\n return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.user.auth);\r\n }\r\n}\r\n/**\r\n * The identifier of the TOTP second factor: `totp`.\r\n */\r\nTotpMultiFactorGenerator.FACTOR_ID = \"totp\" /* FactorId.TOTP */;\r\nclass TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(otp, enrollmentId, secret) {\r\n super(\"totp\" /* FactorId.TOTP */);\r\n this.otp = otp;\r\n this.enrollmentId = enrollmentId;\r\n this.secret = secret;\r\n }\r\n /** @internal */\r\n static _fromSecret(secret, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\r\n }\r\n /** @internal */\r\n static _fromEnrollmentId(enrollmentId, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\r\n }\r\n /** @internal */\r\n async _finalizeEnroll(auth, idToken, displayName) {\r\n _assert(typeof this.secret !== 'undefined', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return finalizeEnrollTotpMfa(auth, {\r\n idToken,\r\n displayName,\r\n totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\r\n });\r\n }\r\n /** @internal */\r\n async _finalizeSignIn(auth, mfaPendingCredential) {\r\n _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n const totpVerificationInfo = { verificationCode: this.otp };\r\n return finalizeSignInTotpMfa(auth, {\r\n mfaPendingCredential,\r\n mfaEnrollmentId: this.enrollmentId,\r\n totpVerificationInfo\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * Stores the shared secret key and other parameters to generate time-based OTPs.\r\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\r\n * @public\r\n */\r\nclass TotpSecret {\r\n // The public members are declared outside the constructor so the docs can be generated.\r\n constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {\r\n this.sessionInfo = sessionInfo;\r\n this.auth = auth;\r\n this.secretKey = secretKey;\r\n this.hashingAlgorithm = hashingAlgorithm;\r\n this.codeLength = codeLength;\r\n this.codeIntervalSeconds = codeIntervalSeconds;\r\n this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\r\n }\r\n /** @internal */\r\n static _fromStartTotpMfaEnrollmentResponse(response, auth) {\r\n return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth);\r\n }\r\n /** @internal */\r\n _makeTotpVerificationInfo(otp) {\r\n return { sessionInfo: this.sessionInfo, verificationCode: otp };\r\n }\r\n /**\r\n * Returns a QR code URL as described in\r\n * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\r\n * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\r\n * If the optional parameters are unspecified, an accountName of and issuer of are used.\r\n *\r\n * @param accountName the name of the account/app along with a user identifier.\r\n * @param issuer issuer of the TOTP (likely the app name).\r\n * @returns A QR code URL string.\r\n */\r\n generateQrCodeUrl(accountName, issuer) {\r\n var _a;\r\n let useDefaults = false;\r\n if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\r\n useDefaults = true;\r\n }\r\n if (useDefaults) {\r\n if (_isEmptyString(accountName)) {\r\n accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';\r\n }\r\n if (_isEmptyString(issuer)) {\r\n issuer = this.auth.name;\r\n }\r\n }\r\n return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\r\n }\r\n}\r\n/** @internal */\r\nfunction _isEmptyString(input) {\r\n return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;\r\n}\n\nvar name = \"@firebase/auth\";\nvar version = \"1.7.5\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthInterop {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.internalListeners = new Map();\r\n }\r\n getUid() {\r\n var _a;\r\n this.assertAuthConfigured();\r\n return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;\r\n }\r\n async getToken(forceRefresh) {\r\n this.assertAuthConfigured();\r\n await this.auth._initializationPromise;\r\n if (!this.auth.currentUser) {\r\n return null;\r\n }\r\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\r\n return { accessToken };\r\n }\r\n addAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n if (this.internalListeners.has(listener)) {\r\n return;\r\n }\r\n const unsubscribe = this.auth.onIdTokenChanged(user => {\r\n listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);\r\n });\r\n this.internalListeners.set(listener, unsubscribe);\r\n this.updateProactiveRefresh();\r\n }\r\n removeAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n const unsubscribe = this.internalListeners.get(listener);\r\n if (!unsubscribe) {\r\n return;\r\n }\r\n this.internalListeners.delete(listener);\r\n unsubscribe();\r\n this.updateProactiveRefresh();\r\n }\r\n assertAuthConfigured() {\r\n _assert(this.auth._initializationPromise, \"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);\r\n }\r\n updateProactiveRefresh() {\r\n if (this.internalListeners.size > 0) {\r\n this.auth._startProactiveRefresh();\r\n }\r\n else {\r\n this.auth._stopProactiveRefresh();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getVersionForPlatform(clientPlatform) {\r\n switch (clientPlatform) {\r\n case \"Node\" /* ClientPlatform.NODE */:\r\n return 'node';\r\n case \"ReactNative\" /* ClientPlatform.REACT_NATIVE */:\r\n return 'rn';\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n return 'webworker';\r\n case \"Cordova\" /* ClientPlatform.CORDOVA */:\r\n return 'cordova';\r\n case \"WebExtension\" /* ClientPlatform.WEB_EXTENSION */:\r\n return 'web-extension';\r\n default:\r\n return undefined;\r\n }\r\n}\r\n/** @internal */\r\nfunction registerAuth(clientPlatform) {\r\n _registerComponent(new Component(\"auth\" /* _ComponentName.AUTH */, (container, { options: deps }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const heartbeatServiceProvider = container.getProvider('heartbeat');\r\n const appCheckServiceProvider = container.getProvider('app-check-internal');\r\n const { apiKey, authDomain } = app.options;\r\n _assert(apiKey && !apiKey.includes(':'), \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });\r\n const config = {\r\n apiKey,\r\n authDomain,\r\n clientPlatform,\r\n apiHost: \"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */,\r\n tokenApiHost: \"securetoken.googleapis.com\" /* DefaultConfig.TOKEN_API_HOST */,\r\n apiScheme: \"https\" /* DefaultConfig.API_SCHEME */,\r\n sdkClientVersion: _getClientVersion(clientPlatform)\r\n };\r\n const authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);\r\n _initializeAuthInstance(authInstance, deps);\r\n return authInstance;\r\n }, \"PUBLIC\" /* ComponentType.PUBLIC */)\r\n /**\r\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\r\n * For why we do this, See go/firebase-next-auth-init\r\n */\r\n .setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */)\r\n /**\r\n * Because all firebase products that depend on auth depend on auth-internal directly,\r\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\r\n */\r\n .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {\r\n const authInternalProvider = container.getProvider(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */);\r\n authInternalProvider.initialize();\r\n }));\r\n _registerComponent(new Component(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */, container => {\r\n const auth = _castAuth(container.getProvider(\"auth\" /* _ComponentName.AUTH */).getImmediate());\r\n return (auth => new AuthInterop(auth))(auth);\r\n }, \"PRIVATE\" /* ComponentType.PRIVATE */).setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */));\r\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\r\nconst authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\r\nlet lastPostedIdToken = null;\r\nconst mintCookieFactory = (url) => async (user) => {\r\n const idTokenResult = user && (await user.getIdTokenResult());\r\n const idTokenAge = idTokenResult &&\r\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;\r\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\r\n return;\r\n }\r\n // Specifically trip null => undefined when logged out, to delete any existing cookie\r\n const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;\r\n if (lastPostedIdToken === idToken) {\r\n return;\r\n }\r\n lastPostedIdToken = idToken;\r\n await fetch(url, {\r\n method: idToken ? 'POST' : 'DELETE',\r\n headers: idToken\r\n ? {\r\n 'Authorization': `Bearer ${idToken}`\r\n }\r\n : {}\r\n });\r\n};\r\n/**\r\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\r\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\r\n *\r\n * @param app - The Firebase App.\r\n *\r\n * @public\r\n */\r\nfunction getAuth(app = getApp()) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n return provider.getImmediate();\r\n }\r\n const auth = initializeAuth(app, {\r\n popupRedirectResolver: browserPopupRedirectResolver,\r\n persistence: [\r\n indexedDBLocalPersistence,\r\n browserLocalPersistence,\r\n browserSessionPersistence\r\n ]\r\n });\r\n const authTokenSyncPath = getExperimentalSetting('authTokenSyncURL');\r\n // Only do the Cookie exchange in a secure context\r\n if (authTokenSyncPath &&\r\n typeof isSecureContext === 'boolean' &&\r\n isSecureContext) {\r\n // Don't allow urls (XSS possibility), only paths on the same domain\r\n const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin);\r\n if (location.origin === authTokenSyncUrl.origin) {\r\n const mintCookie = mintCookieFactory(authTokenSyncUrl.toString());\r\n beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));\r\n onIdTokenChanged(auth, user => mintCookie(user));\r\n }\r\n }\r\n const authEmulatorHost = getDefaultEmulatorHost('auth');\r\n if (authEmulatorHost) {\r\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\r\n }\r\n return auth;\r\n}\r\nfunction getScriptParentElement() {\r\n var _a, _b;\r\n return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;\r\n}\r\n_setExternalJSProvider({\r\n loadJS(url) {\r\n // TODO: consider adding timeout support & cancellation\r\n return new Promise((resolve, reject) => {\r\n const el = document.createElement('script');\r\n el.setAttribute('src', url);\r\n el.onload = resolve;\r\n el.onerror = e => {\r\n const error = _createError(\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n error.customData = e;\r\n reject(error);\r\n };\r\n el.type = 'text/javascript';\r\n el.charset = 'UTF-8';\r\n getScriptParentElement().appendChild(el);\r\n });\r\n },\r\n gapiScript: 'https://apis.google.com/js/api.js',\r\n recaptchaV2Script: 'https://www.google.com/recaptcha/api.js',\r\n recaptchaEnterpriseScript: 'https://www.google.com/recaptcha/enterprise.js?render='\r\n});\r\nregisterAuth(\"Browser\" /* ClientPlatform.BROWSER */);\n\nexport { TwitterAuthProvider as $, ActionCodeOperation as A, updateCurrentUser as B, signOut as C, revokeAccessToken as D, deleteUser as E, FactorId as F, debugErrorMap as G, prodErrorMap as H, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as I, initializeAuth as J, connectAuthEmulator as K, AuthCredential as L, EmailAuthCredential as M, OAuthCredential as N, OperationType as O, PhoneAuthProvider as P, PhoneAuthCredential as Q, RecaptchaVerifier as R, SignInMethod as S, TotpMultiFactorGenerator as T, inMemoryPersistence as U, EmailAuthProvider as V, FacebookAuthProvider as W, GoogleAuthProvider as X, GithubAuthProvider as Y, OAuthProvider as Z, SAMLAuthProvider as _, browserSessionPersistence as a, signInAnonymously as a0, signInWithCredential as a1, linkWithCredential as a2, reauthenticateWithCredential as a3, signInWithCustomToken as a4, sendPasswordResetEmail as a5, confirmPasswordReset as a6, applyActionCode as a7, checkActionCode as a8, verifyPasswordResetCode as a9, _isIOS7Or8 as aA, _createError as aB, _assert as aC, AuthEventManager as aD, _getInstance as aE, _persistenceKeyName as aF, _getRedirectResult as aG, _overrideRedirectResult as aH, _clearRedirectOutcomes as aI, _castAuth as aJ, UserImpl as aK, AuthImpl as aL, _getClientVersion as aM, _generateEventId as aN, AuthPopup as aO, FetchProvider as aP, SAMLAuthCredential as aQ, createUserWithEmailAndPassword as aa, signInWithEmailAndPassword as ab, sendSignInLinkToEmail as ac, isSignInWithEmailLink as ad, signInWithEmailLink as ae, fetchSignInMethodsForEmail as af, sendEmailVerification as ag, verifyBeforeUpdateEmail as ah, ActionCodeURL as ai, parseActionCodeURL as aj, updateProfile as ak, updateEmail as al, updatePassword as am, getIdToken as an, getIdTokenResult as ao, unlink as ap, getAdditionalUserInfo as aq, reload as ar, getMultiFactorResolver as as, multiFactor as at, debugAssert as au, _isIOS as av, _isAndroid as aw, _fail as ax, _getRedirectUrl as ay, _getProjectConfig as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, TotpSecret as n, getAuth as o, ProviderId as p, setPersistence as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, initializeRecaptchaConfig as t, updatePhoneNumber as u, validatePassword as v, onIdTokenChanged as w, beforeAuthStateChanged as x, onAuthStateChanged as y, useDeviceLanguage as z };\n//# sourceMappingURL=index-54738136.js.map\n","import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component, ComponentContainer, Provider } from '@firebase/component';\nimport { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';\nimport { Logger, LogLevel } from '@firebase/logger';\n\nconst name = \"@firebase/database\";\nconst version = \"1.0.6\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** The semver (www.semver.org) version of the SDK. */\r\nlet SDK_VERSION = '';\r\n/**\r\n * SDK_VERSION should be set before any database instance is created\r\n * @internal\r\n */\r\nfunction setSDKVersion(version) {\r\n SDK_VERSION = version;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Wraps a DOM Storage object and:\r\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\r\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\r\n *\r\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\r\n * and one for localStorage.\r\n *\r\n */\r\nclass DOMStorageWrapper {\r\n /**\r\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\r\n */\r\n constructor(domStorage_) {\r\n this.domStorage_ = domStorage_;\r\n // Use a prefix to avoid collisions with other stuff saved by the app.\r\n this.prefix_ = 'firebase:';\r\n }\r\n /**\r\n * @param key - The key to save the value under\r\n * @param value - The value being stored, or null to remove the key.\r\n */\r\n set(key, value) {\r\n if (value == null) {\r\n this.domStorage_.removeItem(this.prefixedName_(key));\r\n }\r\n else {\r\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\r\n }\r\n }\r\n /**\r\n * @returns The value that was stored under this key, or null\r\n */\r\n get(key) {\r\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\r\n if (storedVal == null) {\r\n return null;\r\n }\r\n else {\r\n return jsonEval(storedVal);\r\n }\r\n }\r\n remove(key) {\r\n this.domStorage_.removeItem(this.prefixedName_(key));\r\n }\r\n prefixedName_(name) {\r\n return this.prefix_ + name;\r\n }\r\n toString() {\r\n return this.domStorage_.toString();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\r\n * (TODO: create interface for both to implement).\r\n */\r\nclass MemoryStorage {\r\n constructor() {\r\n this.cache_ = {};\r\n this.isInMemoryStorage = true;\r\n }\r\n set(key, value) {\r\n if (value == null) {\r\n delete this.cache_[key];\r\n }\r\n else {\r\n this.cache_[key] = value;\r\n }\r\n }\r\n get(key) {\r\n if (contains(this.cache_, key)) {\r\n return this.cache_[key];\r\n }\r\n return null;\r\n }\r\n remove(key) {\r\n delete this.cache_[key];\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\r\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\r\n * to reflect this type\r\n *\r\n * @param domStorageName - Name of the underlying storage object\r\n * (e.g. 'localStorage' or 'sessionStorage').\r\n * @returns Turning off type information until a common interface is defined.\r\n */\r\nconst createStoragefor = function (domStorageName) {\r\n try {\r\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\r\n // so it must be inside the try/catch.\r\n if (typeof window !== 'undefined' &&\r\n typeof window[domStorageName] !== 'undefined') {\r\n // Need to test cache. Just because it's here doesn't mean it works\r\n const domStorage = window[domStorageName];\r\n domStorage.setItem('firebase:sentinel', 'cache');\r\n domStorage.removeItem('firebase:sentinel');\r\n return new DOMStorageWrapper(domStorage);\r\n }\r\n }\r\n catch (e) { }\r\n // Failed to create wrapper. Just return in-memory storage.\r\n // TODO: log?\r\n return new MemoryStorage();\r\n};\r\n/** A storage object that lasts across sessions */\r\nconst PersistentStorage = createStoragefor('localStorage');\r\n/** A storage object that only lasts one session */\r\nconst SessionStorage = createStoragefor('sessionStorage');\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logClient = new Logger('@firebase/database');\r\n/**\r\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\r\n */\r\nconst LUIDGenerator = (function () {\r\n let id = 1;\r\n return function () {\r\n return id++;\r\n };\r\n})();\r\n/**\r\n * Sha1 hash of the input string\r\n * @param str - The string to hash\r\n * @returns {!string} The resulting hash\r\n */\r\nconst sha1 = function (str) {\r\n const utf8Bytes = stringToByteArray(str);\r\n const sha1 = new Sha1();\r\n sha1.update(utf8Bytes);\r\n const sha1Bytes = sha1.digest();\r\n return base64.encodeByteArray(sha1Bytes);\r\n};\r\nconst buildLogMessage_ = function (...varArgs) {\r\n let message = '';\r\n for (let i = 0; i < varArgs.length; i++) {\r\n const arg = varArgs[i];\r\n if (Array.isArray(arg) ||\r\n (arg &&\r\n typeof arg === 'object' &&\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n typeof arg.length === 'number')) {\r\n message += buildLogMessage_.apply(null, arg);\r\n }\r\n else if (typeof arg === 'object') {\r\n message += stringify(arg);\r\n }\r\n else {\r\n message += arg;\r\n }\r\n message += ' ';\r\n }\r\n return message;\r\n};\r\n/**\r\n * Use this for all debug messages in Firebase.\r\n */\r\nlet logger = null;\r\n/**\r\n * Flag to check for log availability on first log message\r\n */\r\nlet firstLog_ = true;\r\n/**\r\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\r\n * @param logger_ - A flag to turn on logging, or a custom logger\r\n * @param persistent - Whether or not to persist logging settings across refreshes\r\n */\r\nconst enableLogging$1 = function (logger_, persistent) {\r\n assert(!persistent || logger_ === true || logger_ === false, \"Can't turn on custom loggers persistently.\");\r\n if (logger_ === true) {\r\n logClient.logLevel = LogLevel.VERBOSE;\r\n logger = logClient.log.bind(logClient);\r\n if (persistent) {\r\n SessionStorage.set('logging_enabled', true);\r\n }\r\n }\r\n else if (typeof logger_ === 'function') {\r\n logger = logger_;\r\n }\r\n else {\r\n logger = null;\r\n SessionStorage.remove('logging_enabled');\r\n }\r\n};\r\nconst log = function (...varArgs) {\r\n if (firstLog_ === true) {\r\n firstLog_ = false;\r\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\r\n enableLogging$1(true);\r\n }\r\n }\r\n if (logger) {\r\n const message = buildLogMessage_.apply(null, varArgs);\r\n logger(message);\r\n }\r\n};\r\nconst logWrapper = function (prefix) {\r\n return function (...varArgs) {\r\n log(prefix, ...varArgs);\r\n };\r\n};\r\nconst error = function (...varArgs) {\r\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\r\n logClient.error(message);\r\n};\r\nconst fatal = function (...varArgs) {\r\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\r\n logClient.error(message);\r\n throw new Error(message);\r\n};\r\nconst warn = function (...varArgs) {\r\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\r\n logClient.warn(message);\r\n};\r\n/**\r\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\r\n * does not use https.\r\n */\r\nconst warnIfPageIsSecure = function () {\r\n // Be very careful accessing browser globals. Who knows what may or may not exist.\r\n if (typeof window !== 'undefined' &&\r\n window.location &&\r\n window.location.protocol &&\r\n window.location.protocol.indexOf('https:') !== -1) {\r\n warn('Insecure Firebase access from a secure page. ' +\r\n 'Please use https in calls to new Firebase().');\r\n }\r\n};\r\n/**\r\n * Returns true if data is NaN, or +/- Infinity.\r\n */\r\nconst isInvalidJSONNumber = function (data) {\r\n return (typeof data === 'number' &&\r\n (data !== data || // NaN\r\n data === Number.POSITIVE_INFINITY ||\r\n data === Number.NEGATIVE_INFINITY));\r\n};\r\nconst executeWhenDOMReady = function (fn) {\r\n if (isNodeSdk() || document.readyState === 'complete') {\r\n fn();\r\n }\r\n else {\r\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\r\n // fire before onload), but fall back to onload.\r\n let called = false;\r\n const wrappedFn = function () {\r\n if (!document.body) {\r\n setTimeout(wrappedFn, Math.floor(10));\r\n return;\r\n }\r\n if (!called) {\r\n called = true;\r\n fn();\r\n }\r\n };\r\n if (document.addEventListener) {\r\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\r\n // fallback to onload.\r\n window.addEventListener('load', wrappedFn, false);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (document.attachEvent) {\r\n // IE.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n document.attachEvent('onreadystatechange', () => {\r\n if (document.readyState === 'complete') {\r\n wrappedFn();\r\n }\r\n });\r\n // fallback to onload.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n window.attachEvent('onload', wrappedFn);\r\n // jQuery has an extra hack for IE that we could employ (based on\r\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\r\n // I'm hoping we don't need it.\r\n }\r\n }\r\n};\r\n/**\r\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\r\n */\r\nconst MIN_NAME = '[MIN_NAME]';\r\n/**\r\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\r\n */\r\nconst MAX_NAME = '[MAX_NAME]';\r\n/**\r\n * Compares valid Firebase key names, plus min and max name\r\n */\r\nconst nameCompare = function (a, b) {\r\n if (a === b) {\r\n return 0;\r\n }\r\n else if (a === MIN_NAME || b === MAX_NAME) {\r\n return -1;\r\n }\r\n else if (b === MIN_NAME || a === MAX_NAME) {\r\n return 1;\r\n }\r\n else {\r\n const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);\r\n if (aAsInt !== null) {\r\n if (bAsInt !== null) {\r\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (bAsInt !== null) {\r\n return 1;\r\n }\r\n else {\r\n return a < b ? -1 : 1;\r\n }\r\n }\r\n};\r\n/**\r\n * @returns {!number} comparison result.\r\n */\r\nconst stringCompare = function (a, b) {\r\n if (a === b) {\r\n return 0;\r\n }\r\n else if (a < b) {\r\n return -1;\r\n }\r\n else {\r\n return 1;\r\n }\r\n};\r\nconst requireKey = function (key, obj) {\r\n if (obj && key in obj) {\r\n return obj[key];\r\n }\r\n else {\r\n throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));\r\n }\r\n};\r\nconst ObjectToUniqueKey = function (obj) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return stringify(obj);\r\n }\r\n const keys = [];\r\n // eslint-disable-next-line guard-for-in\r\n for (const k in obj) {\r\n keys.push(k);\r\n }\r\n // Export as json, but with the keys sorted.\r\n keys.sort();\r\n let key = '{';\r\n for (let i = 0; i < keys.length; i++) {\r\n if (i !== 0) {\r\n key += ',';\r\n }\r\n key += stringify(keys[i]);\r\n key += ':';\r\n key += ObjectToUniqueKey(obj[keys[i]]);\r\n }\r\n key += '}';\r\n return key;\r\n};\r\n/**\r\n * Splits a string into a number of smaller segments of maximum size\r\n * @param str - The string\r\n * @param segsize - The maximum number of chars in the string.\r\n * @returns The string, split into appropriately-sized chunks\r\n */\r\nconst splitStringBySize = function (str, segsize) {\r\n const len = str.length;\r\n if (len <= segsize) {\r\n return [str];\r\n }\r\n const dataSegs = [];\r\n for (let c = 0; c < len; c += segsize) {\r\n if (c + segsize > len) {\r\n dataSegs.push(str.substring(c, len));\r\n }\r\n else {\r\n dataSegs.push(str.substring(c, c + segsize));\r\n }\r\n }\r\n return dataSegs;\r\n};\r\n/**\r\n * Apply a function to each (key, value) pair in an object or\r\n * apply a function to each (index, value) pair in an array\r\n * @param obj - The object or array to iterate over\r\n * @param fn - The function to apply\r\n */\r\nfunction each(obj, fn) {\r\n for (const key in obj) {\r\n if (obj.hasOwnProperty(key)) {\r\n fn(key, obj[key]);\r\n }\r\n }\r\n}\r\n/**\r\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\r\n * I made one modification at the end and removed the NaN / Infinity\r\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\r\n * @param v - A double\r\n *\r\n */\r\nconst doubleToIEEE754String = function (v) {\r\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\r\n const ebits = 11, fbits = 52;\r\n const bias = (1 << (ebits - 1)) - 1;\r\n let s, e, f, ln, i;\r\n // Compute sign, exponent, fraction\r\n // Skip NaN / Infinity handling --MJL.\r\n if (v === 0) {\r\n e = 0;\r\n f = 0;\r\n s = 1 / v === -Infinity ? 1 : 0;\r\n }\r\n else {\r\n s = v < 0;\r\n v = Math.abs(v);\r\n if (v >= Math.pow(2, 1 - bias)) {\r\n // Normalized\r\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\r\n e = ln + bias;\r\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\r\n }\r\n else {\r\n // Denormalized\r\n e = 0;\r\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\r\n }\r\n }\r\n // Pack sign, exponent, fraction\r\n const bits = [];\r\n for (i = fbits; i; i -= 1) {\r\n bits.push(f % 2 ? 1 : 0);\r\n f = Math.floor(f / 2);\r\n }\r\n for (i = ebits; i; i -= 1) {\r\n bits.push(e % 2 ? 1 : 0);\r\n e = Math.floor(e / 2);\r\n }\r\n bits.push(s ? 1 : 0);\r\n bits.reverse();\r\n const str = bits.join('');\r\n // Return the data as a hex string. --MJL\r\n let hexByteString = '';\r\n for (i = 0; i < 64; i += 8) {\r\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\r\n if (hexByte.length === 1) {\r\n hexByte = '0' + hexByte;\r\n }\r\n hexByteString = hexByteString + hexByte;\r\n }\r\n return hexByteString.toLowerCase();\r\n};\r\n/**\r\n * Used to detect if we're in a Chrome content script (which executes in an\r\n * isolated environment where long-polling doesn't work).\r\n */\r\nconst isChromeExtensionContentScript = function () {\r\n return !!(typeof window === 'object' &&\r\n window['chrome'] &&\r\n window['chrome']['extension'] &&\r\n !/^chrome/.test(window.location.href));\r\n};\r\n/**\r\n * Used to detect if we're in a Windows 8 Store app.\r\n */\r\nconst isWindowsStoreApp = function () {\r\n // Check for the presence of a couple WinRT globals\r\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\r\n};\r\n/**\r\n * Converts a server error code to a Javascript Error\r\n */\r\nfunction errorForServerCode(code, query) {\r\n let reason = 'Unknown Error';\r\n if (code === 'too_big') {\r\n reason =\r\n 'The data requested exceeds the maximum size ' +\r\n 'that can be accessed with a single request.';\r\n }\r\n else if (code === 'permission_denied') {\r\n reason = \"Client doesn't have permission to access the desired data.\";\r\n }\r\n else if (code === 'unavailable') {\r\n reason = 'The service is unavailable';\r\n }\r\n const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n error.code = code.toUpperCase();\r\n return error;\r\n}\r\n/**\r\n * Used to test for integer-looking strings\r\n */\r\nconst INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\r\n/**\r\n * For use in keys, the minimum possible 32-bit integer.\r\n */\r\nconst INTEGER_32_MIN = -2147483648;\r\n/**\r\n * For use in kyes, the maximum possible 32-bit integer.\r\n */\r\nconst INTEGER_32_MAX = 2147483647;\r\n/**\r\n * If the string contains a 32-bit integer, return it. Else return null.\r\n */\r\nconst tryParseInt = function (str) {\r\n if (INTEGER_REGEXP_.test(str)) {\r\n const intVal = Number(str);\r\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\r\n return intVal;\r\n }\r\n }\r\n return null;\r\n};\r\n/**\r\n * Helper to run some code but catch any exceptions and re-throw them later.\r\n * Useful for preventing user callbacks from breaking internal code.\r\n *\r\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\r\n * convenient (we don't have to try to figure out when is a safe point to\r\n * re-throw it), and the behavior seems reasonable:\r\n *\r\n * * If you aren't pausing on exceptions, you get an error in the console with\r\n * the correct stack trace.\r\n * * If you're pausing on all exceptions, the debugger will pause on your\r\n * exception and then again when we rethrow it.\r\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\r\n * on us re-throwing it.\r\n *\r\n * @param fn - The code to guard.\r\n */\r\nconst exceptionGuard = function (fn) {\r\n try {\r\n fn();\r\n }\r\n catch (e) {\r\n // Re-throw exception when it's safe.\r\n setTimeout(() => {\r\n // It used to be that \"throw e\" would result in a good console error with\r\n // relevant context, but as of Chrome 39, you just get the firebase.js\r\n // file/line number where we re-throw it, which is useless. So we log\r\n // e.stack explicitly.\r\n const stack = e.stack || '';\r\n warn('Exception was thrown by user callback.', stack);\r\n throw e;\r\n }, Math.floor(0));\r\n }\r\n};\r\n/**\r\n * @returns {boolean} true if we think we're currently being crawled.\r\n */\r\nconst beingCrawled = function () {\r\n const userAgent = (typeof window === 'object' &&\r\n window['navigator'] &&\r\n window['navigator']['userAgent']) ||\r\n '';\r\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\r\n // believe to support JavaScript/AJAX rendering.\r\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\r\n // would have seen the page\" is flaky if we don't treat it as a crawler.\r\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\r\n};\r\n/**\r\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\r\n *\r\n * It is removed with clearTimeout() as normal.\r\n *\r\n * @param fn - Function to run.\r\n * @param time - Milliseconds to wait before running.\r\n * @returns The setTimeout() return value.\r\n */\r\nconst setTimeoutNonBlocking = function (fn, time) {\r\n const timeout = setTimeout(fn, time);\r\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\r\n if (typeof timeout === 'number' &&\r\n // @ts-ignore Is only defined in Deno environments.\r\n typeof Deno !== 'undefined' &&\r\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\r\n Deno['unrefTimer']) {\r\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\r\n Deno.unrefTimer(timeout);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (typeof timeout === 'object' && timeout['unref']) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n timeout['unref']();\r\n }\r\n return timeout;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Abstraction around AppCheck's token fetching capabilities.\r\n */\r\nclass AppCheckTokenProvider {\r\n constructor(appName_, appCheckProvider) {\r\n this.appName_ = appName_;\r\n this.appCheckProvider = appCheckProvider;\r\n this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });\r\n if (!this.appCheck) {\r\n appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));\r\n }\r\n }\r\n getToken(forceRefresh) {\r\n if (!this.appCheck) {\r\n return new Promise((resolve, reject) => {\r\n // Support delayed initialization of FirebaseAppCheck. This allows our\r\n // customers to initialize the RTDB SDK before initializing Firebase\r\n // AppCheck and ensures that all requests are authenticated if a token\r\n // becomes available before the timoeout below expires.\r\n setTimeout(() => {\r\n if (this.appCheck) {\r\n this.getToken(forceRefresh).then(resolve, reject);\r\n }\r\n else {\r\n resolve(null);\r\n }\r\n }, 0);\r\n });\r\n }\r\n return this.appCheck.getToken(forceRefresh);\r\n }\r\n addTokenChangeListener(listener) {\r\n var _a;\r\n (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));\r\n }\r\n notifyForInvalidToken() {\r\n warn(`Provided AppCheck credentials for the app named \"${this.appName_}\" ` +\r\n 'are invalid. This usually indicates your app was not initialized correctly.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Abstraction around FirebaseApp's token fetching capabilities.\r\n */\r\nclass FirebaseAuthTokenProvider {\r\n constructor(appName_, firebaseOptions_, authProvider_) {\r\n this.appName_ = appName_;\r\n this.firebaseOptions_ = firebaseOptions_;\r\n this.authProvider_ = authProvider_;\r\n this.auth_ = null;\r\n this.auth_ = authProvider_.getImmediate({ optional: true });\r\n if (!this.auth_) {\r\n authProvider_.onInit(auth => (this.auth_ = auth));\r\n }\r\n }\r\n getToken(forceRefresh) {\r\n if (!this.auth_) {\r\n return new Promise((resolve, reject) => {\r\n // Support delayed initialization of FirebaseAuth. This allows our\r\n // customers to initialize the RTDB SDK before initializing Firebase\r\n // Auth and ensures that all requests are authenticated if a token\r\n // becomes available before the timoeout below expires.\r\n setTimeout(() => {\r\n if (this.auth_) {\r\n this.getToken(forceRefresh).then(resolve, reject);\r\n }\r\n else {\r\n resolve(null);\r\n }\r\n }, 0);\r\n });\r\n }\r\n return this.auth_.getToken(forceRefresh).catch(error => {\r\n // TODO: Need to figure out all the cases this is raised and whether\r\n // this makes sense.\r\n if (error && error.code === 'auth/token-not-initialized') {\r\n log('Got auth/token-not-initialized error. Treating as null token.');\r\n return null;\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n addTokenChangeListener(listener) {\r\n // TODO: We might want to wrap the listener and call it with no args to\r\n // avoid a leaky abstraction, but that makes removing the listener harder.\r\n if (this.auth_) {\r\n this.auth_.addAuthTokenListener(listener);\r\n }\r\n else {\r\n this.authProvider_\r\n .get()\r\n .then(auth => auth.addAuthTokenListener(listener));\r\n }\r\n }\r\n removeTokenChangeListener(listener) {\r\n this.authProvider_\r\n .get()\r\n .then(auth => auth.removeAuthTokenListener(listener));\r\n }\r\n notifyForInvalidToken() {\r\n let errorMessage = 'Provided authentication credentials for the app named \"' +\r\n this.appName_ +\r\n '\" are invalid. This usually indicates your app was not ' +\r\n 'initialized correctly. ';\r\n if ('credential' in this.firebaseOptions_) {\r\n errorMessage +=\r\n 'Make sure the \"credential\" property provided to initializeApp() ' +\r\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\r\n 'project.';\r\n }\r\n else if ('serviceAccount' in this.firebaseOptions_) {\r\n errorMessage +=\r\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\r\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\r\n 'project.';\r\n }\r\n else {\r\n errorMessage +=\r\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\r\n 'initializeApp() match the values provided for your app at ' +\r\n 'https://console.firebase.google.com/.';\r\n }\r\n warn(errorMessage);\r\n }\r\n}\r\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\r\nclass EmulatorTokenProvider {\r\n constructor(accessToken) {\r\n this.accessToken = accessToken;\r\n }\r\n getToken(forceRefresh) {\r\n return Promise.resolve({\r\n accessToken: this.accessToken\r\n });\r\n }\r\n addTokenChangeListener(listener) {\r\n // Invoke the listener immediately to match the behavior in Firebase Auth\r\n // (see packages/auth/src/auth.js#L1807)\r\n listener(this.accessToken);\r\n }\r\n removeTokenChangeListener(listener) { }\r\n notifyForInvalidToken() { }\r\n}\r\n/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\r\nEmulatorTokenProvider.OWNER = 'owner';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PROTOCOL_VERSION = '5';\r\nconst VERSION_PARAM = 'v';\r\nconst TRANSPORT_SESSION_PARAM = 's';\r\nconst REFERER_PARAM = 'r';\r\nconst FORGE_REF = 'f';\r\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\r\n// firebase.corp.google.com\r\nconst FORGE_DOMAIN_RE = /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\r\nconst LAST_SESSION_PARAM = 'ls';\r\nconst APPLICATION_ID_PARAM = 'p';\r\nconst APP_CHECK_TOKEN_PARAM = 'ac';\r\nconst WEBSOCKET = 'websocket';\r\nconst LONG_POLLING = 'long_polling';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A class that holds metadata about a Repo object\r\n */\r\nclass RepoInfo {\r\n /**\r\n * @param host - Hostname portion of the url for the repo\r\n * @param secure - Whether or not this repo is accessed over ssl\r\n * @param namespace - The namespace represented by the repo\r\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\r\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\r\n * @param persistenceKey - Override the default session persistence storage key\r\n */\r\n constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {\r\n this.secure = secure;\r\n this.namespace = namespace;\r\n this.webSocketOnly = webSocketOnly;\r\n this.nodeAdmin = nodeAdmin;\r\n this.persistenceKey = persistenceKey;\r\n this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;\r\n this.isUsingEmulator = isUsingEmulator;\r\n this._host = host.toLowerCase();\r\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\r\n this.internalHost =\r\n PersistentStorage.get('host:' + host) || this._host;\r\n }\r\n isCacheableHost() {\r\n return this.internalHost.substr(0, 2) === 's-';\r\n }\r\n isCustomHost() {\r\n return (this._domain !== 'firebaseio.com' &&\r\n this._domain !== 'firebaseio-demo.com');\r\n }\r\n get host() {\r\n return this._host;\r\n }\r\n set host(newHost) {\r\n if (newHost !== this.internalHost) {\r\n this.internalHost = newHost;\r\n if (this.isCacheableHost()) {\r\n PersistentStorage.set('host:' + this._host, this.internalHost);\r\n }\r\n }\r\n }\r\n toString() {\r\n let str = this.toURLString();\r\n if (this.persistenceKey) {\r\n str += '<' + this.persistenceKey + '>';\r\n }\r\n return str;\r\n }\r\n toURLString() {\r\n const protocol = this.secure ? 'https://' : 'http://';\r\n const query = this.includeNamespaceInQueryParams\r\n ? `?ns=${this.namespace}`\r\n : '';\r\n return `${protocol}${this.host}/${query}`;\r\n }\r\n}\r\nfunction repoInfoNeedsQueryParam(repoInfo) {\r\n return (repoInfo.host !== repoInfo.internalHost ||\r\n repoInfo.isCustomHost() ||\r\n repoInfo.includeNamespaceInQueryParams);\r\n}\r\n/**\r\n * Returns the websocket URL for this repo\r\n * @param repoInfo - RepoInfo object\r\n * @param type - of connection\r\n * @param params - list\r\n * @returns The URL for this repo\r\n */\r\nfunction repoInfoConnectionURL(repoInfo, type, params) {\r\n assert(typeof type === 'string', 'typeof type must == string');\r\n assert(typeof params === 'object', 'typeof params must == object');\r\n let connURL;\r\n if (type === WEBSOCKET) {\r\n connURL =\r\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\r\n }\r\n else if (type === LONG_POLLING) {\r\n connURL =\r\n (repoInfo.secure ? 'https://' : 'http://') +\r\n repoInfo.internalHost +\r\n '/.lp?';\r\n }\r\n else {\r\n throw new Error('Unknown connection type: ' + type);\r\n }\r\n if (repoInfoNeedsQueryParam(repoInfo)) {\r\n params['ns'] = repoInfo.namespace;\r\n }\r\n const pairs = [];\r\n each(params, (key, value) => {\r\n pairs.push(key + '=' + value);\r\n });\r\n return connURL + pairs.join('&');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Tracks a collection of stats.\r\n */\r\nclass StatsCollection {\r\n constructor() {\r\n this.counters_ = {};\r\n }\r\n incrementCounter(name, amount = 1) {\r\n if (!contains(this.counters_, name)) {\r\n this.counters_[name] = 0;\r\n }\r\n this.counters_[name] += amount;\r\n }\r\n get() {\r\n return deepCopy(this.counters_);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst collections = {};\r\nconst reporters = {};\r\nfunction statsManagerGetCollection(repoInfo) {\r\n const hashString = repoInfo.toString();\r\n if (!collections[hashString]) {\r\n collections[hashString] = new StatsCollection();\r\n }\r\n return collections[hashString];\r\n}\r\nfunction statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {\r\n const hashString = repoInfo.toString();\r\n if (!reporters[hashString]) {\r\n reporters[hashString] = creatorFunction();\r\n }\r\n return reporters[hashString];\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class ensures the packets from the server arrive in order\r\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\r\n */\r\nclass PacketReceiver {\r\n /**\r\n * @param onMessage_\r\n */\r\n constructor(onMessage_) {\r\n this.onMessage_ = onMessage_;\r\n this.pendingResponses = [];\r\n this.currentResponseNum = 0;\r\n this.closeAfterResponse = -1;\r\n this.onClose = null;\r\n }\r\n closeAfter(responseNum, callback) {\r\n this.closeAfterResponse = responseNum;\r\n this.onClose = callback;\r\n if (this.closeAfterResponse < this.currentResponseNum) {\r\n this.onClose();\r\n this.onClose = null;\r\n }\r\n }\r\n /**\r\n * Each message from the server comes with a response number, and an array of data. The responseNumber\r\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\r\n * browsers will respond in the same order as the requests we sent\r\n */\r\n handleResponse(requestNum, data) {\r\n this.pendingResponses[requestNum] = data;\r\n while (this.pendingResponses[this.currentResponseNum]) {\r\n const toProcess = this.pendingResponses[this.currentResponseNum];\r\n delete this.pendingResponses[this.currentResponseNum];\r\n for (let i = 0; i < toProcess.length; ++i) {\r\n if (toProcess[i]) {\r\n exceptionGuard(() => {\r\n this.onMessage_(toProcess[i]);\r\n });\r\n }\r\n }\r\n if (this.currentResponseNum === this.closeAfterResponse) {\r\n if (this.onClose) {\r\n this.onClose();\r\n this.onClose = null;\r\n }\r\n break;\r\n }\r\n this.currentResponseNum++;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// URL query parameters associated with longpolling\r\nconst FIREBASE_LONGPOLL_START_PARAM = 'start';\r\nconst FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\r\nconst FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\r\nconst FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\r\nconst FIREBASE_LONGPOLL_ID_PARAM = 'id';\r\nconst FIREBASE_LONGPOLL_PW_PARAM = 'pw';\r\nconst FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\r\nconst FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\r\nconst FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\r\nconst FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\r\nconst FIREBASE_LONGPOLL_DATA_PARAM = 'd';\r\nconst FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\r\n//Data size constants.\r\n//TODO: Perf: the maximum length actually differs from browser to browser.\r\n// We should check what browser we're on and set accordingly.\r\nconst MAX_URL_DATA_SIZE = 1870;\r\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\r\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\r\n/**\r\n * Keepalive period\r\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\r\n * length of 30 seconds that we can't exceed.\r\n */\r\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\r\n/**\r\n * How long to wait before aborting a long-polling connection attempt.\r\n */\r\nconst LP_CONNECT_TIMEOUT = 30000;\r\n/**\r\n * This class manages a single long-polling connection.\r\n */\r\nclass BrowserPollConnection {\r\n /**\r\n * @param connId An identifier for this connection, used for logging\r\n * @param repoInfo The info for the endpoint to send data to.\r\n * @param applicationId The Firebase App ID for this project.\r\n * @param appCheckToken The AppCheck token for this client.\r\n * @param authToken The AuthToken to use for this connection.\r\n * @param transportSessionId Optional transportSessionid if we are\r\n * reconnecting for an existing transport session\r\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\r\n * already created a connection previously\r\n */\r\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.repoInfo = repoInfo;\r\n this.applicationId = applicationId;\r\n this.appCheckToken = appCheckToken;\r\n this.authToken = authToken;\r\n this.transportSessionId = transportSessionId;\r\n this.lastSessionId = lastSessionId;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.everConnected_ = false;\r\n this.log_ = logWrapper(connId);\r\n this.stats_ = statsManagerGetCollection(repoInfo);\r\n this.urlFn = (params) => {\r\n // Always add the token if we have one.\r\n if (this.appCheckToken) {\r\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\r\n }\r\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\r\n };\r\n }\r\n /**\r\n * @param onMessage - Callback when messages arrive\r\n * @param onDisconnect - Callback with connection lost.\r\n */\r\n open(onMessage, onDisconnect) {\r\n this.curSegmentNum = 0;\r\n this.onDisconnect_ = onDisconnect;\r\n this.myPacketOrderer = new PacketReceiver(onMessage);\r\n this.isClosed_ = false;\r\n this.connectTimeoutTimer_ = setTimeout(() => {\r\n this.log_('Timed out trying to connect.');\r\n // Make sure we clear the host cache\r\n this.onClosed_();\r\n this.connectTimeoutTimer_ = null;\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(LP_CONNECT_TIMEOUT));\r\n // Ensure we delay the creation of the iframe until the DOM is loaded.\r\n executeWhenDOMReady(() => {\r\n if (this.isClosed_) {\r\n return;\r\n }\r\n //Set up a callback that gets triggered once a connection is set up.\r\n this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {\r\n const [command, arg1, arg2, arg3, arg4] = args;\r\n this.incrementIncomingBytes_(args);\r\n if (!this.scriptTagHolder) {\r\n return; // we closed the connection.\r\n }\r\n if (this.connectTimeoutTimer_) {\r\n clearTimeout(this.connectTimeoutTimer_);\r\n this.connectTimeoutTimer_ = null;\r\n }\r\n this.everConnected_ = true;\r\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\r\n this.id = arg1;\r\n this.password = arg2;\r\n }\r\n else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\r\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\r\n if (arg1) {\r\n // We aren't expecting any more data (other than what the server's already in the process of sending us\r\n // through our already open polls), so don't send any more.\r\n this.scriptTagHolder.sendNewPolls = false;\r\n // arg1 in this case is the last response number sent by the server. We should try to receive\r\n // all of the responses up to this one before closing\r\n this.myPacketOrderer.closeAfter(arg1, () => {\r\n this.onClosed_();\r\n });\r\n }\r\n else {\r\n this.onClosed_();\r\n }\r\n }\r\n else {\r\n throw new Error('Unrecognized command received: ' + command);\r\n }\r\n }, (...args) => {\r\n const [pN, data] = args;\r\n this.incrementIncomingBytes_(args);\r\n this.myPacketOrderer.handleResponse(pN, data);\r\n }, () => {\r\n this.onClosed_();\r\n }, this.urlFn);\r\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\r\n //from cache.\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\r\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\r\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\r\n this.scriptTagHolder.uniqueCallbackIdentifier;\r\n }\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (this.transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\r\n }\r\n if (this.lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\r\n }\r\n if (this.applicationId) {\r\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\r\n }\r\n if (this.appCheckToken) {\r\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\r\n }\r\n if (typeof location !== 'undefined' &&\r\n location.hostname &&\r\n FORGE_DOMAIN_RE.test(location.hostname)) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n const connectURL = this.urlFn(urlParams);\r\n this.log_('Connecting via long-poll to ' + connectURL);\r\n this.scriptTagHolder.addTag(connectURL, () => {\r\n /* do nothing */\r\n });\r\n });\r\n }\r\n /**\r\n * Call this when a handshake has completed successfully and we want to consider the connection established\r\n */\r\n start() {\r\n this.scriptTagHolder.startLongPoll(this.id, this.password);\r\n this.addDisconnectPingFrame(this.id, this.password);\r\n }\r\n /**\r\n * Forces long polling to be considered as a potential transport\r\n */\r\n static forceAllow() {\r\n BrowserPollConnection.forceAllow_ = true;\r\n }\r\n /**\r\n * Forces longpolling to not be considered as a potential transport\r\n */\r\n static forceDisallow() {\r\n BrowserPollConnection.forceDisallow_ = true;\r\n }\r\n // Static method, use string literal so it can be accessed in a generic way\r\n static isAvailable() {\r\n if (isNodeSdk()) {\r\n return false;\r\n }\r\n else if (BrowserPollConnection.forceAllow_) {\r\n return true;\r\n }\r\n else {\r\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\r\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\r\n return (!BrowserPollConnection.forceDisallow_ &&\r\n typeof document !== 'undefined' &&\r\n document.createElement != null &&\r\n !isChromeExtensionContentScript() &&\r\n !isWindowsStoreApp());\r\n }\r\n }\r\n /**\r\n * No-op for polling\r\n */\r\n markConnectionHealthy() { }\r\n /**\r\n * Stops polling and cleans up the iframe\r\n */\r\n shutdown_() {\r\n this.isClosed_ = true;\r\n if (this.scriptTagHolder) {\r\n this.scriptTagHolder.close();\r\n this.scriptTagHolder = null;\r\n }\r\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\r\n if (this.myDisconnFrame) {\r\n document.body.removeChild(this.myDisconnFrame);\r\n this.myDisconnFrame = null;\r\n }\r\n if (this.connectTimeoutTimer_) {\r\n clearTimeout(this.connectTimeoutTimer_);\r\n this.connectTimeoutTimer_ = null;\r\n }\r\n }\r\n /**\r\n * Triggered when this transport is closed\r\n */\r\n onClosed_() {\r\n if (!this.isClosed_) {\r\n this.log_('Longpoll is closing itself');\r\n this.shutdown_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_(this.everConnected_);\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n }\r\n /**\r\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\r\n * that we've left.\r\n */\r\n close() {\r\n if (!this.isClosed_) {\r\n this.log_('Longpoll is being closed.');\r\n this.shutdown_();\r\n }\r\n }\r\n /**\r\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\r\n * broken into chunks (since URLs have a small maximum length).\r\n * @param data - The JSON data to transmit.\r\n */\r\n send(data) {\r\n const dataStr = stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //first, lets get the base64-encoded data\r\n const base64data = base64Encode(dataStr);\r\n //We can only fit a certain amount in each URL, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\r\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\r\n //of segments so that we can reassemble the packet on the server.\r\n for (let i = 0; i < dataSegs.length; i++) {\r\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\r\n this.curSegmentNum++;\r\n }\r\n }\r\n /**\r\n * This is how we notify the server that we're leaving.\r\n * We aren't able to send requests with DHTML on a window close event, but we can\r\n * trigger XHR requests in some browsers (everything but Opera basically).\r\n */\r\n addDisconnectPingFrame(id, pw) {\r\n if (isNodeSdk()) {\r\n return;\r\n }\r\n this.myDisconnFrame = document.createElement('iframe');\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\r\n this.myDisconnFrame.src = this.urlFn(urlParams);\r\n this.myDisconnFrame.style.display = 'none';\r\n document.body.appendChild(this.myDisconnFrame);\r\n }\r\n /**\r\n * Used to track the bytes received by this client\r\n */\r\n incrementIncomingBytes_(args) {\r\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\r\n const bytesReceived = stringify(args).length;\r\n this.bytesReceived += bytesReceived;\r\n this.stats_.incrementCounter('bytes_received', bytesReceived);\r\n }\r\n}\r\n/*********************************************************************************************\r\n * A wrapper around an iframe that is used as a long-polling script holder.\r\n *********************************************************************************************/\r\nclass FirebaseIFrameScriptHolder {\r\n /**\r\n * @param commandCB - The callback to be called when control commands are recevied from the server.\r\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\r\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\r\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\r\n */\r\n constructor(commandCB, onMessageCB, onDisconnect, urlFn) {\r\n this.onDisconnect = onDisconnect;\r\n this.urlFn = urlFn;\r\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\r\n //problems in some browsers.\r\n this.outstandingRequests = new Set();\r\n //A queue of the pending segments waiting for transmission to the server.\r\n this.pendingSegs = [];\r\n //A serial number. We use this for two things:\r\n // 1) A way to ensure the browser doesn't cache responses to polls\r\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\r\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\r\n // JSONP code in the order it was added to the iframe.\r\n this.currentSerial = Math.floor(Math.random() * 100000000);\r\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\r\n // incoming data from the server that we're waiting for).\r\n this.sendNewPolls = true;\r\n if (!isNodeSdk()) {\r\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\r\n //iframes where we put the long-polling script tags. We have two callbacks:\r\n // 1) Command Callback - Triggered for control issues, like starting a connection.\r\n // 2) Message Callback - Triggered when new data arrives.\r\n this.uniqueCallbackIdentifier = LUIDGenerator();\r\n window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\r\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\r\n onMessageCB;\r\n //Create an iframe for us to add script tags to.\r\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\r\n // Set the iframe's contents.\r\n let script = '';\r\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\r\n // for ie9, but ie8 needs to do it again in the document itself.\r\n if (this.myIFrame.src &&\r\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\r\n const currentDomain = document.domain;\r\n script = '';\r\n }\r\n const iframeContents = '' + script + '';\r\n try {\r\n this.myIFrame.doc.open();\r\n this.myIFrame.doc.write(iframeContents);\r\n this.myIFrame.doc.close();\r\n }\r\n catch (e) {\r\n log('frame writing exception');\r\n if (e.stack) {\r\n log(e.stack);\r\n }\r\n log(e);\r\n }\r\n }\r\n else {\r\n this.commandCB = commandCB;\r\n this.onMessageCB = onMessageCB;\r\n }\r\n }\r\n /**\r\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\r\n * actually use.\r\n */\r\n static createIFrame_() {\r\n const iframe = document.createElement('iframe');\r\n iframe.style.display = 'none';\r\n // This is necessary in order to initialize the document inside the iframe\r\n if (document.body) {\r\n document.body.appendChild(iframe);\r\n try {\r\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\r\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\r\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\r\n const a = iframe.contentWindow.document;\r\n if (!a) {\r\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\r\n log('No IE domain setting required');\r\n }\r\n }\r\n catch (e) {\r\n const domain = document.domain;\r\n iframe.src =\r\n \"javascript:void((function(){document.open();document.domain='\" +\r\n domain +\r\n \"';document.close();})())\";\r\n }\r\n }\r\n else {\r\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\r\n // never gets hit.\r\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\r\n }\r\n // Get the document of the iframe in a browser-specific way.\r\n if (iframe.contentDocument) {\r\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\r\n }\r\n else if (iframe.contentWindow) {\r\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (iframe.document) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n iframe.doc = iframe.document; //others?\r\n }\r\n return iframe;\r\n }\r\n /**\r\n * Cancel all outstanding queries and remove the frame.\r\n */\r\n close() {\r\n //Mark this iframe as dead, so no new requests are sent.\r\n this.alive = false;\r\n if (this.myIFrame) {\r\n //We have to actually remove all of the html inside this iframe before removing it from the\r\n //window, or IE will continue loading and executing the script tags we've already added, which\r\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\r\n this.myIFrame.doc.body.textContent = '';\r\n setTimeout(() => {\r\n if (this.myIFrame !== null) {\r\n document.body.removeChild(this.myIFrame);\r\n this.myIFrame = null;\r\n }\r\n }, Math.floor(0));\r\n }\r\n // Protect from being called recursively.\r\n const onDisconnect = this.onDisconnect;\r\n if (onDisconnect) {\r\n this.onDisconnect = null;\r\n onDisconnect();\r\n }\r\n }\r\n /**\r\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\r\n * @param id - The ID of this connection\r\n * @param pw - The password for this connection\r\n */\r\n startLongPoll(id, pw) {\r\n this.myID = id;\r\n this.myPW = pw;\r\n this.alive = true;\r\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\r\n while (this.newRequest_()) { }\r\n }\r\n /**\r\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\r\n * too many outstanding requests and we are still alive.\r\n *\r\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\r\n * needed.\r\n */\r\n newRequest_() {\r\n // We keep one outstanding request open all the time to receive data, but if we need to send data\r\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\r\n // close the old request.\r\n if (this.alive &&\r\n this.sendNewPolls &&\r\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {\r\n //construct our url\r\n this.currentSerial++;\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\r\n let theURL = this.urlFn(urlParams);\r\n //Now add as much data as we can.\r\n let curDataString = '';\r\n let i = 0;\r\n while (this.pendingSegs.length > 0) {\r\n //first, lets see if the next segment will fit.\r\n const nextSeg = this.pendingSegs[0];\r\n if (nextSeg.d.length +\r\n SEG_HEADER_SIZE +\r\n curDataString.length <=\r\n MAX_URL_DATA_SIZE) {\r\n //great, the segment will fit. Lets append it.\r\n const theSeg = this.pendingSegs.shift();\r\n curDataString =\r\n curDataString +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\r\n i +\r\n '=' +\r\n theSeg.seg +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\r\n i +\r\n '=' +\r\n theSeg.ts +\r\n '&' +\r\n FIREBASE_LONGPOLL_DATA_PARAM +\r\n i +\r\n '=' +\r\n theSeg.d;\r\n i++;\r\n }\r\n else {\r\n break;\r\n }\r\n }\r\n theURL = theURL + curDataString;\r\n this.addLongPollTag_(theURL, this.currentSerial);\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n /**\r\n * Queue a packet for transmission to the server.\r\n * @param segnum - A sequential id for this packet segment used for reassembly\r\n * @param totalsegs - The total number of segments in this packet\r\n * @param data - The data for this segment.\r\n */\r\n enqueueSegment(segnum, totalsegs, data) {\r\n //add this to the queue of segments to send.\r\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\r\n //send the data immediately if there isn't already data being transmitted, unless\r\n //startLongPoll hasn't been called yet.\r\n if (this.alive) {\r\n this.newRequest_();\r\n }\r\n }\r\n /**\r\n * Add a script tag for a regular long-poll request.\r\n * @param url - The URL of the script tag.\r\n * @param serial - The serial number of the request.\r\n */\r\n addLongPollTag_(url, serial) {\r\n //remember that we sent this request.\r\n this.outstandingRequests.add(serial);\r\n const doNewRequest = () => {\r\n this.outstandingRequests.delete(serial);\r\n this.newRequest_();\r\n };\r\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\r\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\r\n const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\r\n const readyStateCB = () => {\r\n // Request completed. Cancel the keepalive.\r\n clearTimeout(keepaliveTimeout);\r\n // Trigger a new request so we can continue receiving data.\r\n doNewRequest();\r\n };\r\n this.addTag(url, readyStateCB);\r\n }\r\n /**\r\n * Add an arbitrary script tag to the iframe.\r\n * @param url - The URL for the script tag source.\r\n * @param loadCB - A callback to be triggered once the script has loaded.\r\n */\r\n addTag(url, loadCB) {\r\n if (isNodeSdk()) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.doNodeLongPoll(url, loadCB);\r\n }\r\n else {\r\n setTimeout(() => {\r\n try {\r\n // if we're already closed, don't add this poll\r\n if (!this.sendNewPolls) {\r\n return;\r\n }\r\n const newScript = this.myIFrame.doc.createElement('script');\r\n newScript.type = 'text/javascript';\r\n newScript.async = true;\r\n newScript.src = url;\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange =\r\n function () {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const rstate = newScript.readyState;\r\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange = null;\r\n if (newScript.parentNode) {\r\n newScript.parentNode.removeChild(newScript);\r\n }\r\n loadCB();\r\n }\r\n };\r\n newScript.onerror = () => {\r\n log('Long-poll script failed to load: ' + url);\r\n this.sendNewPolls = false;\r\n this.close();\r\n };\r\n this.myIFrame.doc.body.appendChild(newScript);\r\n }\r\n catch (e) {\r\n // TODO: we should make this error visible somehow\r\n }\r\n }, Math.floor(1));\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\r\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\r\nlet WebSocketImpl = null;\r\nif (typeof MozWebSocket !== 'undefined') {\r\n WebSocketImpl = MozWebSocket;\r\n}\r\nelse if (typeof WebSocket !== 'undefined') {\r\n WebSocketImpl = WebSocket;\r\n}\r\n/**\r\n * Create a new websocket connection with the given callbacks.\r\n */\r\nclass WebSocketConnection {\r\n /**\r\n * @param connId identifier for this transport\r\n * @param repoInfo The info for the websocket endpoint.\r\n * @param applicationId The Firebase App ID for this project.\r\n * @param appCheckToken The App Check Token for this client.\r\n * @param authToken The Auth Token for this client.\r\n * @param transportSessionId Optional transportSessionId if this is connecting\r\n * to an existing transport session\r\n * @param lastSessionId Optional lastSessionId if there was a previous\r\n * connection\r\n */\r\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.applicationId = applicationId;\r\n this.appCheckToken = appCheckToken;\r\n this.authToken = authToken;\r\n this.keepaliveTimer = null;\r\n this.frames = null;\r\n this.totalFrames = 0;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.log_ = logWrapper(this.connId);\r\n this.stats_ = statsManagerGetCollection(repoInfo);\r\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);\r\n this.nodeAdmin = repoInfo.nodeAdmin;\r\n }\r\n /**\r\n * @param repoInfo - The info for the websocket endpoint.\r\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\r\n * @returns connection url\r\n */\r\n static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {\r\n const urlParams = {};\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (!isNodeSdk() &&\r\n typeof location !== 'undefined' &&\r\n location.hostname &&\r\n FORGE_DOMAIN_RE.test(location.hostname)) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n if (transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\r\n }\r\n if (lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\r\n }\r\n if (appCheckToken) {\r\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\r\n }\r\n if (applicationId) {\r\n urlParams[APPLICATION_ID_PARAM] = applicationId;\r\n }\r\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\r\n }\r\n /**\r\n * @param onMessage - Callback when messages arrive\r\n * @param onDisconnect - Callback with connection lost.\r\n */\r\n open(onMessage, onDisconnect) {\r\n this.onDisconnect = onDisconnect;\r\n this.onMessage = onMessage;\r\n this.log_('Websocket connecting to ' + this.connURL);\r\n this.everConnected_ = false;\r\n // Assume failure until proven otherwise.\r\n PersistentStorage.set('previous_websocket_failure', true);\r\n try {\r\n let options;\r\n if (isNodeSdk()) {\r\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\r\n // UA Format: Firebase////\r\n options = {\r\n headers: {\r\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\r\n 'X-Firebase-GMPID': this.applicationId || ''\r\n }\r\n };\r\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\r\n // Note that we send the credentials here even if they aren't admin credentials, which is\r\n // not a problem.\r\n // Note that this header is just used to bypass appcheck, and the token should still be sent\r\n // through the websocket connection once it is established.\r\n if (this.authToken) {\r\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\r\n }\r\n if (this.appCheckToken) {\r\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\r\n }\r\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\r\n const env = process['env'];\r\n const proxy = this.connURL.indexOf('wss://') === 0\r\n ? env['HTTPS_PROXY'] || env['https_proxy']\r\n : env['HTTP_PROXY'] || env['http_proxy'];\r\n if (proxy) {\r\n options['proxy'] = { origin: proxy };\r\n }\r\n }\r\n this.mySock = new WebSocketImpl(this.connURL, [], options);\r\n }\r\n catch (e) {\r\n this.log_('Error instantiating WebSocket.');\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n return;\r\n }\r\n this.mySock.onopen = () => {\r\n this.log_('Websocket connected.');\r\n this.everConnected_ = true;\r\n };\r\n this.mySock.onclose = () => {\r\n this.log_('Websocket connection was disconnected.');\r\n this.mySock = null;\r\n this.onClosed_();\r\n };\r\n this.mySock.onmessage = m => {\r\n this.handleIncomingFrame(m);\r\n };\r\n this.mySock.onerror = e => {\r\n this.log_('WebSocket error. Closing connection.');\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n };\r\n }\r\n /**\r\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\r\n */\r\n start() { }\r\n static forceDisallow() {\r\n WebSocketConnection.forceDisallow_ = true;\r\n }\r\n static isAvailable() {\r\n let isOldAndroid = false;\r\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\r\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\r\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\r\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\r\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\r\n isOldAndroid = true;\r\n }\r\n }\r\n }\r\n return (!isOldAndroid &&\r\n WebSocketImpl !== null &&\r\n !WebSocketConnection.forceDisallow_);\r\n }\r\n /**\r\n * Returns true if we previously failed to connect with this transport.\r\n */\r\n static previouslyFailed() {\r\n // If our persistent storage is actually only in-memory storage,\r\n // we default to assuming that it previously failed to be safe.\r\n return (PersistentStorage.isInMemoryStorage ||\r\n PersistentStorage.get('previous_websocket_failure') === true);\r\n }\r\n markConnectionHealthy() {\r\n PersistentStorage.remove('previous_websocket_failure');\r\n }\r\n appendFrame_(data) {\r\n this.frames.push(data);\r\n if (this.frames.length === this.totalFrames) {\r\n const fullMess = this.frames.join('');\r\n this.frames = null;\r\n const jsonMess = jsonEval(fullMess);\r\n //handle the message\r\n this.onMessage(jsonMess);\r\n }\r\n }\r\n /**\r\n * @param frameCount - The number of frames we are expecting from the server\r\n */\r\n handleNewFrameCount_(frameCount) {\r\n this.totalFrames = frameCount;\r\n this.frames = [];\r\n }\r\n /**\r\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\r\n * @returns Any remaining data to be process, or null if there is none\r\n */\r\n extractFrameCount_(data) {\r\n assert(this.frames === null, 'We already have a frame buffer');\r\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\r\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\r\n if (data.length <= 6) {\r\n const frameCount = Number(data);\r\n if (!isNaN(frameCount)) {\r\n this.handleNewFrameCount_(frameCount);\r\n return null;\r\n }\r\n }\r\n this.handleNewFrameCount_(1);\r\n return data;\r\n }\r\n /**\r\n * Process a websocket frame that has arrived from the server.\r\n * @param mess - The frame data\r\n */\r\n handleIncomingFrame(mess) {\r\n if (this.mySock === null) {\r\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\r\n }\r\n const data = mess['data'];\r\n this.bytesReceived += data.length;\r\n this.stats_.incrementCounter('bytes_received', data.length);\r\n this.resetKeepAlive();\r\n if (this.frames !== null) {\r\n // we're buffering\r\n this.appendFrame_(data);\r\n }\r\n else {\r\n // try to parse out a frame count, otherwise, assume 1 and process it\r\n const remainingData = this.extractFrameCount_(data);\r\n if (remainingData !== null) {\r\n this.appendFrame_(remainingData);\r\n }\r\n }\r\n }\r\n /**\r\n * Send a message to the server\r\n * @param data - The JSON object to transmit\r\n */\r\n send(data) {\r\n this.resetKeepAlive();\r\n const dataStr = stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //We can only fit a certain amount in each websocket frame, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\r\n //Send the length header\r\n if (dataSegs.length > 1) {\r\n this.sendString_(String(dataSegs.length));\r\n }\r\n //Send the actual data in segments.\r\n for (let i = 0; i < dataSegs.length; i++) {\r\n this.sendString_(dataSegs[i]);\r\n }\r\n }\r\n shutdown_() {\r\n this.isClosed_ = true;\r\n if (this.keepaliveTimer) {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = null;\r\n }\r\n if (this.mySock) {\r\n this.mySock.close();\r\n this.mySock = null;\r\n }\r\n }\r\n onClosed_() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is closing itself');\r\n this.shutdown_();\r\n // since this is an internal close, trigger the close listener\r\n if (this.onDisconnect) {\r\n this.onDisconnect(this.everConnected_);\r\n this.onDisconnect = null;\r\n }\r\n }\r\n }\r\n /**\r\n * External-facing close handler.\r\n * Close the websocket and kill the connection.\r\n */\r\n close() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is being closed');\r\n this.shutdown_();\r\n }\r\n }\r\n /**\r\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\r\n * the last activity.\r\n */\r\n resetKeepAlive() {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = setInterval(() => {\r\n //If there has been no websocket activity for a while, send a no-op\r\n if (this.mySock) {\r\n this.sendString_('0');\r\n }\r\n this.resetKeepAlive();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\r\n }\r\n /**\r\n * Send a string over the websocket.\r\n *\r\n * @param str - String to send.\r\n */\r\n sendString_(str) {\r\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\r\n // calls for some unknown reason. We treat these as an error and disconnect.\r\n // See https://app.asana.com/0/58926111402292/68021340250410\r\n try {\r\n this.mySock.send(str);\r\n }\r\n catch (e) {\r\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\r\n setTimeout(this.onClosed_.bind(this), 0);\r\n }\r\n }\r\n}\r\n/**\r\n * Number of response before we consider the connection \"healthy.\"\r\n */\r\nWebSocketConnection.responsesRequiredToBeHealthy = 2;\r\n/**\r\n * Time to wait for the connection te become healthy before giving up.\r\n */\r\nWebSocketConnection.healthyTimeout = 30000;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\r\n * lifecycle.\r\n *\r\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\r\n * they are available.\r\n */\r\nclass TransportManager {\r\n /**\r\n * @param repoInfo - Metadata around the namespace we're connecting to\r\n */\r\n constructor(repoInfo) {\r\n this.initTransports_(repoInfo);\r\n }\r\n static get ALL_TRANSPORTS() {\r\n return [BrowserPollConnection, WebSocketConnection];\r\n }\r\n /**\r\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\r\n * TransportManager has already set up transports_\r\n */\r\n static get IS_TRANSPORT_INITIALIZED() {\r\n return this.globalTransportInitialized_;\r\n }\r\n initTransports_(repoInfo) {\r\n const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();\r\n let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\r\n if (repoInfo.webSocketOnly) {\r\n if (!isWebSocketsAvailable) {\r\n warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\r\n }\r\n isSkipPollConnection = true;\r\n }\r\n if (isSkipPollConnection) {\r\n this.transports_ = [WebSocketConnection];\r\n }\r\n else {\r\n const transports = (this.transports_ = []);\r\n for (const transport of TransportManager.ALL_TRANSPORTS) {\r\n if (transport && transport['isAvailable']()) {\r\n transports.push(transport);\r\n }\r\n }\r\n TransportManager.globalTransportInitialized_ = true;\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the initial transport to use\r\n */\r\n initialTransport() {\r\n if (this.transports_.length > 0) {\r\n return this.transports_[0];\r\n }\r\n else {\r\n throw new Error('No transports available');\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the next transport, or null\r\n */\r\n upgradeTransport() {\r\n if (this.transports_.length > 1) {\r\n return this.transports_[1];\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\r\n// Keeps track of whether the TransportManager has already chosen a transport to use\r\nTransportManager.globalTransportInitialized_ = false;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Abort upgrade attempt if it takes longer than 60s.\r\nconst UPGRADE_TIMEOUT = 60000;\r\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\r\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\r\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\r\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\r\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\r\n// but we've sent/received enough bytes, we don't cancel the connection.\r\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\r\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\r\nconst MESSAGE_TYPE = 't';\r\nconst MESSAGE_DATA = 'd';\r\nconst CONTROL_SHUTDOWN = 's';\r\nconst CONTROL_RESET = 'r';\r\nconst CONTROL_ERROR = 'e';\r\nconst CONTROL_PONG = 'o';\r\nconst SWITCH_ACK = 'a';\r\nconst END_TRANSMISSION = 'n';\r\nconst PING = 'p';\r\nconst SERVER_HELLO = 'h';\r\n/**\r\n * Creates a new real-time connection to the server using whichever method works\r\n * best in the current browser.\r\n */\r\nclass Connection {\r\n /**\r\n * @param id - an id for this connection\r\n * @param repoInfo_ - the info for the endpoint to connect to\r\n * @param applicationId_ - the Firebase App ID for this project\r\n * @param appCheckToken_ - The App Check Token for this device.\r\n * @param authToken_ - The auth token for this session.\r\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\r\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\r\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\r\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\r\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\r\n */\r\n constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\r\n this.id = id;\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.appCheckToken_ = appCheckToken_;\r\n this.authToken_ = authToken_;\r\n this.onMessage_ = onMessage_;\r\n this.onReady_ = onReady_;\r\n this.onDisconnect_ = onDisconnect_;\r\n this.onKill_ = onKill_;\r\n this.lastSessionId = lastSessionId;\r\n this.connectionCount = 0;\r\n this.pendingDataMessages = [];\r\n this.state_ = 0 /* RealtimeState.CONNECTING */;\r\n this.log_ = logWrapper('c:' + this.id + ':');\r\n this.transportManager_ = new TransportManager(repoInfo_);\r\n this.log_('Connection created');\r\n this.start_();\r\n }\r\n /**\r\n * Starts a connection attempt\r\n */\r\n start_() {\r\n const conn = this.transportManager_.initialTransport();\r\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessageReceived = this.connReceiver_(this.conn_);\r\n const onConnectionLost = this.disconnReceiver_(this.conn_);\r\n this.tx_ = this.conn_;\r\n this.rx_ = this.conn_;\r\n this.secondaryConn_ = null;\r\n this.isHealthy_ = false;\r\n /*\r\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\r\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\r\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\r\n * still have the context of your originating frame.\r\n */\r\n setTimeout(() => {\r\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\r\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\r\n }, Math.floor(0));\r\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\r\n if (healthyTimeoutMS > 0) {\r\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\r\n this.healthyTimeout_ = null;\r\n if (!this.isHealthy_) {\r\n if (this.conn_ &&\r\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has received ' +\r\n this.conn_.bytesReceived +\r\n ' bytes. Marking connection healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n else if (this.conn_ &&\r\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has sent ' +\r\n this.conn_.bytesSent +\r\n ' bytes. Leaving connection alive.');\r\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\r\n // the server.\r\n }\r\n else {\r\n this.log_('Closing unhealthy connection after timeout.');\r\n this.close();\r\n }\r\n }\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(healthyTimeoutMS));\r\n }\r\n }\r\n nextTransportId_() {\r\n return 'c:' + this.id + ':' + this.connectionCount++;\r\n }\r\n disconnReceiver_(conn) {\r\n return everConnected => {\r\n if (conn === this.conn_) {\r\n this.onConnectionLost_(everConnected);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.log_('Secondary connection lost.');\r\n this.onSecondaryConnectionLost_();\r\n }\r\n else {\r\n this.log_('closing an old connection');\r\n }\r\n };\r\n }\r\n connReceiver_(conn) {\r\n return (message) => {\r\n if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\r\n if (conn === this.rx_) {\r\n this.onPrimaryMessageReceived_(message);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.onSecondaryMessageReceived_(message);\r\n }\r\n else {\r\n this.log_('message on old connection');\r\n }\r\n }\r\n };\r\n }\r\n /**\r\n * @param dataMsg - An arbitrary data message to be sent to the server\r\n */\r\n sendRequest(dataMsg) {\r\n // wrap in a data message envelope and send it on\r\n const msg = { t: 'd', d: dataMsg };\r\n this.sendData_(msg);\r\n }\r\n tryCleanupConnection() {\r\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\r\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\r\n this.conn_ = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n // the server will shutdown the old connection\r\n }\r\n }\r\n onSecondaryControl_(controlData) {\r\n if (MESSAGE_TYPE in controlData) {\r\n const cmd = controlData[MESSAGE_TYPE];\r\n if (cmd === SWITCH_ACK) {\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // Most likely the session wasn't valid. Abandon the switch attempt\r\n this.log_('Got a reset on secondary, closing it');\r\n this.secondaryConn_.close();\r\n // If we were already using this connection for something, than we need to fully close\r\n if (this.tx_ === this.secondaryConn_ ||\r\n this.rx_ === this.secondaryConn_) {\r\n this.close();\r\n }\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on secondary.');\r\n this.secondaryResponsesRequired_--;\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n }\r\n }\r\n onSecondaryMessageReceived_(parsedData) {\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onSecondaryControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n // got a data message, but we're still second connection. Need to buffer it up\r\n this.pendingDataMessages.push(data);\r\n }\r\n else {\r\n throw new Error('Unknown protocol layer: ' + layer);\r\n }\r\n }\r\n upgradeIfSecondaryHealthy_() {\r\n if (this.secondaryResponsesRequired_ <= 0) {\r\n this.log_('Secondary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.secondaryConn_.markConnectionHealthy();\r\n this.proceedWithUpgrade_();\r\n }\r\n else {\r\n // Send a ping to make sure the connection is healthy.\r\n this.log_('sending ping on secondary.');\r\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n proceedWithUpgrade_() {\r\n // tell this connection to consider itself open\r\n this.secondaryConn_.start();\r\n // send ack\r\n this.log_('sending client ack on secondary');\r\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\r\n // send end packet on primary transport, switch to sending on this one\r\n // can receive on this one, buffer responses until end received on primary transport\r\n this.log_('Ending transmission on primary');\r\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\r\n this.tx_ = this.secondaryConn_;\r\n this.tryCleanupConnection();\r\n }\r\n onPrimaryMessageReceived_(parsedData) {\r\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n this.onDataMessage_(data);\r\n }\r\n }\r\n onDataMessage_(message) {\r\n this.onPrimaryResponse_();\r\n // We don't do anything with data messages, just kick them up a level\r\n this.onMessage_(message);\r\n }\r\n onPrimaryResponse_() {\r\n if (!this.isHealthy_) {\r\n this.primaryResponsesRequired_--;\r\n if (this.primaryResponsesRequired_ <= 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n }\r\n }\r\n onControl_(controlData) {\r\n const cmd = requireKey(MESSAGE_TYPE, controlData);\r\n if (MESSAGE_DATA in controlData) {\r\n const payload = controlData[MESSAGE_DATA];\r\n if (cmd === SERVER_HELLO) {\r\n const handshakePayload = Object.assign({}, payload);\r\n if (this.repoInfo_.isUsingEmulator) {\r\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\r\n handshakePayload.h = this.repoInfo_.host;\r\n }\r\n this.onHandshake_(handshakePayload);\r\n }\r\n else if (cmd === END_TRANSMISSION) {\r\n this.log_('recvd end transmission on primary');\r\n this.rx_ = this.secondaryConn_;\r\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\r\n this.onDataMessage_(this.pendingDataMessages[i]);\r\n }\r\n this.pendingDataMessages = [];\r\n this.tryCleanupConnection();\r\n }\r\n else if (cmd === CONTROL_SHUTDOWN) {\r\n // This was previously the 'onKill' callback passed to the lower-level connection\r\n // payload in this case is the reason for the shutdown. Generally a human-readable error\r\n this.onConnectionShutdown_(payload);\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // payload in this case is the host we should contact\r\n this.onReset_(payload);\r\n }\r\n else if (cmd === CONTROL_ERROR) {\r\n error('Server Error: ' + payload);\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on primary.');\r\n this.onPrimaryResponse_();\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }\r\n else {\r\n error('Unknown control packet command: ' + cmd);\r\n }\r\n }\r\n }\r\n /**\r\n * @param handshake - The handshake data returned from the server\r\n */\r\n onHandshake_(handshake) {\r\n const timestamp = handshake.ts;\r\n const version = handshake.v;\r\n const host = handshake.h;\r\n this.sessionId = handshake.s;\r\n this.repoInfo_.host = host;\r\n // if we've already closed the connection, then don't bother trying to progress further\r\n if (this.state_ === 0 /* RealtimeState.CONNECTING */) {\r\n this.conn_.start();\r\n this.onConnectionEstablished_(this.conn_, timestamp);\r\n if (PROTOCOL_VERSION !== version) {\r\n warn('Protocol version mismatch detected');\r\n }\r\n // TODO: do we want to upgrade? when? maybe a delay?\r\n this.tryStartUpgrade_();\r\n }\r\n }\r\n tryStartUpgrade_() {\r\n const conn = this.transportManager_.upgradeTransport();\r\n if (conn) {\r\n this.startUpgrade_(conn);\r\n }\r\n }\r\n startUpgrade_(conn) {\r\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.secondaryResponsesRequired_ =\r\n conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessage = this.connReceiver_(this.secondaryConn_);\r\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\r\n this.secondaryConn_.open(onMessage, onDisconnect);\r\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\r\n setTimeoutNonBlocking(() => {\r\n if (this.secondaryConn_) {\r\n this.log_('Timed out trying to upgrade.');\r\n this.secondaryConn_.close();\r\n }\r\n }, Math.floor(UPGRADE_TIMEOUT));\r\n }\r\n onReset_(host) {\r\n this.log_('Reset packet received. New host: ' + host);\r\n this.repoInfo_.host = host;\r\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\r\n // We don't currently support resets after the connection has already been established\r\n if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\r\n this.close();\r\n }\r\n else {\r\n // Close whatever connections we have open and start again.\r\n this.closeConnections_();\r\n this.start_();\r\n }\r\n }\r\n onConnectionEstablished_(conn, timestamp) {\r\n this.log_('Realtime connection established.');\r\n this.conn_ = conn;\r\n this.state_ = 1 /* RealtimeState.CONNECTED */;\r\n if (this.onReady_) {\r\n this.onReady_(timestamp, this.sessionId);\r\n this.onReady_ = null;\r\n }\r\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\r\n // send some pings.\r\n if (this.primaryResponsesRequired_ === 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n }\r\n else {\r\n setTimeoutNonBlocking(() => {\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\r\n }\r\n }\r\n sendPingOnPrimaryIfNecessary_() {\r\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\r\n if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {\r\n this.log_('sending ping on primary.');\r\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n onSecondaryConnectionLost_() {\r\n const conn = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n if (this.tx_ === conn || this.rx_ === conn) {\r\n // we are relying on this connection already in some capacity. Therefore, a failure is real\r\n this.close();\r\n }\r\n }\r\n /**\r\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\r\n * we should flush the host cache\r\n */\r\n onConnectionLost_(everConnected) {\r\n this.conn_ = null;\r\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\r\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\r\n if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {\r\n this.log_('Realtime connection failed.');\r\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\r\n if (this.repoInfo_.isCacheableHost()) {\r\n PersistentStorage.remove('host:' + this.repoInfo_.host);\r\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\r\n this.repoInfo_.internalHost = this.repoInfo_.host;\r\n }\r\n }\r\n else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\r\n this.log_('Realtime connection lost.');\r\n }\r\n this.close();\r\n }\r\n onConnectionShutdown_(reason) {\r\n this.log_('Connection shutdown command received. Shutting down...');\r\n if (this.onKill_) {\r\n this.onKill_(reason);\r\n this.onKill_ = null;\r\n }\r\n // We intentionally don't want to fire onDisconnect (kill is a different case),\r\n // so clear the callback.\r\n this.onDisconnect_ = null;\r\n this.close();\r\n }\r\n sendData_(data) {\r\n if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {\r\n throw 'Connection is not connected';\r\n }\r\n else {\r\n this.tx_.send(data);\r\n }\r\n }\r\n /**\r\n * Cleans up this connection, calling the appropriate callbacks\r\n */\r\n close() {\r\n if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\r\n this.log_('Closing realtime connection.');\r\n this.state_ = 2 /* RealtimeState.DISCONNECTED */;\r\n this.closeConnections_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_();\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n }\r\n closeConnections_() {\r\n this.log_('Shutting down all connections');\r\n if (this.conn_) {\r\n this.conn_.close();\r\n this.conn_ = null;\r\n }\r\n if (this.secondaryConn_) {\r\n this.secondaryConn_.close();\r\n this.secondaryConn_ = null;\r\n }\r\n if (this.healthyTimeout_) {\r\n clearTimeout(this.healthyTimeout_);\r\n this.healthyTimeout_ = null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface defining the set of actions that can be performed against the Firebase server\r\n * (basically corresponds to our wire protocol).\r\n *\r\n * @interface\r\n */\r\nclass ServerActions {\r\n put(pathString, data, onComplete, hash) { }\r\n merge(pathString, data, onComplete, hash) { }\r\n /**\r\n * Refreshes the auth token for the current connection.\r\n * @param token - The authentication token\r\n */\r\n refreshAuthToken(token) { }\r\n /**\r\n * Refreshes the app check token for the current connection.\r\n * @param token The app check token\r\n */\r\n refreshAppCheckToken(token) { }\r\n onDisconnectPut(pathString, data, onComplete) { }\r\n onDisconnectMerge(pathString, data, onComplete) { }\r\n onDisconnectCancel(pathString, onComplete) { }\r\n reportStats(stats) { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Base class to be used if you want to emit events. Call the constructor with\r\n * the set of allowed event names.\r\n */\r\nclass EventEmitter {\r\n constructor(allowedEvents_) {\r\n this.allowedEvents_ = allowedEvents_;\r\n this.listeners_ = {};\r\n assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\r\n }\r\n /**\r\n * To be called by derived classes to trigger events.\r\n */\r\n trigger(eventType, ...varArgs) {\r\n if (Array.isArray(this.listeners_[eventType])) {\r\n // Clone the list, since callbacks could add/remove listeners.\r\n const listeners = [...this.listeners_[eventType]];\r\n for (let i = 0; i < listeners.length; i++) {\r\n listeners[i].callback.apply(listeners[i].context, varArgs);\r\n }\r\n }\r\n }\r\n on(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n this.listeners_[eventType] = this.listeners_[eventType] || [];\r\n this.listeners_[eventType].push({ callback, context });\r\n const eventData = this.getInitialEvent(eventType);\r\n if (eventData) {\r\n callback.apply(context, eventData);\r\n }\r\n }\r\n off(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n const listeners = this.listeners_[eventType] || [];\r\n for (let i = 0; i < listeners.length; i++) {\r\n if (listeners[i].callback === callback &&\r\n (!context || context === listeners[i].context)) {\r\n listeners.splice(i, 1);\r\n return;\r\n }\r\n }\r\n }\r\n validateEventType_(eventType) {\r\n assert(this.allowedEvents_.find(et => {\r\n return et === eventType;\r\n }), 'Unknown event: ' + eventType);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Monitors online state (as reported by window.online/offline events).\r\n *\r\n * The expectation is that this could have many false positives (thinks we are online\r\n * when we're not), but no false negatives. So we can safely use it to determine when\r\n * we definitely cannot reach the internet.\r\n */\r\nclass OnlineMonitor extends EventEmitter {\r\n constructor() {\r\n super(['online']);\r\n this.online_ = true;\r\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\r\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\r\n // It would seem that the 'online' event does not always fire consistently. So we disable it\r\n // for Cordova.\r\n if (typeof window !== 'undefined' &&\r\n typeof window.addEventListener !== 'undefined' &&\r\n !isMobileCordova()) {\r\n window.addEventListener('online', () => {\r\n if (!this.online_) {\r\n this.online_ = true;\r\n this.trigger('online', true);\r\n }\r\n }, false);\r\n window.addEventListener('offline', () => {\r\n if (this.online_) {\r\n this.online_ = false;\r\n this.trigger('online', false);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new OnlineMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\r\n return [this.online_];\r\n }\r\n currentlyOnline() {\r\n return this.online_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Maximum key depth. */\r\nconst MAX_PATH_DEPTH = 32;\r\n/** Maximum number of (UTF8) bytes in a Firebase path. */\r\nconst MAX_PATH_LENGTH_BYTES = 768;\r\n/**\r\n * An immutable object representing a parsed path. It's immutable so that you\r\n * can pass them around to other functions without worrying about them changing\r\n * it.\r\n */\r\nclass Path {\r\n /**\r\n * @param pathOrString - Path string to parse, or another path, or the raw\r\n * tokens array\r\n */\r\n constructor(pathOrString, pieceNum) {\r\n if (pieceNum === void 0) {\r\n this.pieces_ = pathOrString.split('/');\r\n // Remove empty pieces.\r\n let copyTo = 0;\r\n for (let i = 0; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i].length > 0) {\r\n this.pieces_[copyTo] = this.pieces_[i];\r\n copyTo++;\r\n }\r\n }\r\n this.pieces_.length = copyTo;\r\n this.pieceNum_ = 0;\r\n }\r\n else {\r\n this.pieces_ = pathOrString;\r\n this.pieceNum_ = pieceNum;\r\n }\r\n }\r\n toString() {\r\n let pathString = '';\r\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i] !== '') {\r\n pathString += '/' + this.pieces_[i];\r\n }\r\n }\r\n return pathString || '/';\r\n }\r\n}\r\nfunction newEmptyPath() {\r\n return new Path('');\r\n}\r\nfunction pathGetFront(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n return path.pieces_[path.pieceNum_];\r\n}\r\n/**\r\n * @returns The number of segments in this path\r\n */\r\nfunction pathGetLength(path) {\r\n return path.pieces_.length - path.pieceNum_;\r\n}\r\nfunction pathPopFront(path) {\r\n let pieceNum = path.pieceNum_;\r\n if (pieceNum < path.pieces_.length) {\r\n pieceNum++;\r\n }\r\n return new Path(path.pieces_, pieceNum);\r\n}\r\nfunction pathGetBack(path) {\r\n if (path.pieceNum_ < path.pieces_.length) {\r\n return path.pieces_[path.pieces_.length - 1];\r\n }\r\n return null;\r\n}\r\nfunction pathToUrlEncodedString(path) {\r\n let pathString = '';\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n if (path.pieces_[i] !== '') {\r\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\r\n }\r\n }\r\n return pathString || '/';\r\n}\r\n/**\r\n * Shallow copy of the parts of the path.\r\n *\r\n */\r\nfunction pathSlice(path, begin = 0) {\r\n return path.pieces_.slice(path.pieceNum_ + begin);\r\n}\r\nfunction pathParent(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n return new Path(pieces, 0);\r\n}\r\nfunction pathChild(path, childPathObj) {\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n if (childPathObj instanceof Path) {\r\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\r\n pieces.push(childPathObj.pieces_[i]);\r\n }\r\n }\r\n else {\r\n const childPieces = childPathObj.split('/');\r\n for (let i = 0; i < childPieces.length; i++) {\r\n if (childPieces[i].length > 0) {\r\n pieces.push(childPieces[i]);\r\n }\r\n }\r\n }\r\n return new Path(pieces, 0);\r\n}\r\n/**\r\n * @returns True if there are no segments in this path\r\n */\r\nfunction pathIsEmpty(path) {\r\n return path.pieceNum_ >= path.pieces_.length;\r\n}\r\n/**\r\n * @returns The path from outerPath to innerPath\r\n */\r\nfunction newRelativePath(outerPath, innerPath) {\r\n const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);\r\n if (outer === null) {\r\n return innerPath;\r\n }\r\n else if (outer === inner) {\r\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\r\n }\r\n else {\r\n throw new Error('INTERNAL ERROR: innerPath (' +\r\n innerPath +\r\n ') is not within ' +\r\n 'outerPath (' +\r\n outerPath +\r\n ')');\r\n }\r\n}\r\n/**\r\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\r\n */\r\nfunction pathCompare(left, right) {\r\n const leftKeys = pathSlice(left, 0);\r\n const rightKeys = pathSlice(right, 0);\r\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\r\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\r\n if (cmp !== 0) {\r\n return cmp;\r\n }\r\n }\r\n if (leftKeys.length === rightKeys.length) {\r\n return 0;\r\n }\r\n return leftKeys.length < rightKeys.length ? -1 : 1;\r\n}\r\n/**\r\n * @returns true if paths are the same.\r\n */\r\nfunction pathEquals(path, other) {\r\n if (pathGetLength(path) !== pathGetLength(other)) {\r\n return false;\r\n }\r\n for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * @returns True if this path is a parent of (or the same as) other\r\n */\r\nfunction pathContains(path, other) {\r\n let i = path.pieceNum_;\r\n let j = other.pieceNum_;\r\n if (pathGetLength(path) > pathGetLength(other)) {\r\n return false;\r\n }\r\n while (i < path.pieces_.length) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n ++i;\r\n ++j;\r\n }\r\n return true;\r\n}\r\n/**\r\n * Dynamic (mutable) path used to count path lengths.\r\n *\r\n * This class is used to efficiently check paths for valid\r\n * length (in UTF8 bytes) and depth (used in path validation).\r\n *\r\n * Throws Error exception if path is ever invalid.\r\n *\r\n * The definition of a path always begins with '/'.\r\n */\r\nclass ValidationPath {\r\n /**\r\n * @param path - Initial Path.\r\n * @param errorPrefix_ - Prefix for any error messages.\r\n */\r\n constructor(path, errorPrefix_) {\r\n this.errorPrefix_ = errorPrefix_;\r\n this.parts_ = pathSlice(path, 0);\r\n /** Initialize to number of '/' chars needed in path. */\r\n this.byteLength_ = Math.max(1, this.parts_.length);\r\n for (let i = 0; i < this.parts_.length; i++) {\r\n this.byteLength_ += stringLength(this.parts_[i]);\r\n }\r\n validationPathCheckValid(this);\r\n }\r\n}\r\nfunction validationPathPush(validationPath, child) {\r\n // Count the needed '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ += 1;\r\n }\r\n validationPath.parts_.push(child);\r\n validationPath.byteLength_ += stringLength(child);\r\n validationPathCheckValid(validationPath);\r\n}\r\nfunction validationPathPop(validationPath) {\r\n const last = validationPath.parts_.pop();\r\n validationPath.byteLength_ -= stringLength(last);\r\n // Un-count the previous '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ -= 1;\r\n }\r\n}\r\nfunction validationPathCheckValid(validationPath) {\r\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'has a key path longer than ' +\r\n MAX_PATH_LENGTH_BYTES +\r\n ' bytes (' +\r\n validationPath.byteLength_ +\r\n ').');\r\n }\r\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'path specified exceeds the maximum depth that can be written (' +\r\n MAX_PATH_DEPTH +\r\n ') or object contains a cycle ' +\r\n validationPathToErrorString(validationPath));\r\n }\r\n}\r\n/**\r\n * String for use in error messages - uses '.' notation for path.\r\n */\r\nfunction validationPathToErrorString(validationPath) {\r\n if (validationPath.parts_.length === 0) {\r\n return '';\r\n }\r\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass VisibilityMonitor extends EventEmitter {\r\n constructor() {\r\n super(['visible']);\r\n let hidden;\r\n let visibilityChange;\r\n if (typeof document !== 'undefined' &&\r\n typeof document.addEventListener !== 'undefined') {\r\n if (typeof document['hidden'] !== 'undefined') {\r\n // Opera 12.10 and Firefox 18 and later support\r\n visibilityChange = 'visibilitychange';\r\n hidden = 'hidden';\r\n }\r\n else if (typeof document['mozHidden'] !== 'undefined') {\r\n visibilityChange = 'mozvisibilitychange';\r\n hidden = 'mozHidden';\r\n }\r\n else if (typeof document['msHidden'] !== 'undefined') {\r\n visibilityChange = 'msvisibilitychange';\r\n hidden = 'msHidden';\r\n }\r\n else if (typeof document['webkitHidden'] !== 'undefined') {\r\n visibilityChange = 'webkitvisibilitychange';\r\n hidden = 'webkitHidden';\r\n }\r\n }\r\n // Initially, we always assume we are visible. This ensures that in browsers\r\n // without page visibility support or in cases where we are never visible\r\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\r\n // reconnects\r\n this.visible_ = true;\r\n if (visibilityChange) {\r\n document.addEventListener(visibilityChange, () => {\r\n const visible = !document[hidden];\r\n if (visible !== this.visible_) {\r\n this.visible_ = visible;\r\n this.trigger('visible', visible);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new VisibilityMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\r\n return [this.visible_];\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECONNECT_MIN_DELAY = 1000;\r\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\r\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\r\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\r\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\r\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\r\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\r\nconst INVALID_TOKEN_THRESHOLD = 3;\r\n/**\r\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\r\n *\r\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\r\n * in quotes to make sure the closure compiler does not minify them.\r\n */\r\nclass PersistentConnection extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param applicationId_ - The Firebase App ID for this project\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.onConnectStatus_ = onConnectStatus_;\r\n this.onServerInfoUpdate_ = onServerInfoUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n this.authOverride_ = authOverride_;\r\n // Used for diagnostic logging.\r\n this.id = PersistentConnection.nextPersistentConnectionId_++;\r\n this.log_ = logWrapper('p:' + this.id + ':');\r\n this.interruptReasons_ = {};\r\n this.listens = new Map();\r\n this.outstandingPuts_ = [];\r\n this.outstandingGets_ = [];\r\n this.outstandingPutCount_ = 0;\r\n this.outstandingGetCount_ = 0;\r\n this.onDisconnectRequestQueue_ = [];\r\n this.connected_ = false;\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\r\n this.securityDebugCallback_ = null;\r\n this.lastSessionId = null;\r\n this.establishConnectionTimer_ = null;\r\n this.visible_ = false;\r\n // Before we get connected, we keep a queue of pending messages to send.\r\n this.requestCBHash_ = {};\r\n this.requestNumber_ = 0;\r\n this.realtime_ = null;\r\n this.authToken_ = null;\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = false;\r\n this.invalidAuthTokenCount_ = 0;\r\n this.invalidAppCheckTokenCount_ = 0;\r\n this.firstConnection_ = true;\r\n this.lastConnectionAttemptTime_ = null;\r\n this.lastConnectionEstablishedTime_ = null;\r\n if (authOverride_ && !isNodeSdk()) {\r\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\r\n }\r\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\r\n if (repoInfo_.host.indexOf('fblocal') === -1) {\r\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\r\n }\r\n }\r\n sendRequest(action, body, onResponse) {\r\n const curReqNum = ++this.requestNumber_;\r\n const msg = { r: curReqNum, a: action, b: body };\r\n this.log_(stringify(msg));\r\n assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\r\n this.realtime_.sendRequest(msg);\r\n if (onResponse) {\r\n this.requestCBHash_[curReqNum] = onResponse;\r\n }\r\n }\r\n get(query) {\r\n this.initConnection_();\r\n const deferred = new Deferred();\r\n const request = {\r\n p: query._path.toString(),\r\n q: query._queryObject\r\n };\r\n const outstandingGet = {\r\n action: 'g',\r\n request,\r\n onComplete: (message) => {\r\n const payload = message['d'];\r\n if (message['s'] === 'ok') {\r\n deferred.resolve(payload);\r\n }\r\n else {\r\n deferred.reject(payload);\r\n }\r\n }\r\n };\r\n this.outstandingGets_.push(outstandingGet);\r\n this.outstandingGetCount_++;\r\n const index = this.outstandingGets_.length - 1;\r\n if (this.connected_) {\r\n this.sendGet_(index);\r\n }\r\n return deferred.promise;\r\n }\r\n listen(query, currentHashFn, tag, onComplete) {\r\n this.initConnection_();\r\n const queryId = query._queryIdentifier;\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + queryId);\r\n if (!this.listens.has(pathString)) {\r\n this.listens.set(pathString, new Map());\r\n }\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');\r\n assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);\r\n const listenSpec = {\r\n onComplete,\r\n hashFn: currentHashFn,\r\n query,\r\n tag\r\n };\r\n this.listens.get(pathString).set(queryId, listenSpec);\r\n if (this.connected_) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n sendGet_(index) {\r\n const get = this.outstandingGets_[index];\r\n this.sendRequest('g', get.request, (message) => {\r\n delete this.outstandingGets_[index];\r\n this.outstandingGetCount_--;\r\n if (this.outstandingGetCount_ === 0) {\r\n this.outstandingGets_ = [];\r\n }\r\n if (get.onComplete) {\r\n get.onComplete(message);\r\n }\r\n });\r\n }\r\n sendListen_(listenSpec) {\r\n const query = listenSpec.query;\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Listen on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'q';\r\n // Only bother to send query if it's non-default.\r\n if (listenSpec.tag) {\r\n req['q'] = query._queryObject;\r\n req['t'] = listenSpec.tag;\r\n }\r\n req[ /*hash*/'h'] = listenSpec.hashFn();\r\n this.sendRequest(action, req, (message) => {\r\n const payload = message[ /*data*/'d'];\r\n const status = message[ /*status*/'s'];\r\n // print warnings in any case...\r\n PersistentConnection.warnOnListenWarnings_(payload, query);\r\n const currentListenSpec = this.listens.get(pathString) &&\r\n this.listens.get(pathString).get(queryId);\r\n // only trigger actions if the listen hasn't been removed and readded\r\n if (currentListenSpec === listenSpec) {\r\n this.log_('listen response', message);\r\n if (status !== 'ok') {\r\n this.removeListen_(pathString, queryId);\r\n }\r\n if (listenSpec.onComplete) {\r\n listenSpec.onComplete(status, payload);\r\n }\r\n }\r\n });\r\n }\r\n static warnOnListenWarnings_(payload, query) {\r\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const warnings = safeGet(payload, 'w');\r\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\r\n const indexSpec = '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\r\n const indexPath = query._path.toString();\r\n warn(`Using an unspecified index. Your data will be downloaded and ` +\r\n `filtered on the client. Consider adding ${indexSpec} at ` +\r\n `${indexPath} to your security rules for better performance.`);\r\n }\r\n }\r\n }\r\n refreshAuthToken(token) {\r\n this.authToken_ = token;\r\n this.log_('Auth token refreshed');\r\n if (this.authToken_) {\r\n this.tryAuth();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\r\n //the credential so we dont become authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unauth', {}, () => { });\r\n }\r\n }\r\n this.reduceReconnectDelayIfAdminCredential_(token);\r\n }\r\n reduceReconnectDelayIfAdminCredential_(credential) {\r\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\r\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\r\n const isFirebaseSecret = credential && credential.length === 40;\r\n if (isFirebaseSecret || isAdmin(credential)) {\r\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n }\r\n }\r\n refreshAppCheckToken(token) {\r\n this.appCheckToken_ = token;\r\n this.log_('App check token refreshed');\r\n if (this.appCheckToken_) {\r\n this.tryAppCheck();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us.\r\n //If we're not connected, simply delete the credential so we dont become\r\n // authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unappeck', {}, () => { });\r\n }\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\r\n * a auth revoked (the connection is closed).\r\n */\r\n tryAuth() {\r\n if (this.connected_ && this.authToken_) {\r\n const token = this.authToken_;\r\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\r\n const requestData = { cred: token };\r\n if (this.authOverride_ === null) {\r\n requestData['noauth'] = true;\r\n }\r\n else if (typeof this.authOverride_ === 'object') {\r\n requestData['authvar'] = this.authOverride_;\r\n }\r\n this.sendRequest(authMethod, requestData, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (this.authToken_ === token) {\r\n if (status === 'ok') {\r\n this.invalidAuthTokenCount_ = 0;\r\n }\r\n else {\r\n // Triggers reconnect and force refresh for auth token\r\n this.onAuthRevoked_(status, data);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given token. If the authentication\r\n * attempt fails, it's triggered like the token was revoked (the connection is\r\n * closed).\r\n */\r\n tryAppCheck() {\r\n if (this.connected_ && this.appCheckToken_) {\r\n this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (status === 'ok') {\r\n this.invalidAppCheckTokenCount_ = 0;\r\n }\r\n else {\r\n this.onAppCheckRevoked_(status, data);\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n unlisten(query, tag) {\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && this.connected_) {\r\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\r\n }\r\n }\r\n sendUnlisten_(pathString, queryId, queryObj, tag) {\r\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'n';\r\n // Only bother sending queryId if it's non-default.\r\n if (tag) {\r\n req['q'] = queryObj;\r\n req['t'] = tag;\r\n }\r\n this.sendRequest(action, req);\r\n }\r\n onDisconnectPut(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('o', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'o',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectMerge(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('om', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'om',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectCancel(pathString, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'oc',\r\n data: null,\r\n onComplete\r\n });\r\n }\r\n }\r\n sendOnDisconnect_(action, pathString, data, onComplete) {\r\n const request = { /*path*/ p: pathString, /*data*/ d: data };\r\n this.log_('onDisconnect ' + action, request);\r\n this.sendRequest(action, request, (response) => {\r\n if (onComplete) {\r\n setTimeout(() => {\r\n onComplete(response[ /*status*/'s'], response[ /* data */'d']);\r\n }, Math.floor(0));\r\n }\r\n });\r\n }\r\n put(pathString, data, onComplete, hash) {\r\n this.putInternal('p', pathString, data, onComplete, hash);\r\n }\r\n merge(pathString, data, onComplete, hash) {\r\n this.putInternal('m', pathString, data, onComplete, hash);\r\n }\r\n putInternal(action, pathString, data, onComplete, hash) {\r\n this.initConnection_();\r\n const request = {\r\n /*path*/ p: pathString,\r\n /*data*/ d: data\r\n };\r\n if (hash !== undefined) {\r\n request[ /*hash*/'h'] = hash;\r\n }\r\n // TODO: Only keep track of the most recent put for a given path?\r\n this.outstandingPuts_.push({\r\n action,\r\n request,\r\n onComplete\r\n });\r\n this.outstandingPutCount_++;\r\n const index = this.outstandingPuts_.length - 1;\r\n if (this.connected_) {\r\n this.sendPut_(index);\r\n }\r\n else {\r\n this.log_('Buffering put: ' + pathString);\r\n }\r\n }\r\n sendPut_(index) {\r\n const action = this.outstandingPuts_[index].action;\r\n const request = this.outstandingPuts_[index].request;\r\n const onComplete = this.outstandingPuts_[index].onComplete;\r\n this.outstandingPuts_[index].queued = this.connected_;\r\n this.sendRequest(action, request, (message) => {\r\n this.log_(action + ' response', message);\r\n delete this.outstandingPuts_[index];\r\n this.outstandingPutCount_--;\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n if (onComplete) {\r\n onComplete(message[ /*status*/'s'], message[ /* data */'d']);\r\n }\r\n });\r\n }\r\n reportStats(stats) {\r\n // If we're not connected, we just drop the stats.\r\n if (this.connected_) {\r\n const request = { /*counters*/ c: stats };\r\n this.log_('reportStats', request);\r\n this.sendRequest(/*stats*/ 's', request, result => {\r\n const status = result[ /*status*/'s'];\r\n if (status !== 'ok') {\r\n const errorReason = result[ /* data */'d'];\r\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\r\n }\r\n });\r\n }\r\n }\r\n onDataMessage_(message) {\r\n if ('r' in message) {\r\n // this is a response\r\n this.log_('from server: ' + stringify(message));\r\n const reqNum = message['r'];\r\n const onResponse = this.requestCBHash_[reqNum];\r\n if (onResponse) {\r\n delete this.requestCBHash_[reqNum];\r\n onResponse(message[ /*body*/'b']);\r\n }\r\n }\r\n else if ('error' in message) {\r\n throw 'A server-side error has occurred: ' + message['error'];\r\n }\r\n else if ('a' in message) {\r\n // a and b are action and body, respectively\r\n this.onDataPush_(message['a'], message['b']);\r\n }\r\n }\r\n onDataPush_(action, body) {\r\n this.log_('handleServerMessage', action, body);\r\n if (action === 'd') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge*/ false, body['t']);\r\n }\r\n else if (action === 'm') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge=*/ true, body['t']);\r\n }\r\n else if (action === 'c') {\r\n this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);\r\n }\r\n else if (action === 'ac') {\r\n this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'apc') {\r\n this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'sd') {\r\n this.onSecurityDebugPacket_(body);\r\n }\r\n else {\r\n error('Unrecognized action received from server: ' +\r\n stringify(action) +\r\n '\\nAre you using the latest client?');\r\n }\r\n }\r\n onReady_(timestamp, sessionId) {\r\n this.log_('connection ready');\r\n this.connected_ = true;\r\n this.lastConnectionEstablishedTime_ = new Date().getTime();\r\n this.handleTimestamp_(timestamp);\r\n this.lastSessionId = sessionId;\r\n if (this.firstConnection_) {\r\n this.sendConnectStats_();\r\n }\r\n this.restoreState_();\r\n this.firstConnection_ = false;\r\n this.onConnectStatus_(true);\r\n }\r\n scheduleConnect_(timeout) {\r\n assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n }\r\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\r\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\r\n this.establishConnectionTimer_ = setTimeout(() => {\r\n this.establishConnectionTimer_ = null;\r\n this.establishConnection_();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(timeout));\r\n }\r\n initConnection_() {\r\n if (!this.realtime_ && this.firstConnection_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n onVisible_(visible) {\r\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\r\n if (visible &&\r\n !this.visible_ &&\r\n this.reconnectDelay_ === this.maxReconnectDelay_) {\r\n this.log_('Window became visible. Reducing delay.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n this.visible_ = visible;\r\n }\r\n onOnline_(online) {\r\n if (online) {\r\n this.log_('Browser went online.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n else {\r\n this.log_('Browser went offline. Killing connection.');\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n }\r\n }\r\n onRealtimeDisconnect_() {\r\n this.log_('data client disconnected');\r\n this.connected_ = false;\r\n this.realtime_ = null;\r\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\r\n this.cancelSentTransactions_();\r\n // Clear out the pending requests.\r\n this.requestCBHash_ = {};\r\n if (this.shouldReconnect_()) {\r\n if (!this.visible_) {\r\n this.log_(\"Window isn't visible. Delaying reconnect.\");\r\n this.reconnectDelay_ = this.maxReconnectDelay_;\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n }\r\n else if (this.lastConnectionEstablishedTime_) {\r\n // If we've been connected long enough, reset reconnect delay to minimum.\r\n const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\r\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n }\r\n this.lastConnectionEstablishedTime_ = null;\r\n }\r\n const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\r\n let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\r\n reconnectDelay = Math.random() * reconnectDelay;\r\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\r\n this.scheduleConnect_(reconnectDelay);\r\n // Adjust reconnect delay for next time.\r\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\r\n }\r\n this.onConnectStatus_(false);\r\n }\r\n async establishConnection_() {\r\n if (this.shouldReconnect_()) {\r\n this.log_('Making a connection attempt');\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n this.lastConnectionEstablishedTime_ = null;\r\n const onDataMessage = this.onDataMessage_.bind(this);\r\n const onReady = this.onReady_.bind(this);\r\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\r\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\r\n const lastSessionId = this.lastSessionId;\r\n let canceled = false;\r\n let connection = null;\r\n const closeFn = function () {\r\n if (connection) {\r\n connection.close();\r\n }\r\n else {\r\n canceled = true;\r\n onDisconnect();\r\n }\r\n };\r\n const sendRequestFn = function (msg) {\r\n assert(connection, \"sendRequest call when we're not connected not allowed.\");\r\n connection.sendRequest(msg);\r\n };\r\n this.realtime_ = {\r\n close: closeFn,\r\n sendRequest: sendRequestFn\r\n };\r\n const forceRefresh = this.forceTokenRefresh_;\r\n this.forceTokenRefresh_ = false;\r\n try {\r\n // First fetch auth and app check token, and establish connection after\r\n // fetching the token was successful\r\n const [authToken, appCheckToken] = await Promise.all([\r\n this.authTokenProvider_.getToken(forceRefresh),\r\n this.appCheckTokenProvider_.getToken(forceRefresh)\r\n ]);\r\n if (!canceled) {\r\n log('getToken() completed. Creating connection.');\r\n this.authToken_ = authToken && authToken.accessToken;\r\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\r\n connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, \r\n /* onKill= */ reason => {\r\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\r\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\r\n }, lastSessionId);\r\n }\r\n else {\r\n log('getToken() completed but was canceled');\r\n }\r\n }\r\n catch (error) {\r\n this.log_('Failed to get token: ' + error);\r\n if (!canceled) {\r\n if (this.repoInfo_.nodeAdmin) {\r\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\r\n // But getToken() may also just have temporarily failed, so we still want to\r\n // continue retrying.\r\n warn(error);\r\n }\r\n closeFn();\r\n }\r\n }\r\n }\r\n }\r\n interrupt(reason) {\r\n log('Interrupting connection for reason: ' + reason);\r\n this.interruptReasons_[reason] = true;\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n else {\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n this.establishConnectionTimer_ = null;\r\n }\r\n if (this.connected_) {\r\n this.onRealtimeDisconnect_();\r\n }\r\n }\r\n }\r\n resume(reason) {\r\n log('Resuming connection for reason: ' + reason);\r\n delete this.interruptReasons_[reason];\r\n if (isEmpty(this.interruptReasons_)) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n }\r\n handleTimestamp_(timestamp) {\r\n const delta = timestamp - new Date().getTime();\r\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\r\n }\r\n cancelSentTransactions_() {\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n const put = this.outstandingPuts_[i];\r\n if (put && /*hash*/ 'h' in put.request && put.queued) {\r\n if (put.onComplete) {\r\n put.onComplete('disconnect');\r\n }\r\n delete this.outstandingPuts_[i];\r\n this.outstandingPutCount_--;\r\n }\r\n }\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n }\r\n onListenRevoked_(pathString, query) {\r\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\r\n let queryId;\r\n if (!query) {\r\n queryId = 'default';\r\n }\r\n else {\r\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\r\n }\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && listen.onComplete) {\r\n listen.onComplete('permission_denied');\r\n }\r\n }\r\n removeListen_(pathString, queryId) {\r\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\r\n let listen;\r\n if (this.listens.has(normalizedPathString)) {\r\n const map = this.listens.get(normalizedPathString);\r\n listen = map.get(queryId);\r\n map.delete(queryId);\r\n if (map.size === 0) {\r\n this.listens.delete(normalizedPathString);\r\n }\r\n }\r\n else {\r\n // all listens for this path has already been removed\r\n listen = undefined;\r\n }\r\n return listen;\r\n }\r\n onAuthRevoked_(statusCode, explanation) {\r\n log('Auth token revoked: ' + statusCode + '/' + explanation);\r\n this.authToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n this.realtime_.close();\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAuthTokenCount_++;\r\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n // Set a long reconnect delay because recovery is unlikely\r\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n // Notify the auth token provider that the token is invalid, which will log\r\n // a warning\r\n this.authTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onAppCheckRevoked_(statusCode, explanation) {\r\n log('App check token revoked: ' + statusCode + '/' + explanation);\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n // Note: We don't close the connection as the developer may not have\r\n // enforcement enabled. The backend closes connections with enforcements.\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAppCheckTokenCount_++;\r\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n this.appCheckTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onSecurityDebugPacket_(body) {\r\n if (this.securityDebugCallback_) {\r\n this.securityDebugCallback_(body);\r\n }\r\n else {\r\n if ('msg' in body) {\r\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\r\n }\r\n }\r\n }\r\n restoreState_() {\r\n //Re-authenticate ourselves if we have a credential stored.\r\n this.tryAuth();\r\n this.tryAppCheck();\r\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\r\n // make sure to send listens before puts.\r\n for (const queries of this.listens.values()) {\r\n for (const listenSpec of queries.values()) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n if (this.outstandingPuts_[i]) {\r\n this.sendPut_(i);\r\n }\r\n }\r\n while (this.onDisconnectRequestQueue_.length) {\r\n const request = this.onDisconnectRequestQueue_.shift();\r\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\r\n }\r\n for (let i = 0; i < this.outstandingGets_.length; i++) {\r\n if (this.outstandingGets_[i]) {\r\n this.sendGet_(i);\r\n }\r\n }\r\n }\r\n /**\r\n * Sends client stats for first connection\r\n */\r\n sendConnectStats_() {\r\n const stats = {};\r\n let clientName = 'js';\r\n if (isNodeSdk()) {\r\n if (this.repoInfo_.nodeAdmin) {\r\n clientName = 'admin_node';\r\n }\r\n else {\r\n clientName = 'node';\r\n }\r\n }\r\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\r\n if (isMobileCordova()) {\r\n stats['framework.cordova'] = 1;\r\n }\r\n else if (isReactNative()) {\r\n stats['framework.reactnative'] = 1;\r\n }\r\n this.reportStats(stats);\r\n }\r\n shouldReconnect_() {\r\n const online = OnlineMonitor.getInstance().currentlyOnline();\r\n return isEmpty(this.interruptReasons_) && online;\r\n }\r\n}\r\nPersistentConnection.nextPersistentConnectionId_ = 0;\r\n/**\r\n * Counter for number of connections created. Mainly used for tagging in the logs\r\n */\r\nPersistentConnection.nextConnectionId_ = 0;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass NamedNode {\r\n constructor(name, node) {\r\n this.name = name;\r\n this.node = node;\r\n }\r\n static Wrap(name, node) {\r\n return new NamedNode(name, node);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Index {\r\n /**\r\n * @returns A standalone comparison function for\r\n * this index\r\n */\r\n getCompare() {\r\n return this.compare.bind(this);\r\n }\r\n /**\r\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\r\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\r\n *\r\n *\r\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\r\n */\r\n indexedValueChanged(oldNode, newNode) {\r\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\r\n const newWrapped = new NamedNode(MIN_NAME, newNode);\r\n return this.compare(oldWrapped, newWrapped) !== 0;\r\n }\r\n /**\r\n * @returns a node wrapper that will sort equal to or less than\r\n * any other node wrapper, using this index\r\n */\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet __EMPTY_NODE;\r\nclass KeyIndex extends Index {\r\n static get __EMPTY_NODE() {\r\n return __EMPTY_NODE;\r\n }\r\n static set __EMPTY_NODE(val) {\r\n __EMPTY_NODE = val;\r\n }\r\n compare(a, b) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n isDefinedOn(node) {\r\n // We could probably return true here (since every node has a key), but it's never called\r\n // so just leaving unimplemented for now.\r\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return false; // The key for a node never changes.\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // TODO: This should really be created once and cached in a static property, but\r\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\r\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\r\n }\r\n makePost(indexValue, name) {\r\n assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\r\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\r\n return new NamedNode(indexValue, __EMPTY_NODE);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.key';\r\n }\r\n}\r\nconst KEY_INDEX = new KeyIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An iterator over an LLRBNode.\r\n */\r\nclass SortedMapIterator {\r\n /**\r\n * @param node - Node to iterate.\r\n * @param isReverse_ - Whether or not to iterate in reverse\r\n */\r\n constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {\r\n this.isReverse_ = isReverse_;\r\n this.resultGenerator_ = resultGenerator_;\r\n this.nodeStack_ = [];\r\n let cmp = 1;\r\n while (!node.isEmpty()) {\r\n node = node;\r\n cmp = startKey ? comparator(node.key, startKey) : 1;\r\n // flip the comparison if we're going in reverse\r\n if (isReverse_) {\r\n cmp *= -1;\r\n }\r\n if (cmp < 0) {\r\n // This node is less than our start key. ignore it\r\n if (this.isReverse_) {\r\n node = node.left;\r\n }\r\n else {\r\n node = node.right;\r\n }\r\n }\r\n else if (cmp === 0) {\r\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\r\n this.nodeStack_.push(node);\r\n break;\r\n }\r\n else {\r\n // This node is greater than our start key, add it to the stack and move to the next one\r\n this.nodeStack_.push(node);\r\n if (this.isReverse_) {\r\n node = node.right;\r\n }\r\n else {\r\n node = node.left;\r\n }\r\n }\r\n }\r\n }\r\n getNext() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n let node = this.nodeStack_.pop();\r\n let result;\r\n if (this.resultGenerator_) {\r\n result = this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n result = { key: node.key, value: node.value };\r\n }\r\n if (this.isReverse_) {\r\n node = node.left;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.right;\r\n }\r\n }\r\n else {\r\n node = node.right;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.left;\r\n }\r\n }\r\n return result;\r\n }\r\n hasNext() {\r\n return this.nodeStack_.length > 0;\r\n }\r\n peek() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n const node = this.nodeStack_[this.nodeStack_.length - 1];\r\n if (this.resultGenerator_) {\r\n return this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n return { key: node.key, value: node.value };\r\n }\r\n }\r\n}\r\n/**\r\n * Represents a node in a Left-leaning Red-Black tree.\r\n */\r\nclass LLRBNode {\r\n /**\r\n * @param key - Key associated with this node.\r\n * @param value - Value associated with this node.\r\n * @param color - Whether this node is red.\r\n * @param left - Left child.\r\n * @param right - Right child.\r\n */\r\n constructor(key, value, color, left, right) {\r\n this.key = key;\r\n this.value = value;\r\n this.color = color != null ? color : LLRBNode.RED;\r\n this.left =\r\n left != null ? left : SortedMap.EMPTY_NODE;\r\n this.right =\r\n right != null ? right : SortedMap.EMPTY_NODE;\r\n }\r\n /**\r\n * Returns a copy of the current node, optionally replacing pieces of it.\r\n *\r\n * @param key - New key for the node, or null.\r\n * @param value - New value for the node, or null.\r\n * @param color - New color for the node, or null.\r\n * @param left - New left child for the node, or null.\r\n * @param right - New right child for the node, or null.\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return this.left.count() + 1 + this.right.count();\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return (this.left.inorderTraversal(action) ||\r\n !!action(this.key, this.value) ||\r\n this.right.inorderTraversal(action));\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return (this.right.reverseTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.left.reverseTraversal(action));\r\n }\r\n /**\r\n * @returns The minimum node in the tree.\r\n */\r\n min_() {\r\n if (this.left.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n return this.left.min_();\r\n }\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n minKey() {\r\n return this.min_().key;\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n maxKey() {\r\n if (this.right.isEmpty()) {\r\n return this.key;\r\n }\r\n else {\r\n return this.right.maxKey();\r\n }\r\n }\r\n /**\r\n * @param key - Key to insert.\r\n * @param value - Value to insert.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the key/value added.\r\n */\r\n insert(key, value, comparator) {\r\n let n = this;\r\n const cmp = comparator(key, n.key);\r\n if (cmp < 0) {\r\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\r\n }\r\n else if (cmp === 0) {\r\n n = n.copy(null, value, null, null, null);\r\n }\r\n else {\r\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns New tree, with the minimum key removed.\r\n */\r\n removeMin_() {\r\n if (this.left.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n let n = this;\r\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.removeMin_(), null);\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @param key - The key of the item to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the specified item removed.\r\n */\r\n remove(key, comparator) {\r\n let n, smallest;\r\n n = this;\r\n if (comparator(key, n.key) < 0) {\r\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\r\n }\r\n else {\r\n if (n.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\r\n n = n.moveRedRight_();\r\n }\r\n if (comparator(key, n.key) === 0) {\r\n if (n.right.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n else {\r\n smallest = n.right.min_();\r\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\r\n }\r\n }\r\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns Whether this is a RED node.\r\n */\r\n isRed_() {\r\n return this.color;\r\n }\r\n /**\r\n * @returns New tree after performing any needed rotations.\r\n */\r\n fixUp_() {\r\n let n = this;\r\n if (n.right.isRed_() && !n.left.isRed_()) {\r\n n = n.rotateLeft_();\r\n }\r\n if (n.left.isRed_() && n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (n.left.isRed_() && n.right.isRed_()) {\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedLeft.\r\n */\r\n moveRedLeft_() {\r\n let n = this.colorFlip_();\r\n if (n.right.left.isRed_()) {\r\n n = n.copy(null, null, null, null, n.right.rotateRight_());\r\n n = n.rotateLeft_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedRight.\r\n */\r\n moveRedRight_() {\r\n let n = this.colorFlip_();\r\n if (n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after rotateLeft.\r\n */\r\n rotateLeft_() {\r\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\r\n return this.right.copy(null, null, this.color, nl, null);\r\n }\r\n /**\r\n * @returns New tree, after rotateRight.\r\n */\r\n rotateRight_() {\r\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\r\n return this.left.copy(null, null, this.color, null, nr);\r\n }\r\n /**\r\n * @returns Newt ree, after colorFlip.\r\n */\r\n colorFlip_() {\r\n const left = this.left.copy(null, null, !this.left.color, null, null);\r\n const right = this.right.copy(null, null, !this.right.color, null, null);\r\n return this.copy(null, null, !this.color, left, right);\r\n }\r\n /**\r\n * For testing.\r\n *\r\n * @returns True if all is well.\r\n */\r\n checkMaxDepth_() {\r\n const blackDepth = this.check_();\r\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\r\n }\r\n check_() {\r\n if (this.isRed_() && this.left.isRed_()) {\r\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\r\n }\r\n if (this.right.isRed_()) {\r\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\r\n }\r\n const blackDepth = this.left.check_();\r\n if (blackDepth !== this.right.check_()) {\r\n throw new Error('Black depths differ');\r\n }\r\n else {\r\n return blackDepth + (this.isRed_() ? 0 : 1);\r\n }\r\n }\r\n}\r\nLLRBNode.RED = true;\r\nLLRBNode.BLACK = false;\r\n/**\r\n * Represents an empty node (a leaf node in the Red-Black Tree).\r\n */\r\nclass LLRBEmptyNode {\r\n /**\r\n * Returns a copy of the current node.\r\n *\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return this;\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key/value added.\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item added.\r\n */\r\n insert(key, value, comparator) {\r\n return new LLRBNode(key, value, null);\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item removed.\r\n */\r\n remove(key, comparator) {\r\n return this;\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return 0;\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return true;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n inorderTraversal(action) {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return false;\r\n }\r\n minKey() {\r\n return null;\r\n }\r\n maxKey() {\r\n return null;\r\n }\r\n check_() {\r\n return 0;\r\n }\r\n /**\r\n * @returns Whether this node is red.\r\n */\r\n isRed_() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\r\n * tree.\r\n */\r\nclass SortedMap {\r\n /**\r\n * @param comparator_ - Key comparator.\r\n * @param root_ - Optional root node for the map.\r\n */\r\n constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {\r\n this.comparator_ = comparator_;\r\n this.root_ = root_;\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key/value added or replaced.\r\n * (TODO: We should perhaps rename this method to 'put')\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @returns New map, with item added.\r\n */\r\n insert(key, value) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .insert(key, value, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @returns New map, with item removed.\r\n */\r\n remove(key) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .remove(key, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns the value of the node with the given key, or null.\r\n *\r\n * @param key - The key to look up.\r\n * @returns The value of the node with the given key, or null if the\r\n * key doesn't exist.\r\n */\r\n get(key) {\r\n let cmp;\r\n let node = this.root_;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n return node.value;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n node = node.right;\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n * Returns the key of the item *before* the specified key, or null if key is the first item.\r\n * @param key - The key to find the predecessor of\r\n * @returns The predecessor key.\r\n */\r\n getPredecessorKey(key) {\r\n let cmp, node = this.root_, rightParent = null;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n if (!node.left.isEmpty()) {\r\n node = node.left;\r\n while (!node.right.isEmpty()) {\r\n node = node.right;\r\n }\r\n return node.key;\r\n }\r\n else if (rightParent) {\r\n return rightParent.key;\r\n }\r\n else {\r\n return null; // first item.\r\n }\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n rightParent = node;\r\n node = node.right;\r\n }\r\n }\r\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\r\n }\r\n /**\r\n * @returns True if the map is empty.\r\n */\r\n isEmpty() {\r\n return this.root_.isEmpty();\r\n }\r\n /**\r\n * @returns The total number of nodes in the map.\r\n */\r\n count() {\r\n return this.root_.count();\r\n }\r\n /**\r\n * @returns The minimum key in the map.\r\n */\r\n minKey() {\r\n return this.root_.minKey();\r\n }\r\n /**\r\n * @returns The maximum key in the map.\r\n */\r\n maxKey() {\r\n return this.root_.maxKey();\r\n }\r\n /**\r\n * Traverses the map in key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return this.root_.inorderTraversal(action);\r\n }\r\n /**\r\n * Traverses the map in reverse key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns True if the traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return this.root_.reverseTraversal(action);\r\n }\r\n /**\r\n * Returns an iterator over the SortedMap.\r\n * @returns The iterator.\r\n */\r\n getIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\r\n }\r\n getIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\r\n }\r\n getReverseIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\r\n }\r\n getReverseIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\r\n }\r\n}\r\n/**\r\n * Always use the same empty node, to reduce memory.\r\n */\r\nSortedMap.EMPTY_NODE = new LLRBEmptyNode();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction NAME_ONLY_COMPARATOR(left, right) {\r\n return nameCompare(left.name, right.name);\r\n}\r\nfunction NAME_COMPARATOR(left, right) {\r\n return nameCompare(left, right);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet MAX_NODE$2;\r\nfunction setMaxNode$1(val) {\r\n MAX_NODE$2 = val;\r\n}\r\nconst priorityHashText = function (priority) {\r\n if (typeof priority === 'number') {\r\n return 'number:' + doubleToIEEE754String(priority);\r\n }\r\n else {\r\n return 'string:' + priority;\r\n }\r\n};\r\n/**\r\n * Validates that a priority snapshot Node is valid.\r\n */\r\nconst validatePriorityNode = function (priorityNode) {\r\n if (priorityNode.isLeafNode()) {\r\n const val = priorityNode.val();\r\n assert(typeof val === 'string' ||\r\n typeof val === 'number' ||\r\n (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');\r\n }\r\n else {\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');\r\n }\r\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet __childrenNodeConstructor;\r\n/**\r\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\r\n * implements Node and stores the value of the node (a string,\r\n * number, or boolean) accessible via getValue().\r\n */\r\nclass LeafNode {\r\n /**\r\n * @param value_ - The value to store in this leaf node. The object type is\r\n * possible in the event of a deferred value\r\n * @param priorityNode_ - The priority of this node.\r\n */\r\n constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n this.value_ = value_;\r\n this.priorityNode_ = priorityNode_;\r\n this.lazyHash_ = null;\r\n assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n static set __childrenNodeConstructor(val) {\r\n __childrenNodeConstructor = val;\r\n }\r\n static get __childrenNodeConstructor() {\r\n return __childrenNodeConstructor;\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return true;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n return new LeafNode(this.value_, newPriorityNode);\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n if (pathIsEmpty(path)) {\r\n return this;\r\n }\r\n else if (pathGetFront(path) === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n hasChild() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode) {\r\n return null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else if (newChildNode.isEmpty() && childName !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else if (newChildNode.isEmpty() && front !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return 0;\r\n }\r\n /** @inheritDoc */\r\n forEachChild(index, action) {\r\n return false;\r\n }\r\n val(exportFormat) {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n return {\r\n '.value': this.getValue(),\r\n '.priority': this.getPriority().val()\r\n };\r\n }\r\n else {\r\n return this.getValue();\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.priorityNode_.isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.priorityNode_.val()) +\r\n ':';\r\n }\r\n const type = typeof this.value_;\r\n toHash += type + ':';\r\n if (type === 'number') {\r\n toHash += doubleToIEEE754String(this.value_);\r\n }\r\n else {\r\n toHash += this.value_;\r\n }\r\n this.lazyHash_ = sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /**\r\n * Returns the value of the leaf node.\r\n * @returns The value of the node.\r\n */\r\n getValue() {\r\n return this.value_;\r\n }\r\n compareTo(other) {\r\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n return 1;\r\n }\r\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\r\n return -1;\r\n }\r\n else {\r\n assert(other.isLeafNode(), 'Unknown node type');\r\n return this.compareToLeafNode_(other);\r\n }\r\n }\r\n /**\r\n * Comparison specifically for two leaf nodes\r\n */\r\n compareToLeafNode_(otherLeaf) {\r\n const otherLeafType = typeof otherLeaf.value_;\r\n const thisLeafType = typeof this.value_;\r\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\r\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\r\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\r\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\r\n if (otherIndex === thisIndex) {\r\n // Same type, compare values\r\n if (thisLeafType === 'object') {\r\n // Deferred value nodes are all equal, but we should also never get to this point...\r\n return 0;\r\n }\r\n else {\r\n // Note that this works because true > false, all others are number or string comparisons\r\n if (this.value_ < otherLeaf.value_) {\r\n return -1;\r\n }\r\n else if (this.value_ === otherLeaf.value_) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n }\r\n else {\r\n return thisIndex - otherIndex;\r\n }\r\n }\r\n withIndex() {\r\n return this;\r\n }\r\n isIndexed() {\r\n return true;\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n const otherLeaf = other;\r\n return (this.value_ === otherLeaf.value_ &&\r\n this.priorityNode_.equals(otherLeaf.priorityNode_));\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n}\r\n/**\r\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\r\n * the same type, the comparison falls back to their value\r\n */\r\nLeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet nodeFromJSON$1;\r\nlet MAX_NODE$1;\r\nfunction setNodeFromJSON(val) {\r\n nodeFromJSON$1 = val;\r\n}\r\nfunction setMaxNode(val) {\r\n MAX_NODE$1 = val;\r\n}\r\nclass PriorityIndex extends Index {\r\n compare(a, b) {\r\n const aPriority = a.node.getPriority();\r\n const bPriority = b.node.getPriority();\r\n const indexCmp = aPriority.compareTo(bPriority);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return !node.getPriority().isEmpty();\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.getPriority().equals(newNode.getPriority());\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));\r\n }\r\n makePost(indexValue, name) {\r\n const priorityNode = nodeFromJSON$1(indexValue);\r\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.priority';\r\n }\r\n}\r\nconst PRIORITY_INDEX = new PriorityIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst LOG_2 = Math.log(2);\r\nclass Base12Num {\r\n constructor(length) {\r\n const logBase2 = (num) => \r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n parseInt((Math.log(num) / LOG_2), 10);\r\n const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);\r\n this.count = logBase2(length + 1);\r\n this.current_ = this.count - 1;\r\n const mask = bitMask(this.count);\r\n this.bits_ = (length + 1) & mask;\r\n }\r\n nextBitIsOne() {\r\n //noinspection JSBitwiseOperatorUsage\r\n const result = !(this.bits_ & (0x1 << this.current_));\r\n this.current_--;\r\n return result;\r\n }\r\n}\r\n/**\r\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\r\n * function\r\n *\r\n * Uses the algorithm described in the paper linked here:\r\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\r\n *\r\n * @param childList - Unsorted list of children\r\n * @param cmp - The comparison method to be used\r\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\r\n * type is not NamedNode\r\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\r\n */\r\nconst buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\r\n childList.sort(cmp);\r\n const buildBalancedTree = function (low, high) {\r\n const length = high - low;\r\n let namedNode;\r\n let key;\r\n if (length === 0) {\r\n return null;\r\n }\r\n else if (length === 1) {\r\n namedNode = childList[low];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);\r\n }\r\n else {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const middle = parseInt((length / 2), 10) + low;\r\n const left = buildBalancedTree(low, middle);\r\n const right = buildBalancedTree(middle + 1, high);\r\n namedNode = childList[middle];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);\r\n }\r\n };\r\n const buildFrom12Array = function (base12) {\r\n let node = null;\r\n let root = null;\r\n let index = childList.length;\r\n const buildPennant = function (chunkSize, color) {\r\n const low = index - chunkSize;\r\n const high = index;\r\n index -= chunkSize;\r\n const childTree = buildBalancedTree(low + 1, high);\r\n const namedNode = childList[low];\r\n const key = keyFn ? keyFn(namedNode) : namedNode;\r\n attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));\r\n };\r\n const attachPennant = function (pennant) {\r\n if (node) {\r\n node.left = pennant;\r\n node = pennant;\r\n }\r\n else {\r\n root = pennant;\r\n node = pennant;\r\n }\r\n };\r\n for (let i = 0; i < base12.count; ++i) {\r\n const isOne = base12.nextBitIsOne();\r\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\r\n const chunkSize = Math.pow(2, base12.count - (i + 1));\r\n if (isOne) {\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n }\r\n else {\r\n // current == 2\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n buildPennant(chunkSize, LLRBNode.RED);\r\n }\r\n }\r\n return root;\r\n };\r\n const base12 = new Base12Num(childList.length);\r\n const root = buildFrom12Array(base12);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return new SortedMap(mapSortFn || cmp, root);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet _defaultIndexMap;\r\nconst fallbackObject = {};\r\nclass IndexMap {\r\n constructor(indexes_, indexSet_) {\r\n this.indexes_ = indexes_;\r\n this.indexSet_ = indexSet_;\r\n }\r\n /**\r\n * The default IndexMap for nodes without a priority\r\n */\r\n static get Default() {\r\n assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\r\n _defaultIndexMap =\r\n _defaultIndexMap ||\r\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });\r\n return _defaultIndexMap;\r\n }\r\n get(indexKey) {\r\n const sortedMap = safeGet(this.indexes_, indexKey);\r\n if (!sortedMap) {\r\n throw new Error('No index defined for ' + indexKey);\r\n }\r\n if (sortedMap instanceof SortedMap) {\r\n return sortedMap;\r\n }\r\n else {\r\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\r\n // regular child map\r\n return null;\r\n }\r\n }\r\n hasIndex(indexDefinition) {\r\n return contains(this.indexSet_, indexDefinition.toString());\r\n }\r\n addIndex(indexDefinition, existingChildren) {\r\n assert(indexDefinition !== KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\r\n const childList = [];\r\n let sawIndexedValue = false;\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n sawIndexedValue =\r\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\r\n childList.push(next);\r\n next = iter.getNext();\r\n }\r\n let newIndex;\r\n if (sawIndexedValue) {\r\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\r\n }\r\n else {\r\n newIndex = fallbackObject;\r\n }\r\n const indexName = indexDefinition.toString();\r\n const newIndexSet = Object.assign({}, this.indexSet_);\r\n newIndexSet[indexName] = indexDefinition;\r\n const newIndexes = Object.assign({}, this.indexes_);\r\n newIndexes[indexName] = newIndex;\r\n return new IndexMap(newIndexes, newIndexSet);\r\n }\r\n /**\r\n * Ensure that this node is properly tracked in any indexes that we're maintaining\r\n */\r\n addToIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {\r\n const index = safeGet(this.indexSet_, indexName);\r\n assert(index, 'Missing index implementation for ' + indexName);\r\n if (indexedChildren === fallbackObject) {\r\n // Check to see if we need to index everything\r\n if (index.isDefinedOn(namedNode.node)) {\r\n // We need to build this index\r\n const childList = [];\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n if (next.name !== namedNode.name) {\r\n childList.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n childList.push(namedNode);\r\n return buildChildSet(childList, index.getCompare());\r\n }\r\n else {\r\n // No change, this remains a fallback\r\n return fallbackObject;\r\n }\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n let newChildren = indexedChildren;\r\n if (existingSnap) {\r\n newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n return newChildren.insert(namedNode, namedNode.node);\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n }\r\n /**\r\n * Create a new IndexMap instance with the given value removed\r\n */\r\n removeFromIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren) => {\r\n if (indexedChildren === fallbackObject) {\r\n // This is the fallback. Just return it, nothing to do in this case\r\n return indexedChildren;\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n if (existingSnap) {\r\n return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n else {\r\n // No record of this child\r\n return indexedChildren;\r\n }\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\r\nlet EMPTY_NODE;\r\n/**\r\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\r\n * (i.e. nodes with children). It implements Node and stores the\r\n * list of children in the children property, sorted by child name.\r\n */\r\nclass ChildrenNode {\r\n /**\r\n * @param children_ - List of children of this node..\r\n * @param priorityNode_ - The priority of this node (as a snapshot node).\r\n */\r\n constructor(children_, priorityNode_, indexMap_) {\r\n this.children_ = children_;\r\n this.priorityNode_ = priorityNode_;\r\n this.indexMap_ = indexMap_;\r\n this.lazyHash_ = null;\r\n /**\r\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\r\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\r\n * class instead of an empty ChildrenNode.\r\n */\r\n if (this.priorityNode_) {\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n if (this.children_.isEmpty()) {\r\n assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\r\n }\r\n }\r\n static get EMPTY_NODE() {\r\n return (EMPTY_NODE ||\r\n (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_ || EMPTY_NODE;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n if (this.children_.isEmpty()) {\r\n // Don't allow priorities on empty nodes\r\n return this;\r\n }\r\n else {\r\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.getPriority();\r\n }\r\n else {\r\n const child = this.children_.get(childName);\r\n return child === null ? EMPTY_NODE : child;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return this;\r\n }\r\n return this.getImmediateChild(front).getChild(pathPopFront(path));\r\n }\r\n /** @inheritDoc */\r\n hasChild(childName) {\r\n return this.children_.get(childName) !== null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n assert(newChildNode, 'We should always be passing snapshot nodes');\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else {\r\n const namedNode = new NamedNode(childName, newChildNode);\r\n let newChildren, newIndexMap;\r\n if (newChildNode.isEmpty()) {\r\n newChildren = this.children_.remove(childName);\r\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\r\n }\r\n else {\r\n newChildren = this.children_.insert(childName, newChildNode);\r\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\r\n }\r\n const newPriority = newChildren.isEmpty()\r\n ? EMPTY_NODE\r\n : this.priorityNode_;\r\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else {\r\n assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);\r\n return this.updateImmediateChild(front, newImmediateChild);\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return this.children_.isEmpty();\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return this.children_.count();\r\n }\r\n /** @inheritDoc */\r\n val(exportFormat) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const obj = {};\r\n let numKeys = 0, maxKey = 0, allIntegerKeys = true;\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n obj[key] = childNode.val(exportFormat);\r\n numKeys++;\r\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\r\n maxKey = Math.max(maxKey, Number(key));\r\n }\r\n else {\r\n allIntegerKeys = false;\r\n }\r\n });\r\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\r\n // convert to array.\r\n const array = [];\r\n // eslint-disable-next-line guard-for-in\r\n for (const key in obj) {\r\n array[key] = obj[key];\r\n }\r\n return array;\r\n }\r\n else {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n obj['.priority'] = this.getPriority().val();\r\n }\r\n return obj;\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.getPriority().isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.getPriority().val()) +\r\n ':';\r\n }\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n const childHash = childNode.hash();\r\n if (childHash !== '') {\r\n toHash += ':' + key + ':' + childHash;\r\n }\r\n });\r\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode, index) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));\r\n return predecessor ? predecessor.name : null;\r\n }\r\n else {\r\n return this.children_.getPredecessorKey(childName);\r\n }\r\n }\r\n getFirstChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const minKey = idx.minKey();\r\n return minKey && minKey.name;\r\n }\r\n else {\r\n return this.children_.minKey();\r\n }\r\n }\r\n getFirstChild(indexDefinition) {\r\n const minKey = this.getFirstChildName(indexDefinition);\r\n if (minKey) {\r\n return new NamedNode(minKey, this.children_.get(minKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n /**\r\n * Given an index, return the key name of the largest value we have, according to that index\r\n */\r\n getLastChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const maxKey = idx.maxKey();\r\n return maxKey && maxKey.name;\r\n }\r\n else {\r\n return this.children_.maxKey();\r\n }\r\n }\r\n getLastChild(indexDefinition) {\r\n const maxKey = this.getLastChildName(indexDefinition);\r\n if (maxKey) {\r\n return new NamedNode(maxKey, this.children_.get(maxKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n forEachChild(index, action) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n return idx.inorderTraversal(wrappedNode => {\r\n return action(wrappedNode.name, wrappedNode.node);\r\n });\r\n }\r\n else {\r\n return this.children_.inorderTraversal(action);\r\n }\r\n }\r\n getIterator(indexDefinition) {\r\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\r\n }\r\n getIteratorFrom(startPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getIteratorFrom(startPost, key => key);\r\n }\r\n else {\r\n const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n getReverseIterator(indexDefinition) {\r\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\r\n }\r\n getReverseIteratorFrom(endPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getReverseIteratorFrom(endPost, key => {\r\n return key;\r\n });\r\n }\r\n else {\r\n const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n compareTo(other) {\r\n if (this.isEmpty()) {\r\n if (other.isEmpty()) {\r\n return 0;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (other.isLeafNode() || other.isEmpty()) {\r\n return 1;\r\n }\r\n else if (other === MAX_NODE) {\r\n return -1;\r\n }\r\n else {\r\n // Must be another node with children.\r\n return 0;\r\n }\r\n }\r\n withIndex(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX ||\r\n this.indexMap_.hasIndex(indexDefinition)) {\r\n return this;\r\n }\r\n else {\r\n const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\r\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\r\n }\r\n }\r\n isIndexed(index) {\r\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n const otherChildrenNode = other;\r\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\r\n return false;\r\n }\r\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\r\n const thisIter = this.getIterator(PRIORITY_INDEX);\r\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\r\n let thisCurrent = thisIter.getNext();\r\n let otherCurrent = otherIter.getNext();\r\n while (thisCurrent && otherCurrent) {\r\n if (thisCurrent.name !== otherCurrent.name ||\r\n !thisCurrent.node.equals(otherCurrent.node)) {\r\n return false;\r\n }\r\n thisCurrent = thisIter.getNext();\r\n otherCurrent = otherIter.getNext();\r\n }\r\n return thisCurrent === null && otherCurrent === null;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n }\r\n /**\r\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\r\n * instead.\r\n *\r\n */\r\n resolveIndex_(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX) {\r\n return null;\r\n }\r\n else {\r\n return this.indexMap_.get(indexDefinition.toString());\r\n }\r\n }\r\n}\r\nChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\r\nclass MaxNode extends ChildrenNode {\r\n constructor() {\r\n super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);\r\n }\r\n compareTo(other) {\r\n if (other === this) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n equals(other) {\r\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\r\n return other === this;\r\n }\r\n getPriority() {\r\n return this;\r\n }\r\n getImmediateChild(childName) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n isEmpty() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Marker that will sort higher than any other snapshot.\r\n */\r\nconst MAX_NODE = new MaxNode();\r\nObject.defineProperties(NamedNode, {\r\n MIN: {\r\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\r\n },\r\n MAX: {\r\n value: new NamedNode(MAX_NAME, MAX_NODE)\r\n }\r\n});\r\n/**\r\n * Reference Extensions\r\n */\r\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\r\nLeafNode.__childrenNodeConstructor = ChildrenNode;\r\nsetMaxNode$1(MAX_NODE);\r\nsetMaxNode(MAX_NODE);\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst USE_HINZE = true;\r\n/**\r\n * Constructs a snapshot node representing the passed JSON and returns it.\r\n * @param json - JSON to create a node for.\r\n * @param priority - Optional priority to use. This will be ignored if the\r\n * passed JSON contains a .priority property.\r\n */\r\nfunction nodeFromJSON(json, priority = null) {\r\n if (json === null) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n if (typeof json === 'object' && '.priority' in json) {\r\n priority = json['.priority'];\r\n }\r\n assert(priority === null ||\r\n typeof priority === 'string' ||\r\n typeof priority === 'number' ||\r\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\r\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\r\n json = json['.value'];\r\n }\r\n // Valid leaf nodes include non-objects or server-value wrapper objects\r\n if (typeof json !== 'object' || '.sv' in json) {\r\n const jsonLeaf = json;\r\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\r\n }\r\n if (!(json instanceof Array) && USE_HINZE) {\r\n const children = [];\r\n let childrenHavePriority = false;\r\n const hinzeJsonObj = json;\r\n each(hinzeJsonObj, (key, child) => {\r\n if (key.substring(0, 1) !== '.') {\r\n // Ignore metadata nodes\r\n const childNode = nodeFromJSON(child);\r\n if (!childNode.isEmpty()) {\r\n childrenHavePriority =\r\n childrenHavePriority || !childNode.getPriority().isEmpty();\r\n children.push(new NamedNode(key, childNode));\r\n }\r\n }\r\n });\r\n if (children.length === 0) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);\r\n if (childrenHavePriority) {\r\n const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));\r\n }\r\n else {\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);\r\n }\r\n }\r\n else {\r\n let node = ChildrenNode.EMPTY_NODE;\r\n each(json, (key, childData) => {\r\n if (contains(json, key)) {\r\n if (key.substring(0, 1) !== '.') {\r\n // ignore metadata nodes.\r\n const childNode = nodeFromJSON(childData);\r\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\r\n node = node.updateImmediateChild(key, childNode);\r\n }\r\n }\r\n }\r\n });\r\n return node.updatePriority(nodeFromJSON(priority));\r\n }\r\n}\r\nsetNodeFromJSON(nodeFromJSON);\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PathIndex extends Index {\r\n constructor(indexPath_) {\r\n super();\r\n this.indexPath_ = indexPath_;\r\n assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\r\n }\r\n extractChild(snap) {\r\n return snap.getChild(this.indexPath_);\r\n }\r\n isDefinedOn(node) {\r\n return !node.getChild(this.indexPath_).isEmpty();\r\n }\r\n compare(a, b) {\r\n const aChild = this.extractChild(a.node);\r\n const bChild = this.extractChild(b.node);\r\n const indexCmp = aChild.compareTo(bChild);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\r\n return new NamedNode(name, node);\r\n }\r\n maxPost() {\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\r\n return new NamedNode(MAX_NAME, node);\r\n }\r\n toString() {\r\n return pathSlice(this.indexPath_, 0).join('/');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ValueIndex extends Index {\r\n compare(a, b) {\r\n const indexCmp = a.node.compareTo(b.node);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return true;\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.equals(newNode);\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MAX;\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n return new NamedNode(name, valueNode);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.value';\r\n }\r\n}\r\nconst VALUE_INDEX = new ValueIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction changeValue(snapshotNode) {\r\n return { type: \"value\" /* ChangeType.VALUE */, snapshotNode };\r\n}\r\nfunction changeChildAdded(childName, snapshotNode) {\r\n return { type: \"child_added\" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };\r\n}\r\nfunction changeChildRemoved(childName, snapshotNode) {\r\n return { type: \"child_removed\" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };\r\n}\r\nfunction changeChildChanged(childName, snapshotNode, oldSnap) {\r\n return {\r\n type: \"child_changed\" /* ChangeType.CHILD_CHANGED */,\r\n snapshotNode,\r\n childName,\r\n oldSnap\r\n };\r\n}\r\nfunction changeChildMoved(childName, snapshotNode) {\r\n return { type: \"child_moved\" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\r\n */\r\nclass IndexedFilter {\r\n constructor(index_) {\r\n this.index_ = index_;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\r\n const oldChild = snap.getImmediateChild(key);\r\n // Check if anything actually changed.\r\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\r\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\r\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\r\n // to avoid treating these cases as \"nothing changed.\"\r\n if (oldChild.isEmpty() === newChild.isEmpty()) {\r\n // Nothing changed.\r\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\r\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\r\n return snap;\r\n }\r\n }\r\n if (optChangeAccumulator != null) {\r\n if (newChild.isEmpty()) {\r\n if (snap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));\r\n }\r\n else {\r\n assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\r\n }\r\n }\r\n else if (oldChild.isEmpty()) {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));\r\n }\r\n }\r\n if (snap.isLeafNode() && newChild.isEmpty()) {\r\n return snap;\r\n }\r\n else {\r\n // Make sure the node is indexed\r\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (optChangeAccumulator != null) {\r\n if (!oldSnap.isLeafNode()) {\r\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!newSnap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));\r\n }\r\n });\r\n }\r\n if (!newSnap.isLeafNode()) {\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (oldSnap.hasChild(key)) {\r\n const oldChild = oldSnap.getImmediateChild(key);\r\n if (!oldChild.equals(childNode)) {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));\r\n }\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));\r\n }\r\n });\r\n }\r\n }\r\n return newSnap.withIndex(this.index_);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n if (oldSnap.isEmpty()) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n else {\r\n return oldSnap.updatePriority(newPriority);\r\n }\r\n }\r\n filtersNodes() {\r\n return false;\r\n }\r\n getIndexedFilter() {\r\n return this;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\r\n */\r\nclass RangedFilter {\r\n constructor(params) {\r\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\r\n this.index_ = params.getIndex();\r\n this.startPost_ = RangedFilter.getStartPost_(params);\r\n this.endPost_ = RangedFilter.getEndPost_(params);\r\n this.startIsInclusive_ = !params.startAfterSet_;\r\n this.endIsInclusive_ = !params.endBeforeSet_;\r\n }\r\n getStartPost() {\r\n return this.startPost_;\r\n }\r\n getEndPost() {\r\n return this.endPost_;\r\n }\r\n matches(node) {\r\n const isWithinStart = this.startIsInclusive_\r\n ? this.index_.compare(this.getStartPost(), node) <= 0\r\n : this.index_.compare(this.getStartPost(), node) < 0;\r\n const isWithinEnd = this.endIsInclusive_\r\n ? this.index_.compare(node, this.getEndPost()) <= 0\r\n : this.index_.compare(node, this.getEndPost()) < 0;\r\n return isWithinStart && isWithinEnd;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (newSnap.isLeafNode()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n newSnap = ChildrenNode.EMPTY_NODE;\r\n }\r\n let filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n const self = this;\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!self.matches(new NamedNode(key, childNode))) {\r\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\r\n }\r\n });\r\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.indexedFilter_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n static getStartPost_(params) {\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\r\n }\r\n else {\r\n return params.getIndex().minPost();\r\n }\r\n }\r\n static getEndPost_(params) {\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\r\n }\r\n else {\r\n return params.getIndex().maxPost();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\r\n */\r\nclass LimitedFilter {\r\n constructor(params) {\r\n this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\r\n this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\r\n this.withinStartPost = (node) => {\r\n const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);\r\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\r\n };\r\n this.withinEndPost = (node) => {\r\n const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());\r\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\r\n };\r\n this.rangedFilter_ = new RangedFilter(params);\r\n this.index_ = params.getIndex();\r\n this.limit_ = params.getLimit();\r\n this.reverse_ = !params.isViewFromLeft();\r\n this.startIsInclusive_ = !params.startAfterSet_;\r\n this.endIsInclusive_ = !params.endBeforeSet_;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n if (snap.getImmediateChild(key).equals(newChild)) {\r\n // No change\r\n return snap;\r\n }\r\n else if (snap.numChildren() < this.limit_) {\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n else {\r\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n let filtered;\r\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n }\r\n else {\r\n if (this.limit_ * 2 < newSnap.numChildren() &&\r\n newSnap.isIndexed(this.index_)) {\r\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n // anchor to the startPost, endPost, or last element as appropriate\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\r\n }\r\n else {\r\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\r\n }\r\n let count = 0;\r\n while (iterator.hasNext() && count < this.limit_) {\r\n const next = iterator.getNext();\r\n if (!this.withinDirectionalStart(next)) {\r\n // if we have not reached the start, skip to the next element\r\n continue;\r\n }\r\n else if (!this.withinDirectionalEnd(next)) {\r\n // if we have reached the end, stop adding elements\r\n break;\r\n }\r\n else {\r\n filtered = filtered.updateImmediateChild(next.name, next.node);\r\n count++;\r\n }\r\n }\r\n }\r\n else {\r\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\r\n filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = filtered.getReverseIterator(this.index_);\r\n }\r\n else {\r\n iterator = filtered.getIterator(this.index_);\r\n }\r\n let count = 0;\r\n while (iterator.hasNext()) {\r\n const next = iterator.getNext();\r\n const inRange = count < this.limit_ &&\r\n this.withinDirectionalStart(next) &&\r\n this.withinDirectionalEnd(next);\r\n if (inRange) {\r\n count++;\r\n }\r\n else {\r\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n }\r\n }\r\n }\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.rangedFilter_.getIndexedFilter();\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {\r\n // TODO: rename all cache stuff etc to general snap terminology\r\n let cmp;\r\n if (this.reverse_) {\r\n const indexCmp = this.index_.getCompare();\r\n cmp = (a, b) => indexCmp(b, a);\r\n }\r\n else {\r\n cmp = this.index_.getCompare();\r\n }\r\n const oldEventCache = snap;\r\n assert(oldEventCache.numChildren() === this.limit_, '');\r\n const newChildNamedNode = new NamedNode(childKey, childSnap);\r\n const windowBoundary = this.reverse_\r\n ? oldEventCache.getFirstChild(this.index_)\r\n : oldEventCache.getLastChild(this.index_);\r\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\r\n if (oldEventCache.hasChild(childKey)) {\r\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\r\n let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\r\n while (nextChild != null &&\r\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {\r\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\r\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\r\n // the limited filter...\r\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\r\n }\r\n const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\r\n const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\r\n if (remainsInWindow) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));\r\n }\r\n return oldEventCache.updateImmediateChild(childKey, childSnap);\r\n }\r\n else {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));\r\n }\r\n const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);\r\n const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\r\n if (nextChildInRange) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));\r\n }\r\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\r\n }\r\n else {\r\n return newEventCache;\r\n }\r\n }\r\n }\r\n else if (childSnap.isEmpty()) {\r\n // we're deleting a node, but it was not in the window, so ignore it\r\n return snap;\r\n }\r\n else if (inRange) {\r\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));\r\n changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));\r\n }\r\n return oldEventCache\r\n .updateImmediateChild(childKey, childSnap)\r\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\r\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\r\n * user-facing API level, so it is not done here.\r\n *\r\n * @internal\r\n */\r\nclass QueryParams {\r\n constructor() {\r\n this.limitSet_ = false;\r\n this.startSet_ = false;\r\n this.startNameSet_ = false;\r\n this.startAfterSet_ = false; // can only be true if startSet_ is true\r\n this.endSet_ = false;\r\n this.endNameSet_ = false;\r\n this.endBeforeSet_ = false; // can only be true if endSet_ is true\r\n this.limit_ = 0;\r\n this.viewFrom_ = '';\r\n this.indexStartValue_ = null;\r\n this.indexStartName_ = '';\r\n this.indexEndValue_ = null;\r\n this.indexEndName_ = '';\r\n this.index_ = PRIORITY_INDEX;\r\n }\r\n hasStart() {\r\n return this.startSet_;\r\n }\r\n /**\r\n * @returns True if it would return from left.\r\n */\r\n isViewFromLeft() {\r\n if (this.viewFrom_ === '') {\r\n // limit(), rather than limitToFirst or limitToLast was called.\r\n // This means that only one of startSet_ and endSet_ is true. Use them\r\n // to calculate which side of the view to anchor to. If neither is set,\r\n // anchor to the end.\r\n return this.startSet_;\r\n }\r\n else {\r\n return this.viewFrom_ === \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\r\n }\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true\r\n */\r\n getIndexStartValue() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n return this.indexStartValue_;\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true.\r\n * Returns the starting key name for the range defined by these query parameters\r\n */\r\n getIndexStartName() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n if (this.startNameSet_) {\r\n return this.indexStartName_;\r\n }\r\n else {\r\n return MIN_NAME;\r\n }\r\n }\r\n hasEnd() {\r\n return this.endSet_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n */\r\n getIndexEndValue() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n return this.indexEndValue_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n * Returns the end key name for the range defined by these query parameters\r\n */\r\n getIndexEndName() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n if (this.endNameSet_) {\r\n return this.indexEndName_;\r\n }\r\n else {\r\n return MAX_NAME;\r\n }\r\n }\r\n hasLimit() {\r\n return this.limitSet_;\r\n }\r\n /**\r\n * @returns True if a limit has been set and it has been explicitly anchored\r\n */\r\n hasAnchoredLimit() {\r\n return this.limitSet_ && this.viewFrom_ !== '';\r\n }\r\n /**\r\n * Only valid to call if hasLimit() returns true\r\n */\r\n getLimit() {\r\n assert(this.limitSet_, 'Only valid if limit has been set');\r\n return this.limit_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n loadsAllData() {\r\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\r\n }\r\n isDefault() {\r\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\r\n }\r\n copy() {\r\n const copy = new QueryParams();\r\n copy.limitSet_ = this.limitSet_;\r\n copy.limit_ = this.limit_;\r\n copy.startSet_ = this.startSet_;\r\n copy.startAfterSet_ = this.startAfterSet_;\r\n copy.indexStartValue_ = this.indexStartValue_;\r\n copy.startNameSet_ = this.startNameSet_;\r\n copy.indexStartName_ = this.indexStartName_;\r\n copy.endSet_ = this.endSet_;\r\n copy.endBeforeSet_ = this.endBeforeSet_;\r\n copy.indexEndValue_ = this.indexEndValue_;\r\n copy.endNameSet_ = this.endNameSet_;\r\n copy.indexEndName_ = this.indexEndName_;\r\n copy.index_ = this.index_;\r\n copy.viewFrom_ = this.viewFrom_;\r\n return copy;\r\n }\r\n}\r\nfunction queryParamsGetNodeFilter(queryParams) {\r\n if (queryParams.loadsAllData()) {\r\n return new IndexedFilter(queryParams.getIndex());\r\n }\r\n else if (queryParams.hasLimit()) {\r\n return new LimitedFilter(queryParams);\r\n }\r\n else {\r\n return new RangedFilter(queryParams);\r\n }\r\n}\r\nfunction queryParamsLimitToFirst(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\r\n return newParams;\r\n}\r\nfunction queryParamsLimitToLast(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\r\n return newParams;\r\n}\r\nfunction queryParamsStartAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.startSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexStartValue_ = indexValue;\r\n if (key != null) {\r\n newParams.startNameSet_ = true;\r\n newParams.indexStartName_ = key;\r\n }\r\n else {\r\n newParams.startNameSet_ = false;\r\n newParams.indexStartName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsStartAfter(queryParams, indexValue, key) {\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX || !!key) {\r\n params = queryParamsStartAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\r\n }\r\n params.startAfterSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsEndAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.endSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexEndValue_ = indexValue;\r\n if (key !== undefined) {\r\n newParams.endNameSet_ = true;\r\n newParams.indexEndName_ = key;\r\n }\r\n else {\r\n newParams.endNameSet_ = false;\r\n newParams.indexEndName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsEndBefore(queryParams, indexValue, key) {\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX || !!key) {\r\n params = queryParamsEndAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\r\n }\r\n params.endBeforeSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsOrderBy(queryParams, index) {\r\n const newParams = queryParams.copy();\r\n newParams.index_ = index;\r\n return newParams;\r\n}\r\n/**\r\n * Returns a set of REST query string parameters representing this query.\r\n *\r\n * @returns query string parameters\r\n */\r\nfunction queryParamsToRestQueryStringParameters(queryParams) {\r\n const qs = {};\r\n if (queryParams.isDefault()) {\r\n return qs;\r\n }\r\n let orderBy;\r\n if (queryParams.index_ === PRIORITY_INDEX) {\r\n orderBy = \"$priority\" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;\r\n }\r\n else if (queryParams.index_ === VALUE_INDEX) {\r\n orderBy = \"$value\" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;\r\n }\r\n else if (queryParams.index_ === KEY_INDEX) {\r\n orderBy = \"$key\" /* REST_QUERY_CONSTANTS.KEY_INDEX */;\r\n }\r\n else {\r\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\r\n orderBy = queryParams.index_.toString();\r\n }\r\n qs[\"orderBy\" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);\r\n if (queryParams.startSet_) {\r\n const startParam = queryParams.startAfterSet_\r\n ? \"startAfter\" /* REST_QUERY_CONSTANTS.START_AFTER */\r\n : \"startAt\" /* REST_QUERY_CONSTANTS.START_AT */;\r\n qs[startParam] = stringify(queryParams.indexStartValue_);\r\n if (queryParams.startNameSet_) {\r\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\r\n }\r\n }\r\n if (queryParams.endSet_) {\r\n const endParam = queryParams.endBeforeSet_\r\n ? \"endBefore\" /* REST_QUERY_CONSTANTS.END_BEFORE */\r\n : \"endAt\" /* REST_QUERY_CONSTANTS.END_AT */;\r\n qs[endParam] = stringify(queryParams.indexEndValue_);\r\n if (queryParams.endNameSet_) {\r\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\r\n }\r\n }\r\n if (queryParams.limitSet_) {\r\n if (queryParams.isViewFromLeft()) {\r\n qs[\"limitToFirst\" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;\r\n }\r\n else {\r\n qs[\"limitToLast\" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;\r\n }\r\n }\r\n return qs;\r\n}\r\nfunction queryParamsGetQueryObject(queryParams) {\r\n const obj = {};\r\n if (queryParams.startSet_) {\r\n obj[\"sp\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =\r\n queryParams.indexStartValue_;\r\n if (queryParams.startNameSet_) {\r\n obj[\"sn\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =\r\n queryParams.indexStartName_;\r\n }\r\n obj[\"sin\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =\r\n !queryParams.startAfterSet_;\r\n }\r\n if (queryParams.endSet_) {\r\n obj[\"ep\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;\r\n if (queryParams.endNameSet_) {\r\n obj[\"en\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;\r\n }\r\n obj[\"ein\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =\r\n !queryParams.endBeforeSet_;\r\n }\r\n if (queryParams.limitSet_) {\r\n obj[\"l\" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;\r\n let viewFrom = queryParams.viewFrom_;\r\n if (viewFrom === '') {\r\n if (queryParams.isViewFromLeft()) {\r\n viewFrom = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\r\n }\r\n else {\r\n viewFrom = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\r\n }\r\n }\r\n obj[\"vf\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;\r\n }\r\n // For now, priority index is the default, so we only specify if it's some other index\r\n if (queryParams.index_ !== PRIORITY_INDEX) {\r\n obj[\"i\" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();\r\n }\r\n return obj;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of ServerActions that communicates with the server via REST requests.\r\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\r\n * persistent connection (using WebSockets or long-polling)\r\n */\r\nclass ReadonlyRestClient extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n /** @private {function(...[*])} */\r\n this.log_ = logWrapper('p:rest:');\r\n /**\r\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\r\n * that's been removed. :-/\r\n */\r\n this.listens_ = {};\r\n }\r\n reportStats(stats) {\r\n throw new Error('Method not implemented.');\r\n }\r\n static getListenId_(query, tag) {\r\n if (tag !== undefined) {\r\n return 'tag$' + tag;\r\n }\r\n else {\r\n assert(query._queryParams.isDefault(), \"should have a tag if it's not a default query.\");\r\n return query._path.toString();\r\n }\r\n }\r\n /** @inheritDoc */\r\n listen(query, currentHashFn, tag, onComplete) {\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\r\n // Mark this listener so we can tell if it's removed.\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n const thisListen = {};\r\n this.listens_[listenId] = thisListen;\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\r\n }\r\n if (safeGet(this.listens_, listenId) === thisListen) {\r\n let status;\r\n if (!error) {\r\n status = 'ok';\r\n }\r\n else if (error === 401) {\r\n status = 'permission_denied';\r\n }\r\n else {\r\n status = 'rest_error:' + error;\r\n }\r\n onComplete(status, null);\r\n }\r\n });\r\n }\r\n /** @inheritDoc */\r\n unlisten(query, tag) {\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n delete this.listens_[listenId];\r\n }\r\n get(query) {\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n const pathString = query._path.toString();\r\n const deferred = new Deferred();\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, \r\n /*isMerge=*/ false, \r\n /*tag=*/ null);\r\n deferred.resolve(data);\r\n }\r\n else {\r\n deferred.reject(new Error(data));\r\n }\r\n });\r\n return deferred.promise;\r\n }\r\n /** @inheritDoc */\r\n refreshAuthToken(token) {\r\n // no-op since we just always call getToken.\r\n }\r\n /**\r\n * Performs a REST request to the given path, with the provided query string parameters,\r\n * and any auth credentials we have.\r\n */\r\n restRequest_(pathString, queryStringParameters = {}, callback) {\r\n queryStringParameters['format'] = 'export';\r\n return Promise.all([\r\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\r\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\r\n ]).then(([authToken, appCheckToken]) => {\r\n if (authToken && authToken.accessToken) {\r\n queryStringParameters['auth'] = authToken.accessToken;\r\n }\r\n if (appCheckToken && appCheckToken.token) {\r\n queryStringParameters['ac'] = appCheckToken.token;\r\n }\r\n const url = (this.repoInfo_.secure ? 'https://' : 'http://') +\r\n this.repoInfo_.host +\r\n pathString +\r\n '?' +\r\n 'ns=' +\r\n this.repoInfo_.namespace +\r\n querystring(queryStringParameters);\r\n this.log_('Sending REST request for ' + url);\r\n const xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange = () => {\r\n if (callback && xhr.readyState === 4) {\r\n this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\r\n let res = null;\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n try {\r\n res = jsonEval(xhr.responseText);\r\n }\r\n catch (e) {\r\n warn('Failed to parse JSON response for ' +\r\n url +\r\n ': ' +\r\n xhr.responseText);\r\n }\r\n callback(null, res);\r\n }\r\n else {\r\n // 401 and 404 are expected.\r\n if (xhr.status !== 401 && xhr.status !== 404) {\r\n warn('Got unsuccessful REST response for ' +\r\n url +\r\n ' Status: ' +\r\n xhr.status);\r\n }\r\n callback(xhr.status);\r\n }\r\n callback = null;\r\n }\r\n };\r\n xhr.open('GET', url, /*asynchronous=*/ true);\r\n xhr.send();\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\r\n */\r\nclass SnapshotHolder {\r\n constructor() {\r\n this.rootNode_ = ChildrenNode.EMPTY_NODE;\r\n }\r\n getNode(path) {\r\n return this.rootNode_.getChild(path);\r\n }\r\n updateSnapshot(path, newSnapshotNode) {\r\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newSparseSnapshotTree() {\r\n return {\r\n value: null,\r\n children: new Map()\r\n };\r\n}\r\n/**\r\n * Stores the given node at the specified path. If there is already a node\r\n * at a shallower path, it merges the new data into that snapshot node.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @param data - The new data, or null.\r\n */\r\nfunction sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = data;\r\n sparseSnapshotTree.children.clear();\r\n }\r\n else if (sparseSnapshotTree.value !== null) {\r\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n if (!sparseSnapshotTree.children.has(childKey)) {\r\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\r\n }\r\n const child = sparseSnapshotTree.children.get(childKey);\r\n path = pathPopFront(path);\r\n sparseSnapshotTreeRemember(child, path, data);\r\n }\r\n}\r\n/**\r\n * Purge the data at path from the cache.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @returns True if this node should now be removed.\r\n */\r\nfunction sparseSnapshotTreeForget(sparseSnapshotTree, path) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = null;\r\n sparseSnapshotTree.children.clear();\r\n return true;\r\n }\r\n else {\r\n if (sparseSnapshotTree.value !== null) {\r\n if (sparseSnapshotTree.value.isLeafNode()) {\r\n // We're trying to forget a node that doesn't exist\r\n return false;\r\n }\r\n else {\r\n const value = sparseSnapshotTree.value;\r\n sparseSnapshotTree.value = null;\r\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\r\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\r\n });\r\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\r\n }\r\n }\r\n else if (sparseSnapshotTree.children.size > 0) {\r\n const childKey = pathGetFront(path);\r\n path = pathPopFront(path);\r\n if (sparseSnapshotTree.children.has(childKey)) {\r\n const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);\r\n if (safeToRemove) {\r\n sparseSnapshotTree.children.delete(childKey);\r\n }\r\n }\r\n return sparseSnapshotTree.children.size === 0;\r\n }\r\n else {\r\n return true;\r\n }\r\n }\r\n}\r\n/**\r\n * Recursively iterates through all of the stored tree and calls the\r\n * callback on each one.\r\n *\r\n * @param prefixPath - Path to look up node for.\r\n * @param func - The function to invoke for each tree.\r\n */\r\nfunction sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {\r\n if (sparseSnapshotTree.value !== null) {\r\n func(prefixPath, sparseSnapshotTree.value);\r\n }\r\n else {\r\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\r\n const path = new Path(prefixPath.toString() + '/' + key);\r\n sparseSnapshotTreeForEachTree(tree, path, func);\r\n });\r\n }\r\n}\r\n/**\r\n * Iterates through each immediate child and triggers the callback.\r\n * Only seems to be used in tests.\r\n *\r\n * @param func - The function to invoke for each child.\r\n */\r\nfunction sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {\r\n sparseSnapshotTree.children.forEach((tree, key) => {\r\n func(key, tree);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns the delta from the previous call to get stats.\r\n *\r\n * @param collection_ - The collection to \"listen\" to.\r\n */\r\nclass StatsListener {\r\n constructor(collection_) {\r\n this.collection_ = collection_;\r\n this.last_ = null;\r\n }\r\n get() {\r\n const newStats = this.collection_.get();\r\n const delta = Object.assign({}, newStats);\r\n if (this.last_) {\r\n each(this.last_, (stat, value) => {\r\n delta[stat] = delta[stat] - value;\r\n });\r\n }\r\n this.last_ = newStats;\r\n return delta;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\r\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\r\n// seconds to try to ensure the Firebase connection is established / settled.\r\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\r\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\r\n// We'll continue to report stats on average every 5 minutes.\r\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\r\nclass StatsReporter {\r\n constructor(collection, server_) {\r\n this.server_ = server_;\r\n this.statsToReport_ = {};\r\n this.statsListener_ = new StatsListener(collection);\r\n const timeout = FIRST_STATS_MIN_TIME +\r\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\r\n }\r\n reportStats_() {\r\n const stats = this.statsListener_.get();\r\n const reportedStats = {};\r\n let haveStatsToReport = false;\r\n each(stats, (stat, value) => {\r\n if (value > 0 && contains(this.statsToReport_, stat)) {\r\n reportedStats[stat] = value;\r\n haveStatsToReport = true;\r\n }\r\n });\r\n if (haveStatsToReport) {\r\n this.server_.reportStats(reportedStats);\r\n }\r\n // queue our next run.\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n *\r\n * @enum\r\n */\r\nvar OperationType;\r\n(function (OperationType) {\r\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\r\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\r\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\r\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\r\n})(OperationType || (OperationType = {}));\r\nfunction newOperationSourceUser() {\r\n return {\r\n fromUser: true,\r\n fromServer: false,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServer() {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServerTaggedQuery(queryId) {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId,\r\n tagged: true\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AckUserWrite {\r\n /**\r\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\r\n */\r\n constructor(\r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ affectedTree, \r\n /** @inheritDoc */ revert) {\r\n this.path = path;\r\n this.affectedTree = affectedTree;\r\n this.revert = revert;\r\n /** @inheritDoc */\r\n this.type = OperationType.ACK_USER_WRITE;\r\n /** @inheritDoc */\r\n this.source = newOperationSourceUser();\r\n }\r\n operationForChild(childName) {\r\n if (!pathIsEmpty(this.path)) {\r\n assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');\r\n return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);\r\n }\r\n else if (this.affectedTree.value != null) {\r\n assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\r\n // All child locations are affected as well; just return same operation.\r\n return this;\r\n }\r\n else {\r\n const childTree = this.affectedTree.subtree(new Path(childName));\r\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ListenComplete {\r\n constructor(source, path) {\r\n this.source = source;\r\n this.path = path;\r\n /** @inheritDoc */\r\n this.type = OperationType.LISTEN_COMPLETE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new ListenComplete(this.source, newEmptyPath());\r\n }\r\n else {\r\n return new ListenComplete(this.source, pathPopFront(this.path));\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Overwrite {\r\n constructor(source, path, snap) {\r\n this.source = source;\r\n this.path = path;\r\n this.snap = snap;\r\n /** @inheritDoc */\r\n this.type = OperationType.OVERWRITE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));\r\n }\r\n else {\r\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Merge {\r\n constructor(\r\n /** @inheritDoc */ source, \r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ children) {\r\n this.source = source;\r\n this.path = path;\r\n this.children = children;\r\n /** @inheritDoc */\r\n this.type = OperationType.MERGE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n const childTree = this.children.subtree(new Path(childName));\r\n if (childTree.isEmpty()) {\r\n // This child is unaffected\r\n return null;\r\n }\r\n else if (childTree.value) {\r\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\r\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\r\n }\r\n else {\r\n // This is a merge at a deeper level\r\n return new Merge(this.source, newEmptyPath(), childTree);\r\n }\r\n }\r\n else {\r\n assert(pathGetFront(this.path) === childName, \"Can't get a merge for a child not on the path of the operation\");\r\n return new Merge(this.source, pathPopFront(this.path), this.children);\r\n }\r\n }\r\n toString() {\r\n return ('Operation(' +\r\n this.path +\r\n ': ' +\r\n this.source.toString() +\r\n ' merge: ' +\r\n this.children.toString() +\r\n ')');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\r\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\r\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\r\n * whether a node potentially had children removed due to a filter.\r\n */\r\nclass CacheNode {\r\n constructor(node_, fullyInitialized_, filtered_) {\r\n this.node_ = node_;\r\n this.fullyInitialized_ = fullyInitialized_;\r\n this.filtered_ = filtered_;\r\n }\r\n /**\r\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\r\n */\r\n isFullyInitialized() {\r\n return this.fullyInitialized_;\r\n }\r\n /**\r\n * Returns whether this node is potentially missing children due to a filter applied to the node\r\n */\r\n isFiltered() {\r\n return this.filtered_;\r\n }\r\n isCompleteForPath(path) {\r\n if (pathIsEmpty(path)) {\r\n return this.isFullyInitialized() && !this.filtered_;\r\n }\r\n const childKey = pathGetFront(path);\r\n return this.isCompleteForChild(childKey);\r\n }\r\n isCompleteForChild(key) {\r\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\r\n }\r\n getNode() {\r\n return this.node_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\r\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\r\n * for details.\r\n *\r\n */\r\nclass EventGenerator {\r\n constructor(query_) {\r\n this.query_ = query_;\r\n this.index_ = this.query_._queryParams.getIndex();\r\n }\r\n}\r\n/**\r\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\r\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\r\n *\r\n * Notes:\r\n * - child_moved events will be synthesized at this time for any child_changed events that affect\r\n * our index.\r\n * - prevName will be calculated based on the index ordering.\r\n */\r\nfunction eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {\r\n const events = [];\r\n const moves = [];\r\n changes.forEach(change => {\r\n if (change.type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\r\n eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\r\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\r\n }\r\n });\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_removed\" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_added\" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_moved\" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_changed\" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"value\" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);\r\n return events;\r\n}\r\n/**\r\n * Given changes of a single change type, generate the corresponding events.\r\n */\r\nfunction eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {\r\n const filteredChanges = changes.filter(change => change.type === eventType);\r\n filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));\r\n filteredChanges.forEach(change => {\r\n const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);\r\n registrations.forEach(registration => {\r\n if (registration.respondsTo(change.type)) {\r\n events.push(registration.createEvent(materializedChange, eventGenerator.query_));\r\n }\r\n });\r\n });\r\n}\r\nfunction eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {\r\n if (change.type === 'value' || change.type === 'child_removed') {\r\n return change;\r\n }\r\n else {\r\n change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);\r\n return change;\r\n }\r\n}\r\nfunction eventGeneratorCompareChanges(eventGenerator, a, b) {\r\n if (a.childName == null || b.childName == null) {\r\n throw assertionError('Should only compare child_ events.');\r\n }\r\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\r\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\r\n return eventGenerator.index_.compare(aWrapped, bWrapped);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newViewCache(eventCache, serverCache) {\r\n return { eventCache, serverCache };\r\n}\r\nfunction viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {\r\n return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);\r\n}\r\nfunction viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {\r\n return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));\r\n}\r\nfunction viewCacheGetCompleteEventSnap(viewCache) {\r\n return viewCache.eventCache.isFullyInitialized()\r\n ? viewCache.eventCache.getNode()\r\n : null;\r\n}\r\nfunction viewCacheGetCompleteServerSnap(viewCache) {\r\n return viewCache.serverCache.isFullyInitialized()\r\n ? viewCache.serverCache.getNode()\r\n : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet emptyChildrenSingleton;\r\n/**\r\n * Singleton empty children collection.\r\n *\r\n */\r\nconst EmptyChildren = () => {\r\n if (!emptyChildrenSingleton) {\r\n emptyChildrenSingleton = new SortedMap(stringCompare);\r\n }\r\n return emptyChildrenSingleton;\r\n};\r\n/**\r\n * A tree with immutable elements.\r\n */\r\nclass ImmutableTree {\r\n constructor(value, children = EmptyChildren()) {\r\n this.value = value;\r\n this.children = children;\r\n }\r\n static fromObject(obj) {\r\n let tree = new ImmutableTree(null);\r\n each(obj, (childPath, childSnap) => {\r\n tree = tree.set(new Path(childPath), childSnap);\r\n });\r\n return tree;\r\n }\r\n /**\r\n * True if the value is empty and there are no children\r\n */\r\n isEmpty() {\r\n return this.value === null && this.children.isEmpty();\r\n }\r\n /**\r\n * Given a path and predicate, return the first node and the path to that node\r\n * where the predicate returns true.\r\n *\r\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\r\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\r\n *\r\n * @param relativePath - The remainder of the path\r\n * @param predicate - The predicate to satisfy to return a node\r\n */\r\n findRootMostMatchingPathAndValue(relativePath, predicate) {\r\n if (this.value != null && predicate(this.value)) {\r\n return { path: newEmptyPath(), value: this.value };\r\n }\r\n else {\r\n if (pathIsEmpty(relativePath)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child !== null) {\r\n const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);\r\n if (childExistingPathAndValue != null) {\r\n const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);\r\n return { path: fullPath, value: childExistingPathAndValue.value };\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n /**\r\n * Find, if it exists, the shortest subpath of the given path that points a defined\r\n * value in the tree\r\n */\r\n findRootMostValueAndPath(relativePath) {\r\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\r\n }\r\n /**\r\n * @returns The subtree at the given path\r\n */\r\n subtree(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const childTree = this.children.get(front);\r\n if (childTree !== null) {\r\n return childTree.subtree(pathPopFront(relativePath));\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Sets a value at the specified path.\r\n *\r\n * @param relativePath - Path to set value at.\r\n * @param toSet - Value to set.\r\n * @returns Resulting tree.\r\n */\r\n set(relativePath, toSet) {\r\n if (pathIsEmpty(relativePath)) {\r\n return new ImmutableTree(toSet, this.children);\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.set(pathPopFront(relativePath), toSet);\r\n const newChildren = this.children.insert(front, newChild);\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Removes the value at the specified path.\r\n *\r\n * @param relativePath - Path to value to remove.\r\n * @returns Resulting tree.\r\n */\r\n remove(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n if (this.children.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(null, this.children);\r\n }\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n const newChild = child.remove(pathPopFront(relativePath));\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n if (this.value === null && newChildren.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n else {\r\n return this;\r\n }\r\n }\r\n }\r\n /**\r\n * Gets a value from the tree.\r\n *\r\n * @param relativePath - Path to get value for.\r\n * @returns Value at path, or null.\r\n */\r\n get(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this.value;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n return child.get(pathPopFront(relativePath));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n /**\r\n * Replace the subtree at the specified path with the given new tree.\r\n *\r\n * @param relativePath - Path to replace subtree for.\r\n * @param newTree - New tree.\r\n * @returns Resulting tree.\r\n */\r\n setTree(relativePath, newTree) {\r\n if (pathIsEmpty(relativePath)) {\r\n return newTree;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Performs a depth first fold on this tree. Transforms a tree into a single\r\n * value, given a function that operates on the path to a node, an optional\r\n * current value, and a map of child names to folded subtrees\r\n */\r\n fold(fn) {\r\n return this.fold_(newEmptyPath(), fn);\r\n }\r\n /**\r\n * Recursive helper for public-facing fold() method\r\n */\r\n fold_(pathSoFar, fn) {\r\n const accum = {};\r\n this.children.inorderTraversal((childKey, childTree) => {\r\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\r\n });\r\n return fn(pathSoFar, this.value, accum);\r\n }\r\n /**\r\n * Find the first matching value on the given path. Return the result of applying f to it.\r\n */\r\n findOnPath(path, f) {\r\n return this.findOnPath_(path, newEmptyPath(), f);\r\n }\r\n findOnPath_(pathToFollow, pathSoFar, f) {\r\n const result = this.value ? f(pathSoFar, this.value) : false;\r\n if (result) {\r\n return result;\r\n }\r\n else {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n foreachOnPath(path, f) {\r\n return this.foreachOnPath_(path, newEmptyPath(), f);\r\n }\r\n foreachOnPath_(pathToFollow, currentRelativePath, f) {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return this;\r\n }\r\n else {\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Calls the given function for each node in the tree that has a value.\r\n *\r\n * @param f - A function to be called with the path from the root of the tree to\r\n * a node, and the value at that node. Called in depth-first order.\r\n */\r\n foreach(f) {\r\n this.foreach_(newEmptyPath(), f);\r\n }\r\n foreach_(currentRelativePath, f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\r\n });\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n }\r\n foreachChild(f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value) {\r\n f(childName, childTree.value);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\r\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\r\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\r\n * to reflect the write added.\r\n */\r\nclass CompoundWrite {\r\n constructor(writeTree_) {\r\n this.writeTree_ = writeTree_;\r\n }\r\n static empty() {\r\n return new CompoundWrite(new ImmutableTree(null));\r\n }\r\n}\r\nfunction compoundWriteAddWrite(compoundWrite, path, node) {\r\n if (pathIsEmpty(path)) {\r\n return new CompoundWrite(new ImmutableTree(node));\r\n }\r\n else {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n const rootMostPath = rootmost.path;\r\n let value = rootmost.value;\r\n const relativePath = newRelativePath(rootMostPath, path);\r\n value = value.updateChild(relativePath, node);\r\n return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));\r\n }\r\n else {\r\n const subtree = new ImmutableTree(node);\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n }\r\n}\r\nfunction compoundWriteAddWrites(compoundWrite, path, updates) {\r\n let newWrite = compoundWrite;\r\n each(updates, (childKey, node) => {\r\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\r\n });\r\n return newWrite;\r\n}\r\n/**\r\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\r\n * location, which must be removed by calling this method with that path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to remove.\r\n * @param path - The path at which a write and all deeper writes should be removed\r\n * @returns The new CompoundWrite with the removed path\r\n */\r\nfunction compoundWriteRemoveWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return CompoundWrite.empty();\r\n }\r\n else {\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n}\r\n/**\r\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\r\n * considered \"complete\".\r\n *\r\n * @param compoundWrite - The CompoundWrite to check.\r\n * @param path - The path to check for\r\n * @returns Whether there is a complete write at that path\r\n */\r\nfunction compoundWriteHasCompleteWrite(compoundWrite, path) {\r\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\r\n}\r\n/**\r\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\r\n * writes from deeper paths, but will return child nodes from a more shallow path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get the node from.\r\n * @param path - The path to get a complete write\r\n * @returns The node if complete at that path, or null otherwise.\r\n */\r\nfunction compoundWriteGetCompleteNode(compoundWrite, path) {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n return compoundWrite.writeTree_\r\n .get(rootmost.path)\r\n .getChild(newRelativePath(rootmost.path, path));\r\n }\r\n else {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Returns all children that are guaranteed to be a complete overwrite.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get children from.\r\n * @returns A list of all complete children.\r\n */\r\nfunction compoundWriteGetCompleteChildren(compoundWrite) {\r\n const children = [];\r\n const node = compoundWrite.writeTree_.value;\r\n if (node != null) {\r\n // If it's a leaf node, it has no children; so nothing to do.\r\n if (!node.isLeafNode()) {\r\n node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n children.push(new NamedNode(childName, childNode));\r\n });\r\n }\r\n }\r\n else {\r\n compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value != null) {\r\n children.push(new NamedNode(childName, childTree.value));\r\n }\r\n });\r\n }\r\n return children;\r\n}\r\nfunction compoundWriteChildCompoundWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return compoundWrite;\r\n }\r\n else {\r\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\r\n if (shadowingNode != null) {\r\n return new CompoundWrite(new ImmutableTree(shadowingNode));\r\n }\r\n else {\r\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\r\n * @returns Whether this CompoundWrite is empty\r\n */\r\nfunction compoundWriteIsEmpty(compoundWrite) {\r\n return compoundWrite.writeTree_.isEmpty();\r\n}\r\n/**\r\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\r\n * node\r\n * @param node - The node to apply this CompoundWrite to\r\n * @returns The node with all writes applied\r\n */\r\nfunction compoundWriteApply(compoundWrite, node) {\r\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\r\n}\r\nfunction applySubtreeWrite(relativePath, writeTree, node) {\r\n if (writeTree.value != null) {\r\n // Since there a write is always a leaf, we're done here\r\n return node.updateChild(relativePath, writeTree.value);\r\n }\r\n else {\r\n let priorityWrite = null;\r\n writeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (childKey === '.priority') {\r\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\r\n // to apply priorities to empty nodes that are later filled\r\n assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\r\n priorityWrite = childTree.value;\r\n }\r\n else {\r\n node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);\r\n }\r\n });\r\n // If there was a priority write, we only apply it if the node is not empty\r\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\r\n node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);\r\n }\r\n return node;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\r\n *\r\n */\r\nfunction writeTreeChildWrites(writeTree, path) {\r\n return newWriteTreeRef(path, writeTree);\r\n}\r\n/**\r\n * Record a new overwrite from user code.\r\n *\r\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\r\n */\r\nfunction writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');\r\n if (visible === undefined) {\r\n visible = true;\r\n }\r\n writeTree.allWrites.push({\r\n path,\r\n snap,\r\n writeId,\r\n visible\r\n });\r\n if (visible) {\r\n writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);\r\n }\r\n writeTree.lastWriteId = writeId;\r\n}\r\n/**\r\n * Record a new merge from user code.\r\n */\r\nfunction writeTreeAddMerge(writeTree, path, changedChildren, writeId) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');\r\n writeTree.allWrites.push({\r\n path,\r\n children: changedChildren,\r\n writeId,\r\n visible: true\r\n });\r\n writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);\r\n writeTree.lastWriteId = writeId;\r\n}\r\nfunction writeTreeGetWrite(writeTree, writeId) {\r\n for (let i = 0; i < writeTree.allWrites.length; i++) {\r\n const record = writeTree.allWrites[i];\r\n if (record.writeId === writeId) {\r\n return record;\r\n }\r\n }\r\n return null;\r\n}\r\n/**\r\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\r\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\r\n *\r\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\r\n * events as a result).\r\n */\r\nfunction writeTreeRemoveWrite(writeTree, writeId) {\r\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\r\n // out of order.\r\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\r\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\r\n const idx = writeTree.allWrites.findIndex(s => {\r\n return s.writeId === writeId;\r\n });\r\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\r\n const writeToRemove = writeTree.allWrites[idx];\r\n writeTree.allWrites.splice(idx, 1);\r\n let removedWriteWasVisible = writeToRemove.visible;\r\n let removedWriteOverlapsWithOtherWrites = false;\r\n let i = writeTree.allWrites.length - 1;\r\n while (removedWriteWasVisible && i >= 0) {\r\n const currentWrite = writeTree.allWrites[i];\r\n if (currentWrite.visible) {\r\n if (i >= idx &&\r\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {\r\n // The removed write was completely shadowed by a subsequent write.\r\n removedWriteWasVisible = false;\r\n }\r\n else if (pathContains(writeToRemove.path, currentWrite.path)) {\r\n // Either we're covering some writes or they're covering part of us (depending on which came first).\r\n removedWriteOverlapsWithOtherWrites = true;\r\n }\r\n }\r\n i--;\r\n }\r\n if (!removedWriteWasVisible) {\r\n return false;\r\n }\r\n else if (removedWriteOverlapsWithOtherWrites) {\r\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\r\n writeTreeResetTree_(writeTree);\r\n return true;\r\n }\r\n else {\r\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\r\n if (writeToRemove.snap) {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);\r\n }\r\n else {\r\n const children = writeToRemove.children;\r\n each(children, (childName) => {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));\r\n });\r\n }\r\n return true;\r\n }\r\n}\r\nfunction writeTreeRecordContainsPath_(writeRecord, path) {\r\n if (writeRecord.snap) {\r\n return pathContains(writeRecord.path, path);\r\n }\r\n else {\r\n for (const childName in writeRecord.children) {\r\n if (writeRecord.children.hasOwnProperty(childName) &&\r\n pathContains(pathChild(writeRecord.path, childName), path)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n}\r\n/**\r\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\r\n */\r\nfunction writeTreeResetTree_(writeTree) {\r\n writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());\r\n if (writeTree.allWrites.length > 0) {\r\n writeTree.lastWriteId =\r\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\r\n }\r\n else {\r\n writeTree.lastWriteId = -1;\r\n }\r\n}\r\n/**\r\n * The default filter used when constructing the tree. Keep everything that's visible.\r\n */\r\nfunction writeTreeDefaultFilter_(write) {\r\n return write.visible;\r\n}\r\n/**\r\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\r\n * event data at that path.\r\n */\r\nfunction writeTreeLayerTree_(writes, filter, treeRoot) {\r\n let compoundWrite = CompoundWrite.empty();\r\n for (let i = 0; i < writes.length; ++i) {\r\n const write = writes[i];\r\n // Theory, a later set will either:\r\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\r\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\r\n if (filter(write)) {\r\n const writePath = write.path;\r\n let relativePath;\r\n if (write.snap) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));\r\n }\r\n else ;\r\n }\r\n else if (write.children) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n if (pathIsEmpty(relativePath)) {\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);\r\n }\r\n else {\r\n const child = safeGet(write.children, pathGetFront(relativePath));\r\n if (child) {\r\n // There exists a child in this node that matches the root path\r\n const deepNode = child.getChild(pathPopFront(relativePath));\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);\r\n }\r\n }\r\n }\r\n else ;\r\n }\r\n else {\r\n throw assertionError('WriteRecord should have .snap or .children');\r\n }\r\n }\r\n }\r\n return compoundWrite;\r\n}\r\n/**\r\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\r\n * writes), attempt to calculate a complete snapshot for the given path\r\n *\r\n * @param writeIdsToExclude - An optional set to be excluded\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n if (!writeIdsToExclude && !includeHiddenWrites) {\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (compoundWriteIsEmpty(subMerge)) {\r\n return completeServerCache;\r\n }\r\n else if (completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {\r\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\r\n return null;\r\n }\r\n else {\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(subMerge, layeredCache);\r\n }\r\n }\r\n }\r\n else {\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\r\n return completeServerCache;\r\n }\r\n else {\r\n // If the server cache is null, and we don't have a complete cache, we need to return null\r\n if (!includeHiddenWrites &&\r\n completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {\r\n return null;\r\n }\r\n else {\r\n const filter = function (write) {\r\n return ((write.visible || includeHiddenWrites) &&\r\n (!writeIdsToExclude ||\r\n !~writeIdsToExclude.indexOf(write.writeId)) &&\r\n (pathContains(write.path, treePath) ||\r\n pathContains(treePath, write.path)));\r\n };\r\n const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(mergeAtPath, layeredCache);\r\n }\r\n }\r\n }\r\n}\r\n/**\r\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\r\n * Used when creating new views, to pre-fill their complete event children snapshot.\r\n */\r\nfunction writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {\r\n let completeChildren = ChildrenNode.EMPTY_NODE;\r\n const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (topLevelSet) {\r\n if (!topLevelSet.isLeafNode()) {\r\n // we're shadowing everything. Return the children.\r\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\r\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\r\n });\r\n }\r\n return completeChildren;\r\n }\r\n else if (completeServerChildren) {\r\n // Layer any children we have on top of this\r\n // We know we don't have a top-level set, so just enumerate existing children\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);\r\n completeChildren = completeChildren.updateImmediateChild(childName, node);\r\n });\r\n // Add any complete children we have from the set\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n else {\r\n // We don't have anything to layer on top of. Layer on any children we have\r\n // Note that we can return an empty snap if we have a defined delete\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n}\r\n/**\r\n * Given that the underlying server data has updated, determine what, if anything, needs to be\r\n * applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist\r\n */\r\nfunction writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {\r\n assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\r\n const path = pathChild(treePath, childPath);\r\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\r\n // At this point we can probably guarantee that we're in case 2, meaning no events\r\n // May need to check visibility while doing the findRootMostValueAndPath call\r\n return null;\r\n }\r\n else {\r\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n if (compoundWriteIsEmpty(childMerge)) {\r\n // We're not shadowing at all. Case 1\r\n return existingServerSnap.getChild(childPath);\r\n }\r\n else {\r\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\r\n // However this is tricky to find out, since user updates don't necessary change the server\r\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\r\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\r\n // only check if the updates change the serverNode.\r\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\r\n return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {\r\n const path = pathChild(treePath, childKey);\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n if (existingServerSnap.isCompleteForChild(childKey)) {\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n */\r\nfunction writeTreeShadowingWrite(writeTree, path) {\r\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window.\r\n */\r\nfunction writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {\r\n let toIterate;\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\r\n if (shadowingNode != null) {\r\n toIterate = shadowingNode;\r\n }\r\n else if (completeServerData != null) {\r\n toIterate = compoundWriteApply(merge, completeServerData);\r\n }\r\n else {\r\n // no children to iterate on\r\n return [];\r\n }\r\n toIterate = toIterate.withIndex(index);\r\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\r\n const nodes = [];\r\n const cmp = index.getCompare();\r\n const iter = reverse\r\n ? toIterate.getReverseIteratorFrom(startPost, index)\r\n : toIterate.getIteratorFrom(startPost, index);\r\n let next = iter.getNext();\r\n while (next && nodes.length < count) {\r\n if (cmp(next, startPost) !== 0) {\r\n nodes.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n return nodes;\r\n }\r\n else {\r\n return [];\r\n }\r\n}\r\nfunction newWriteTree() {\r\n return {\r\n visibleWrites: CompoundWrite.empty(),\r\n allWrites: [],\r\n lastWriteId: -1\r\n };\r\n}\r\n/**\r\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\r\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\r\n * can lead to a more expensive calculation.\r\n *\r\n * @param writeIdsToExclude - Optional writes to exclude.\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);\r\n}\r\n/**\r\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\r\n * mix of the given server data and write data.\r\n *\r\n */\r\nfunction writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {\r\n return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);\r\n}\r\n/**\r\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\r\n * if anything, needs to be applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events should be raised\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\r\n *\r\n *\r\n */\r\nfunction writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {\r\n return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n *\r\n */\r\nfunction writeTreeRefShadowingWrite(writeTreeRef, path) {\r\n return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window\r\n */\r\nfunction writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {\r\n return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {\r\n return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);\r\n}\r\n/**\r\n * Return a WriteTreeRef for a child.\r\n */\r\nfunction writeTreeRefChild(writeTreeRef, childName) {\r\n return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);\r\n}\r\nfunction newWriteTreeRef(path, writeTree) {\r\n return {\r\n treePath: path,\r\n writeTree\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ChildChangeAccumulator {\r\n constructor() {\r\n this.changeMap = new Map();\r\n }\r\n trackChildChange(change) {\r\n const type = change.type;\r\n const childKey = change.childName;\r\n assert(type === \"child_added\" /* ChangeType.CHILD_ADDED */ ||\r\n type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ ||\r\n type === \"child_removed\" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');\r\n assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\r\n const oldChange = this.changeMap.get(childKey);\r\n if (oldChange) {\r\n const oldType = oldChange.type;\r\n if (type === \"child_added\" /* ChangeType.CHILD_ADDED */ &&\r\n oldType === \"child_removed\" /* ChangeType.CHILD_REMOVED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));\r\n }\r\n else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\r\n oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\r\n this.changeMap.delete(childKey);\r\n }\r\n else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\r\n oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));\r\n }\r\n else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\r\n oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\r\n this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));\r\n }\r\n else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\r\n oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));\r\n }\r\n else {\r\n throw assertionError('Illegal combination of changes: ' +\r\n change +\r\n ' occurred after ' +\r\n oldChange);\r\n }\r\n }\r\n else {\r\n this.changeMap.set(childKey, change);\r\n }\r\n }\r\n getChanges() {\r\n return Array.from(this.changeMap.values());\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of CompleteChildSource that never returns any additional children\r\n */\r\n// eslint-disable-next-line @typescript-eslint/naming-convention\r\nclass NoCompleteChildSource_ {\r\n getCompleteChild(childKey) {\r\n return null;\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Singleton instance.\r\n */\r\nconst NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\r\n/**\r\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\r\n * old event caches available to calculate complete children.\r\n */\r\nclass WriteTreeCompleteChildSource {\r\n constructor(writes_, viewCache_, optCompleteServerCache_ = null) {\r\n this.writes_ = writes_;\r\n this.viewCache_ = viewCache_;\r\n this.optCompleteServerCache_ = optCompleteServerCache_;\r\n }\r\n getCompleteChild(childKey) {\r\n const node = this.viewCache_.eventCache;\r\n if (node.isCompleteForChild(childKey)) {\r\n return node.getNode().getImmediateChild(childKey);\r\n }\r\n else {\r\n const serverNode = this.optCompleteServerCache_ != null\r\n ? new CacheNode(this.optCompleteServerCache_, true, false)\r\n : this.viewCache_.serverCache;\r\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\r\n }\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n const completeServerData = this.optCompleteServerCache_ != null\r\n ? this.optCompleteServerCache_\r\n : viewCacheGetCompleteServerSnap(this.viewCache_);\r\n const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);\r\n if (nodes.length === 0) {\r\n return null;\r\n }\r\n else {\r\n return nodes[0];\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newViewProcessor(filter) {\r\n return { filter };\r\n}\r\nfunction viewProcessorAssertIndexed(viewProcessor, viewCache) {\r\n assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');\r\n assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');\r\n}\r\nfunction viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {\r\n const accumulator = new ChildChangeAccumulator();\r\n let newViewCache, filterServerNode;\r\n if (operation.type === OperationType.OVERWRITE) {\r\n const overwrite = operation;\r\n if (overwrite.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(overwrite.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered and the\r\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\r\n // again\r\n filterServerNode =\r\n overwrite.source.tagged ||\r\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\r\n newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.MERGE) {\r\n const merge = operation;\r\n if (merge.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(merge.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered\r\n filterServerNode =\r\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\r\n newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.ACK_USER_WRITE) {\r\n const ackUserWrite = operation;\r\n if (!ackUserWrite.revert) {\r\n newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.LISTEN_COMPLETE) {\r\n newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);\r\n }\r\n else {\r\n throw assertionError('Unknown operation type: ' + operation.type);\r\n }\r\n const changes = accumulator.getChanges();\r\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\r\n return { viewCache: newViewCache, changes };\r\n}\r\nfunction viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {\r\n const eventSnap = newViewCache.eventCache;\r\n if (eventSnap.isFullyInitialized()) {\r\n const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\r\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\r\n if (accumulator.length > 0 ||\r\n !oldViewCache.eventCache.isFullyInitialized() ||\r\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\r\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {\r\n accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));\r\n }\r\n }\r\n}\r\nfunction viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {\r\n const oldEventSnap = viewCache.eventCache;\r\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\r\n // we have a shadowing write, ignore changes\r\n return viewCache;\r\n }\r\n else {\r\n let newEventCache, serverNode;\r\n if (pathIsEmpty(changePath)) {\r\n // TODO: figure out how this plays with \"sliding ack windows\"\r\n assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');\r\n if (viewCache.serverCache.isFiltered()) {\r\n // We need to special case this, because we need to only apply writes to complete children, or\r\n // we might end up raising events for incomplete children. If the server data is filtered deep\r\n // writes cannot be guaranteed to be complete\r\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\r\n const completeChildren = serverCache instanceof ChildrenNode\r\n ? serverCache\r\n : ChildrenNode.EMPTY_NODE;\r\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);\r\n }\r\n else {\r\n const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);\r\n }\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n assert(pathGetLength(changePath) === 1, \"Can't have a priority with additional path components\");\r\n const oldEventNode = oldEventSnap.getNode();\r\n serverNode = viewCache.serverCache.getNode();\r\n // we might have overwrites for this priority\r\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);\r\n if (updatedPriority != null) {\r\n newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);\r\n }\r\n else {\r\n // priority didn't change, keep old node\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n // update child\r\n let newEventChild;\r\n if (oldEventSnap.isCompleteForChild(childKey)) {\r\n serverNode = viewCache.serverCache.getNode();\r\n const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);\r\n if (eventChildUpdate != null) {\r\n newEventChild = oldEventSnap\r\n .getNode()\r\n .getImmediateChild(childKey)\r\n .updateChild(childChangePath, eventChildUpdate);\r\n }\r\n else {\r\n // Nothing changed, just keep the old child\r\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n }\r\n }\r\n else {\r\n newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n }\r\n if (newEventChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\r\n }\r\n else {\r\n // no complete child available or no change\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n }\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());\r\n }\r\n}\r\nfunction viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\r\n const oldServerSnap = oldViewCache.serverCache;\r\n let newServerCache;\r\n const serverFilter = filterServerNode\r\n ? viewProcessor.filter\r\n : viewProcessor.filter.getIndexedFilter();\r\n if (pathIsEmpty(changePath)) {\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\r\n }\r\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\r\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\r\n const newServerNode = oldServerSnap\r\n .getNode()\r\n .updateChild(changePath, changedSnap);\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (!oldServerSnap.isCompleteForPath(changePath) &&\r\n pathGetLength(changePath) > 1) {\r\n // We don't update incomplete nodes with updates intended for other listeners\r\n return oldViewCache;\r\n }\r\n const childChangePath = pathPopFront(changePath);\r\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\r\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\r\n if (childKey === '.priority') {\r\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\r\n }\r\n else {\r\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);\r\n }\r\n }\r\n const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());\r\n const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);\r\n}\r\nfunction viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\r\n const oldEventSnap = oldViewCache.eventCache;\r\n let newViewCache, newEventCache;\r\n const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\r\n if (pathIsEmpty(changePath)) {\r\n newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n let newChild;\r\n if (pathIsEmpty(childChangePath)) {\r\n // Child overwrite, we can replace the child\r\n newChild = changedSnap;\r\n }\r\n else {\r\n const childNode = source.getCompleteChild(childKey);\r\n if (childNode != null) {\r\n if (pathGetBack(childChangePath) === '.priority' &&\r\n childNode.getChild(pathParent(childChangePath)).isEmpty()) {\r\n // This is a priority update on an empty node. If this node exists on the server, the\r\n // server will send down the priority in the update, so ignore for now\r\n newChild = childNode;\r\n }\r\n else {\r\n newChild = childNode.updateChild(childChangePath, changedSnap);\r\n }\r\n }\r\n else {\r\n // There is no complete child node available\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n }\r\n if (!oldChild.equals(newChild)) {\r\n const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n newViewCache = oldViewCache;\r\n }\r\n }\r\n }\r\n return newViewCache;\r\n}\r\nfunction viewProcessorCacheHasChild(viewCache, childKey) {\r\n return viewCache.eventCache.isCompleteForChild(childKey);\r\n}\r\nfunction viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorApplyMerge(viewProcessor, node, merge) {\r\n merge.foreach((relativePath, childNode) => {\r\n node = node.updateChild(relativePath, childNode);\r\n });\r\n return node;\r\n}\r\nfunction viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\r\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\r\n // wait for the complete data update coming soon.\r\n if (viewCache.serverCache.getNode().isEmpty() &&\r\n !viewCache.serverCache.isFullyInitialized()) {\r\n return viewCache;\r\n }\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n let viewMergeTree;\r\n if (pathIsEmpty(path)) {\r\n viewMergeTree = changedChildren;\r\n }\r\n else {\r\n viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);\r\n }\r\n const serverNode = viewCache.serverCache.getNode();\r\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (serverNode.hasChild(childKey)) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\r\n const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&\r\n childMergeTree.value === null;\r\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\r\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\r\n return viewCache;\r\n }\r\n // Only filter server node if it is currently filtered\r\n const filterServerNode = viewCache.serverCache.isFiltered();\r\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\r\n // now that it won't be shadowed.\r\n const serverCache = viewCache.serverCache;\r\n if (affectedTree.value != null) {\r\n // This is an overwrite.\r\n if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\r\n serverCache.isCompleteForPath(ackPath)) {\r\n return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else if (pathIsEmpty(ackPath)) {\r\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\r\n // should just re-apply whatever we have in our cache as a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\r\n changedChildren = changedChildren.set(new Path(name), node);\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else {\r\n return viewCache;\r\n }\r\n }\r\n else {\r\n // This is a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n affectedTree.foreach((mergePath, value) => {\r\n const serverCachePath = pathChild(ackPath, mergePath);\r\n if (serverCache.isCompleteForPath(serverCachePath)) {\r\n changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));\r\n }\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n}\r\nfunction viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {\r\n const oldServerNode = viewCache.serverCache;\r\n const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);\r\n}\r\nfunction viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {\r\n let complete;\r\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\r\n return viewCache;\r\n }\r\n else {\r\n const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\r\n const oldEventCache = viewCache.eventCache.getNode();\r\n let newEventCache;\r\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\r\n let newNode;\r\n if (viewCache.serverCache.isFullyInitialized()) {\r\n newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n }\r\n else {\r\n const serverChildren = viewCache.serverCache.getNode();\r\n assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');\r\n newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);\r\n }\r\n newNode = newNode;\r\n newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n if (newChild == null &&\r\n viewCache.serverCache.isCompleteForChild(childKey)) {\r\n newChild = oldEventCache.getImmediateChild(childKey);\r\n }\r\n if (newChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);\r\n }\r\n else if (viewCache.eventCache.getNode().hasChild(childKey)) {\r\n // No complete child available, delete the existing one, if any\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);\r\n }\r\n else {\r\n newEventCache = oldEventCache;\r\n }\r\n if (newEventCache.isEmpty() &&\r\n viewCache.serverCache.isFullyInitialized()) {\r\n // We might have reverted all child writes. Maybe the old event was a leaf node\r\n complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n if (complete.isLeafNode()) {\r\n newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);\r\n }\r\n }\r\n }\r\n complete =\r\n viewCache.serverCache.isFullyInitialized() ||\r\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A view represents a specific location and query that has 1 or more event registrations.\r\n *\r\n * It does several things:\r\n * - Maintains the list of event registrations for this location/query.\r\n * - Maintains a cache of the data visible for this location/query.\r\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\r\n * registrations returns the set of events to be raised.\r\n */\r\nclass View {\r\n constructor(query_, initialViewCache) {\r\n this.query_ = query_;\r\n this.eventRegistrations_ = [];\r\n const params = this.query_._queryParams;\r\n const indexFilter = new IndexedFilter(params.getIndex());\r\n const filter = queryParamsGetNodeFilter(params);\r\n this.processor_ = newViewProcessor(filter);\r\n const initialServerCache = initialViewCache.serverCache;\r\n const initialEventCache = initialViewCache.eventCache;\r\n // Don't filter server node with other filter than index, wait for tagged listen\r\n const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\r\n const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\r\n const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\r\n const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\r\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\r\n this.eventGenerator_ = new EventGenerator(this.query_);\r\n }\r\n get query() {\r\n return this.query_;\r\n }\r\n}\r\nfunction viewGetServerCache(view) {\r\n return view.viewCache_.serverCache.getNode();\r\n}\r\nfunction viewGetCompleteNode(view) {\r\n return viewCacheGetCompleteEventSnap(view.viewCache_);\r\n}\r\nfunction viewGetCompleteServerCache(view, path) {\r\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\r\n if (cache) {\r\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\r\n // we need to see if it contains the child we're interested in.\r\n if (view.query._queryParams.loadsAllData() ||\r\n (!pathIsEmpty(path) &&\r\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {\r\n return cache.getChild(path);\r\n }\r\n }\r\n return null;\r\n}\r\nfunction viewIsEmpty(view) {\r\n return view.eventRegistrations_.length === 0;\r\n}\r\nfunction viewAddEventRegistration(view, eventRegistration) {\r\n view.eventRegistrations_.push(eventRegistration);\r\n}\r\n/**\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction viewRemoveEventRegistration(view, eventRegistration, cancelError) {\r\n const cancelEvents = [];\r\n if (cancelError) {\r\n assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\r\n const path = view.query._path;\r\n view.eventRegistrations_.forEach(registration => {\r\n const maybeEvent = registration.createCancelEvent(cancelError, path);\r\n if (maybeEvent) {\r\n cancelEvents.push(maybeEvent);\r\n }\r\n });\r\n }\r\n if (eventRegistration) {\r\n let remaining = [];\r\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\r\n const existing = view.eventRegistrations_[i];\r\n if (!existing.matches(eventRegistration)) {\r\n remaining.push(existing);\r\n }\r\n else if (eventRegistration.hasAnyCallback()) {\r\n // We're removing just this one\r\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\r\n break;\r\n }\r\n }\r\n view.eventRegistrations_ = remaining;\r\n }\r\n else {\r\n view.eventRegistrations_ = [];\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Applies the given Operation, updates our cache, and returns the appropriate events.\r\n */\r\nfunction viewApplyOperation(view, operation, writesCache, completeServerCache) {\r\n if (operation.type === OperationType.MERGE &&\r\n operation.source.queryId !== null) {\r\n assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');\r\n assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');\r\n }\r\n const oldViewCache = view.viewCache_;\r\n const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);\r\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\r\n assert(result.viewCache.serverCache.isFullyInitialized() ||\r\n !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');\r\n view.viewCache_ = result.viewCache;\r\n return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);\r\n}\r\nfunction viewGetInitialEvents(view, registration) {\r\n const eventSnap = view.viewCache_.eventCache;\r\n const initialChanges = [];\r\n if (!eventSnap.getNode().isLeafNode()) {\r\n const eventNode = eventSnap.getNode();\r\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n initialChanges.push(changeChildAdded(key, childNode));\r\n });\r\n }\r\n if (eventSnap.isFullyInitialized()) {\r\n initialChanges.push(changeValue(eventSnap.getNode()));\r\n }\r\n return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);\r\n}\r\nfunction viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {\r\n const registrations = eventRegistration\r\n ? [eventRegistration]\r\n : view.eventRegistrations_;\r\n return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet referenceConstructor$1;\r\n/**\r\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\r\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\r\n * and user writes (set, transaction, update).\r\n *\r\n * It's responsible for:\r\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\r\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\r\n * applyUserOverwrite, etc.)\r\n */\r\nclass SyncPoint {\r\n constructor() {\r\n /**\r\n * The Views being tracked at this location in the tree, stored as a map where the key is a\r\n * queryId and the value is the View for that query.\r\n *\r\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\r\n */\r\n this.views = new Map();\r\n }\r\n}\r\nfunction syncPointSetReferenceConstructor(val) {\r\n assert(!referenceConstructor$1, '__referenceConstructor has already been defined');\r\n referenceConstructor$1 = val;\r\n}\r\nfunction syncPointGetReferenceConstructor() {\r\n assert(referenceConstructor$1, 'Reference.ts has not been loaded');\r\n return referenceConstructor$1;\r\n}\r\nfunction syncPointIsEmpty(syncPoint) {\r\n return syncPoint.views.size === 0;\r\n}\r\nfunction syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {\r\n const queryId = operation.source.queryId;\r\n if (queryId !== null) {\r\n const view = syncPoint.views.get(queryId);\r\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\r\n return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);\r\n }\r\n else {\r\n let events = [];\r\n for (const view of syncPoint.views.values()) {\r\n events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Get a view for the specified query.\r\n *\r\n * @param query - The query to return a view for\r\n * @param writesCache\r\n * @param serverCache\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {\r\n const queryId = query._queryIdentifier;\r\n const view = syncPoint.views.get(queryId);\r\n if (!view) {\r\n // TODO: make writesCache take flag for complete server node\r\n let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);\r\n let eventCacheComplete = false;\r\n if (eventCache) {\r\n eventCacheComplete = true;\r\n }\r\n else if (serverCache instanceof ChildrenNode) {\r\n eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);\r\n eventCacheComplete = false;\r\n }\r\n else {\r\n eventCache = ChildrenNode.EMPTY_NODE;\r\n eventCacheComplete = false;\r\n }\r\n const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));\r\n return new View(query, viewCache);\r\n }\r\n return view;\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @param query\r\n * @param eventRegistration\r\n * @param writesCache\r\n * @param serverCache - Complete server cache, if we have it.\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);\r\n if (!syncPoint.views.has(query._queryIdentifier)) {\r\n syncPoint.views.set(query._queryIdentifier, view);\r\n }\r\n // This is guaranteed to exist now, we just created anything that was missing\r\n viewAddEventRegistration(view, eventRegistration);\r\n return viewGetInitialEvents(view, eventRegistration);\r\n}\r\n/**\r\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\r\n *\r\n * If query is the default query, we'll check all views for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\r\n *\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns removed queries and any cancel events\r\n */\r\nfunction syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {\r\n const queryId = query._queryIdentifier;\r\n const removed = [];\r\n let cancelEvents = [];\r\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\r\n if (queryId === 'default') {\r\n // When you do ref.off(...), we search all views for the registration to remove.\r\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(viewQueryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // remove the callback from the specific view.\r\n const view = syncPoint.views.get(queryId);\r\n if (view) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(queryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\r\n // We removed our last complete view.\r\n removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));\r\n }\r\n return { removed, events: cancelEvents };\r\n}\r\nfunction syncPointGetQueryViews(syncPoint) {\r\n const result = [];\r\n for (const view of syncPoint.views.values()) {\r\n if (!view.query._queryParams.loadsAllData()) {\r\n result.push(view);\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * @param path - The path to the desired complete snapshot\r\n * @returns A complete cache, if it exists\r\n */\r\nfunction syncPointGetCompleteServerCache(syncPoint, path) {\r\n let serverCache = null;\r\n for (const view of syncPoint.views.values()) {\r\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\r\n }\r\n return serverCache;\r\n}\r\nfunction syncPointViewForQuery(syncPoint, query) {\r\n const params = query._queryParams;\r\n if (params.loadsAllData()) {\r\n return syncPointGetCompleteView(syncPoint);\r\n }\r\n else {\r\n const queryId = query._queryIdentifier;\r\n return syncPoint.views.get(queryId);\r\n }\r\n}\r\nfunction syncPointViewExistsForQuery(syncPoint, query) {\r\n return syncPointViewForQuery(syncPoint, query) != null;\r\n}\r\nfunction syncPointHasCompleteView(syncPoint) {\r\n return syncPointGetCompleteView(syncPoint) != null;\r\n}\r\nfunction syncPointGetCompleteView(syncPoint) {\r\n for (const view of syncPoint.views.values()) {\r\n if (view.query._queryParams.loadsAllData()) {\r\n return view;\r\n }\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet referenceConstructor;\r\nfunction syncTreeSetReferenceConstructor(val) {\r\n assert(!referenceConstructor, '__referenceConstructor has already been defined');\r\n referenceConstructor = val;\r\n}\r\nfunction syncTreeGetReferenceConstructor() {\r\n assert(referenceConstructor, 'Reference.ts has not been loaded');\r\n return referenceConstructor;\r\n}\r\n/**\r\n * Static tracker for next query tag.\r\n */\r\nlet syncTreeNextQueryTag_ = 1;\r\n/**\r\n * SyncTree is the central class for managing event callback registration, data caching, views\r\n * (query processing), and event generation. There are typically two SyncTree instances for\r\n * each Repo, one for the normal Firebase data, and one for the .info data.\r\n *\r\n * It has a number of responsibilities, including:\r\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\r\n * - Applying and caching data changes for user set(), transaction(), and update() calls\r\n * (applyUserOverwrite(), applyUserMerge()).\r\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\r\n * applyServerMerge()).\r\n * - Generating user-facing events for server and user changes (all of the apply* methods\r\n * return the set of events that need to be raised as a result).\r\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\r\n * to the correct set of paths and queries to satisfy the current set of user event\r\n * callbacks (listens are started/stopped using the provided listenProvider).\r\n *\r\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\r\n * events are returned to the caller rather than raised synchronously.\r\n *\r\n */\r\nclass SyncTree {\r\n /**\r\n * @param listenProvider_ - Used by SyncTree to start / stop listening\r\n * to server data.\r\n */\r\n constructor(listenProvider_) {\r\n this.listenProvider_ = listenProvider_;\r\n /**\r\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\r\n */\r\n this.syncPointTree_ = new ImmutableTree(null);\r\n /**\r\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\r\n */\r\n this.pendingWriteTree_ = newWriteTree();\r\n this.tagToQueryMap = new Map();\r\n this.queryToTagMap = new Map();\r\n }\r\n}\r\n/**\r\n * Apply the data changes for a user-generated set() or transaction() call.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {\r\n // Record pending write.\r\n writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);\r\n if (!visible) {\r\n return [];\r\n }\r\n else {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));\r\n }\r\n}\r\n/**\r\n * Apply the data from a user-generated update() call\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {\r\n // Record pending merge.\r\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));\r\n}\r\n/**\r\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\r\n *\r\n * @param revert - True if the given write failed and needs to be reverted\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAckUserWrite(syncTree, writeId, revert = false) {\r\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\r\n const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);\r\n if (!needToReevaluate) {\r\n return [];\r\n }\r\n else {\r\n let affectedTree = new ImmutableTree(null);\r\n if (write.snap != null) {\r\n // overwrite\r\n affectedTree = affectedTree.set(newEmptyPath(), true);\r\n }\r\n else {\r\n each(write.children, (pathString) => {\r\n affectedTree = affectedTree.set(new Path(pathString), true);\r\n });\r\n }\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));\r\n }\r\n}\r\n/**\r\n * Apply new server data for the specified path..\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerOverwrite(syncTree, path, newData) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));\r\n}\r\n/**\r\n * Apply new server data to be merged in at the specified path.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerMerge(syncTree, path, changedChildren) {\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));\r\n}\r\n/**\r\n * Apply a listen complete for a query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyListenComplete(syncTree, path) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));\r\n}\r\n/**\r\n * Apply a listen complete for a tagged query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedListenComplete(syncTree, path, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Remove event callback(s).\r\n *\r\n * If query is the default query, we'll check all queries for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\r\n *\r\n * @param eventRegistration - If null, all callbacks are removed.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\r\n * deduping needs to take place. This flag allows toggling of that behavior\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {\r\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\r\n const path = query._path;\r\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\r\n let cancelEvents = [];\r\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\r\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\r\n // not loadsAllData().\r\n if (maybeSyncPoint &&\r\n (query._queryIdentifier === 'default' ||\r\n syncPointViewExistsForQuery(maybeSyncPoint, query))) {\r\n const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);\r\n if (syncPointIsEmpty(maybeSyncPoint)) {\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\r\n }\r\n const removed = removedAndEvents.removed;\r\n cancelEvents = removedAndEvents.events;\r\n if (!skipListenerDedup) {\r\n /**\r\n * We may have just removed one of many listeners and can short-circuit this whole process\r\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\r\n * properly set up.\r\n */\r\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\r\n // queryId === 'default'\r\n const removingDefault = -1 !==\r\n removed.findIndex(query => {\r\n return query._queryParams.loadsAllData();\r\n });\r\n const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));\r\n if (removingDefault && !covered) {\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\r\n // removal\r\n if (!subtree.isEmpty()) {\r\n // We need to fold over our subtree and collect the listeners to send\r\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\r\n // Ok, we've collected all the listens we need. Set them up.\r\n for (let i = 0; i < newViews.length; ++i) {\r\n const view = newViews[i], newQuery = view.query;\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);\r\n }\r\n }\r\n // Otherwise there's nothing below us, so nothing we need to start listening on\r\n }\r\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\r\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\r\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\r\n if (!covered && removed.length > 0 && !cancelError) {\r\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\r\n // default. Otherwise, we need to iterate through and cancel each individual query\r\n if (removingDefault) {\r\n // We don't tag default listeners\r\n const defaultTag = null;\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);\r\n }\r\n else {\r\n removed.forEach((queryToRemove) => {\r\n const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);\r\n });\r\n }\r\n }\r\n }\r\n // Now, clear all of the tags we're tracking for the removed listens\r\n syncTreeRemoveTags_(syncTree, removed);\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Apply new server data for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey != null) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // Query must have been removed already\r\n return [];\r\n }\r\n}\r\n/**\r\n * Apply server data to be merged in for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {\r\n const path = query._path;\r\n let serverCache = null;\r\n let foundAncestorDefaultView = false;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let serverCacheComplete;\r\n if (serverCache != null) {\r\n serverCacheComplete = true;\r\n }\r\n else {\r\n serverCacheComplete = false;\r\n serverCache = ChildrenNode.EMPTY_NODE;\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n subtree.foreachChild((childName, childSyncPoint) => {\r\n const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());\r\n if (completeCache) {\r\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\r\n }\r\n });\r\n }\r\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\r\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\r\n // We need to track a tag for this query\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');\r\n const tag = syncTreeGetNextQueryTag_();\r\n syncTree.queryToTagMap.set(queryKey, tag);\r\n syncTree.tagToQueryMap.set(tag, queryKey);\r\n }\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\r\n let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);\r\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\r\n const view = syncPointViewForQuery(syncPoint, query);\r\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\r\n }\r\n return events;\r\n}\r\n/**\r\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\r\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\r\n * have a listener above, and atomic operations would correctly show a jitter of ->\r\n * as the write is applied locally and then acknowledged at the server.\r\n *\r\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\r\n *\r\n * @param path - The path to the data we want\r\n * @param writeIdsToExclude - A specific set to be excluded\r\n */\r\nfunction syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {\r\n const includeHiddenSets = true;\r\n const writeTree = syncTree.pendingWriteTree_;\r\n const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {\r\n const relativePath = newRelativePath(pathSoFar, path);\r\n const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);\r\n if (serverCache) {\r\n return serverCache;\r\n }\r\n });\r\n return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);\r\n}\r\nfunction syncTreeGetServerValue(syncTree, query) {\r\n const path = query._path;\r\n let serverCache = null;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n const serverCacheComplete = serverCache != null;\r\n const serverCacheNode = serverCacheComplete\r\n ? new CacheNode(serverCache, true, false)\r\n : null;\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);\r\n return viewGetCompleteNode(view);\r\n}\r\n/**\r\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\r\n *\r\n * NOTES:\r\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\r\n *\r\n * - We call applyOperation() on each SyncPoint passing three things:\r\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\r\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\r\n * 3. A snapshot Node with cached server data, if we have it.\r\n *\r\n * - We concatenate all of the events returned by each SyncPoint and return the result.\r\n */\r\nfunction syncTreeApplyOperationToSyncPoints_(syncTree, operation) {\r\n return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, \r\n /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n if (pathIsEmpty(operation.path)) {\r\n return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\r\n }\r\n else {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n const childName = pathGetFront(operation.path);\r\n const childOperation = operation.operationForChild(childName);\r\n const childTree = syncPointTree.children.get(childName);\r\n if (childTree && childOperation) {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n syncPointTree.children.inorderTraversal((childName, childTree) => {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n const childOperation = operation.operationForChild(childName);\r\n if (childOperation) {\r\n events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n });\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n}\r\nfunction syncTreeCreateListenerForView_(syncTree, view) {\r\n const query = view.query;\r\n const tag = syncTreeTagForQuery(syncTree, query);\r\n return {\r\n hashFn: () => {\r\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\r\n return cache.hash();\r\n },\r\n onComplete: (status) => {\r\n if (status === 'ok') {\r\n if (tag) {\r\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\r\n }\r\n else {\r\n return syncTreeApplyListenComplete(syncTree, query._path);\r\n }\r\n }\r\n else {\r\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\r\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\r\n const error = errorForServerCode(status, query);\r\n return syncTreeRemoveEventRegistration(syncTree, query, \r\n /*eventRegistration*/ null, error);\r\n }\r\n }\r\n };\r\n}\r\n/**\r\n * Return the tag associated with the given query.\r\n */\r\nfunction syncTreeTagForQuery(syncTree, query) {\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n return syncTree.queryToTagMap.get(queryKey);\r\n}\r\n/**\r\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\r\n */\r\nfunction syncTreeMakeQueryKey_(query) {\r\n return query._path.toString() + '$' + query._queryIdentifier;\r\n}\r\n/**\r\n * Return the query associated with the given tag, if we have one\r\n */\r\nfunction syncTreeQueryKeyForTag_(syncTree, tag) {\r\n return syncTree.tagToQueryMap.get(tag);\r\n}\r\n/**\r\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\r\n */\r\nfunction syncTreeParseQueryKey_(queryKey) {\r\n const splitIndex = queryKey.indexOf('$');\r\n assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\r\n return {\r\n queryId: queryKey.substr(splitIndex + 1),\r\n path: new Path(queryKey.substr(0, splitIndex))\r\n };\r\n}\r\n/**\r\n * A helper method to apply tagged operations\r\n */\r\nfunction syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {\r\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\r\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);\r\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\r\n}\r\n/**\r\n * This collapses multiple unfiltered views into a single view, since we only need a single\r\n * listener for them.\r\n */\r\nfunction syncTreeCollectDistinctViewsForSubTree_(subtree) {\r\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\r\n return [completeView];\r\n }\r\n else {\r\n // No complete view here, flatten any deeper listens into an array\r\n let views = [];\r\n if (maybeChildSyncPoint) {\r\n views = syncPointGetQueryViews(maybeChildSyncPoint);\r\n }\r\n each(childMap, (_key, childViews) => {\r\n views = views.concat(childViews);\r\n });\r\n return views;\r\n }\r\n });\r\n}\r\n/**\r\n * Normalizes a query to a query we send the server for listening\r\n *\r\n * @returns The normalized query\r\n */\r\nfunction syncTreeQueryForListening_(query) {\r\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\r\n // We treat queries that load all data as default queries\r\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\r\n // from Query\r\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\r\n }\r\n else {\r\n return query;\r\n }\r\n}\r\nfunction syncTreeRemoveTags_(syncTree, queries) {\r\n for (let j = 0; j < queries.length; ++j) {\r\n const removedQuery = queries[j];\r\n if (!removedQuery._queryParams.loadsAllData()) {\r\n // We should have a tag for this\r\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\r\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\r\n syncTree.queryToTagMap.delete(removedQueryKey);\r\n syncTree.tagToQueryMap.delete(removedQueryTag);\r\n }\r\n }\r\n}\r\n/**\r\n * Static accessor for query tags.\r\n */\r\nfunction syncTreeGetNextQueryTag_() {\r\n return syncTreeNextQueryTag_++;\r\n}\r\n/**\r\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\r\n *\r\n * @returns This method can return events to support synchronous data sources\r\n */\r\nfunction syncTreeSetupListener_(syncTree, query, view) {\r\n const path = query._path;\r\n const tag = syncTreeTagForQuery(syncTree, query);\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\r\n // may need to shadow other listens as well.\r\n if (tag) {\r\n assert(!syncPointHasCompleteView(subtree.value), \"If we're adding a query, it shouldn't be shadowed\");\r\n }\r\n else {\r\n // Shadow everything at or below this location, this is a default listener.\r\n const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (!pathIsEmpty(relativePath) &&\r\n maybeChildSyncPoint &&\r\n syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\r\n }\r\n else {\r\n // No default listener here, flatten any deeper queries into an array\r\n let queries = [];\r\n if (maybeChildSyncPoint) {\r\n queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));\r\n }\r\n each(childMap, (_key, childQueries) => {\r\n queries = queries.concat(childQueries);\r\n });\r\n return queries;\r\n }\r\n });\r\n for (let i = 0; i < queriesToStop.length; ++i) {\r\n const queryToStop = queriesToStop[i];\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));\r\n }\r\n }\r\n return events;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ExistingValueProvider {\r\n constructor(node_) {\r\n this.node_ = node_;\r\n }\r\n getImmediateChild(childName) {\r\n const child = this.node_.getImmediateChild(childName);\r\n return new ExistingValueProvider(child);\r\n }\r\n node() {\r\n return this.node_;\r\n }\r\n}\r\nclass DeferredValueProvider {\r\n constructor(syncTree, path) {\r\n this.syncTree_ = syncTree;\r\n this.path_ = path;\r\n }\r\n getImmediateChild(childName) {\r\n const childPath = pathChild(this.path_, childName);\r\n return new DeferredValueProvider(this.syncTree_, childPath);\r\n }\r\n node() {\r\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\r\n }\r\n}\r\n/**\r\n * Generate placeholders for deferred values.\r\n */\r\nconst generateWithValues = function (values) {\r\n values = values || {};\r\n values['timestamp'] = values['timestamp'] || new Date().getTime();\r\n return values;\r\n};\r\n/**\r\n * Value to use when firing local events. When writing server values, fire\r\n * local events with an approximate value, otherwise return value as-is.\r\n */\r\nconst resolveDeferredLeafValue = function (value, existingVal, serverValues) {\r\n if (!value || typeof value !== 'object') {\r\n return value;\r\n }\r\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\r\n if (typeof value['.sv'] === 'string') {\r\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\r\n }\r\n else if (typeof value['.sv'] === 'object') {\r\n return resolveComplexDeferredValue(value['.sv'], existingVal);\r\n }\r\n else {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\r\n }\r\n};\r\nconst resolveScalarDeferredValue = function (op, existing, serverValues) {\r\n switch (op) {\r\n case 'timestamp':\r\n return serverValues['timestamp'];\r\n default:\r\n assert(false, 'Unexpected server value: ' + op);\r\n }\r\n};\r\nconst resolveComplexDeferredValue = function (op, existing, unused) {\r\n if (!op.hasOwnProperty('increment')) {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\r\n }\r\n const delta = op['increment'];\r\n if (typeof delta !== 'number') {\r\n assert(false, 'Unexpected increment value: ' + delta);\r\n }\r\n const existingNode = existing.node();\r\n assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');\r\n // Incrementing a non-number sets the value to the incremented amount\r\n if (!existingNode.isLeafNode()) {\r\n return delta;\r\n }\r\n const leaf = existingNode;\r\n const existingVal = leaf.getValue();\r\n if (typeof existingVal !== 'number') {\r\n return delta;\r\n }\r\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\r\n return existingVal + delta;\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the tree with the\r\n * specified generated replacement values.\r\n * @param path - path to which write is relative\r\n * @param node - new data written at path\r\n * @param syncTree - current data\r\n */\r\nconst resolveDeferredValueTree = function (path, node, syncTree, serverValues) {\r\n return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the node with the\r\n * specified generated replacement values. If there are no server values in the node,\r\n * it'll be returned as-is.\r\n */\r\nconst resolveDeferredValueSnapshot = function (node, existing, serverValues) {\r\n return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);\r\n};\r\nfunction resolveDeferredValue(node, existingVal, serverValues) {\r\n const rawPri = node.getPriority().val();\r\n const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);\r\n let newNode;\r\n if (node.isLeafNode()) {\r\n const leafNode = node;\r\n const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);\r\n if (value !== leafNode.getValue() ||\r\n priority !== leafNode.getPriority().val()) {\r\n return new LeafNode(value, nodeFromJSON(priority));\r\n }\r\n else {\r\n return node;\r\n }\r\n }\r\n else {\r\n const childrenNode = node;\r\n newNode = childrenNode;\r\n if (priority !== childrenNode.getPriority().val()) {\r\n newNode = newNode.updatePriority(new LeafNode(priority));\r\n }\r\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);\r\n if (newChildNode !== childNode) {\r\n newNode = newNode.updateImmediateChild(childName, newChildNode);\r\n }\r\n });\r\n return newNode;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A light-weight tree, traversable by path. Nodes can have both values and children.\r\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\r\n * children.\r\n */\r\nclass Tree {\r\n /**\r\n * @param name - Optional name of the node.\r\n * @param parent - Optional parent node.\r\n * @param node - Optional node to wrap.\r\n */\r\n constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {\r\n this.name = name;\r\n this.parent = parent;\r\n this.node = node;\r\n }\r\n}\r\n/**\r\n * Returns a sub-Tree for the given path.\r\n *\r\n * @param pathObj - Path to look up.\r\n * @returns Tree for path.\r\n */\r\nfunction treeSubTree(tree, pathObj) {\r\n // TODO: Require pathObj to be Path?\r\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\r\n let child = tree, next = pathGetFront(path);\r\n while (next !== null) {\r\n const childNode = safeGet(child.node.children, next) || {\r\n children: {},\r\n childCount: 0\r\n };\r\n child = new Tree(next, child, childNode);\r\n path = pathPopFront(path);\r\n next = pathGetFront(path);\r\n }\r\n return child;\r\n}\r\n/**\r\n * Returns the data associated with this tree node.\r\n *\r\n * @returns The data or null if no data exists.\r\n */\r\nfunction treeGetValue(tree) {\r\n return tree.node.value;\r\n}\r\n/**\r\n * Sets data to this tree node.\r\n *\r\n * @param value - Value to set.\r\n */\r\nfunction treeSetValue(tree, value) {\r\n tree.node.value = value;\r\n treeUpdateParents(tree);\r\n}\r\n/**\r\n * @returns Whether the tree has any children.\r\n */\r\nfunction treeHasChildren(tree) {\r\n return tree.node.childCount > 0;\r\n}\r\n/**\r\n * @returns Whethe rthe tree is empty (no value or children).\r\n */\r\nfunction treeIsEmpty(tree) {\r\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\r\n}\r\n/**\r\n * Calls action for each child of this tree node.\r\n *\r\n * @param action - Action to be called for each child.\r\n */\r\nfunction treeForEachChild(tree, action) {\r\n each(tree.node.children, (child, childTree) => {\r\n action(new Tree(child, tree, childTree));\r\n });\r\n}\r\n/**\r\n * Does a depth-first traversal of this node's descendants, calling action for each one.\r\n *\r\n * @param action - Action to be called for each child.\r\n * @param includeSelf - Whether to call action on this node as well. Defaults to\r\n * false.\r\n * @param childrenFirst - Whether to call action on children before calling it on\r\n * parent.\r\n */\r\nfunction treeForEachDescendant(tree, action, includeSelf, childrenFirst) {\r\n if (includeSelf && !childrenFirst) {\r\n action(tree);\r\n }\r\n treeForEachChild(tree, child => {\r\n treeForEachDescendant(child, action, true, childrenFirst);\r\n });\r\n if (includeSelf && childrenFirst) {\r\n action(tree);\r\n }\r\n}\r\n/**\r\n * Calls action on each ancestor node.\r\n *\r\n * @param action - Action to be called on each parent; return\r\n * true to abort.\r\n * @param includeSelf - Whether to call action on this node as well.\r\n * @returns true if the action callback returned true.\r\n */\r\nfunction treeForEachAncestor(tree, action, includeSelf) {\r\n let node = includeSelf ? tree : tree.parent;\r\n while (node !== null) {\r\n if (action(node)) {\r\n return true;\r\n }\r\n node = node.parent;\r\n }\r\n return false;\r\n}\r\n/**\r\n * @returns The path of this tree node, as a Path.\r\n */\r\nfunction treeGetPath(tree) {\r\n return new Path(tree.parent === null\r\n ? tree.name\r\n : treeGetPath(tree.parent) + '/' + tree.name);\r\n}\r\n/**\r\n * Adds or removes this child from its parent based on whether it's empty or not.\r\n */\r\nfunction treeUpdateParents(tree) {\r\n if (tree.parent !== null) {\r\n treeUpdateChild(tree.parent, tree.name, tree);\r\n }\r\n}\r\n/**\r\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\r\n *\r\n * @param childName - The name of the child to update.\r\n * @param child - The child to update.\r\n */\r\nfunction treeUpdateChild(tree, childName, child) {\r\n const childEmpty = treeIsEmpty(child);\r\n const childExists = contains(tree.node.children, childName);\r\n if (childEmpty && childExists) {\r\n delete tree.node.children[childName];\r\n tree.node.childCount--;\r\n treeUpdateParents(tree);\r\n }\r\n else if (!childEmpty && !childExists) {\r\n tree.node.children[childName] = child.node;\r\n tree.node.childCount++;\r\n treeUpdateParents(tree);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * True for invalid Firebase keys\r\n */\r\nconst INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * True for invalid Firebase paths.\r\n * Allows '/' in paths.\r\n */\r\nconst INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * Maximum number of characters to allow in leaf value\r\n */\r\nconst MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\r\nconst isValidKey = function (key) {\r\n return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));\r\n};\r\nconst isValidPathString = function (pathString) {\r\n return (typeof pathString === 'string' &&\r\n pathString.length !== 0 &&\r\n !INVALID_PATH_REGEX_.test(pathString));\r\n};\r\nconst isValidRootPathString = function (pathString) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n return isValidPathString(pathString);\r\n};\r\nconst isValidPriority = function (priority) {\r\n return (priority === null ||\r\n typeof priority === 'string' ||\r\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\r\n (priority &&\r\n typeof priority === 'object' &&\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n contains(priority, '.sv')));\r\n};\r\n/**\r\n * Pre-validate a datum passed as an argument to Firebase function.\r\n */\r\nconst validateFirebaseDataArg = function (fnName, value, path, optional) {\r\n if (optional && value === undefined) {\r\n return;\r\n }\r\n validateFirebaseData(errorPrefix(fnName, 'value'), value, path);\r\n};\r\n/**\r\n * Validate a data object client-side before sending to server.\r\n */\r\nconst validateFirebaseData = function (errorPrefix, data, path_) {\r\n const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\r\n if (data === undefined) {\r\n throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));\r\n }\r\n if (typeof data === 'function') {\r\n throw new Error(errorPrefix +\r\n 'contains a function ' +\r\n validationPathToErrorString(path) +\r\n ' with contents = ' +\r\n data.toString());\r\n }\r\n if (isInvalidJSONNumber(data)) {\r\n throw new Error(errorPrefix +\r\n 'contains ' +\r\n data.toString() +\r\n ' ' +\r\n validationPathToErrorString(path));\r\n }\r\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\r\n if (typeof data === 'string' &&\r\n data.length > MAX_LEAF_SIZE_ / 3 &&\r\n stringLength(data) > MAX_LEAF_SIZE_) {\r\n throw new Error(errorPrefix +\r\n 'contains a string greater than ' +\r\n MAX_LEAF_SIZE_ +\r\n ' utf8 bytes ' +\r\n validationPathToErrorString(path) +\r\n \" ('\" +\r\n data.substring(0, 50) +\r\n \"...')\");\r\n }\r\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\r\n // to save extra walking of large objects.\r\n if (data && typeof data === 'object') {\r\n let hasDotValue = false;\r\n let hasActualChild = false;\r\n each(data, (key, value) => {\r\n if (key === '.value') {\r\n hasDotValue = true;\r\n }\r\n else if (key !== '.priority' && key !== '.sv') {\r\n hasActualChild = true;\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix +\r\n ' contains an invalid key (' +\r\n key +\r\n ') ' +\r\n validationPathToErrorString(path) +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n validationPathPush(path, key);\r\n validateFirebaseData(errorPrefix, value, path);\r\n validationPathPop(path);\r\n });\r\n if (hasDotValue && hasActualChild) {\r\n throw new Error(errorPrefix +\r\n ' contains \".value\" child ' +\r\n validationPathToErrorString(path) +\r\n ' in addition to actual children.');\r\n }\r\n }\r\n};\r\n/**\r\n * Pre-validate paths passed in the firebase function.\r\n */\r\nconst validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\r\n let i, curPath;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n const keys = pathSlice(curPath);\r\n for (let j = 0; j < keys.length; j++) {\r\n if (keys[j] === '.priority' && j === keys.length - 1) ;\r\n else if (!isValidKey(keys[j])) {\r\n throw new Error(errorPrefix +\r\n 'contains an invalid key (' +\r\n keys[j] +\r\n ') in path ' +\r\n curPath.toString() +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n }\r\n // Check that update keys are not descendants of each other.\r\n // We rely on the property that sorting guarantees that ancestors come\r\n // right before descendants.\r\n mergePaths.sort(pathCompare);\r\n let prevPath = null;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n if (prevPath !== null && pathContains(prevPath, curPath)) {\r\n throw new Error(errorPrefix +\r\n 'contains a path ' +\r\n prevPath.toString() +\r\n ' that is ancestor of another path ' +\r\n curPath.toString());\r\n }\r\n prevPath = curPath;\r\n }\r\n};\r\n/**\r\n * pre-validate an object passed as an argument to firebase function (\r\n * must be an object - e.g. for firebase.update()).\r\n */\r\nconst validateFirebaseMergeDataArg = function (fnName, data, path, optional) {\r\n if (optional && data === undefined) {\r\n return;\r\n }\r\n const errorPrefix$1 = errorPrefix(fnName, 'values');\r\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\r\n throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');\r\n }\r\n const mergePaths = [];\r\n each(data, (key, value) => {\r\n const curPath = new Path(key);\r\n validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));\r\n if (pathGetBack(curPath) === '.priority') {\r\n if (!isValidPriority(value)) {\r\n throw new Error(errorPrefix$1 +\r\n \"contains an invalid value for '\" +\r\n curPath.toString() +\r\n \"', which must be a valid \" +\r\n 'Firebase priority (a string, finite number, server value, or null).');\r\n }\r\n }\r\n mergePaths.push(curPath);\r\n });\r\n validateFirebaseMergePaths(errorPrefix$1, mergePaths);\r\n};\r\nconst validatePriority = function (fnName, priority, optional) {\r\n if (optional && priority === undefined) {\r\n return;\r\n }\r\n if (isInvalidJSONNumber(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'is ' +\r\n priority.toString() +\r\n ', but must be a valid Firebase priority (a string, finite number, ' +\r\n 'server value, or null).');\r\n }\r\n // Special case to allow importing data with a .sv.\r\n if (!isValidPriority(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'must be a valid Firebase priority ' +\r\n '(a string, finite number, server value, or null).');\r\n }\r\n};\r\nconst validateKey = function (fnName, argumentName, key, optional) {\r\n if (optional && key === undefined) {\r\n return;\r\n }\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid key = \"' +\r\n key +\r\n '\". Firebase keys must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\r\n }\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validatePathString = function (fnName, argumentName, pathString, optional) {\r\n if (optional && pathString === undefined) {\r\n return;\r\n }\r\n if (!isValidPathString(pathString)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid path = \"' +\r\n pathString +\r\n '\". Paths must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\r\n }\r\n};\r\nconst validateRootPathString = function (fnName, argumentName, pathString, optional) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n validatePathString(fnName, argumentName, pathString, optional);\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validateWritablePath = function (fnName, path) {\r\n if (pathGetFront(path) === '.info') {\r\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\r\n }\r\n};\r\nconst validateUrl = function (fnName, parsedUrl) {\r\n // TODO = Validate server better.\r\n const pathString = parsedUrl.path.toString();\r\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\r\n parsedUrl.repoInfo.host.length === 0 ||\r\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\r\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\r\n (pathString.length !== 0 && !isValidRootPathString(pathString))) {\r\n throw new Error(errorPrefix(fnName, 'url') +\r\n 'must be a valid firebase URL and ' +\r\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\r\n }\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The event queue serves a few purposes:\r\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\r\n * events being queued.\r\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\r\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\r\n * left off, ensuring that the events are still raised synchronously and in order.\r\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\r\n * events are raised synchronously.\r\n *\r\n * NOTE: This can all go away if/when we move to async events.\r\n *\r\n */\r\nclass EventQueue {\r\n constructor() {\r\n this.eventLists_ = [];\r\n /**\r\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\r\n */\r\n this.recursionDepth_ = 0;\r\n }\r\n}\r\n/**\r\n * @param eventDataList - The new events to queue.\r\n */\r\nfunction eventQueueQueueEvents(eventQueue, eventDataList) {\r\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\r\n let currList = null;\r\n for (let i = 0; i < eventDataList.length; i++) {\r\n const data = eventDataList[i];\r\n const path = data.getPath();\r\n if (currList !== null && !pathEquals(path, currList.path)) {\r\n eventQueue.eventLists_.push(currList);\r\n currList = null;\r\n }\r\n if (currList === null) {\r\n currList = { events: [], path };\r\n }\r\n currList.events.push(data);\r\n }\r\n if (currList) {\r\n eventQueue.eventLists_.push(currList);\r\n }\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones)\r\n * for the specified path.\r\n *\r\n * It is assumed that the new events are all for the specified path.\r\n *\r\n * @param path - The path to raise events for.\r\n * @param eventDataList - The new events to raise.\r\n */\r\nfunction eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\r\n * locations related to the specified change path (i.e. all ancestors and descendants).\r\n *\r\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\r\n *\r\n * @param changedPath - The path to raise events for.\r\n * @param eventDataList - The events to raise\r\n */\r\nfunction eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||\r\n pathContains(changedPath, eventPath));\r\n}\r\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {\r\n eventQueue.recursionDepth_++;\r\n let sentAll = true;\r\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\r\n const eventList = eventQueue.eventLists_[i];\r\n if (eventList) {\r\n const eventPath = eventList.path;\r\n if (predicate(eventPath)) {\r\n eventListRaise(eventQueue.eventLists_[i]);\r\n eventQueue.eventLists_[i] = null;\r\n }\r\n else {\r\n sentAll = false;\r\n }\r\n }\r\n }\r\n if (sentAll) {\r\n eventQueue.eventLists_ = [];\r\n }\r\n eventQueue.recursionDepth_--;\r\n}\r\n/**\r\n * Iterates through the list and raises each event\r\n */\r\nfunction eventListRaise(eventList) {\r\n for (let i = 0; i < eventList.events.length; i++) {\r\n const eventData = eventList.events[i];\r\n if (eventData !== null) {\r\n eventList.events[i] = null;\r\n const eventFn = eventData.getEventRunner();\r\n if (logger) {\r\n log('event: ' + eventData.toString());\r\n }\r\n exceptionGuard(eventFn);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INTERRUPT_REASON = 'repo_interrupt';\r\n/**\r\n * If a transaction does not succeed after 25 retries, we abort it. Among other\r\n * things this ensure that if there's ever a bug causing a mismatch between\r\n * client / server hashes for some data, we won't retry indefinitely.\r\n */\r\nconst MAX_TRANSACTION_RETRIES = 25;\r\n/**\r\n * A connection to a single data repository.\r\n */\r\nclass Repo {\r\n constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {\r\n this.repoInfo_ = repoInfo_;\r\n this.forceRestClient_ = forceRestClient_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckProvider_ = appCheckProvider_;\r\n this.dataUpdateCount = 0;\r\n this.statsListener_ = null;\r\n this.eventQueue_ = new EventQueue();\r\n this.nextWriteId_ = 1;\r\n this.interceptServerDataCallback_ = null;\r\n /** A list of data pieces and paths to be set when this client disconnects. */\r\n this.onDisconnect_ = newSparseSnapshotTree();\r\n /** Stores queues of outstanding transactions for Firebase locations. */\r\n this.transactionQueueTree_ = new Tree();\r\n // TODO: This should be @private but it's used by test_access.js and internal.js\r\n this.persistentConnection_ = null;\r\n // This key is intentionally not updated if RepoInfo is later changed or replaced\r\n this.key = this.repoInfo_.toURLString();\r\n }\r\n /**\r\n * @returns The URL corresponding to the root of this Firebase.\r\n */\r\n toString() {\r\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\r\n }\r\n}\r\nfunction repoStart(repo, appId, authOverride) {\r\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\r\n if (repo.forceRestClient_ || beingCrawled()) {\r\n repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_);\r\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\r\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\r\n }\r\n else {\r\n // Validate authOverride\r\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\r\n if (typeof authOverride !== 'object') {\r\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\r\n }\r\n try {\r\n stringify(authOverride);\r\n }\r\n catch (e) {\r\n throw new Error('Invalid authOverride provided: ' + e);\r\n }\r\n }\r\n repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, (connectStatus) => {\r\n repoOnConnectStatus(repo, connectStatus);\r\n }, (updates) => {\r\n repoOnServerInfoUpdate(repo, updates);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);\r\n repo.server_ = repo.persistentConnection_;\r\n }\r\n repo.authTokenProvider_.addTokenChangeListener(token => {\r\n repo.server_.refreshAuthToken(token);\r\n });\r\n repo.appCheckProvider_.addTokenChangeListener(result => {\r\n repo.server_.refreshAppCheckToken(result.token);\r\n });\r\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\r\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\r\n repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));\r\n // Used for .info.\r\n repo.infoData_ = new SnapshotHolder();\r\n repo.infoSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n let infoEvents = [];\r\n const node = repo.infoData_.getNode(query._path);\r\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\r\n // on initial data...\r\n if (!node.isEmpty()) {\r\n infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);\r\n setTimeout(() => {\r\n onComplete('ok');\r\n }, 0);\r\n }\r\n return infoEvents;\r\n },\r\n stopListening: () => { }\r\n });\r\n repoUpdateInfo(repo, 'connected', false);\r\n repo.serverSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\r\n const events = onComplete(status, data);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\r\n });\r\n // No synchronous events for network-backed sync trees\r\n return [];\r\n },\r\n stopListening: (query, tag) => {\r\n repo.server_.unlisten(query, tag);\r\n }\r\n });\r\n}\r\n/**\r\n * @returns The time in milliseconds, taking the server offset into account if we have one.\r\n */\r\nfunction repoServerTime(repo) {\r\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\r\n const offset = offsetNode.val() || 0;\r\n return new Date().getTime() + offset;\r\n}\r\n/**\r\n * Generate ServerValues using some variables from the repo object.\r\n */\r\nfunction repoGenerateServerValues(repo) {\r\n return generateWithValues({\r\n timestamp: repoServerTime(repo)\r\n });\r\n}\r\n/**\r\n * Called by realtime when we get new messages from the server.\r\n */\r\nfunction repoOnDataUpdate(repo, pathString, data, isMerge, tag) {\r\n // For testing.\r\n repo.dataUpdateCount++;\r\n const path = new Path(pathString);\r\n data = repo.interceptServerDataCallback_\r\n ? repo.interceptServerDataCallback_(pathString, data)\r\n : data;\r\n let events = [];\r\n if (tag) {\r\n if (isMerge) {\r\n const taggedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);\r\n }\r\n else {\r\n const taggedSnap = nodeFromJSON(data);\r\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);\r\n }\r\n }\r\n else if (isMerge) {\r\n const changedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);\r\n }\r\n else {\r\n const snap = nodeFromJSON(data);\r\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\r\n }\r\n let affectedPath = path;\r\n if (events.length > 0) {\r\n // Since we have a listener outstanding for each transaction, receiving any events\r\n // is a proxy for some change having occurred.\r\n affectedPath = repoRerunTransactions(repo, path);\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\r\n}\r\nfunction repoOnConnectStatus(repo, connectStatus) {\r\n repoUpdateInfo(repo, 'connected', connectStatus);\r\n if (connectStatus === false) {\r\n repoRunOnDisconnectEvents(repo);\r\n }\r\n}\r\nfunction repoOnServerInfoUpdate(repo, updates) {\r\n each(updates, (key, value) => {\r\n repoUpdateInfo(repo, key, value);\r\n });\r\n}\r\nfunction repoUpdateInfo(repo, pathString, value) {\r\n const path = new Path('/.info/' + pathString);\r\n const newNode = nodeFromJSON(value);\r\n repo.infoData_.updateSnapshot(path, newNode);\r\n const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n}\r\nfunction repoGetNextWriteId(repo) {\r\n return repo.nextWriteId_++;\r\n}\r\n/**\r\n * The purpose of `getValue` is to return the latest known value\r\n * satisfying `query`.\r\n *\r\n * This method will first check for in-memory cached values\r\n * belonging to active listeners. If they are found, such values\r\n * are considered to be the most up-to-date.\r\n *\r\n * If the client is not connected, this method will wait until the\r\n * repo has established a connection and then request the value for `query`.\r\n * If the client is not able to retrieve the query result for another reason,\r\n * it reports an error.\r\n *\r\n * @param query - The query to surface a value for.\r\n */\r\nfunction repoGetValue(repo, query, eventRegistration) {\r\n // Only active queries are cached. There is no persisted cache.\r\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\r\n if (cached != null) {\r\n return Promise.resolve(cached);\r\n }\r\n return repo.server_.get(query).then(payload => {\r\n const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());\r\n /**\r\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\r\n * Add an event registration,\r\n * Update data at the path,\r\n * Raise any events,\r\n * Cleanup the SyncTree\r\n */\r\n syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);\r\n let events;\r\n if (query._queryParams.loadsAllData()) {\r\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);\r\n }\r\n else {\r\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\r\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);\r\n }\r\n /*\r\n * We need to raise events in the scenario where `get()` is called at a parent path, and\r\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\r\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\r\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\r\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\r\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\r\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\r\n * ensure the corresponding child events will get fired.\r\n */\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\r\n syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);\r\n return node;\r\n }, err => {\r\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\r\n return Promise.reject(new Error(err));\r\n });\r\n}\r\nfunction repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {\r\n repoLog(repo, 'set', {\r\n path: path.toString(),\r\n value: newVal,\r\n priority: newPriority\r\n });\r\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\r\n // (b) store unresolved paths on JSON parse\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\r\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('set at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\r\n}\r\nfunction repoUpdate(repo, path, childrenToMerge, onComplete) {\r\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\r\n // Start with our existing data and merge each child into it.\r\n let empty = true;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const changedChildren = {};\r\n each(childrenToMerge, (changedKey, changedValue) => {\r\n empty = false;\r\n changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);\r\n });\r\n if (!empty) {\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('update at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n each(childrenToMerge, (changedPath) => {\r\n const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\r\n }\r\n else {\r\n log(\"update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n }\r\n}\r\n/**\r\n * Applies all of the changes stored up in the onDisconnect_ tree.\r\n */\r\nfunction repoRunOnDisconnectEvents(repo) {\r\n repoLog(repo, 'onDisconnectEvents');\r\n const serverValues = repoGenerateServerValues(repo);\r\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\r\n sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {\r\n const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);\r\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\r\n });\r\n let events = [];\r\n sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {\r\n events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n repo.onDisconnect_ = newSparseSnapshotTree();\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\r\n}\r\nfunction repoOnDisconnectCancel(repo, path, onComplete) {\r\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSet(repo, path, value, onComplete) {\r\n const newNode = nodeFromJSON(value);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {\r\n const newNode = nodeFromJSON(value, priority);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {\r\n if (isEmpty(childrenToMerge)) {\r\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n return;\r\n }\r\n repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n if (status === 'ok') {\r\n each(childrenToMerge, (childName, childNode) => {\r\n const newChildNode = nodeFromJSON(childNode);\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);\r\n });\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoAddEventCallbackForQuery(repo, query, eventRegistration) {\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {\r\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\r\n // a little bit by handling the return values anyways.\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoInterrupt(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoResume(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.resume(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoLog(repo, ...varArgs) {\r\n let prefix = '';\r\n if (repo.persistentConnection_) {\r\n prefix = repo.persistentConnection_.id + ':';\r\n }\r\n log(prefix, ...varArgs);\r\n}\r\nfunction repoCallOnCompleteCallback(repo, callback, status, errorReason) {\r\n if (callback) {\r\n exceptionGuard(() => {\r\n if (status === 'ok') {\r\n callback(null);\r\n }\r\n else {\r\n const code = (status || 'error').toUpperCase();\r\n let message = code;\r\n if (errorReason) {\r\n message += ': ' + errorReason;\r\n }\r\n const error = new Error(message);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n error.code = code;\r\n callback(error);\r\n }\r\n });\r\n }\r\n}\r\n/**\r\n * Creates a new transaction, adds it to the transactions we're tracking, and\r\n * sends it to the server if possible.\r\n *\r\n * @param path - Path at which to do transaction.\r\n * @param transactionUpdate - Update callback.\r\n * @param onComplete - Completion callback.\r\n * @param unwatcher - Function that will be called when the transaction no longer\r\n * need data updates for `path`.\r\n * @param applyLocally - Whether or not to make intermediate results visible\r\n */\r\nfunction repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {\r\n repoLog(repo, 'transaction on ' + path);\r\n // Initialize transaction.\r\n const transaction = {\r\n path,\r\n update: transactionUpdate,\r\n onComplete,\r\n // One of TransactionStatus enums.\r\n status: null,\r\n // Used when combining transactions at different locations to figure out\r\n // which one goes first.\r\n order: LUIDGenerator(),\r\n // Whether to raise local events for this transaction.\r\n applyLocally,\r\n // Count of how many times we've retried the transaction.\r\n retryCount: 0,\r\n // Function to call to clean up our .on() listener.\r\n unwatcher,\r\n // Stores why a transaction was aborted.\r\n abortReason: null,\r\n currentWriteId: null,\r\n currentInputSnapshot: null,\r\n currentOutputSnapshotRaw: null,\r\n currentOutputSnapshotResolved: null\r\n };\r\n // Run transaction initially.\r\n const currentState = repoGetLatestState(repo, path, undefined);\r\n transaction.currentInputSnapshot = currentState;\r\n const newVal = transaction.update(currentState.val());\r\n if (newVal === undefined) {\r\n // Abort transaction.\r\n transaction.unwatcher();\r\n transaction.currentOutputSnapshotRaw = null;\r\n transaction.currentOutputSnapshotResolved = null;\r\n if (transaction.onComplete) {\r\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\r\n }\r\n }\r\n else {\r\n validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\r\n // Mark as run and add to our queue.\r\n transaction.status = 0 /* TransactionStatus.RUN */;\r\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\r\n const nodeQueue = treeGetValue(queueNode) || [];\r\n nodeQueue.push(transaction);\r\n treeSetValue(queueNode, nodeQueue);\r\n // Update visibleData and raise events\r\n // Note: We intentionally raise events after updating all of our\r\n // transaction state, since the user could start new transactions from the\r\n // event callbacks.\r\n let priorityForNode;\r\n if (typeof newVal === 'object' &&\r\n newVal !== null &&\r\n contains(newVal, '.priority')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n priorityForNode = safeGet(newVal, '.priority');\r\n assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\r\n 'Priority must be a valid string, finite number, server value, or null.');\r\n }\r\n else {\r\n const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\r\n ChildrenNode.EMPTY_NODE;\r\n priorityForNode = currentNode.getPriority().val();\r\n }\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);\r\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\r\n transaction.currentOutputSnapshotResolved = newNode;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n }\r\n}\r\n/**\r\n * @param excludeSets - A specific set to exclude\r\n */\r\nfunction repoGetLatestState(repo, path, excludeSets) {\r\n return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\r\n ChildrenNode.EMPTY_NODE);\r\n}\r\n/**\r\n * Sends any already-run transactions that aren't waiting for outstanding\r\n * transactions to complete.\r\n *\r\n * Externally it's called with no arguments, but it calls itself recursively\r\n * with a particular transactionQueueTree node to recurse through the tree.\r\n *\r\n * @param node - transactionQueueTree node to start at.\r\n */\r\nfunction repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {\r\n // Before recursing, make sure any completed transactions are removed.\r\n if (!node) {\r\n repoPruneCompletedTransactionsBelowNode(repo, node);\r\n }\r\n if (treeGetValue(node)) {\r\n const queue = repoBuildTransactionQueue(repo, node);\r\n assert(queue.length > 0, 'Sending zero length transaction queue');\r\n const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);\r\n // If they're all run (and not sent), we can send them. Else, we must wait.\r\n if (allRun) {\r\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\r\n }\r\n }\r\n else if (treeHasChildren(node)) {\r\n treeForEachChild(node, childNode => {\r\n repoSendReadyTransactions(repo, childNode);\r\n });\r\n }\r\n}\r\n/**\r\n * Given a list of run transactions, send them to the server and then handle\r\n * the result (success or failure).\r\n *\r\n * @param path - The location of the queue.\r\n * @param queue - Queue of transactions under the specified location.\r\n */\r\nfunction repoSendTransactionQueue(repo, path, queue) {\r\n // Mark transactions as sent and increment retry count!\r\n const setsToIgnore = queue.map(txn => {\r\n return txn.currentWriteId;\r\n });\r\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\r\n let snapToSend = latestState;\r\n const latestHash = latestState.hash();\r\n for (let i = 0; i < queue.length; i++) {\r\n const txn = queue[i];\r\n assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');\r\n txn.status = 1 /* TransactionStatus.SENT */;\r\n txn.retryCount++;\r\n const relativePath = newRelativePath(path, txn.path);\r\n // If we've gotten to this point, the output snapshot must be defined.\r\n snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);\r\n }\r\n const dataToSend = snapToSend.val(true);\r\n const pathToSend = path;\r\n // Send the put.\r\n repo.server_.put(pathToSend.toString(), dataToSend, (status) => {\r\n repoLog(repo, 'transaction put response', {\r\n path: pathToSend.toString(),\r\n status\r\n });\r\n let events = [];\r\n if (status === 'ok') {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more\r\n // transactions or sets.\r\n const callbacks = [];\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 2 /* TransactionStatus.COMPLETED */;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));\r\n if (queue[i].onComplete) {\r\n // We never unset the output snapshot, and given that this\r\n // transaction is complete, it should be set\r\n callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));\r\n }\r\n queue[i].unwatcher();\r\n }\r\n // Now remove the completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));\r\n // There may be pending transactions that we can now send.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n // Finally, trigger onComplete callbacks.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n else {\r\n // transactions are no longer sent. Update their status appropriately.\r\n if (status === 'datastale') {\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {\r\n queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\r\n }\r\n else {\r\n queue[i].status = 0 /* TransactionStatus.RUN */;\r\n }\r\n }\r\n }\r\n else {\r\n warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\r\n queue[i].abortReason = status;\r\n }\r\n }\r\n repoRerunTransactions(repo, path);\r\n }\r\n }, latestHash);\r\n}\r\n/**\r\n * Finds all transactions dependent on the data at changedPath and reruns them.\r\n *\r\n * Should be called any time cached data changes.\r\n *\r\n * Return the highest path that was affected by rerunning transactions. This\r\n * is the path at which events need to be raised for.\r\n *\r\n * @param changedPath - The path in mergedData that changed.\r\n * @returns The rootmost path that was affected by rerunning transactions.\r\n */\r\nfunction repoRerunTransactions(repo, changedPath) {\r\n const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);\r\n const path = treeGetPath(rootMostTransactionNode);\r\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\r\n repoRerunTransactionQueue(repo, queue, path);\r\n return path;\r\n}\r\n/**\r\n * Does all the work of rerunning transactions (as well as cleans up aborted\r\n * transactions and whatnot).\r\n *\r\n * @param queue - The queue of transactions to run.\r\n * @param path - The path the queue is for.\r\n */\r\nfunction repoRerunTransactionQueue(repo, queue, path) {\r\n if (queue.length === 0) {\r\n return; // Nothing to do!\r\n }\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions or\r\n // sets.\r\n const callbacks = [];\r\n let events = [];\r\n // Ignore all of the sets we're going to re-run.\r\n const txnsToRerun = queue.filter(q => {\r\n return q.status === 0 /* TransactionStatus.RUN */;\r\n });\r\n const setsToIgnore = txnsToRerun.map(q => {\r\n return q.currentWriteId;\r\n });\r\n for (let i = 0; i < queue.length; i++) {\r\n const transaction = queue[i];\r\n const relativePath = newRelativePath(path, transaction.path);\r\n let abortTransaction = false, abortReason;\r\n assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\r\n if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {\r\n abortTransaction = true;\r\n abortReason = transaction.abortReason;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else if (transaction.status === 0 /* TransactionStatus.RUN */) {\r\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\r\n abortTransaction = true;\r\n abortReason = 'maxretry';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else {\r\n // This code reruns a transaction\r\n const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);\r\n transaction.currentInputSnapshot = currentNode;\r\n const newData = queue[i].update(currentNode.val());\r\n if (newData !== undefined) {\r\n validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\r\n let newDataNode = nodeFromJSON(newData);\r\n const hasExplicitPriority = typeof newData === 'object' &&\r\n newData != null &&\r\n contains(newData, '.priority');\r\n if (!hasExplicitPriority) {\r\n // Keep the old priority if there wasn't a priority explicitly specified.\r\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\r\n }\r\n const oldWriteId = transaction.currentWriteId;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);\r\n transaction.currentOutputSnapshotRaw = newDataNode;\r\n transaction.currentOutputSnapshotResolved = newNodeResolved;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n // Mutates setsToIgnore in place\r\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\r\n events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));\r\n }\r\n else {\r\n abortTransaction = true;\r\n abortReason = 'nodata';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n }\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n events = [];\r\n if (abortTransaction) {\r\n // Abort.\r\n queue[i].status = 2 /* TransactionStatus.COMPLETED */;\r\n // Removing a listener can trigger pruning which can muck with\r\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\r\n // until we're done.\r\n (function (unwatcher) {\r\n setTimeout(unwatcher, Math.floor(0));\r\n })(queue[i].unwatcher);\r\n if (queue[i].onComplete) {\r\n if (abortReason === 'nodata') {\r\n callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));\r\n }\r\n else {\r\n callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));\r\n }\r\n }\r\n }\r\n }\r\n // Clean up completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\r\n // Now fire callbacks, now that we're in a good, known state.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n // Try to send the transaction result to the server.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n}\r\n/**\r\n * Returns the rootmost ancestor node of the specified path that has a pending\r\n * transaction on it, or just returns the node for the given path if there are\r\n * no pending transactions on any ancestor.\r\n *\r\n * @param path - The location to start at.\r\n * @returns The rootmost node with a transaction.\r\n */\r\nfunction repoGetAncestorTransactionNode(repo, path) {\r\n let front;\r\n // Start at the root and walk deeper into the tree towards path until we\r\n // find a node with pending transactions.\r\n let transactionNode = repo.transactionQueueTree_;\r\n front = pathGetFront(path);\r\n while (front !== null && treeGetValue(transactionNode) === undefined) {\r\n transactionNode = treeSubTree(transactionNode, front);\r\n path = pathPopFront(path);\r\n front = pathGetFront(path);\r\n }\r\n return transactionNode;\r\n}\r\n/**\r\n * Builds the queue of all transactions at or below the specified\r\n * transactionNode.\r\n *\r\n * @param transactionNode\r\n * @returns The generated queue.\r\n */\r\nfunction repoBuildTransactionQueue(repo, transactionNode) {\r\n // Walk any child transaction queues and aggregate them into a single queue.\r\n const transactionQueue = [];\r\n repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);\r\n // Sort them by the order the transactions were created.\r\n transactionQueue.sort((a, b) => a.order - b.order);\r\n return transactionQueue;\r\n}\r\nfunction repoAggregateTransactionQueuesForNode(repo, node, queue) {\r\n const nodeQueue = treeGetValue(node);\r\n if (nodeQueue) {\r\n for (let i = 0; i < nodeQueue.length; i++) {\r\n queue.push(nodeQueue[i]);\r\n }\r\n }\r\n treeForEachChild(node, child => {\r\n repoAggregateTransactionQueuesForNode(repo, child, queue);\r\n });\r\n}\r\n/**\r\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\r\n */\r\nfunction repoPruneCompletedTransactionsBelowNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n let to = 0;\r\n for (let from = 0; from < queue.length; from++) {\r\n if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {\r\n queue[to] = queue[from];\r\n to++;\r\n }\r\n }\r\n queue.length = to;\r\n treeSetValue(node, queue.length > 0 ? queue : undefined);\r\n }\r\n treeForEachChild(node, childNode => {\r\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\r\n });\r\n}\r\n/**\r\n * Aborts all transactions on ancestors or descendants of the specified path.\r\n * Called when doing a set() or update() since we consider them incompatible\r\n * with transactions.\r\n *\r\n * @param path - Path for which we want to abort related transactions.\r\n */\r\nfunction repoAbortTransactions(repo, path) {\r\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\r\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\r\n treeForEachAncestor(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n repoAbortTransactionsOnNode(repo, transactionNode);\r\n treeForEachDescendant(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n return affectedPath;\r\n}\r\n/**\r\n * Abort transactions stored in this transaction queue node.\r\n *\r\n * @param node - Node to abort transactions for.\r\n */\r\nfunction repoAbortTransactionsOnNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions\r\n // or sets.\r\n const callbacks = [];\r\n // Go through queue. Any already-sent transactions must be marked for\r\n // abort, while the unsent ones can be immediately aborted and removed.\r\n let events = [];\r\n let lastSent = -1;\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;\r\n else if (queue[i].status === 1 /* TransactionStatus.SENT */) {\r\n assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\r\n lastSent = i;\r\n // Mark transaction for abort when it comes back.\r\n queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;\r\n queue[i].abortReason = 'set';\r\n }\r\n else {\r\n assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');\r\n // We can abort it immediately.\r\n queue[i].unwatcher();\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));\r\n if (queue[i].onComplete) {\r\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));\r\n }\r\n }\r\n }\r\n if (lastSent === -1) {\r\n // We're not waiting for any sent transactions. We can clear the queue.\r\n treeSetValue(node, undefined);\r\n }\r\n else {\r\n // Remove the transactions we aborted.\r\n queue.length = lastSent + 1;\r\n }\r\n // Now fire the callbacks.\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction decodePath(pathString) {\r\n let pathStringDecoded = '';\r\n const pieces = pathString.split('/');\r\n for (let i = 0; i < pieces.length; i++) {\r\n if (pieces[i].length > 0) {\r\n let piece = pieces[i];\r\n try {\r\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\r\n }\r\n catch (e) { }\r\n pathStringDecoded += '/' + piece;\r\n }\r\n }\r\n return pathStringDecoded;\r\n}\r\n/**\r\n * @returns key value hash\r\n */\r\nfunction decodeQuery(queryString) {\r\n const results = {};\r\n if (queryString.charAt(0) === '?') {\r\n queryString = queryString.substring(1);\r\n }\r\n for (const segment of queryString.split('&')) {\r\n if (segment.length === 0) {\r\n continue;\r\n }\r\n const kv = segment.split('=');\r\n if (kv.length === 2) {\r\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\r\n }\r\n else {\r\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\r\n }\r\n }\r\n return results;\r\n}\r\nconst parseRepoInfo = function (dataURL, nodeAdmin) {\r\n const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;\r\n if (parsedUrl.domain === 'firebase.com') {\r\n fatal(parsedUrl.host +\r\n ' is no longer supported. ' +\r\n 'Please use .firebaseio.com instead');\r\n }\r\n // Catch common error of uninitialized namespace value.\r\n if ((!namespace || namespace === 'undefined') &&\r\n parsedUrl.domain !== 'localhost') {\r\n fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\r\n }\r\n if (!parsedUrl.secure) {\r\n warnIfPageIsSecure();\r\n }\r\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\r\n return {\r\n repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, \r\n /*persistenceKey=*/ '', \r\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),\r\n path: new Path(parsedUrl.pathString)\r\n };\r\n};\r\nconst parseDatabaseURL = function (dataURL) {\r\n // Default to empty strings in the event of a malformed string.\r\n let host = '', domain = '', subdomain = '', pathString = '', namespace = '';\r\n // Always default to SSL, unless otherwise specified.\r\n let secure = true, scheme = 'https', port = 443;\r\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\r\n if (typeof dataURL === 'string') {\r\n // Parse scheme.\r\n let colonInd = dataURL.indexOf('//');\r\n if (colonInd >= 0) {\r\n scheme = dataURL.substring(0, colonInd - 1);\r\n dataURL = dataURL.substring(colonInd + 2);\r\n }\r\n // Parse host, path, and query string.\r\n let slashInd = dataURL.indexOf('/');\r\n if (slashInd === -1) {\r\n slashInd = dataURL.length;\r\n }\r\n let questionMarkInd = dataURL.indexOf('?');\r\n if (questionMarkInd === -1) {\r\n questionMarkInd = dataURL.length;\r\n }\r\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\r\n if (slashInd < questionMarkInd) {\r\n // For pathString, questionMarkInd will always come after slashInd\r\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\r\n }\r\n const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\r\n // If we have a port, use scheme for determining if it's secure.\r\n colonInd = host.indexOf(':');\r\n if (colonInd >= 0) {\r\n secure = scheme === 'https' || scheme === 'wss';\r\n port = parseInt(host.substring(colonInd + 1), 10);\r\n }\r\n else {\r\n colonInd = host.length;\r\n }\r\n const hostWithoutPort = host.slice(0, colonInd);\r\n if (hostWithoutPort.toLowerCase() === 'localhost') {\r\n domain = 'localhost';\r\n }\r\n else if (hostWithoutPort.split('.').length <= 2) {\r\n domain = hostWithoutPort;\r\n }\r\n else {\r\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\r\n const dotInd = host.indexOf('.');\r\n subdomain = host.substring(0, dotInd).toLowerCase();\r\n domain = host.substring(dotInd + 1);\r\n // Normalize namespaces to lowercase to share storage / connection.\r\n namespace = subdomain;\r\n }\r\n // Always treat the value of the `ns` as the namespace name if it is present.\r\n if ('ns' in queryParams) {\r\n namespace = queryParams['ns'];\r\n }\r\n }\r\n return {\r\n host,\r\n port,\r\n domain,\r\n subdomain,\r\n secure,\r\n scheme,\r\n pathString,\r\n namespace\r\n };\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Modeled after base64 web-safe chars, but ordered by ASCII.\r\nconst PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\r\n/**\r\n * Fancy ID generator that creates 20-character string identifiers with the\r\n * following properties:\r\n *\r\n * 1. They're based on timestamp so that they sort *after* any existing ids.\r\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\r\n * collide with other clients' IDs.\r\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\r\n * that will sort properly).\r\n * 4. They're monotonically increasing. Even if you generate more than one in\r\n * the same timestamp, the latter ones will sort after the former ones. We do\r\n * this by using the previous random bits but \"incrementing\" them by 1 (only\r\n * in the case of a timestamp collision).\r\n */\r\nconst nextPushId = (function () {\r\n // Timestamp of last push, used to prevent local collisions if you push twice\r\n // in one ms.\r\n let lastPushTime = 0;\r\n // We generate 72-bits of randomness which get turned into 12 characters and\r\n // appended to the timestamp to prevent collisions with other clients. We\r\n // store the last characters we generated because in the event of a collision,\r\n // we'll use those same characters except \"incremented\" by one.\r\n const lastRandChars = [];\r\n return function (now) {\r\n const duplicateTime = now === lastPushTime;\r\n lastPushTime = now;\r\n let i;\r\n const timeStampChars = new Array(8);\r\n for (i = 7; i >= 0; i--) {\r\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\r\n // NOTE: Can't use << here because javascript will convert to int and lose\r\n // the upper bits.\r\n now = Math.floor(now / 64);\r\n }\r\n assert(now === 0, 'Cannot push at time == 0');\r\n let id = timeStampChars.join('');\r\n if (!duplicateTime) {\r\n for (i = 0; i < 12; i++) {\r\n lastRandChars[i] = Math.floor(Math.random() * 64);\r\n }\r\n }\r\n else {\r\n // If the timestamp hasn't changed since last push, use the same random\r\n // number, except incremented by 1.\r\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\r\n lastRandChars[i] = 0;\r\n }\r\n lastRandChars[i]++;\r\n }\r\n for (i = 0; i < 12; i++) {\r\n id += PUSH_CHARS.charAt(lastRandChars[i]);\r\n }\r\n assert(id.length === 20, 'nextPushId: Length should be 20.');\r\n return id;\r\n };\r\n})();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Encapsulates the data needed to raise an event\r\n */\r\nclass DataEvent {\r\n /**\r\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\r\n * @param eventRegistration - The function to call to with the event data. User provided\r\n * @param snapshot - The data backing the event\r\n * @param prevName - Optional, the name of the previous child for child_* events.\r\n */\r\n constructor(eventType, eventRegistration, snapshot, prevName) {\r\n this.eventType = eventType;\r\n this.eventRegistration = eventRegistration;\r\n this.snapshot = snapshot;\r\n this.prevName = prevName;\r\n }\r\n getPath() {\r\n const ref = this.snapshot.ref;\r\n if (this.eventType === 'value') {\r\n return ref._path;\r\n }\r\n else {\r\n return ref.parent._path;\r\n }\r\n }\r\n getEventType() {\r\n return this.eventType;\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return (this.getPath().toString() +\r\n ':' +\r\n this.eventType +\r\n ':' +\r\n stringify(this.snapshot.exportVal()));\r\n }\r\n}\r\nclass CancelEvent {\r\n constructor(eventRegistration, error, path) {\r\n this.eventRegistration = eventRegistration;\r\n this.error = error;\r\n this.path = path;\r\n }\r\n getPath() {\r\n return this.path;\r\n }\r\n getEventType() {\r\n return 'cancel';\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return this.path.toString() + ':cancel';\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A wrapper class that converts events from the database@exp SDK to the legacy\r\n * Database SDK. Events are not converted directly as event registration relies\r\n * on reference comparison of the original user callback (see `matches()`) and\r\n * relies on equality of the legacy SDK's `context` object.\r\n */\r\nclass CallbackContext {\r\n constructor(snapshotCallback, cancelCallback) {\r\n this.snapshotCallback = snapshotCallback;\r\n this.cancelCallback = cancelCallback;\r\n }\r\n onValue(expDataSnapshot, previousChildName) {\r\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\r\n }\r\n onCancel(error) {\r\n assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');\r\n return this.cancelCallback.call(null, error);\r\n }\r\n get hasCancelCallback() {\r\n return !!this.cancelCallback;\r\n }\r\n matches(other) {\r\n return (this.snapshotCallback === other.snapshotCallback ||\r\n (this.snapshotCallback.userCallback !== undefined &&\r\n this.snapshotCallback.userCallback ===\r\n other.snapshotCallback.userCallback &&\r\n this.snapshotCallback.context === other.snapshotCallback.context));\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The `onDisconnect` class allows you to write or clear data when your client\r\n * disconnects from the Database server. These updates occur whether your\r\n * client disconnects cleanly or not, so you can rely on them to clean up data\r\n * even if a connection is dropped or a client crashes.\r\n *\r\n * The `onDisconnect` class is most commonly used to manage presence in\r\n * applications where it is useful to detect how many clients are connected and\r\n * when other clients disconnect. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * To avoid problems when a connection is dropped before the requests can be\r\n * transferred to the Database server, these functions should be called before\r\n * writing any data.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time you reconnect.\r\n */\r\nclass OnDisconnect {\r\n /** @hideconstructor */\r\n constructor(_repo, _path) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n }\r\n /**\r\n * Cancels all previously queued `onDisconnect()` set or update events for this\r\n * location and all children.\r\n *\r\n * If a write has been queued for this location via a `set()` or `update()` at a\r\n * parent location, the write at this location will be canceled, though writes\r\n * to sibling locations will still occur.\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n cancel() {\r\n const deferred = new Deferred();\r\n repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is deleted when the client is disconnected\r\n * (due to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n remove() {\r\n validateWritablePath('OnDisconnect.remove', this._path);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value when the\r\n * client is disconnected (due to closing the browser, navigating to a new page,\r\n * or network issues).\r\n *\r\n * `set()` is especially useful for implementing \"presence\" systems, where a\r\n * value should be changed or cleared when a user disconnects so that they\r\n * appear \"offline\" to other users. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time.\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n set(value) {\r\n validateWritablePath('OnDisconnect.set', this._path);\r\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value and priority\r\n * when the client is disconnected (due to closing the browser, navigating to a\r\n * new page, or network issues).\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n setWithPriority(value, priority) {\r\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\r\n validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);\r\n validatePriority('OnDisconnect.setWithPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Writes multiple values at this location when the client is disconnected (due\r\n * to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\r\n * from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n update(values) {\r\n validateWritablePath('OnDisconnect.update', this._path);\r\n validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nclass QueryImpl {\r\n /**\r\n * @hideconstructor\r\n */\r\n constructor(_repo, _path, _queryParams, _orderByCalled) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n this._queryParams = _queryParams;\r\n this._orderByCalled = _orderByCalled;\r\n }\r\n get key() {\r\n if (pathIsEmpty(this._path)) {\r\n return null;\r\n }\r\n else {\r\n return pathGetBack(this._path);\r\n }\r\n }\r\n get ref() {\r\n return new ReferenceImpl(this._repo, this._path);\r\n }\r\n get _queryIdentifier() {\r\n const obj = queryParamsGetQueryObject(this._queryParams);\r\n const id = ObjectToUniqueKey(obj);\r\n return id === '{}' ? 'default' : id;\r\n }\r\n /**\r\n * An object representation of the query parameters used by this Query.\r\n */\r\n get _queryObject() {\r\n return queryParamsGetQueryObject(this._queryParams);\r\n }\r\n isEqual(other) {\r\n other = getModularInstance(other);\r\n if (!(other instanceof QueryImpl)) {\r\n return false;\r\n }\r\n const sameRepo = this._repo === other._repo;\r\n const samePath = pathEquals(this._path, other._path);\r\n const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;\r\n return sameRepo && samePath && sameQueryIdentifier;\r\n }\r\n toJSON() {\r\n return this.toString();\r\n }\r\n toString() {\r\n return this._repo.toString() + pathToUrlEncodedString(this._path);\r\n }\r\n}\r\n/**\r\n * Validates that no other order by call has been made\r\n */\r\nfunction validateNoPreviousOrderByCall(query, fnName) {\r\n if (query._orderByCalled === true) {\r\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\r\n }\r\n}\r\n/**\r\n * Validates start/end values for queries.\r\n */\r\nfunction validateQueryEndpoints(params) {\r\n let startNode = null;\r\n let endNode = null;\r\n if (params.hasStart()) {\r\n startNode = params.getIndexStartValue();\r\n }\r\n if (params.hasEnd()) {\r\n endNode = params.getIndexEndValue();\r\n }\r\n if (params.getIndex() === KEY_INDEX) {\r\n const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\r\n 'startAt(), endAt(), or equalTo().';\r\n const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\r\n 'endAt(), endBefore(), or equalTo() must be a string.';\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n if (startName !== MIN_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof startNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n if (endName !== MAX_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof endNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n }\r\n else if (params.getIndex() === PRIORITY_INDEX) {\r\n if ((startNode != null && !isValidPriority(startNode)) ||\r\n (endNode != null && !isValidPriority(endNode))) {\r\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\r\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\r\n '(null, a number, or a string).');\r\n }\r\n }\r\n else {\r\n assert(params.getIndex() instanceof PathIndex ||\r\n params.getIndex() === VALUE_INDEX, 'unknown index type.');\r\n if ((startNode != null && typeof startNode === 'object') ||\r\n (endNode != null && typeof endNode === 'object')) {\r\n throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\r\n 'equalTo() cannot be an object.');\r\n }\r\n }\r\n}\r\n/**\r\n * Validates that limit* has been called with the correct combination of parameters\r\n */\r\nfunction validateLimit(params) {\r\n if (params.hasStart() &&\r\n params.hasEnd() &&\r\n params.hasLimit() &&\r\n !params.hasAnchoredLimit()) {\r\n throw new Error(\"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\r\n 'limitToFirst() or limitToLast() instead.');\r\n }\r\n}\r\n/**\r\n * @internal\r\n */\r\nclass ReferenceImpl extends QueryImpl {\r\n /** @hideconstructor */\r\n constructor(repo, path) {\r\n super(repo, path, new QueryParams(), false);\r\n }\r\n get parent() {\r\n const parentPath = pathParent(this._path);\r\n return parentPath === null\r\n ? null\r\n : new ReferenceImpl(this._repo, parentPath);\r\n }\r\n get root() {\r\n let ref = this;\r\n while (ref.parent !== null) {\r\n ref = ref.parent;\r\n }\r\n return ref;\r\n }\r\n}\r\n/**\r\n * A `DataSnapshot` contains data from a Database location.\r\n *\r\n * Any time you read data from the Database, you receive the data as a\r\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\r\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\r\n * JavaScript object by calling the `val()` method. Alternatively, you can\r\n * traverse into the snapshot by calling `child()` to return child snapshots\r\n * (which you could then call `val()` on).\r\n *\r\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\r\n * a Database location. It cannot be modified and will never change (to modify\r\n * data, you always call the `set()` method on a `Reference` directly).\r\n */\r\nclass DataSnapshot {\r\n /**\r\n * @param _node - A SnapshotNode to wrap.\r\n * @param ref - The location this snapshot came from.\r\n * @param _index - The iteration order for this snapshot\r\n * @hideconstructor\r\n */\r\n constructor(_node, \r\n /**\r\n * The location of this DataSnapshot.\r\n */\r\n ref, _index) {\r\n this._node = _node;\r\n this.ref = ref;\r\n this._index = _index;\r\n }\r\n /**\r\n * Gets the priority value of the data in this `DataSnapshot`.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\r\n * ).\r\n */\r\n get priority() {\r\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\r\n return this._node.getPriority().val();\r\n }\r\n /**\r\n * The key (last part of the path) of the location of this `DataSnapshot`.\r\n *\r\n * The last token in a Database location is considered its key. For example,\r\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\r\n * `DataSnapshot` will return the key for the location that generated it.\r\n * However, accessing the key on the root URL of a Database will return\r\n * `null`.\r\n */\r\n get key() {\r\n return this.ref.key;\r\n }\r\n /** Returns the number of child properties of this `DataSnapshot`. */\r\n get size() {\r\n return this._node.numChildren();\r\n }\r\n /**\r\n * Gets another `DataSnapshot` for the location at the specified relative path.\r\n *\r\n * Passing a relative path to the `child()` method of a DataSnapshot returns\r\n * another `DataSnapshot` for the location at the specified relative path. The\r\n * relative path can either be a simple child name (for example, \"ada\") or a\r\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\r\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\r\n * whose value is `null`) is returned.\r\n *\r\n * @param path - A relative path to the location of child data.\r\n */\r\n child(path) {\r\n const childPath = new Path(path);\r\n const childRef = child(this.ref, path);\r\n return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);\r\n }\r\n /**\r\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\r\n * efficient than using `snapshot.val() !== null`.\r\n */\r\n exists() {\r\n return !this._node.isEmpty();\r\n }\r\n /**\r\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\r\n *\r\n * The `exportVal()` method is similar to `val()`, except priority information\r\n * is included (if available), making it suitable for backing up your data.\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n exportVal() {\r\n return this._node.val(true);\r\n }\r\n /**\r\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\r\n *\r\n * Because of the way JavaScript objects work, the ordering of data in the\r\n * JavaScript object returned by `val()` is not guaranteed to match the\r\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\r\n * where `forEach()` comes in handy. It guarantees the children of a\r\n * `DataSnapshot` will be iterated in their query order.\r\n *\r\n * If no explicit `orderBy*()` method is used, results are returned\r\n * ordered by key (unless priorities are used, in which case, results are\r\n * returned by priority).\r\n *\r\n * @param action - A function that will be called for each child DataSnapshot.\r\n * The callback can return true to cancel further enumeration.\r\n * @returns true if enumeration was canceled due to your callback returning\r\n * true.\r\n */\r\n forEach(action) {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n const childrenNode = this._node;\r\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\r\n return !!childrenNode.forEachChild(this._index, (key, node) => {\r\n return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));\r\n });\r\n }\r\n /**\r\n * Returns true if the specified child path has (non-null) data.\r\n *\r\n * @param path - A relative path to the location of a potential child.\r\n * @returns `true` if data exists at the specified child path; else\r\n * `false`.\r\n */\r\n hasChild(path) {\r\n const childPath = new Path(path);\r\n return !this._node.getChild(childPath).isEmpty();\r\n }\r\n /**\r\n * Returns whether or not the `DataSnapshot` has any non-`null` child\r\n * properties.\r\n *\r\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\r\n * children. If it does, you can enumerate them using `forEach()`. If it\r\n * doesn't, then either this snapshot contains a primitive value (which can be\r\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\r\n * `null`).\r\n *\r\n * @returns true if this snapshot has any children; else false.\r\n */\r\n hasChildren() {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n return !this._node.isEmpty();\r\n }\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return this.exportVal();\r\n }\r\n /**\r\n * Extracts a JavaScript value from a `DataSnapshot`.\r\n *\r\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\r\n * scalar type (string, number, or boolean), an array, or an object. It may\r\n * also return null, indicating that the `DataSnapshot` is empty (contains no\r\n * data).\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n val() {\r\n return this._node.val();\r\n }\r\n}\r\n/**\r\n *\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided path. If no path is provided, the `Reference`\r\n * will point to the root of the Database.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param path - Optional path representing the location the returned\r\n * `Reference` will point. If not provided, the returned `Reference` will\r\n * point to the root of the Database.\r\n * @returns If a path is provided, a `Reference`\r\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\r\n * root of the Database.\r\n */\r\nfunction ref(db, path) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('ref');\r\n return path !== undefined ? child(db._root, path) : db._root;\r\n}\r\n/**\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided Firebase URL.\r\n *\r\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\r\n * has a different domain than the current `Database` instance.\r\n *\r\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\r\n * and are not applied to the returned `Reference`.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param url - The Firebase URL at which the returned `Reference` will\r\n * point.\r\n * @returns A `Reference` pointing to the provided\r\n * Firebase URL.\r\n */\r\nfunction refFromURL(db, url) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('refFromURL');\r\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\r\n validateUrl('refFromURL', parsedURL);\r\n const repoInfo = parsedURL.repoInfo;\r\n if (!db._repo.repoInfo_.isCustomHost() &&\r\n repoInfo.host !== db._repo.repoInfo_.host) {\r\n fatal('refFromURL' +\r\n ': Host name does not match the current database: ' +\r\n '(found ' +\r\n repoInfo.host +\r\n ' but expected ' +\r\n db._repo.repoInfo_.host +\r\n ')');\r\n }\r\n return ref(db, parsedURL.path.toString());\r\n}\r\n/**\r\n * Gets a `Reference` for the location at the specified relative path.\r\n *\r\n * The relative path can either be a simple child name (for example, \"ada\") or\r\n * a deeper slash-separated path (for example, \"ada/name/first\").\r\n *\r\n * @param parent - The parent location.\r\n * @param path - A relative path from this location to the desired child\r\n * location.\r\n * @returns The specified child location.\r\n */\r\nfunction child(parent, path) {\r\n parent = getModularInstance(parent);\r\n if (pathGetFront(parent._path) === null) {\r\n validateRootPathString('child', 'path', path, false);\r\n }\r\n else {\r\n validatePathString('child', 'path', path, false);\r\n }\r\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\r\n}\r\n/**\r\n * Returns an `OnDisconnect` object - see\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information on how to use it.\r\n *\r\n * @param ref - The reference to add OnDisconnect triggers for.\r\n */\r\nfunction onDisconnect(ref) {\r\n ref = getModularInstance(ref);\r\n return new OnDisconnect(ref._repo, ref._path);\r\n}\r\n/**\r\n * Generates a new child location using a unique key and returns its\r\n * `Reference`.\r\n *\r\n * This is the most common pattern for adding data to a collection of items.\r\n *\r\n * If you provide a value to `push()`, the value is written to the\r\n * generated location. If you don't pass a value, nothing is written to the\r\n * database and the child remains empty (but you can use the `Reference`\r\n * elsewhere).\r\n *\r\n * The unique keys generated by `push()` are ordered by the current time, so the\r\n * resulting list of items is chronologically sorted. The keys are also\r\n * designed to be unguessable (they contain 72 random bits of entropy).\r\n *\r\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\r\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\r\n *\r\n * @param parent - The parent location.\r\n * @param value - Optional value to be written at the generated location.\r\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\r\n * but can be used immediately as the `Reference` to the child location.\r\n */\r\nfunction push(parent, value) {\r\n parent = getModularInstance(parent);\r\n validateWritablePath('push', parent._path);\r\n validateFirebaseDataArg('push', value, parent._path, true);\r\n const now = repoServerTime(parent._repo);\r\n const name = nextPushId(now);\r\n // push() returns a ThennableReference whose promise is fulfilled with a\r\n // regular Reference. We use child() to create handles to two different\r\n // references. The first is turned into a ThennableReference below by adding\r\n // then() and catch() methods and is used as the return value of push(). The\r\n // second remains a regular Reference and is used as the fulfilled value of\r\n // the first ThennableReference.\r\n const thennablePushRef = child(parent, name);\r\n const pushRef = child(parent, name);\r\n let promise;\r\n if (value != null) {\r\n promise = set(pushRef, value).then(() => pushRef);\r\n }\r\n else {\r\n promise = Promise.resolve(pushRef);\r\n }\r\n thennablePushRef.then = promise.then.bind(promise);\r\n thennablePushRef.catch = promise.then.bind(promise, undefined);\r\n return thennablePushRef;\r\n}\r\n/**\r\n * Removes the data at this Database location.\r\n *\r\n * Any data at child locations will also be deleted.\r\n *\r\n * The effect of the remove will be visible immediately and the corresponding\r\n * event 'value' will be triggered. Synchronization of the remove to the\r\n * Firebase servers will also be started, and the returned Promise will resolve\r\n * when complete. If provided, the onComplete callback will be called\r\n * asynchronously after synchronization has finished.\r\n *\r\n * @param ref - The location to remove.\r\n * @returns Resolves when remove on server is complete.\r\n */\r\nfunction remove(ref) {\r\n validateWritablePath('remove', ref._path);\r\n return set(ref, null);\r\n}\r\n/**\r\n * Writes data to this Database location.\r\n *\r\n * This will overwrite any data at this location and all child locations.\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\r\n * all data at this location and all child locations will be deleted.\r\n *\r\n * `set()` will remove any priority stored at this location, so if priority is\r\n * meant to be preserved, you need to use `setWithPriority()` instead.\r\n *\r\n * Note that modifying data with `set()` will cancel any pending transactions\r\n * at that location, so extreme care should be taken if mixing `set()` and\r\n * `transaction()` to modify the same data.\r\n *\r\n * A single `set()` will generate a single \"value\" event at the location where\r\n * the `set()` was performed.\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction set(ref, value) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('set', ref._path);\r\n validateFirebaseDataArg('set', value, ref._path, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, \r\n /*priority=*/ null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Sets a priority for the data at this Database location.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setPriority(ref, priority) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('setPriority', ref._path);\r\n validatePriority('setPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes data the Database location. Like `set()` but also specifies the\r\n * priority for that data.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setWithPriority(ref, value, priority) {\r\n validateWritablePath('setWithPriority', ref._path);\r\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\r\n validatePriority('setWithPriority', priority, false);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\r\n }\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes multiple values to the Database at once.\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example,\r\n * \"name/first\") from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * A single `update()` will generate a single \"value\" event at the location\r\n * where the `update()` was performed, regardless of how many children were\r\n * modified.\r\n *\r\n * Note that modifying data with `update()` will cancel any pending\r\n * transactions at that location, so extreme care should be taken if mixing\r\n * `update()` and `transaction()` to modify the same data.\r\n *\r\n * Passing `null` to `update()` will remove the data at this location.\r\n *\r\n * See\r\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\r\n *\r\n * @param ref - The location to write to.\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when update on server is complete.\r\n */\r\nfunction update(ref, values) {\r\n validateFirebaseMergeDataArg('update', values, ref._path, false);\r\n const deferred = new Deferred();\r\n repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Gets the most up-to-date result for this query.\r\n *\r\n * @param query - The query to run.\r\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\r\n * available, or rejects if the client is unable to return a value (e.g., if the\r\n * server is unreachable and there is nothing cached).\r\n */\r\nfunction get(query) {\r\n query = getModularInstance(query);\r\n const callbackContext = new CallbackContext(() => { });\r\n const container = new ValueEventRegistration(callbackContext);\r\n return repoGetValue(query._repo, query, container).then(node => {\r\n return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());\r\n });\r\n}\r\n/**\r\n * Represents registration for 'value' events.\r\n */\r\nclass ValueEventRegistration {\r\n constructor(callbackContext) {\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n return eventType === 'value';\r\n }\r\n createEvent(change, query) {\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, null);\r\n }\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n matches(other) {\r\n if (!(other instanceof ValueEventRegistration)) {\r\n return false;\r\n }\r\n else if (!other.callbackContext || !this.callbackContext) {\r\n // If no callback specified, we consider it to match any callback.\r\n return true;\r\n }\r\n else {\r\n return other.callbackContext.matches(this.callbackContext);\r\n }\r\n }\r\n hasAnyCallback() {\r\n return this.callbackContext !== null;\r\n }\r\n}\r\n/**\r\n * Represents the registration of a child_x event.\r\n */\r\nclass ChildEventRegistration {\r\n constructor(eventType, callbackContext) {\r\n this.eventType = eventType;\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\r\n eventToCheck =\r\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\r\n return this.eventType === eventToCheck;\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n createEvent(change, query) {\r\n assert(change.childName != null, 'Child events should have a childName.');\r\n const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);\r\n }\r\n }\r\n matches(other) {\r\n if (other instanceof ChildEventRegistration) {\r\n return (this.eventType === other.eventType &&\r\n (!this.callbackContext ||\r\n !other.callbackContext ||\r\n this.callbackContext.matches(other.callbackContext)));\r\n }\r\n return false;\r\n }\r\n hasAnyCallback() {\r\n return !!this.callbackContext;\r\n }\r\n}\r\nfunction addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {\r\n let cancelCallback;\r\n if (typeof cancelCallbackOrListenOptions === 'object') {\r\n cancelCallback = undefined;\r\n options = cancelCallbackOrListenOptions;\r\n }\r\n if (typeof cancelCallbackOrListenOptions === 'function') {\r\n cancelCallback = cancelCallbackOrListenOptions;\r\n }\r\n if (options && options.onlyOnce) {\r\n const userCallback = callback;\r\n const onceCallback = (dataSnapshot, previousChildName) => {\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n userCallback(dataSnapshot, previousChildName);\r\n };\r\n onceCallback.userCallback = callback.userCallback;\r\n onceCallback.context = callback.context;\r\n callback = onceCallback;\r\n }\r\n const callbackContext = new CallbackContext(callback, cancelCallback || undefined);\r\n const container = eventType === 'value'\r\n ? new ValueEventRegistration(callbackContext)\r\n : new ChildEventRegistration(eventType, callbackContext);\r\n repoAddEventCallbackForQuery(query._repo, query, container);\r\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\nfunction onValue(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\n/**\r\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\r\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\r\n * the respective `on*` callbacks.\r\n *\r\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\r\n * will not automatically remove listeners registered on child nodes, `off()`\r\n * must also be called on any child listeners to remove the callback.\r\n *\r\n * If a callback is not specified, all callbacks for the specified eventType\r\n * will be removed. Similarly, if no eventType is specified, all callbacks\r\n * for the `Reference` will be removed.\r\n *\r\n * Individual listeners can also be removed by invoking their unsubscribe\r\n * callbacks.\r\n *\r\n * @param query - The query that the listener was registered with.\r\n * @param eventType - One of the following strings: \"value\", \"child_added\",\r\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\r\n * for the `Reference` will be removed.\r\n * @param callback - The callback function that was passed to `on()` or\r\n * `undefined` to remove all callbacks.\r\n */\r\nfunction off(query, eventType, callback) {\r\n let container = null;\r\n const expCallback = callback ? new CallbackContext(callback) : null;\r\n if (eventType === 'value') {\r\n container = new ValueEventRegistration(expCallback);\r\n }\r\n else if (eventType) {\r\n container = new ChildEventRegistration(eventType, expCallback);\r\n }\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\n/**\r\n * A `QueryConstraint` is used to narrow the set of documents returned by a\r\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\r\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\r\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\r\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\r\n * {@link orderByValue} or {@link equalTo} and\r\n * can then be passed to {@link query} to create a new query instance that\r\n * also contains this `QueryConstraint`.\r\n */\r\nclass QueryConstraint {\r\n}\r\nclass QueryEndAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'endAt';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endAt', this._value, query._path, true);\r\n const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endAt: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name less than or equal\r\n * to the specified key.\r\n *\r\n * You can read more about `endAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to end at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end at, among the children with the previously\r\n * specified priority. This argument is only allowed if ordering by child,\r\n * value, or priority.\r\n */\r\nfunction endAt(value, key) {\r\n validateKey('endAt', 'key', key, true);\r\n return new QueryEndAtConstraint(value, key);\r\n}\r\nclass QueryEndBeforeConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'endBefore';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\r\n const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is exclusive. If only a value is provided, children\r\n * with a value less than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value less than or equal\r\n * to the specified value and a key name less than the specified key.\r\n *\r\n * @param value - The value to end before. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end before, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction endBefore(value, key) {\r\n validateKey('endBefore', 'key', key, true);\r\n return new QueryEndBeforeConstraint(value, key);\r\n}\r\nclass QueryStartAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'startAt';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAt', this._value, query._path, true);\r\n const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAt: Starting point was already set (by another call to startAt, ' +\r\n 'startBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name greater than or\r\n * equal to the specified key.\r\n *\r\n * You can read more about `startAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to start at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAt(value = null, key) {\r\n validateKey('startAt', 'key', key, true);\r\n return new QueryStartAtConstraint(value, key);\r\n}\r\nclass QueryStartAfterConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'startAfter';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\r\n const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +\r\n 'startAfter, or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is exclusive. If only a value is provided, children\r\n * with a value greater than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value greater than or equal\r\n * to the specified value and a a key name greater than the specified key.\r\n *\r\n * @param value - The value to start after. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start after. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAfter(value, key) {\r\n validateKey('startAfter', 'key', key, true);\r\n return new QueryStartAfterConstraint(value, key);\r\n}\r\nclass QueryLimitToFirstConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n this.type = 'limitToFirst';\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that if limited to the first specific number\r\n * of children.\r\n *\r\n * The `limitToFirst()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the first 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToFirst()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToFirst(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToFirst: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToFirstConstraint(limit);\r\n}\r\nclass QueryLimitToLastConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n this.type = 'limitToLast';\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that is limited to return only the last\r\n * specified number of children.\r\n *\r\n * The `limitToLast()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the last 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToLast()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToLast(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToLast: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToLastConstraint(limit);\r\n}\r\nclass QueryOrderByChildConstraint extends QueryConstraint {\r\n constructor(_path) {\r\n super();\r\n this._path = _path;\r\n this.type = 'orderByChild';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByChild');\r\n const parsedPath = new Path(this._path);\r\n if (pathIsEmpty(parsedPath)) {\r\n throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');\r\n }\r\n const index = new PathIndex(parsedPath);\r\n const newParams = queryParamsOrderBy(query._queryParams, index);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the specified child key.\r\n *\r\n * Queries can only order by one key at a time. Calling `orderByChild()`\r\n * multiple times on the same query is an error.\r\n *\r\n * Firebase queries allow you to order your data by any child key on the fly.\r\n * However, if you know in advance what your indexes will be, you can define\r\n * them via the .indexOn rule in your Security Rules for better performance. See\r\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\r\n * rule for more information.\r\n *\r\n * You can read more about `orderByChild()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n *\r\n * @param path - The path to order by.\r\n */\r\nfunction orderByChild(path) {\r\n if (path === '$key') {\r\n throw new Error('orderByChild: \"$key\" is invalid. Use orderByKey() instead.');\r\n }\r\n else if (path === '$priority') {\r\n throw new Error('orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.');\r\n }\r\n else if (path === '$value') {\r\n throw new Error('orderByChild: \"$value\" is invalid. Use orderByValue() instead.');\r\n }\r\n validatePathString('orderByChild', 'path', path, false);\r\n return new QueryOrderByChildConstraint(path);\r\n}\r\nclass QueryOrderByKeyConstraint extends QueryConstraint {\r\n constructor() {\r\n super(...arguments);\r\n this.type = 'orderByKey';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByKey');\r\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the key.\r\n *\r\n * Sorts the results of a query by their (ascending) key values.\r\n *\r\n * You can read more about `orderByKey()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByKey() {\r\n return new QueryOrderByKeyConstraint();\r\n}\r\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\r\n constructor() {\r\n super(...arguments);\r\n this.type = 'orderByPriority';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByPriority');\r\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by priority.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\r\n * for alternatives to priority.\r\n */\r\nfunction orderByPriority() {\r\n return new QueryOrderByPriorityConstraint();\r\n}\r\nclass QueryOrderByValueConstraint extends QueryConstraint {\r\n constructor() {\r\n super(...arguments);\r\n this.type = 'orderByValue';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByValue');\r\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by value.\r\n *\r\n * If the children of a query are all scalar values (string, number, or\r\n * boolean), you can order the results by their (ascending) values.\r\n *\r\n * You can read more about `orderByValue()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByValue() {\r\n return new QueryOrderByValueConstraint();\r\n}\r\nclass QueryEqualToValueConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'equalTo';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\r\n 'equalTo).');\r\n }\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\r\n 'equalTo).');\r\n }\r\n return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` that includes children that match the specified\r\n * value.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The optional key argument can be used to further limit the range of the\r\n * query. If it is specified, then children that have exactly the specified\r\n * value must also have exactly the specified key as their key name. This can be\r\n * used to filter result sets with many matches for the same value.\r\n *\r\n * You can read more about `equalTo()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to match for. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction equalTo(value, key) {\r\n validateKey('equalTo', 'key', key, true);\r\n return new QueryEqualToValueConstraint(value, key);\r\n}\r\n/**\r\n * Creates a new immutable instance of `Query` that is extended to also include\r\n * additional query constraints.\r\n *\r\n * @param query - The Query instance to use as a base for the new constraints.\r\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\r\n * @throws if any of the provided query constraints cannot be combined with the\r\n * existing or new constraints.\r\n */\r\nfunction query(query, ...queryConstraints) {\r\n let queryImpl = getModularInstance(query);\r\n for (const constraint of queryConstraints) {\r\n queryImpl = constraint._apply(queryImpl);\r\n }\r\n return queryImpl;\r\n}\r\n/**\r\n * Define reference constructor in various modules\r\n *\r\n * We are doing this here to avoid several circular\r\n * dependency issues\r\n */\r\nsyncPointSetReferenceConstructor(ReferenceImpl);\r\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This variable is also defined in the firebase Node.js Admin SDK. Before\r\n * modifying this definition, consult the definition in:\r\n *\r\n * https://github.com/firebase/firebase-admin-node\r\n *\r\n * and make sure the two are consistent.\r\n */\r\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\r\n/**\r\n * Creates and caches `Repo` instances.\r\n */\r\nconst repos = {};\r\n/**\r\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\r\n */\r\nlet useRestClient = false;\r\n/**\r\n * Update an existing `Repo` in place to point to a new host/port.\r\n */\r\nfunction repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {\r\n repo.repoInfo_ = new RepoInfo(`${host}:${port}`, \r\n /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, \r\n /*isUsingEmulator=*/ true);\r\n if (tokenProvider) {\r\n repo.authTokenProvider_ = tokenProvider;\r\n }\r\n}\r\n/**\r\n * This function should only ever be called to CREATE a new database instance.\r\n * @internal\r\n */\r\nfunction repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {\r\n let dbUrl = url || app.options.databaseURL;\r\n if (dbUrl === undefined) {\r\n if (!app.options.projectId) {\r\n fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\r\n ' a Project ID when calling firebase.initializeApp().');\r\n }\r\n log('Using default host for project ', app.options.projectId);\r\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\r\n }\r\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n let repoInfo = parsedUrl.repoInfo;\r\n let isEmulator;\r\n let dbEmulatorHost = undefined;\r\n if (typeof process !== 'undefined' && process.env) {\r\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\r\n }\r\n if (dbEmulatorHost) {\r\n isEmulator = true;\r\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\r\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n repoInfo = parsedUrl.repoInfo;\r\n }\r\n else {\r\n isEmulator = !parsedUrl.repoInfo.secure;\r\n }\r\n const authTokenProvider = nodeAdmin && isEmulator\r\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\r\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\r\n validateUrl('Invalid Firebase Database URL', parsedUrl);\r\n if (!pathIsEmpty(parsedUrl.path)) {\r\n fatal('Database URL must point to the root of a Firebase Database ' +\r\n '(not including a child path).');\r\n }\r\n const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));\r\n return new Database(repo, app);\r\n}\r\n/**\r\n * Remove the repo and make sure it is disconnected.\r\n *\r\n */\r\nfunction repoManagerDeleteRepo(repo, appName) {\r\n const appRepos = repos[appName];\r\n // This should never happen...\r\n if (!appRepos || appRepos[repo.key] !== repo) {\r\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\r\n }\r\n repoInterrupt(repo);\r\n delete appRepos[repo.key];\r\n}\r\n/**\r\n * Ensures a repo doesn't already exist and then creates one using the\r\n * provided app.\r\n *\r\n * @param repoInfo - The metadata about the Repo\r\n * @returns The Repo object for the specified server / repoName.\r\n */\r\nfunction repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {\r\n let appRepos = repos[app.name];\r\n if (!appRepos) {\r\n appRepos = {};\r\n repos[app.name] = appRepos;\r\n }\r\n let repo = appRepos[repoInfo.toURLString()];\r\n if (repo) {\r\n fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\r\n }\r\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\r\n appRepos[repoInfo.toURLString()] = repo;\r\n return repo;\r\n}\r\n/**\r\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\r\n */\r\nfunction repoManagerForceRestClient(forceRestClient) {\r\n useRestClient = forceRestClient;\r\n}\r\n/**\r\n * Class representing a Firebase Realtime Database.\r\n */\r\nclass Database {\r\n /** @hideconstructor */\r\n constructor(_repoInternal, \r\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\r\n app) {\r\n this._repoInternal = _repoInternal;\r\n this.app = app;\r\n /** Represents a `Database` instance. */\r\n this['type'] = 'database';\r\n /** Track if the instance has been used (root or repo accessed) */\r\n this._instanceStarted = false;\r\n }\r\n get _repo() {\r\n if (!this._instanceStarted) {\r\n repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);\r\n this._instanceStarted = true;\r\n }\r\n return this._repoInternal;\r\n }\r\n get _root() {\r\n if (!this._rootInternal) {\r\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\r\n }\r\n return this._rootInternal;\r\n }\r\n _delete() {\r\n if (this._rootInternal !== null) {\r\n repoManagerDeleteRepo(this._repo, this.app.name);\r\n this._repoInternal = null;\r\n this._rootInternal = null;\r\n }\r\n return Promise.resolve();\r\n }\r\n _checkNotDeleted(apiName) {\r\n if (this._rootInternal === null) {\r\n fatal('Cannot call ' + apiName + ' on a deleted database.');\r\n }\r\n }\r\n}\r\nfunction checkTransportInit() {\r\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\r\n warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');\r\n }\r\n}\r\n/**\r\n * Force the use of websockets instead of longPolling.\r\n */\r\nfunction forceWebSockets() {\r\n checkTransportInit();\r\n BrowserPollConnection.forceDisallow();\r\n}\r\n/**\r\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\r\n */\r\nfunction forceLongPolling() {\r\n checkTransportInit();\r\n WebSocketConnection.forceDisallow();\r\n BrowserPollConnection.forceAllow();\r\n}\r\n/**\r\n * Returns the instance of the Realtime Database SDK that is associated\r\n * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with\r\n * with default settings if no instance exists or if the existing instance uses\r\n * a custom database URL.\r\n *\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\r\n * Database instance is associated with.\r\n * @param url - The URL of the Realtime Database instance to connect to. If not\r\n * provided, the SDK connects to the default instance of the Firebase App.\r\n * @returns The `Database` instance of the provided app.\r\n */\r\nfunction getDatabase(app = getApp(), url) {\r\n const db = _getProvider(app, 'database').getImmediate({\r\n identifier: url\r\n });\r\n if (!db._instanceStarted) {\r\n const emulator = getDefaultEmulatorHostnameAndPort('database');\r\n if (emulator) {\r\n connectDatabaseEmulator(db, ...emulator);\r\n }\r\n }\r\n return db;\r\n}\r\n/**\r\n * Modify the provided instance to communicate with the Realtime Database\r\n * emulator.\r\n *\r\n *

Note: This method must be called before performing any other operation.\r\n *\r\n * @param db - The instance to modify.\r\n * @param host - The emulator host (ex: localhost)\r\n * @param port - The emulator port (ex: 8080)\r\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\r\n */\r\nfunction connectDatabaseEmulator(db, host, port, options = {}) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('useEmulator');\r\n if (db._instanceStarted) {\r\n fatal('Cannot call useEmulator() after instance has already been initialized.');\r\n }\r\n const repo = db._repoInternal;\r\n let tokenProvider = undefined;\r\n if (repo.repoInfo_.nodeAdmin) {\r\n if (options.mockUserToken) {\r\n fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".');\r\n }\r\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\r\n }\r\n else if (options.mockUserToken) {\r\n const token = typeof options.mockUserToken === 'string'\r\n ? options.mockUserToken\r\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\r\n tokenProvider = new EmulatorTokenProvider(token);\r\n }\r\n // Modify the repo to apply emulator settings\r\n repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);\r\n}\r\n/**\r\n * Disconnects from the server (all Database operations will be completed\r\n * offline).\r\n *\r\n * The client automatically maintains a persistent connection to the Database\r\n * server, which will remain active indefinitely and reconnect when\r\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\r\n * to control the client connection in cases where a persistent connection is\r\n * undesirable.\r\n *\r\n * While offline, the client will no longer receive data updates from the\r\n * Database. However, all Database operations performed locally will continue to\r\n * immediately fire events, allowing your application to continue behaving\r\n * normally. Additionally, each operation performed locally will automatically\r\n * be queued and retried upon reconnection to the Database server.\r\n *\r\n * To reconnect to the Database and begin receiving remote events, see\r\n * `goOnline()`.\r\n *\r\n * @param db - The instance to disconnect.\r\n */\r\nfunction goOffline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOffline');\r\n repoInterrupt(db._repo);\r\n}\r\n/**\r\n * Reconnects to the server and synchronizes the offline Database state\r\n * with the server state.\r\n *\r\n * This method should be used after disabling the active connection with\r\n * `goOffline()`. Once reconnected, the client will transmit the proper data\r\n * and fire the appropriate events so that your client \"catches up\"\r\n * automatically.\r\n *\r\n * @param db - The instance to reconnect.\r\n */\r\nfunction goOnline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOnline');\r\n repoResume(db._repo);\r\n}\r\nfunction enableLogging(logger, persistent) {\r\n enableLogging$1(logger, persistent);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerDatabase(variant) {\r\n setSDKVersion(SDK_VERSION$1);\r\n _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const authProvider = container.getProvider('auth-internal');\r\n const appCheckProvider = container.getProvider('app-check-internal');\r\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);\r\n }, \"PUBLIC\" /* ComponentType.PUBLIC */).setMultipleInstances(true));\r\n registerVersion(name, version, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SERVER_TIMESTAMP = {\r\n '.sv': 'timestamp'\r\n};\r\n/**\r\n * Returns a placeholder value for auto-populating the current timestamp (time\r\n * since the Unix epoch, in milliseconds) as determined by the Firebase\r\n * servers.\r\n */\r\nfunction serverTimestamp() {\r\n return SERVER_TIMESTAMP;\r\n}\r\n/**\r\n * Returns a placeholder value that can be used to atomically increment the\r\n * current database value by the provided delta.\r\n *\r\n * @param delta - the amount to modify the current value atomically.\r\n * @returns A placeholder value for modifying data atomically server-side.\r\n */\r\nfunction increment(delta) {\r\n return {\r\n '.sv': {\r\n 'increment': delta\r\n }\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A type for the resolve value of {@link runTransaction}.\r\n */\r\nclass TransactionResult {\r\n /** @hideconstructor */\r\n constructor(\r\n /** Whether the transaction was successfully committed. */\r\n committed, \r\n /** The resulting data snapshot. */\r\n snapshot) {\r\n this.committed = committed;\r\n this.snapshot = snapshot;\r\n }\r\n /** Returns a JSON-serializable representation of this object. */\r\n toJSON() {\r\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\r\n }\r\n}\r\n/**\r\n * Atomically modifies the data at this location.\r\n *\r\n * Atomically modify the data at this location. Unlike a normal `set()`, which\r\n * just overwrites the data regardless of its previous value, `runTransaction()` is\r\n * used to modify the existing value to a new value, ensuring there are no\r\n * conflicts with other clients writing to the same location at the same time.\r\n *\r\n * To accomplish this, you pass `runTransaction()` an update function which is\r\n * used to transform the current value into a new value. If another client\r\n * writes to the location before your new value is successfully written, your\r\n * update function will be called again with the new current value, and the\r\n * write will be retried. This will happen repeatedly until your write succeeds\r\n * without conflict or you abort the transaction by not returning a value from\r\n * your update function.\r\n *\r\n * Note: Modifying data with `set()` will cancel any pending transactions at\r\n * that location, so extreme care should be taken if mixing `set()` and\r\n * `runTransaction()` to update the same data.\r\n *\r\n * Note: When using transactions with Security and Firebase Rules in place, be\r\n * aware that a client needs `.read` access in addition to `.write` access in\r\n * order to perform a transaction. This is because the client-side nature of\r\n * transactions requires the client to read the data in order to transactionally\r\n * update it.\r\n *\r\n * @param ref - The location to atomically modify.\r\n * @param transactionUpdate - A developer-supplied function which will be passed\r\n * the current data stored at this location (as a JavaScript object). The\r\n * function should return the new value it would like written (as a JavaScript\r\n * object). If `undefined` is returned (i.e. you return with no arguments) the\r\n * transaction will be aborted and the data at this location will not be\r\n * modified.\r\n * @param options - An options object to configure transactions.\r\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\r\n * callback to handle success and failure.\r\n */\r\nfunction runTransaction(ref, \r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\ntransactionUpdate, options) {\r\n var _a;\r\n ref = getModularInstance(ref);\r\n validateWritablePath('Reference.transaction', ref._path);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');\r\n }\r\n const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;\r\n const deferred = new Deferred();\r\n const promiseComplete = (error, committed, node) => {\r\n let dataSnapshot = null;\r\n if (error) {\r\n deferred.reject(error);\r\n }\r\n else {\r\n dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);\r\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\r\n }\r\n };\r\n // Add a watch to make sure we get server updates.\r\n const unwatcher = onValue(ref, () => { });\r\n repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);\r\n return deferred.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nPersistentConnection;\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\r\n this.sendRequest('q', { p: pathString }, onComplete);\r\n};\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.echo = function (data, onEcho) {\r\n this.sendRequest('echo', { d: data }, onEcho);\r\n};\r\n// RealTimeConnection properties that we use in tests.\r\nConnection;\r\n/**\r\n * @internal\r\n */\r\nconst hijackHash = function (newHash) {\r\n const oldPut = PersistentConnection.prototype.put;\r\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\r\n if (hash !== undefined) {\r\n hash = newHash();\r\n }\r\n oldPut.call(this, pathString, data, onComplete, hash);\r\n };\r\n return function () {\r\n PersistentConnection.prototype.put = oldPut;\r\n };\r\n};\r\nRepoInfo;\r\n/**\r\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\r\n * @internal\r\n */\r\nconst forceRestClient = function (forceRestClient) {\r\n repoManagerForceRestClient(forceRestClient);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Used by console to create a database based on the app,\r\n * passed database URL and a custom auth implementation.\r\n * @internal\r\n * @param app - A valid FirebaseApp-like object\r\n * @param url - A valid Firebase databaseURL\r\n * @param version - custom version e.g. firebase-admin version\r\n * @param customAppCheckImpl - custom app check implementation\r\n * @param customAuthImpl - custom auth implementation\r\n */\r\nfunction _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {\r\n setSDKVersion(version);\r\n /**\r\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\r\n * any actual function.\r\n */\r\n const componentContainer = new ComponentContainer('database-standalone');\r\n const authProvider = new Provider('auth-internal', componentContainer);\r\n let appCheckProvider;\r\n if (customAppCheckImpl) {\r\n appCheckProvider = new Provider('app-check-internal', componentContainer);\r\n appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n }\r\n authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);\r\n}\n\n/**\r\n * Firebase Realtime Database\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterDatabase();\n\nexport { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, _initStandalone, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };\n//# sourceMappingURL=index.esm2017.js.map\n","/* eslint-disable import/prefer-default-export */\n/* eslint-disable import/no-extraneous-dependencies */\nimport { initializeApp } from 'firebase/app';\nimport {\n\tgetAuth,\n\tsignInWithEmailAndPassword,\n\tonAuthStateChanged,\n\tsignOut,\n} from 'firebase/auth';\nimport { getDatabase } from 'firebase/database';\n\nfunction loadFirebaseConfig() {\n\tconst el = document.getElementById('wp-script-module-data-@prc/firebase');\n\ttry {\n\t\tconst config = JSON.parse(el.textContent);\n\t\treturn config;\n\t} catch (err) {\n\t\tconsole.error(err);\n\t\treturn {};\n\t}\n}\n\nconst _app = initializeApp(loadFirebaseConfig());\nconst _auth = getAuth();\nconst _signInWithEmailAndPassword = signInWithEmailAndPassword;\nconst _onAuthStateChanged = onAuthStateChanged;\nconst _signOut = signOut;\nconst _db = getDatabase();\n\nexport {\n\t_app as app,\n\t_auth as auth,\n\t_signInWithEmailAndPassword as signInWithEmailAndPassword,\n\t_onAuthStateChanged as onAuthStateChanged,\n\t_signOut as signOut,\n\t_db as getDatabase,\n};\n"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","g","globalThis","this","Function","e","window","obj","prop","prototype","hasOwnProperty","call","assertion","message","assertionError","Error","stringToByteArray$1","str","out","p","i","length","c","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","push","join","encodeString","btoa","decodeString","bytes","pos","c1","String","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","super","arguments","name","base64Encode","utf8Bytes","base64urlEncodeWithoutPadding","replace","base64Decode","console","error","deepCopy","value","deepExtend","undefined","target","source","Date","getTime","getDefaults","self","getGlobal","__FIREBASE_DEFAULTS__","process","env","defaultsJsonString","JSON","parse","getDefaultsFromEnvVariable","document","match","cookie","decoded","getDefaultsFromCookie","info","getDefaultEmulatorHost","productName","_a","_b","emulatorHosts","getDefaultAppConfig","config","getExperimentalSetting","reject","resolve","promise","Promise","wrapCallback","callback","catch","navigator","isMobileCordova","test","isReactNative","FirebaseError","code","customData","setPrototypeOf","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","PATTERN","_","replaceTemplate","fullMessage","jsonEval","stringify","decode","token","header","claims","signature","parts","split","map","fn","contextObj","res","deepEqual","a","b","aKeys","keys","bKeys","k","includes","aProp","bProp","isObject","thing","querystringParams","params","entries","forEach","arrayVal","encodeURIComponent","querystringDecode","querystring","decodeURIComponent","extractQuerystring","url","queryStart","indexOf","fragmentStart","substring","Sha1","chain_","buf_","W_","pad_","inbuf_","total_","blockSize","reset","compress_","buf","offset","W","t","f","d","update","lengthMinusBlock","n","inbuf","digest","totalBits","j","ObserverProxy","executor","onNoObservers","observers","unsubscribes","observerCount","task","finalized","then","next","forEachObserver","observer","close","complete","subscribe","nextOrObserver","methods","method","implementsAnyMethods","noop","unsub","unsubscribeOne","bind","finalError","sendOne","err","stringLength","_delegate","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","container","component","instances","Map","instancesDeferred","instancesOptions","onInitCallbacks","identifier","normalizedIdentifier","normalizeInstanceIdentifier","has","deferred","set","isInitialized","shouldAutoInitialize","instance","getOrInitializeService","instanceIdentifier","getImmediate","options","optional","getComponent","setComponent","isComponentEager","instanceDeferred","clearInstance","delete","services","from","values","all","filter","INTERNAL","_delete","isComponentSet","getOptions","initialize","opts","onInit","existingCallbacks","Set","add","existingInstance","invokeOnInitCallbacks","callbacks","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","LogLevel","levelStringToEnum","DEBUG","VERBOSE","INFO","WARN","ERROR","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","args","logLevel","now","toISOString","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","debug","log","warn","instanceOfAny","object","constructors","some","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","receiver","IDBTransaction","objectStoreNames","objectStore","transformCachableValue","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","apply","unwrap","storeNames","tx","sort","done","unlisten","removeEventListener","DOMException","addEventListener","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","Proxy","IDBRequest","request","success","result","promisifyRequest","newValue","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","async","storeName","store","index","shift","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","isVersionServiceProvider","library","version","logString","name$p","version$1","logger","name$o","name$n","name$m","name$l","name$k","name$j","name$i","name$h","name$g","name$f","name$e","name$d","name$c","name$b","name$a","name$9","name$8","name$7","name$6","name$5","name$4","name$3","name$2","name$1","PLATFORM_LOG_STRING","_apps","_serverApps","_components","_addComponent","app","_registerComponent","componentName","serverApp","_getProvider","heartbeatController","triggerHeartbeat","settings","ERROR_FACTORY","FirebaseAppImpl","_isDeleted","_options","assign","_config","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","_container","checkDestroyed","isDeleted","appName","SDK_VERSION","initializeApp","rawConfig","existingApp","newApp","getApp","registerVersion","libraryKeyOrName","variant","libraryMismatch","versionMismatch","warning","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","blocked","upgrade","blocking","terminated","indexedDB","open","openPromise","event","oldVersion","newVersion","db","openDB","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","put","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","read","agent","date","getUTCDateString","heartbeats","lastSentHeartbeatDate","singleDateHeartbeat","hbTimestamp","valueOf","overwrite","getHeartbeatsHeader","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","slice","heartbeatEntry","find","hb","dates","countBytes","pop","extractHeartbeatsForHeader","headerString","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","isIndexedDBAvailable","preExist","DB_CHECK_NAME","onsuccess","deleteDatabase","onupgradeneeded","onerror","idbHeartbeatObject","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","__rest","s","getOwnPropertySymbols","propertyIsEnumerable","SuppressedError","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logError","msg","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","_serverAppCurrentUserOperationNotSupportedError","fullParams","_errorFactory","_assert","debugFail","failure","debugAssert","_getCurrentUrl","location","href","_getCurrentScheme","protocol","_isOnline","onLine","runtime","chrome","browser","id","isBrowserExtension","Delay","shortDelay","longDelay","isMobile","Math","min","_emulatorUrl","path","emulator","startsWith","FetchProvider","fetchImpl","headersImpl","responseImpl","fetch","headers","Headers","response","Response","SERVER_ERROR_MAP","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","tenantId","_performApiRequest","customErrorMap","_performFetchWithErrorHandling","body","query","apiKey","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","race","clearNetworkTimeout","json","_makeTaggedError","ok","errorMessage","serverErrorCode","serverErrorMessage","authError","toLowerCase","_performSignInRequest","serverResponse","_serverResponse","host","base","apiScheme","_parseEnforcementState","enforcementStateStr","timer","setTimeout","clearTimeout","errorParams","email","phoneNumber","_tokenResponse","isEnterprise","grecaptcha","enterprise","RecaptchaConfig","siteKey","recaptchaEnforcementState","recaptchaKey","getProviderEnforcementState","providerStr","enforcementState","isProviderEnabled","getAccountInfo","utcTimestampToDateString","utcTimestamp","Number","isNaN","toUTCString","secondsStringToMilliseconds","seconds","_parseToken","algorithm","payload","toString","_tokenExpiresIn","parsedToken","exp","iat","_logoutIfInvalidated","user","bypassAuthState","isUserInvalidated","currentUser","signOut","ProactiveRefresh","isRunning","timerId","errorBackoff","_start","schedule","_stop","getInterval","wasError","interval","stsTokenManager","expirationTime","max","iteration","getIdToken","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","creationTime","_copy","metadata","toJSON","_reloadWithoutSaving","idToken","users","coreAccount","_notifyReloadListener","newProviderData","providerUserInfo","extractProviderData","providerData","original","newData","providerId","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","updates","uid","localId","displayName","photoURL","photoUrl","emailVerified","rawId","StsTokenManager","refreshToken","accessToken","isExpired","updateFromServerResponse","expiresIn","updateTokensAndExpiration","updateFromIdToken","getToken","forceRefresh","refresh","clearRefreshToken","oldToken","tokenApiHost","access_token","expires_in","refresh_token","requestStsToken","expiresInSec","fromJSON","manager","_assign","_clone","_performRefresh","assertStringOrUndefined","UserImpl","opt","proactiveRefresh","reloadUserInfo","reloadListener","_persistUserIfCurrent","_notifyListenersIfCurrent","getIdTokenResult","userInternal","auth_time","firebase","signInProvider","authTime","issuedAtTime","signInSecondFactor","reload","userInfo","newUser","_onReload","_startProactiveRefresh","_stopProactiveRefresh","_updateTokensIfNecessary","tokensRefreshed","deleteAccount","_redirectEventId","_fromJSON","_c","_d","_e","_f","_g","_h","plainObjectTokenManager","_fromIdTokenResponse","idTokenResponse","_fromGetAccountInfoResponse","instanceCache","_getInstance","cls","InMemoryPersistence","storage","_isAvailable","_set","_get","_remove","_addListener","_key","_listener","_removeListener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","setCurrentUser","getCurrentUser","blob","removeCurrentUser","savePersistenceForRedirect","setPersistence","newPersistence","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","userAgent","ua","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","re","matches","_isIOS","_isMobileBrowser","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","AuthMiddlewareQueue","queue","pushCallback","onAbort","wrappedCallback","runMiddleware","nextUser","onAbortStack","beforeStateCallback","reverse","originalMessage","PasswordPolicyImpl","responseOptions","customStrengthOptions","minPasswordLength","maxPasswordLength","containsLowercaseCharacter","containsLowercaseLetter","containsUppercaseCharacter","containsUppercaseLetter","containsNumericCharacter","containsNonAlphanumericCharacter","allowedNonAlphanumericCharacters","forceUpgradeOnSignin","schemaVersion","validatePassword","password","status","isValid","passwordPolicy","validatePasswordLengthOptions","validatePasswordCharacterOptions","meetsMinPasswordLength","meetsMaxPasswordLength","passwordChar","updatePasswordCharacterOptionsStatuses","AuthImpl","heartbeatServiceProvider","appCheckServiceProvider","emulatorConfig","operations","authStateSubscription","Subscription","idTokenSubscription","beforeStateQueue","redirectUser","isProactiveRefreshEnabled","EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","_agentRecaptchaConfig","_tenantRecaptchaConfigs","_projectPasswordPolicy","_tenantPasswordPolicies","lastNotifiedUid","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","_initializeWithPersistence","popupRedirectResolver","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","initializeCurrentUserFromIdToken","directlySetCurrentUser","authIdToken","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","authDomain","getOrInitRedirectPersistenceManager","redirectUserEventId","storedUserEventId","tryRedirectSignIn","_overrideRedirectResult","reloadAndSetCurrentUserOrClear","redirectResolver","_completeRedirectFn","_setRedirectUser","useDeviceLanguage","navigatorLanguage","languages","language","_getUserLanguage","updateCurrentUser","userExtern","skipBeforeStateCallbacks","notifyAuthListeners","redirectPersistenceManager","_getRecaptchaConfig","_getPasswordPolicyInternal","_updatePasswordPolicy","_getPasswordPolicy","_getPersistence","_updateErrorMap","onAuthStateChanged","completed","registerStateListener","beforeAuthStateChanged","onIdTokenChanged","authStateReady","unsubscribe","revokeAccessToken","tokenType","revokeToken","redirectManager","resolver","_redirectPersistence","_redirectUserForId","currentUid","subscription","cb","isUnsubscribed","addObserver","action","_logFramework","framework","_getFrameworks","heartbeatsHeader","appCheckToken","_getAppCheckToken","appCheckTokenResult","_logWarn","_castAuth","proxy","createSubscribe","externalJSProvider","loadJS","recaptchaV2Script","recaptchaEnterpriseScript","gapiScript","_loadJS","_generateCallbackName","prefix","floor","random","RecaptchaEnterpriseVerifier","authExtern","verify","retrieveRecaptchaToken","ready","execute","getRecaptchaConfig","clientType","retrieveSiteKey","injectRecaptchaFields","captchaResp","verifier","captchaResponse","newRequest","handleRecaptchaFlow","authInstance","actionName","actionMethod","requestWithRecaptcha","extractProtocol","protocolEnd","substr","parsePort","portStr","port","AuthCredential","signInMethod","_getIdTokenResponse","_auth","_linkToIdToken","_idToken","_getReauthenticationResolver","linkEmailPassword","signInWithPassword","EmailAuthCredential","_email","_password","_tenantId","_fromEmailAndPassword","_fromEmailAndCode","oobCode","returnSecureToken","signInWithEmailLink$1","signInWithEmailLinkForLinking","signInWithIdp","OAuthCredential","pendingToken","_fromParams","cred","nonce","oauthToken","oauthTokenSecret","secret","buildRequest","autoCreate","requestUri","postBody","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","PhoneAuthCredential","_fromVerification","verificationId","verificationCode","_fromTokenResponse","temporaryProof","signInWithPhoneNumber$1","_makeVerificationRequest","linkWithPhoneNumber$1","operation","verifyPhoneNumberForExisting","sessionInfo","ActionCodeURL","actionLink","searchParams","parseMode","continueUrl","parseLink","link","doubleDeepLink","iOSDeepLink","parseDeepLink","EmailAuthProvider","PROVIDER_ID","credential","credentialWithLink","emailLink","actionCodeUrl","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_LINK_SIGN_IN_METHOD","FederatedAuthProvider","defaultLanguageCode","customParameters","setDefaultLanguage","setCustomParameters","customOAuthParameters","getCustomParameters","BaseOAuthProvider","scopes","addScope","scope","getScopes","FacebookAuthProvider","FACEBOOK_SIGN_IN_METHOD","credentialFromResult","userCredential","credentialFromTaggedObject","credentialFromError","tokenResponse","oauthAccessToken","GoogleAuthProvider","GOOGLE_SIGN_IN_METHOD","oauthIdToken","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","UserCredentialImpl","operationType","providerIdForResponse","_forOperation","MultiFactorError","_fromErrorAndOperation","_processCredentialSavingMfaContextIfNecessary","_signInWithCredential","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","setItem","removeItem","getItem","BrowserLocalPersistence","localStorage","poll","onStorageEvent","listeners","localCache","pollTimer","safariLocalStorageNotSynced","_iframeCannotSyncWebStorage","top","_isIframe","fallbackToPolling","forAllChangedKeys","oldValue","_oldValue","notifyListeners","detachListener","stopPolling","storedValue","triggerListeners","isIE","documentMode","listener","startPolling","setInterval","StorageEvent","clearInterval","attachListener","size","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","Receiver","eventTarget","handlersMap","handleEvent","receivers","isListeningto","newInstance","messageEvent","eventId","eventType","handlers","ports","postMessage","promises","handler","origin","fulfilled","reason","_allSettled","_subscribe","eventHandler","_unsubscribe","_generateEventId","digits","Sender","removeMessageHandler","messageChannel","port1","onMessage","_send","timeout","MessageChannel","completionTimer","start","ackTimer","port2","finally","_window","_isWorker","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","toPromise","getObjectStore","isReadWrite","_openDatabase","keyPath","contains","_deleteDatabase","_putObject","_deleteObject","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","_openDb","_withRetries","op","numAttempts","initializeReceiver","initializeSender","_origin","keyProcessed","_poll","_data","serviceWorker","active","_getActiveServiceWorker","results","notifyServiceWorker","controller","_withPendingWrite","write","getObject","getAllRequest","getAll","keysInResult","fbase_key","localKey","indexedDBLocalPersistence","PhoneAuthProvider","verifyPhoneNumber","phoneOptions","applicationVerifier","recaptchaToken","phoneInfoOptions","session","startEnrollPhoneMfa","phoneEnrollmentInfo","phoneSessionInfo","mfaEnrollmentId","multiFactorHint","multiFactorUid","startSignInPhoneMfa","mfaPendingCredential","phoneSignInInfo","phoneResponseInfo","sendPhoneVerificationCode","_reset","_verifyPhoneNumber","PHONE_SIGN_IN_METHOD","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_reauth","parsed","sub","_reauthenticate","_link","_link$1","AbstractPopupRedirectOperation","pendingPromise","eventManager","onExecution","registerConsumer","onAuthEvent","urlResponse","getIdpTask","onError","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","authWindow","pollId","currentPopupAction","cancel","executeNotNull","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","isSupported","pollUserCancellation","closed","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","pendingRedirectKey","resolverPersistence","hasPendingRedirect","_getAndClearPendingRedirectStatus","_getRedirectResult","resolverExtern","authInternal","resolverOverride","_withDefaultResolver","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","onEvent","hasEventBeenHandled","handled","consumer","isNullRedirectEvent","isRedirectEvent","eventIdMatches","clear","eventUid","v","IP_ADDRESS_REGEX","HTTP_REGEX","matchDomain","expected","currentUrl","hostname","URL","ceUrl","escapedDomainPattern","RegExp","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","H","hint","r","L","CP","loadGapi","loadGapiIframe","gapi","load","iframes","getContext","ontimeout","Iframe","cbName","cachedGApiLoader","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","style","position","width","height","tabindex","EID_FROM_APIHOST","getIframeUrl","eid","fw","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","AuthPopup","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","authType","redirectUrl","additionalParams","tid","paramsDict","appCheckTokenFragment","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","eventManagers","originValidationPromises","screen","availHeight","left","availWidth","scrollbars","optionsString","reduce","accum","standalone","_isIOSStandalone","el","createElement","click","createEvent","initMouseEvent","dispatchEvent","openAsNewWindowIOS","newWin","focus","_open","_openRedirect","initAndGetManager","iframe","context","_loadGapi","where","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","attributes","dontclear","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","_openIframe","register","iframeEvent","authEvent","send","authorizedDomains","_getProjectConfig","domain","_validateOrigin","AuthInterop","internalListeners","getUid","assertAuthConfigured","addAuthTokenListener","updateProactiveRefresh","removeAuthTokenListener","authIdTokenMaxAge","lastPostedIdToken","setAttribute","onload","charset","getElementsByTagName","appendChild","deps","hierarchy","_initializeAuthInstance","_instanceIdentifier","_instance","getVersionForPlatform","DOMStorageWrapper","domStorage_","prefix_","prefixedName_","storedVal","remove","MemoryStorage","cache_","isInMemoryStorage","createStoragefor","domStorageName","domStorage","PersistentStorage","SessionStorage","LUIDGenerator","sha1","high","stringToByteArray","sha1Bytes","buildLogMessage_","varArgs","arg","firstLog_","logger_","persistent","logWrapper","fatal","isInvalidJSONNumber","POSITIVE_INFINITY","NEGATIVE_INFINITY","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","ObjectToUniqueKey","splitStringBySize","segsize","len","dataSegs","each","doubleToIEEE754String","ln","abs","pow","LN2","round","bits","hexByteString","hexByte","parseInt","INTEGER_REGEXP_","intVal","exceptionGuard","stack","setTimeoutNonBlocking","time","Deno","unrefTimer","AppCheckTokenProvider","appName_","appCheckProvider","appCheck","addTokenChangeListener","addTokenListener","notifyForInvalidToken","FirebaseAuthTokenProvider","firebaseOptions_","authProvider_","auth_","removeTokenChangeListener","EmulatorTokenProvider","OWNER","PROTOCOL_VERSION","FORGE_DOMAIN_RE","APP_CHECK_TOKEN_PARAM","WEBSOCKET","LONG_POLLING","RepoInfo","secure","namespace","webSocketOnly","nodeAdmin","persistenceKey","includeNamespaceInQueryParams","isUsingEmulator","_host","_domain","internalHost","isCacheableHost","isCustomHost","newHost","toURLString","repoInfoConnectionURL","repoInfo","connURL","repoInfoNeedsQueryParam","pairs","StatsCollection","counters_","incrementCounter","amount","collections","reporters","statsManagerGetCollection","hashString","PacketReceiver","onMessage_","pendingResponses","currentResponseNum","closeAfterResponse","onClose","closeAfter","responseNum","handleResponse","requestNum","toProcess","FIREBASE_LONGPOLL_START_PARAM","BrowserPollConnection","connId","applicationId","authToken","transportSessionId","lastSessionId","bytesSent","bytesReceived","everConnected_","log_","stats_","urlFn","onDisconnect","curSegmentNum","onDisconnect_","myPacketOrderer","isClosed_","connectTimeoutTimer_","onClosed_","readyState","called","wrappedFn","attachEvent","executeWhenDOMReady","scriptTagHolder","FirebaseIFrameScriptHolder","command","arg1","arg2","arg3","arg4","incrementIncomingBytes_","sendNewPolls","pN","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","isAvailable","Windows","UI","markConnectionHealthy","shutdown_","myDisconnFrame","removeChild","dataStr","base64data","MAX_URL_DATA_SIZE","enqueueSegment","pw","src","display","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","script","iframeContents","doc","contentWindow","contentDocument","alive","textContent","myID","myPW","newRequest_","theURL","curDataString","theSeg","seg","ts","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","loadCB","newScript","onreadystatechange","rstate","parentNode","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","CONSTANTS","mySock","onopen","onclose","onmessage","m","handleIncomingFrame","isOldAndroid","oldAndroidRegex","oldAndroidMatch","parseFloat","previouslyFailed","appendFrame_","fullMess","jsonMess","handleNewFrameCount_","frameCount","extractFrameCount_","mess","resetKeepAlive","remainingData","sendString_","responsesRequiredToBeHealthy","healthyTimeout","TransportManager","initTransports_","ALL_TRANSPORTS","IS_TRANSPORT_INITIALIZED","globalTransportInitialized_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports","transport","initialTransport","upgradeTransport","Connection","repoInfo_","applicationId_","appCheckToken_","authToken_","onReady_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","start_","conn","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeoutMS","healthyTimeout_","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","sendRequest","dataMsg","sendData_","tryCleanupConnection","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","onControl_","onDataMessage_","onPrimaryResponse_","handshakePayload","h","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","timestamp","onConnectionEstablished_","tryStartUpgrade_","startUpgrade_","closeConnections_","ServerActions","pathString","onComplete","hash","merge","refreshAuthToken","refreshAppCheckToken","onDisconnectPut","onDisconnectMerge","onDisconnectCancel","reportStats","stats","EventEmitter","allowedEvents_","listeners_","trigger","on","validateEventType_","eventData","getInitialEvent","off","splice","et","OnlineMonitor","online_","getInstance","currentlyOnline","Path","pathOrString","pieceNum","pieces_","copyTo","pieceNum_","newEmptyPath","pathGetFront","pathGetLength","pathPopFront","pathGetBack","pathSlice","begin","pathParent","pieces","pathChild","childPathObj","childPieces","pathIsEmpty","newRelativePath","outerPath","innerPath","outer","inner","pathEquals","other","pathContains","ValidationPath","errorPrefix_","parts_","byteLength_","validationPathCheckValid","validationPath","validationPathToErrorString","VisibilityMonitor","hidden","visibilityChange","visible_","visible","RECONNECT_MIN_DELAY","PersistentConnection","onDataUpdate_","onConnectStatus_","onServerInfoUpdate_","authTokenProvider_","appCheckTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens","outstandingPuts_","outstandingGets_","outstandingPutCount_","outstandingGetCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","establishConnectionTimer_","requestCBHash_","requestNumber_","realtime_","forceTokenRefresh_","invalidAuthTokenCount_","invalidAppCheckTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","onVisible_","onOnline_","onResponse","curReqNum","initConnection_","outstandingGet","_path","q","_queryObject","sendGet_","listen","currentHashFn","tag","queryId","_queryIdentifier","_queryParams","isDefault","loadsAllData","listenSpec","hashFn","sendListen_","req","warnOnListenWarnings_","removeListen_","warnings","indexSpec","getIndex","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","isAdmin","tryAppCheck","authMethod","isValidFormat","requestData","onAuthRevoked_","onAppCheckRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","putInternal","sendPut_","queued","errorReason","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","handleTimestamp_","sendConnectStats_","restoreState_","scheduleConnect_","establishConnection_","online","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage","onReady","nextConnectionId_","canceled","connection","closeFn","sendRequestFn","interrupt","resume","delta","serverTimeOffset","normalizedPathString","statusCode","explanation","queries","clientName","NamedNode","node","Wrap","Index","getCompare","compare","indexedValueChanged","oldNode","newNode","oldWrapped","newWrapped","minPost","MIN","__EMPTY_NODE","KeyIndex","isDefinedOn","maxPost","makePost","indexValue","KEY_INDEX","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","cmp","isEmpty","right","getNext","hasNext","peek","LLRBNode","color","RED","SortedMap","EMPTY_NODE","copy","count","inorderTraversal","reverseTraversal","min_","minKey","maxKey","insert","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","nr","checkMaxDepth_","blackDepth","check_","BLACK","comparator_","root_","getPredecessorKey","rightParent","getIterator","resultGenerator","getIteratorFrom","getReverseIteratorFrom","getReverseIterator","NAME_ONLY_COMPARATOR","NAME_COMPARATOR","MAX_NODE$2","priorityHashText","priority","validatePriorityNode","priorityNode","isLeafNode","getPriority","__childrenNodeConstructor","nodeFromJSON$1","MAX_NODE$1","LeafNode","value_","priorityNode_","lazyHash_","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","hasChild","getPredecessorChildName","childNode","updateImmediateChild","newChildNode","updateChild","front","numChildren","forEachChild","exportFormat","getValue","toHash","compareTo","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","withIndex","isIndexed","equals","PRIORITY_INDEX","aPriority","bPriority","indexCmp","LOG_2","Base12Num","num","current_","mask","bits_","nextBitIsOne","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","low","namedNode","middle","root","base12","buildPennant","chunkSize","childTree","attachPennant","pennant","isOne","buildFrom12Array","_defaultIndexMap","fallbackObject","IndexMap","indexes_","indexSet_","Default","indexKey","sortedMap","hasIndex","indexDefinition","addIndex","existingChildren","sawIndexedValue","iter","newIndex","indexName","newIndexSet","newIndexes","addToIndexes","indexedChildren","existingSnap","newChildren","removeFromIndexes","ChildrenNode","children_","indexMap_","child","newIndexMap","newPriority","newImmediateChild","numKeys","allIntegerKeys","array","childHash","idx","resolveIndex_","predecessor","getFirstChildName","getFirstChild","getLastChildName","getLastChild","wrappedNode","startPost","iterator","endPost","MAX_NODE","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","defineProperties","MAX","USE_HINZE","nodeFromJSON","childData","children","childrenHavePriority","childSet","sortedChildSet","PathIndex","indexPath_","extractChild","snap","aChild","bChild","valueNode","VALUE_INDEX","changeChildChanged","snapshotNode","oldSnap","QueryParams","limitSet_","startSet_","startNameSet_","startAfterSet_","endSet_","endNameSet_","endBeforeSet_","limit_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","index_","hasStart","isViewFromLeft","getIndexStartValue","getIndexStartName","hasEnd","getIndexEndValue","getIndexEndName","hasLimit","hasAnchoredLimit","getLimit","queryParamsToRestQueryStringParameters","queryParams","qs","orderBy","startParam","endParam","queryParamsGetQueryObject","viewFrom","ReadonlyRestClient","listens_","getListenId_","listenId","thisListen","queryStringParameters","restRequest_","xhr","XMLHttpRequest","responseText","SnapshotHolder","rootNode_","getNode","updateSnapshot","newSnapshotNode","newSparseSnapshotTree","sparseSnapshotTreeRemember","sparseSnapshotTree","childKey","sparseSnapshotTreeForEachTree","prefixPath","tree","sparseSnapshotTreeForEachChild","StatsListener","collection_","last_","newStats","stat","StatsReporter","collection","server_","statsToReport_","statsListener_","reportStats_","reportedStats","haveStatsToReport","OperationType","newOperationSourceServerTaggedQuery","fromUser","fromServer","tagged","AckUserWrite","affectedTree","revert","ACK_USER_WRITE","operationForChild","subtree","Overwrite","OVERWRITE","Merge","MERGE","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","eventGeneratorGenerateEventsForType","eventGenerator","events","changes","registrations","eventCache","filteredChanges","change","aWrapped","bWrapped","eventGeneratorCompareChanges","materializedChange","prevName","eventGeneratorMaterializeSingleChange","registration","respondsTo","query_","newViewCache","serverCache","viewCacheUpdateEventSnap","viewCache","eventSnap","filtered","viewCacheUpdateServerSnap","serverSnap","viewCacheGetCompleteEventSnap","viewCacheGetCompleteServerSnap","emptyChildrenSingleton","ImmutableTree","EmptyChildren","fromObject","childPath","childSnap","findRootMostMatchingPathAndValue","relativePath","predicate","childExistingPathAndValue","findRootMostValueAndPath","toSet","newChild","setTree","newTree","fold","fold_","pathSoFar","findOnPath","findOnPath_","pathToFollow","nextChild","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","CompoundWrite","writeTree_","empty","compoundWriteAddWrite","compoundWrite","rootmost","rootMostPath","newWriteTree","compoundWriteAddWrites","newWrite","compoundWriteRemoveWrite","compoundWriteHasCompleteWrite","compoundWriteGetCompleteNode","compoundWriteGetCompleteChildren","compoundWriteChildCompoundWrite","shadowingNode","compoundWriteIsEmpty","compoundWriteApply","applySubtreeWrite","writeTree","priorityWrite","writeTreeChildWrites","newWriteTreeRef","writeTreeRecordContainsPath_","writeRecord","writeTreeDefaultFilter_","writeTreeLayerTree_","writes","treeRoot","writePath","deepNode","writeTreeCalcCompleteEventCache","treePath","completeServerCache","writeIdsToExclude","includeHiddenWrites","visibleWrites","writeId","allWrites","subMerge","writeTreeRefCalcCompleteEventCache","writeTreeRef","writeTreeRefCalcCompleteEventChildren","completeServerChildren","completeChildren","topLevelSet","writeTreeCalcCompleteEventChildren","writeTreeRefCalcEventCacheAfterServerOverwrite","existingEventSnap","existingServerSnap","childMerge","writeTreeCalcEventCacheAfterServerOverwrite","writeTreeRefShadowingWrite","writeTreeShadowingWrite","writeTreeRefCalcCompleteChild","existingServerCache","writeTreeCalcCompleteChild","writeTreeRefChild","ChildChangeAccumulator","changeMap","trackChildChange","oldChange","oldType","changeChildAdded","getChanges","NO_COMPLETE_CHILD_SOURCE","getCompleteChild","getChildAfterChild","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","completeServerData","nodes","toIterate","writeTreeCalcIndexedSlice","writeTreeRefCalcIndexedSlice","viewProcessorGenerateEventCacheAfterServerEvent","viewProcessor","changePath","writesCache","accumulator","oldEventSnap","newEventCache","completeEventChildren","updateFullNode","completeNode","oldEventNode","updatedPriority","childChangePath","newEventChild","eventChildUpdate","filtersNodes","viewProcessorApplyServerOverwrite","oldViewCache","changedSnap","completeCache","filterServerNode","oldServerSnap","newServerCache","serverFilter","getIndexedFilter","newServerNode","viewProcessorApplyUserOverwrite","oldChild","viewProcessorCacheHasChild","viewProcessorApplyMerge","viewProcessorApplyServerMerge","changedChildren","viewMergeTree","curViewCache","childMergeTree","isUnknownDeepMerge","viewGetCompleteServerCache","view","cache","viewApplyOperation","viewProcessorApplyUserMerge","ackUserWrite","oldEventCache","serverChildren","viewProcessorRevertUserWrite","ackPath","mergePath","serverCachePath","viewProcessorAckUserWrite","LISTEN_COMPLETE","oldServerNode","viewProcessorListenComplete","isLeafOrEmpty","oldCompleteSnap","viewProcessorMaybeAddValueEvent","viewProcessorApplyOperation","processor_","eventRegistration","eventRegistrations_","eventRegistrations","moves","eventGeneratorGenerateEventsForChanges","eventGenerator_","viewGenerateEventsForChanges_","referenceConstructor$1","referenceConstructor","syncPointApplyOperation","syncPoint","optCompleteServerCache","views","concat","syncPointGetCompleteServerCache","SyncTree","listenProvider_","syncPointTree_","pendingWriteTree_","lastWriteId","tagToQueryMap","queryToTagMap","syncTreeApplyUserOverwrite","syncTree","writeTreeAddOverwrite","syncTreeApplyOperationToSyncPoints_","syncTreeAckUserWrite","record","writeTreeGetWrite","findIndex","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","writeTreeResetTree_","writeTreeRemoveWrite","syncTreeApplyServerOverwrite","syncTreeCalcCompleteEventCache","syncTreeApplyOperationHelper_","syncPointTree","syncTreeApplyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","syncTreeQueryKeyForTag_","syncTreeParseQueryKey_","queryKey","splitIndex","syncTreeApplyTaggedOperation_","queryPath","ExistingValueProvider","DeferredValueProvider","syncTree_","path_","generateWithValues","resolveDeferredLeafValue","existingVal","serverValues","resolveScalarDeferredValue","resolveComplexDeferredValue","existing","unused","existingNode","resolveDeferredValueTree","resolveDeferredValue","resolveDeferredValueSnapshot","rawPri","leafNode","childrenNode","Tree","parent","childCount","treeSubTree","pathObj","treeGetValue","treeSetValue","treeUpdateParents","treeHasChildren","treeForEachChild","treeForEachDescendant","includeSelf","childrenFirst","treeGetPath","childEmpty","treeIsEmpty","childExists","treeUpdateChild","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","validateFirebaseData","errorPrefix","hasDotValue","hasActualChild","last","validationPathPop","validateUrl","fnName","parsedUrl","isValidPathString","isValidRootPathString","argName","EventQueue","eventLists_","recursionDepth_","eventQueueRaiseEventsForChangedPath","eventQueue","changedPath","eventDataList","currList","getPath","eventQueueQueueEvents","sentAll","eventList","eventListRaise","eventQueueRaiseQueuedEventsMatchingPredicate","eventPath","eventFn","getEventRunner","MAX_TRANSACTION_RETRIES","Repo","forceRestClient_","appCheckProvider_","dataUpdateCount","eventQueue_","nextWriteId_","interceptServerDataCallback_","transactionQueueTree_","persistentConnection_","repoStart","repo","authOverride","search","isMerge","repoOnDataUpdate","repoOnConnectStatus","connectStatus","repoUpdateInfo","repoOnServerInfoUpdate","statsReporter_","creatorFunction","statsManagerGetOrCreateReporter","infoData_","infoSyncTree_","startListening","infoEvents","stopListening","serverSyncTree_","repoServerTime","repoGenerateServerValues","taggedChildren","raw","changeTree","syncTreeApplyTaggedQueryMerge","taggedSnap","syncTreeApplyTaggedQueryOverwrite","syncTreeApplyServerMerge","affectedPath","repoRerunTransactions","repoLog","resolvedOnDisconnectTree","resolved","repoGetAncestorTransactionNode","transactionNode","treeForEachAncestor","repoAbortTransactionsOnNode","repoAbortTransactions","repoRunOnDisconnectEvents","repoGetNextWriteId","repoGetLatestState","excludeSets","repoSendReadyTransactions","repoPruneCompletedTransactionsBelowNode","repoBuildTransactionQueue","every","setsToIgnore","txn","currentWriteId","latestState","snapToSend","latestHash","retryCount","currentOutputSnapshotRaw","dataToSend","pathToSend","currentOutputSnapshotResolved","unwatcher","abortReason","repoSendTransactionQueue","rootMostTransactionNode","abortTransaction","currentNode","currentInputSnapshot","newDataNode","oldWriteId","newNodeResolved","applyLocally","repoRerunTransactionQueue","transactionQueue","repoAggregateTransactionQueuesForNode","order","nodeQueue","to","lastSent","parseRepoInfo","dataURL","parseDatabaseURL","scheme","subdomain","colonInd","slashInd","questionMarkInd","pathStringDecoded","piece","decodePath","queryString","segment","kv","decodeQuery","hostWithoutPort","dotInd","QueryImpl","_repo","_orderByCalled","ref","ReferenceImpl","isEqual","sameRepo","samePath","sameQueryIdentifier","pathToUrlEncodedString","parentPath","syncTreeSetReferenceConstructor","repos","Database","_repoInternal","_instanceStarted","_root","_rootInternal","appRepos","repoInterrupt","repoManagerDeleteRepo","_checkNotDeleted","apiName","simpleListen","echo","onEcho","authProvider","dbUrl","databaseURL","projectId","isEmulator","dbEmulatorHost","authTokenProvider","repoManagerCreateRepo","repoManagerDatabaseFromApp","registerDatabase","_app","getElementById","loadFirebaseConfig","initializeAuth","authTokenSyncPath","isSecureContext","authTokenSyncUrl","mintCookie","idTokenResult","idTokenAge","authEmulatorHost","disableWarnings","authority","exec","hostAndPort","bracketedIPv6","extractHostAndPort","freeze","attachBanner","sty","innerText","backgroundColor","border","bottom","margin","zIndex","textAlign","classList","emitEmulatorWarning","connectAuthEmulator","getAuth","_signInWithEmailAndPassword","signInWithCredential","recachePasswordPolicy","_onAuthStateChanged","_signOut","_db","separatorIndex","lastIndexOf","getDefaultEmulatorHostnameAndPort","tokenProvider","mockUserToken","project","user_id","iss","aud","sign_in_provider","identities","alg","createMockUserToken","repoManagerApplyEmulatorSettings","connectDatabaseEmulator","getDatabase"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"./module.min.js","mappings":"AACA,IAAIA,EAAsB,CCA1BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,IAE1E,GCNDH,EAAoBS,EAAI,WACvB,GAA0B,iBAAfC,WAAyB,OAAOA,WAC3C,IACC,OAAOC,MAAQ,IAAIC,SAAS,cAAb,EAChB,CAAE,MAAOC,GACR,GAAsB,iBAAXC,OAAqB,OAAOA,MACxC,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IU,CAAiC1M,EAAM74D,EAAMsX,EAAMutD,EACvD,CAtCYW,CAAwBpuE,KAAOiG,EAEvC,CACA,OAAOjG,CACX,CCpzaYquE,G","sources":["webpack://@pewresearch/prc-platform-firebase/webpack/bootstrap","webpack://@pewresearch/prc-platform-firebase/webpack/runtime/define property getters","webpack://@pewresearch/prc-platform-firebase/webpack/runtime/global","webpack://@pewresearch/prc-platform-firebase/webpack/runtime/hasOwnProperty shorthand","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/util/dist/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/component/dist/esm/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/logger/dist/esm/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/idb/build/wrap-idb-value.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/idb/build/index.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/app/dist/esm/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/tslib/tslib.es6.mjs","webpack://@pewresearch/prc-platform-firebase/./node_modules/firebase/app/dist/esm/index.esm.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/firebase/node_modules/@firebase/auth/dist/esm2017/index-54738136.js","webpack://@pewresearch/prc-platform-firebase/./node_modules/@firebase/database/dist/index.esm2017.js","webpack://@pewresearch/prc-platform-firebase/./src/index.js"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\r\n */\r\nconst CONSTANTS = {\r\n /**\r\n * @define {boolean} Whether this is the client Node.js SDK.\r\n */\r\n NODE_CLIENT: false,\r\n /**\r\n * @define {boolean} Whether this is the Admin Node.js SDK.\r\n */\r\n NODE_ADMIN: false,\r\n /**\r\n * Firebase SDK Version\r\n */\r\n SDK_VERSION: '${JSCORE_VERSION}'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Throws an error if the provided assertion is falsy\r\n */\r\nconst assert = function (assertion, message) {\r\n if (!assertion) {\r\n throw assertionError(message);\r\n }\r\n};\r\n/**\r\n * Returns an Error object suitable for throwing.\r\n */\r\nconst assertionError = function (message) {\r\n return new Error('Firebase Database (' +\r\n CONSTANTS.SDK_VERSION +\r\n ') INTERNAL ASSERT FAILED: ' +\r\n message);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst stringToByteArray$1 = function (str) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if ((c & 0xfc00) === 0xd800 &&\r\n i + 1 < str.length &&\r\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\r\n // Surrogate Pair\r\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Turns an array of numbers into the string given by the concatenation of the\r\n * characters to which the numbers correspond.\r\n * @param bytes Array of numbers representing characters.\r\n * @return Stringification of the array.\r\n */\r\nconst byteArrayToString = function (bytes) {\r\n // TODO(user): Use native implementations if/when available\r\n const out = [];\r\n let pos = 0, c = 0;\r\n while (pos < bytes.length) {\r\n const c1 = bytes[pos++];\r\n if (c1 < 128) {\r\n out[c++] = String.fromCharCode(c1);\r\n }\r\n else if (c1 > 191 && c1 < 224) {\r\n const c2 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\r\n }\r\n else if (c1 > 239 && c1 < 365) {\r\n // Surrogate Pair\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n const c4 = bytes[pos++];\r\n const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\r\n 0x10000;\r\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\r\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\r\n }\r\n else {\r\n const c2 = bytes[pos++];\r\n const c3 = bytes[pos++];\r\n out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\r\n }\r\n }\r\n return out.join('');\r\n};\r\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\r\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\r\n// Static lookup maps, lazily populated by init_()\r\nconst base64 = {\r\n /**\r\n * Maps bytes to characters.\r\n */\r\n byteToCharMap_: null,\r\n /**\r\n * Maps characters to bytes.\r\n */\r\n charToByteMap_: null,\r\n /**\r\n * Maps bytes to websafe characters.\r\n * @private\r\n */\r\n byteToCharMapWebSafe_: null,\r\n /**\r\n * Maps websafe characters to bytes.\r\n * @private\r\n */\r\n charToByteMapWebSafe_: null,\r\n /**\r\n * Our default alphabet, shared between\r\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\r\n */\r\n ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\r\n /**\r\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\r\n */\r\n get ENCODED_VALS() {\r\n return this.ENCODED_VALS_BASE + '+/=';\r\n },\r\n /**\r\n * Our websafe alphabet.\r\n */\r\n get ENCODED_VALS_WEBSAFE() {\r\n return this.ENCODED_VALS_BASE + '-_.';\r\n },\r\n /**\r\n * Whether this browser supports the atob and btoa functions. This extension\r\n * started at Mozilla but is now implemented by many browsers. We use the\r\n * ASSUME_* variables to avoid pulling in the full useragent detection library\r\n * but still allowing the standard per-browser compilations.\r\n *\r\n */\r\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\r\n /**\r\n * Base64-encode an array of bytes.\r\n *\r\n * @param input An array of bytes (numbers with\r\n * value in [0, 255]) to encode.\r\n * @param webSafe Boolean indicating we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeByteArray(input, webSafe) {\r\n if (!Array.isArray(input)) {\r\n throw Error('encodeByteArray takes an array as a parameter');\r\n }\r\n this.init_();\r\n const byteToCharMap = webSafe\r\n ? this.byteToCharMapWebSafe_\r\n : this.byteToCharMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length; i += 3) {\r\n const byte1 = input[i];\r\n const haveByte2 = i + 1 < input.length;\r\n const byte2 = haveByte2 ? input[i + 1] : 0;\r\n const haveByte3 = i + 2 < input.length;\r\n const byte3 = haveByte3 ? input[i + 2] : 0;\r\n const outByte1 = byte1 >> 2;\r\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\r\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\r\n let outByte4 = byte3 & 0x3f;\r\n if (!haveByte3) {\r\n outByte4 = 64;\r\n if (!haveByte2) {\r\n outByte3 = 64;\r\n }\r\n }\r\n output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);\r\n }\r\n return output.join('');\r\n },\r\n /**\r\n * Base64-encode a string.\r\n *\r\n * @param input A string to encode.\r\n * @param webSafe If true, we should use the\r\n * alternative alphabet.\r\n * @return The base64 encoded string.\r\n */\r\n encodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return btoa(input);\r\n }\r\n return this.encodeByteArray(stringToByteArray$1(input), webSafe);\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * @param input to decode.\r\n * @param webSafe True if we should use the\r\n * alternative alphabet.\r\n * @return string representing the decoded value.\r\n */\r\n decodeString(input, webSafe) {\r\n // Shortcut for Mozilla browsers that implement\r\n // a native base64 encoder in the form of \"btoa/atob\"\r\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\r\n return atob(input);\r\n }\r\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\r\n },\r\n /**\r\n * Base64-decode a string.\r\n *\r\n * In base-64 decoding, groups of four characters are converted into three\r\n * bytes. If the encoder did not apply padding, the input length may not\r\n * be a multiple of 4.\r\n *\r\n * In this case, the last group will have fewer than 4 characters, and\r\n * padding will be inferred. If the group has one or two characters, it decodes\r\n * to one byte. If the group has three characters, it decodes to two bytes.\r\n *\r\n * @param input Input to decode.\r\n * @param webSafe True if we should use the web-safe alphabet.\r\n * @return bytes representing the decoded value.\r\n */\r\n decodeStringToByteArray(input, webSafe) {\r\n this.init_();\r\n const charToByteMap = webSafe\r\n ? this.charToByteMapWebSafe_\r\n : this.charToByteMap_;\r\n const output = [];\r\n for (let i = 0; i < input.length;) {\r\n const byte1 = charToByteMap[input.charAt(i++)];\r\n const haveByte2 = i < input.length;\r\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\r\n ++i;\r\n const haveByte3 = i < input.length;\r\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n const haveByte4 = i < input.length;\r\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\r\n ++i;\r\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\r\n throw new DecodeBase64StringError();\r\n }\r\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\r\n output.push(outByte1);\r\n if (byte3 !== 64) {\r\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\r\n output.push(outByte2);\r\n if (byte4 !== 64) {\r\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\r\n output.push(outByte3);\r\n }\r\n }\r\n }\r\n return output;\r\n },\r\n /**\r\n * Lazy static initialization function. Called before\r\n * accessing any of the static map variables.\r\n * @private\r\n */\r\n init_() {\r\n if (!this.byteToCharMap_) {\r\n this.byteToCharMap_ = {};\r\n this.charToByteMap_ = {};\r\n this.byteToCharMapWebSafe_ = {};\r\n this.charToByteMapWebSafe_ = {};\r\n // We want quick mappings back and forth, so we precompute two maps.\r\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\r\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\r\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\r\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\r\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\r\n // Be forgiving when decoding and correctly decode both encodings.\r\n if (i >= this.ENCODED_VALS_BASE.length) {\r\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\r\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\r\n }\r\n }\r\n }\r\n }\r\n};\r\n/**\r\n * An error encountered while decoding base64 string.\r\n */\r\nclass DecodeBase64StringError extends Error {\r\n constructor() {\r\n super(...arguments);\r\n this.name = 'DecodeBase64StringError';\r\n }\r\n}\r\n/**\r\n * URL-safe base64 encoding\r\n */\r\nconst base64Encode = function (str) {\r\n const utf8Bytes = stringToByteArray$1(str);\r\n return base64.encodeByteArray(utf8Bytes, true);\r\n};\r\n/**\r\n * URL-safe base64 encoding (without \".\" padding in the end).\r\n * e.g. Used in JSON Web Token (JWT) parts.\r\n */\r\nconst base64urlEncodeWithoutPadding = function (str) {\r\n // Use base64url encoding and remove padding in the end (dot characters).\r\n return base64Encode(str).replace(/\\./g, '');\r\n};\r\n/**\r\n * URL-safe base64 decoding\r\n *\r\n * NOTE: DO NOT use the global atob() function - it does NOT support the\r\n * base64Url variant encoding.\r\n *\r\n * @param str To be decoded\r\n * @return Decoded result, if possible\r\n */\r\nconst base64Decode = function (str) {\r\n try {\r\n return base64.decodeString(str, true);\r\n }\r\n catch (e) {\r\n console.error('base64Decode failed: ', e);\r\n }\r\n return null;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\r\nfunction deepCopy(value) {\r\n return deepExtend(undefined, value);\r\n}\r\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n *\r\n * Note: we don't merge __proto__ to prevent prototype pollution\r\n */\r\nfunction deepExtend(target, source) {\r\n if (!(source instanceof Object)) {\r\n return source;\r\n }\r\n switch (source.constructor) {\r\n case Date:\r\n // Treat Dates like scalars; if the target date object had any child\r\n // properties - they will be lost!\r\n const dateValue = source;\r\n return new Date(dateValue.getTime());\r\n case Object:\r\n if (target === undefined) {\r\n target = {};\r\n }\r\n break;\r\n case Array:\r\n // Always copy the array source and overwrite the target.\r\n target = [];\r\n break;\r\n default:\r\n // Not a plain Object - treat it as a scalar.\r\n return source;\r\n }\r\n for (const prop in source) {\r\n // use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202\r\n if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {\r\n continue;\r\n }\r\n target[prop] = deepExtend(target[prop], source[prop]);\r\n }\r\n return target;\r\n}\r\nfunction isValidKey(key) {\r\n return key !== '__proto__';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Polyfill for `globalThis` object.\r\n * @returns the `globalThis` object for the given environment.\r\n * @public\r\n */\r\nfunction getGlobal() {\r\n if (typeof self !== 'undefined') {\r\n return self;\r\n }\r\n if (typeof window !== 'undefined') {\r\n return window;\r\n }\r\n if (typeof global !== 'undefined') {\r\n return global;\r\n }\r\n throw new Error('Unable to locate global object.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;\r\n/**\r\n * Attempt to read defaults from a JSON string provided to\r\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\r\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\r\n * The dots are in parens because certain compilers (Vite?) cannot\r\n * handle seeing that variable in comments.\r\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\r\n */\r\nconst getDefaultsFromEnvVariable = () => {\r\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\r\n return;\r\n }\r\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\r\n if (defaultsJsonString) {\r\n return JSON.parse(defaultsJsonString);\r\n }\r\n};\r\nconst getDefaultsFromCookie = () => {\r\n if (typeof document === 'undefined') {\r\n return;\r\n }\r\n let match;\r\n try {\r\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\r\n }\r\n catch (e) {\r\n // Some environments such as Angular Universal SSR have a\r\n // `document` object but error on accessing `document.cookie`.\r\n return;\r\n }\r\n const decoded = match && base64Decode(match[1]);\r\n return decoded && JSON.parse(decoded);\r\n};\r\n/**\r\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\r\n * (1) if such an object exists as a property of `globalThis`\r\n * (2) if such an object was provided on a shell environment variable\r\n * (3) if such an object exists in a cookie\r\n * @public\r\n */\r\nconst getDefaults = () => {\r\n try {\r\n return (getDefaultsFromGlobal() ||\r\n getDefaultsFromEnvVariable() ||\r\n getDefaultsFromCookie());\r\n }\r\n catch (e) {\r\n /**\r\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\r\n * to any environment case we have not accounted for. Log to\r\n * info instead of swallowing so we can find these unknown cases\r\n * and add paths for them if needed.\r\n */\r\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\r\n return;\r\n }\r\n};\r\n/**\r\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHost = (productName) => { var _a, _b; return (_b = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName]; };\r\n/**\r\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\r\n * for the given product.\r\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\r\n * @public\r\n */\r\nconst getDefaultEmulatorHostnameAndPort = (productName) => {\r\n const host = getDefaultEmulatorHost(productName);\r\n if (!host) {\r\n return undefined;\r\n }\r\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\r\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\r\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\r\n }\r\n // eslint-disable-next-line no-restricted-globals\r\n const port = parseInt(host.substring(separatorIndex + 1), 10);\r\n if (host[0] === '[') {\r\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\r\n return [host.substring(1, separatorIndex - 1), port];\r\n }\r\n else {\r\n return [host.substring(0, separatorIndex), port];\r\n }\r\n};\r\n/**\r\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\r\n * @public\r\n */\r\nconst getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };\r\n/**\r\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\r\n * prefixed by \"_\")\r\n * @public\r\n */\r\nconst getExperimentalSetting = (name) => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a[`_${name}`]; };\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Deferred {\r\n constructor() {\r\n this.reject = () => { };\r\n this.resolve = () => { };\r\n this.promise = new Promise((resolve, reject) => {\r\n this.resolve = resolve;\r\n this.reject = reject;\r\n });\r\n }\r\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n */\r\n wrapCallback(callback) {\r\n return (error, value) => {\r\n if (error) {\r\n this.reject(error);\r\n }\r\n else {\r\n this.resolve(value);\r\n }\r\n if (typeof callback === 'function') {\r\n // Attaching noop handler just in case developer wasn't expecting\r\n // promises\r\n this.promise.catch(() => { });\r\n // Some of our callbacks don't expect a value and our own tests\r\n // assert that the parameter length is 1\r\n if (callback.length === 1) {\r\n callback(error);\r\n }\r\n else {\r\n callback(error, value);\r\n }\r\n }\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction createMockUserToken(token, projectId) {\r\n if (token.uid) {\r\n throw new Error('The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.');\r\n }\r\n // Unsecured JWTs use \"none\" as the algorithm.\r\n const header = {\r\n alg: 'none',\r\n type: 'JWT'\r\n };\r\n const project = projectId || 'demo-project';\r\n const iat = token.iat || 0;\r\n const sub = token.sub || token.user_id;\r\n if (!sub) {\r\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\r\n }\r\n const payload = Object.assign({ \r\n // Set all required fields to decent defaults\r\n iss: `https://securetoken.google.com/${project}`, aud: project, iat, exp: iat + 3600, auth_time: iat, sub, user_id: sub, firebase: {\r\n sign_in_provider: 'custom',\r\n identities: {}\r\n } }, token);\r\n // Unsecured JWTs use the empty string as a signature.\r\n const signature = '';\r\n return [\r\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\r\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\r\n signature\r\n ].join('.');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns navigator.userAgent string or '' if it's not defined.\r\n * @return user agent string\r\n */\r\nfunction getUA() {\r\n if (typeof navigator !== 'undefined' &&\r\n typeof navigator['userAgent'] === 'string') {\r\n return navigator['userAgent'];\r\n }\r\n else {\r\n return '';\r\n }\r\n}\r\n/**\r\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\r\n *\r\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\r\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\r\n * wait for a callback.\r\n */\r\nfunction isMobileCordova() {\r\n return (typeof window !== 'undefined' &&\r\n // @ts-ignore Setting up an broadly applicable index signature for Window\r\n // just to deal with this case would probably be a bad idea.\r\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\r\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA()));\r\n}\r\n/**\r\n * Detect Node.js.\r\n *\r\n * @return true if Node.js environment is detected or specified.\r\n */\r\n// Node detection logic from: https://github.com/iliakan/detect-node/\r\nfunction isNode() {\r\n var _a;\r\n const forceEnvironment = (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.forceEnvironment;\r\n if (forceEnvironment === 'node') {\r\n return true;\r\n }\r\n else if (forceEnvironment === 'browser') {\r\n return false;\r\n }\r\n try {\r\n return (Object.prototype.toString.call(global.process) === '[object process]');\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Detect Browser Environment\r\n */\r\nfunction isBrowser() {\r\n return typeof window !== 'undefined' || isWebWorker();\r\n}\r\n/**\r\n * Detect Web Worker context\r\n */\r\nfunction isWebWorker() {\r\n return (typeof WorkerGlobalScope !== 'undefined' &&\r\n typeof self !== 'undefined' &&\r\n self instanceof WorkerGlobalScope);\r\n}\r\nfunction isBrowserExtension() {\r\n const runtime = typeof chrome === 'object'\r\n ? chrome.runtime\r\n : typeof browser === 'object'\r\n ? browser.runtime\r\n : undefined;\r\n return typeof runtime === 'object' && runtime.id !== undefined;\r\n}\r\n/**\r\n * Detect React Native.\r\n *\r\n * @return true if ReactNative environment is detected.\r\n */\r\nfunction isReactNative() {\r\n return (typeof navigator === 'object' && navigator['product'] === 'ReactNative');\r\n}\r\n/** Detects Electron apps. */\r\nfunction isElectron() {\r\n return getUA().indexOf('Electron/') >= 0;\r\n}\r\n/** Detects Internet Explorer. */\r\nfunction isIE() {\r\n const ua = getUA();\r\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\r\n}\r\n/** Detects Universal Windows Platform apps. */\r\nfunction isUWP() {\r\n return getUA().indexOf('MSAppHost/') >= 0;\r\n}\r\n/**\r\n * Detect whether the current SDK build is the Node version.\r\n *\r\n * @return true if it's the Node SDK build.\r\n */\r\nfunction isNodeSdk() {\r\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\r\n}\r\n/** Returns true if we are running in Safari. */\r\nfunction isSafari() {\r\n return (!isNode() &&\r\n !!navigator.userAgent &&\r\n navigator.userAgent.includes('Safari') &&\r\n !navigator.userAgent.includes('Chrome'));\r\n}\r\n/**\r\n * This method checks if indexedDB is supported by current browser/service worker context\r\n * @return true if indexedDB is supported by current browser/service worker context\r\n */\r\nfunction isIndexedDBAvailable() {\r\n try {\r\n return typeof indexedDB === 'object';\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\r\n/**\r\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\r\n * if errors occur during the database open operation.\r\n *\r\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\r\n * private browsing)\r\n */\r\nfunction validateIndexedDBOpenable() {\r\n return new Promise((resolve, reject) => {\r\n try {\r\n let preExist = true;\r\n const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';\r\n const request = self.indexedDB.open(DB_CHECK_NAME);\r\n request.onsuccess = () => {\r\n request.result.close();\r\n // delete database only when it doesn't pre-exist\r\n if (!preExist) {\r\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\r\n }\r\n resolve(true);\r\n };\r\n request.onupgradeneeded = () => {\r\n preExist = false;\r\n };\r\n request.onerror = () => {\r\n var _a;\r\n reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');\r\n };\r\n }\r\n catch (error) {\r\n reject(error);\r\n }\r\n });\r\n}\r\n/**\r\n *\r\n * This method checks whether cookie is enabled within current browser\r\n * @return true if cookie is enabled within current browser\r\n */\r\nfunction areCookiesEnabled() {\r\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\r\n return false;\r\n }\r\n return true;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview Standardized Firebase Error.\r\n *\r\n * Usage:\r\n *\r\n * // Typescript string literals for type-safe codes\r\n * type Err =\r\n * 'unknown' |\r\n * 'object-not-found'\r\n * ;\r\n *\r\n * // Closure enum for type-safe error codes\r\n * // at-enum {string}\r\n * var Err = {\r\n * UNKNOWN: 'unknown',\r\n * OBJECT_NOT_FOUND: 'object-not-found',\r\n * }\r\n *\r\n * let errors: Map = {\r\n * 'generic-error': \"Unknown error\",\r\n * 'file-not-found': \"Could not find file: {$file}\",\r\n * };\r\n *\r\n * // Type-safe function - must pass a valid error code as param.\r\n * let error = new ErrorFactory('service', 'Service', errors);\r\n *\r\n * ...\r\n * throw error.create(Err.GENERIC);\r\n * ...\r\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\r\n * ...\r\n * // Service: Could not file file: foo.txt (service/file-not-found).\r\n *\r\n * catch (e) {\r\n * assert(e.message === \"Could not find file: foo.txt.\");\r\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\r\n * console.log(\"Could not read file: \" + e['file']);\r\n * }\r\n * }\r\n */\r\nconst ERROR_NAME = 'FirebaseError';\r\n// Based on code from:\r\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\r\nclass FirebaseError extends Error {\r\n constructor(\r\n /** The error code for this error. */\r\n code, message, \r\n /** Custom data for this error. */\r\n customData) {\r\n super(message);\r\n this.code = code;\r\n this.customData = customData;\r\n /** The custom name for all FirebaseErrors. */\r\n this.name = ERROR_NAME;\r\n // Fix For ES5\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, FirebaseError.prototype);\r\n // Maintains proper stack trace for where our error was thrown.\r\n // Only available on V8.\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\r\n }\r\n }\r\n}\r\nclass ErrorFactory {\r\n constructor(service, serviceName, errors) {\r\n this.service = service;\r\n this.serviceName = serviceName;\r\n this.errors = errors;\r\n }\r\n create(code, ...data) {\r\n const customData = data[0] || {};\r\n const fullCode = `${this.service}/${code}`;\r\n const template = this.errors[code];\r\n const message = template ? replaceTemplate(template, customData) : 'Error';\r\n // Service Name: Error message (service/code).\r\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\r\n const error = new FirebaseError(fullCode, fullMessage, customData);\r\n return error;\r\n }\r\n}\r\nfunction replaceTemplate(template, data) {\r\n return template.replace(PATTERN, (_, key) => {\r\n const value = data[key];\r\n return value != null ? String(value) : `<${key}?>`;\r\n });\r\n}\r\nconst PATTERN = /\\{\\$([^}]+)}/g;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Evaluates a JSON string into a javascript object.\r\n *\r\n * @param {string} str A string containing JSON.\r\n * @return {*} The javascript object representing the specified JSON.\r\n */\r\nfunction jsonEval(str) {\r\n return JSON.parse(str);\r\n}\r\n/**\r\n * Returns JSON representing a javascript object.\r\n * @param {*} data Javascript object to be stringified.\r\n * @return {string} The JSON contents of the object.\r\n */\r\nfunction stringify(data) {\r\n return JSON.stringify(data);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Decodes a Firebase auth. token into constituent parts.\r\n *\r\n * Notes:\r\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst decode = function (token) {\r\n let header = {}, claims = {}, data = {}, signature = '';\r\n try {\r\n const parts = token.split('.');\r\n header = jsonEval(base64Decode(parts[0]) || '');\r\n claims = jsonEval(base64Decode(parts[1]) || '');\r\n signature = parts[2];\r\n data = claims['d'] || {};\r\n delete claims['d'];\r\n }\r\n catch (e) { }\r\n return {\r\n header,\r\n claims,\r\n data,\r\n signature\r\n };\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\r\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidTimestamp = function (token) {\r\n const claims = decode(token).claims;\r\n const now = Math.floor(new Date().getTime() / 1000);\r\n let validSince = 0, validUntil = 0;\r\n if (typeof claims === 'object') {\r\n if (claims.hasOwnProperty('nbf')) {\r\n validSince = claims['nbf'];\r\n }\r\n else if (claims.hasOwnProperty('iat')) {\r\n validSince = claims['iat'];\r\n }\r\n if (claims.hasOwnProperty('exp')) {\r\n validUntil = claims['exp'];\r\n }\r\n else {\r\n // token will expire after 24h by default\r\n validUntil = validSince + 86400;\r\n }\r\n }\r\n return (!!now &&\r\n !!validSince &&\r\n !!validUntil &&\r\n now >= validSince &&\r\n now <= validUntil);\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\r\n *\r\n * Notes:\r\n * - May return null if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst issuedAtTime = function (token) {\r\n const claims = decode(token).claims;\r\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\r\n return claims['iat'];\r\n }\r\n return null;\r\n};\r\n/**\r\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isValidFormat = function (token) {\r\n const decoded = decode(token), claims = decoded.claims;\r\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\r\n};\r\n/**\r\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\r\n *\r\n * Notes:\r\n * - May return a false negative if there's no native base64 decoding support.\r\n * - Doesn't check if the token is actually valid.\r\n */\r\nconst isAdmin = function (token) {\r\n const claims = decode(token).claims;\r\n return typeof claims === 'object' && claims['admin'] === true;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction contains(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n}\r\nfunction safeGet(obj, key) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return obj[key];\r\n }\r\n else {\r\n return undefined;\r\n }\r\n}\r\nfunction isEmpty(obj) {\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction map(obj, fn, contextObj) {\r\n const res = {};\r\n for (const key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n res[key] = fn.call(contextObj, obj[key], key, obj);\r\n }\r\n }\r\n return res;\r\n}\r\n/**\r\n * Deep equal two objects. Support Arrays and Objects.\r\n */\r\nfunction deepEqual(a, b) {\r\n if (a === b) {\r\n return true;\r\n }\r\n const aKeys = Object.keys(a);\r\n const bKeys = Object.keys(b);\r\n for (const k of aKeys) {\r\n if (!bKeys.includes(k)) {\r\n return false;\r\n }\r\n const aProp = a[k];\r\n const bProp = b[k];\r\n if (isObject(aProp) && isObject(bProp)) {\r\n if (!deepEqual(aProp, bProp)) {\r\n return false;\r\n }\r\n }\r\n else if (aProp !== bProp) {\r\n return false;\r\n }\r\n }\r\n for (const k of bKeys) {\r\n if (!aKeys.includes(k)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction isObject(thing) {\r\n return thing !== null && typeof thing === 'object';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Rejects if the given promise doesn't resolve in timeInMS milliseconds.\r\n * @internal\r\n */\r\nfunction promiseWithTimeout(promise, timeInMS = 2000) {\r\n const deferredPromise = new Deferred();\r\n setTimeout(() => deferredPromise.reject('timeout!'), timeInMS);\r\n promise.then(deferredPromise.resolve, deferredPromise.reject);\r\n return deferredPromise.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\r\n * params object (e.g. {arg: 'val', arg2: 'val2'})\r\n * Note: You must prepend it with ? when adding it to a URL.\r\n */\r\nfunction querystring(querystringParams) {\r\n const params = [];\r\n for (const [key, value] of Object.entries(querystringParams)) {\r\n if (Array.isArray(value)) {\r\n value.forEach(arrayVal => {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal));\r\n });\r\n }\r\n else {\r\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\r\n }\r\n }\r\n return params.length ? '&' + params.join('&') : '';\r\n}\r\n/**\r\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object\r\n * (e.g. {arg: 'val', arg2: 'val2'})\r\n */\r\nfunction querystringDecode(querystring) {\r\n const obj = {};\r\n const tokens = querystring.replace(/^\\?/, '').split('&');\r\n tokens.forEach(token => {\r\n if (token) {\r\n const [key, value] = token.split('=');\r\n obj[decodeURIComponent(key)] = decodeURIComponent(value);\r\n }\r\n });\r\n return obj;\r\n}\r\n/**\r\n * Extract the query string part of a URL, including the leading question mark (if present).\r\n */\r\nfunction extractQuerystring(url) {\r\n const queryStart = url.indexOf('?');\r\n if (!queryStart) {\r\n return '';\r\n }\r\n const fragmentStart = url.indexOf('#', queryStart);\r\n return url.substring(queryStart, fragmentStart > 0 ? fragmentStart : undefined);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\r\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\nclass Sha1 {\r\n constructor() {\r\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @private\r\n */\r\n this.chain_ = [];\r\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @private\r\n */\r\n this.buf_ = [];\r\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @private\r\n */\r\n this.W_ = [];\r\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @private\r\n */\r\n this.pad_ = [];\r\n /**\r\n * @private {number}\r\n */\r\n this.inbuf_ = 0;\r\n /**\r\n * @private {number}\r\n */\r\n this.total_ = 0;\r\n this.blockSize = 512 / 8;\r\n this.pad_[0] = 128;\r\n for (let i = 1; i < this.blockSize; ++i) {\r\n this.pad_[i] = 0;\r\n }\r\n this.reset();\r\n }\r\n reset() {\r\n this.chain_[0] = 0x67452301;\r\n this.chain_[1] = 0xefcdab89;\r\n this.chain_[2] = 0x98badcfe;\r\n this.chain_[3] = 0x10325476;\r\n this.chain_[4] = 0xc3d2e1f0;\r\n this.inbuf_ = 0;\r\n this.total_ = 0;\r\n }\r\n /**\r\n * Internal compress helper function.\r\n * @param buf Block to compress.\r\n * @param offset Offset of the block in the buffer.\r\n * @private\r\n */\r\n compress_(buf, offset) {\r\n if (!offset) {\r\n offset = 0;\r\n }\r\n const W = this.W_;\r\n // get 16 big endian words\r\n if (typeof buf === 'string') {\r\n for (let i = 0; i < 16; i++) {\r\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\r\n // have a bug that turns the post-increment ++ operator into pre-increment\r\n // during JIT compilation. We have code that depends heavily on SHA-1 for\r\n // correctness and which is affected by this bug, so I've removed all uses\r\n // of post-increment ++ in which the result value is used. We can revert\r\n // this change once the Safari bug\r\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\r\n // most clients have been updated.\r\n W[i] =\r\n (buf.charCodeAt(offset) << 24) |\r\n (buf.charCodeAt(offset + 1) << 16) |\r\n (buf.charCodeAt(offset + 2) << 8) |\r\n buf.charCodeAt(offset + 3);\r\n offset += 4;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < 16; i++) {\r\n W[i] =\r\n (buf[offset] << 24) |\r\n (buf[offset + 1] << 16) |\r\n (buf[offset + 2] << 8) |\r\n buf[offset + 3];\r\n offset += 4;\r\n }\r\n }\r\n // expand to 80 words\r\n for (let i = 16; i < 80; i++) {\r\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\r\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\r\n }\r\n let a = this.chain_[0];\r\n let b = this.chain_[1];\r\n let c = this.chain_[2];\r\n let d = this.chain_[3];\r\n let e = this.chain_[4];\r\n let f, k;\r\n // TODO(user): Try to unroll this loop to speed up the computation.\r\n for (let i = 0; i < 80; i++) {\r\n if (i < 40) {\r\n if (i < 20) {\r\n f = d ^ (b & (c ^ d));\r\n k = 0x5a827999;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0x6ed9eba1;\r\n }\r\n }\r\n else {\r\n if (i < 60) {\r\n f = (b & c) | (d & (b | c));\r\n k = 0x8f1bbcdc;\r\n }\r\n else {\r\n f = b ^ c ^ d;\r\n k = 0xca62c1d6;\r\n }\r\n }\r\n const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\r\n e = d;\r\n d = c;\r\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\r\n b = a;\r\n a = t;\r\n }\r\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\r\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\r\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\r\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\r\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\r\n }\r\n update(bytes, length) {\r\n // TODO(johnlenz): tighten the function signature and remove this check\r\n if (bytes == null) {\r\n return;\r\n }\r\n if (length === undefined) {\r\n length = bytes.length;\r\n }\r\n const lengthMinusBlock = length - this.blockSize;\r\n let n = 0;\r\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\r\n const buf = this.buf_;\r\n let inbuf = this.inbuf_;\r\n // The outer while loop should execute at most twice.\r\n while (n < length) {\r\n // When we have no data in the block to top up, we can directly process the\r\n // input buffer (assuming it contains sufficient data). This gives ~25%\r\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\r\n // the data is provided in large chunks (or in multiples of 64 bytes).\r\n if (inbuf === 0) {\r\n while (n <= lengthMinusBlock) {\r\n this.compress_(bytes, n);\r\n n += this.blockSize;\r\n }\r\n }\r\n if (typeof bytes === 'string') {\r\n while (n < length) {\r\n buf[inbuf] = bytes.charCodeAt(n);\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n while (n < length) {\r\n buf[inbuf] = bytes[n];\r\n ++inbuf;\r\n ++n;\r\n if (inbuf === this.blockSize) {\r\n this.compress_(buf);\r\n inbuf = 0;\r\n // Jump to the outer loop so we use the full-block optimization.\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n this.inbuf_ = inbuf;\r\n this.total_ += length;\r\n }\r\n /** @override */\r\n digest() {\r\n const digest = [];\r\n let totalBits = this.total_ * 8;\r\n // Add pad 0x80 0x00*.\r\n if (this.inbuf_ < 56) {\r\n this.update(this.pad_, 56 - this.inbuf_);\r\n }\r\n else {\r\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\r\n }\r\n // Add # bits.\r\n for (let i = this.blockSize - 1; i >= 56; i--) {\r\n this.buf_[i] = totalBits & 255;\r\n totalBits /= 256; // Don't use bit-shifting here!\r\n }\r\n this.compress_(this.buf_);\r\n let n = 0;\r\n for (let i = 0; i < 5; i++) {\r\n for (let j = 24; j >= 0; j -= 8) {\r\n digest[n] = (this.chain_[i] >> j) & 255;\r\n ++n;\r\n }\r\n }\r\n return digest;\r\n }\r\n}\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\nfunction createSubscribe(executor, onNoObservers) {\r\n const proxy = new ObserverProxy(executor, onNoObservers);\r\n return proxy.subscribe.bind(proxy);\r\n}\r\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\r\nclass ObserverProxy {\r\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\r\n constructor(executor, onNoObservers) {\r\n this.observers = [];\r\n this.unsubscribes = [];\r\n this.observerCount = 0;\r\n // Micro-task scheduling by calling task.then().\r\n this.task = Promise.resolve();\r\n this.finalized = false;\r\n this.onNoObservers = onNoObservers;\r\n // Call the executor asynchronously so subscribers that are called\r\n // synchronously after the creation of the subscribe function\r\n // can still receive the very first value generated in the executor.\r\n this.task\r\n .then(() => {\r\n executor(this);\r\n })\r\n .catch(e => {\r\n this.error(e);\r\n });\r\n }\r\n next(value) {\r\n this.forEachObserver((observer) => {\r\n observer.next(value);\r\n });\r\n }\r\n error(error) {\r\n this.forEachObserver((observer) => {\r\n observer.error(error);\r\n });\r\n this.close(error);\r\n }\r\n complete() {\r\n this.forEachObserver((observer) => {\r\n observer.complete();\r\n });\r\n this.close();\r\n }\r\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\r\n subscribe(nextOrObserver, error, complete) {\r\n let observer;\r\n if (nextOrObserver === undefined &&\r\n error === undefined &&\r\n complete === undefined) {\r\n throw new Error('Missing Observer.');\r\n }\r\n // Assemble an Observer object when passed as callback functions.\r\n if (implementsAnyMethods(nextOrObserver, [\r\n 'next',\r\n 'error',\r\n 'complete'\r\n ])) {\r\n observer = nextOrObserver;\r\n }\r\n else {\r\n observer = {\r\n next: nextOrObserver,\r\n error,\r\n complete\r\n };\r\n }\r\n if (observer.next === undefined) {\r\n observer.next = noop;\r\n }\r\n if (observer.error === undefined) {\r\n observer.error = noop;\r\n }\r\n if (observer.complete === undefined) {\r\n observer.complete = noop;\r\n }\r\n const unsub = this.unsubscribeOne.bind(this, this.observers.length);\r\n // Attempt to subscribe to a terminated Observable - we\r\n // just respond to the Observer with the final error or complete\r\n // event.\r\n if (this.finalized) {\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n try {\r\n if (this.finalError) {\r\n observer.error(this.finalError);\r\n }\r\n else {\r\n observer.complete();\r\n }\r\n }\r\n catch (e) {\r\n // nothing\r\n }\r\n return;\r\n });\r\n }\r\n this.observers.push(observer);\r\n return unsub;\r\n }\r\n // Unsubscribe is synchronous - we guarantee that no events are sent to\r\n // any unsubscribed Observer.\r\n unsubscribeOne(i) {\r\n if (this.observers === undefined || this.observers[i] === undefined) {\r\n return;\r\n }\r\n delete this.observers[i];\r\n this.observerCount -= 1;\r\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\r\n this.onNoObservers(this);\r\n }\r\n }\r\n forEachObserver(fn) {\r\n if (this.finalized) {\r\n // Already closed by previous event....just eat the additional values.\r\n return;\r\n }\r\n // Since sendOne calls asynchronously - there is no chance that\r\n // this.observers will become undefined.\r\n for (let i = 0; i < this.observers.length; i++) {\r\n this.sendOne(i, fn);\r\n }\r\n }\r\n // Call the Observer via one of it's callback function. We are careful to\r\n // confirm that the observe has not been unsubscribed since this asynchronous\r\n // function had been queued.\r\n sendOne(i, fn) {\r\n // Execute the callback asynchronously\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n if (this.observers !== undefined && this.observers[i] !== undefined) {\r\n try {\r\n fn(this.observers[i]);\r\n }\r\n catch (e) {\r\n // Ignore exceptions raised in Observers or missing methods of an\r\n // Observer.\r\n // Log error to console. b/31404806\r\n if (typeof console !== 'undefined' && console.error) {\r\n console.error(e);\r\n }\r\n }\r\n }\r\n });\r\n }\r\n close(err) {\r\n if (this.finalized) {\r\n return;\r\n }\r\n this.finalized = true;\r\n if (err !== undefined) {\r\n this.finalError = err;\r\n }\r\n // Proxy is no longer needed - garbage collect references\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n this.task.then(() => {\r\n this.observers = undefined;\r\n this.onNoObservers = undefined;\r\n });\r\n }\r\n}\r\n/** Turn synchronous function into one called asynchronously. */\r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\nfunction async(fn, onError) {\r\n return (...args) => {\r\n Promise.resolve(true)\r\n .then(() => {\r\n fn(...args);\r\n })\r\n .catch((error) => {\r\n if (onError) {\r\n onError(error);\r\n }\r\n });\r\n };\r\n}\r\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\r\nfunction implementsAnyMethods(obj, methods) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return false;\r\n }\r\n for (const method of methods) {\r\n if (method in obj && typeof obj[method] === 'function') {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nfunction noop() {\r\n // do nothing\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Check to make sure the appropriate number of arguments are provided for a public function.\r\n * Throws an error if it fails.\r\n *\r\n * @param fnName The function name\r\n * @param minCount The minimum number of arguments to allow for the function call\r\n * @param maxCount The maximum number of argument to allow for the function call\r\n * @param argCount The actual number of arguments provided.\r\n */\r\nconst validateArgCount = function (fnName, minCount, maxCount, argCount) {\r\n let argError;\r\n if (argCount < minCount) {\r\n argError = 'at least ' + minCount;\r\n }\r\n else if (argCount > maxCount) {\r\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\r\n }\r\n if (argError) {\r\n const error = fnName +\r\n ' failed: Was called with ' +\r\n argCount +\r\n (argCount === 1 ? ' argument.' : ' arguments.') +\r\n ' Expects ' +\r\n argError +\r\n '.';\r\n throw new Error(error);\r\n }\r\n};\r\n/**\r\n * Generates a string to prefix an error message about failed argument validation\r\n *\r\n * @param fnName The function name\r\n * @param argName The name of the argument\r\n * @return The prefix to add to the error thrown for validation.\r\n */\r\nfunction errorPrefix(fnName, argName) {\r\n return `${fnName} failed: ${argName} argument `;\r\n}\r\n/**\r\n * @param fnName\r\n * @param argumentNumber\r\n * @param namespace\r\n * @param optional\r\n */\r\nfunction validateNamespace(fnName, namespace, optional) {\r\n if (optional && !namespace) {\r\n return;\r\n }\r\n if (typeof namespace !== 'string') {\r\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\r\n throw new Error(errorPrefix(fnName, 'namespace') + 'must be a valid firebase namespace.');\r\n }\r\n}\r\nfunction validateCallback(fnName, argumentName, \r\n// eslint-disable-next-line @typescript-eslint/ban-types\r\ncallback, optional) {\r\n if (optional && !callback) {\r\n return;\r\n }\r\n if (typeof callback !== 'function') {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid function.');\r\n }\r\n}\r\nfunction validateContextObject(fnName, argumentName, context, optional) {\r\n if (optional && !context) {\r\n return;\r\n }\r\n if (typeof context !== 'object' || context === null) {\r\n throw new Error(errorPrefix(fnName, argumentName) + 'must be a valid context object.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\r\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\r\n// so it's been modified.\r\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\r\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\r\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\r\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\r\n// pair).\r\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\r\n/**\r\n * @param {string} str\r\n * @return {Array}\r\n */\r\nconst stringToByteArray = function (str) {\r\n const out = [];\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n let c = str.charCodeAt(i);\r\n // Is this the lead surrogate in a surrogate pair?\r\n if (c >= 0xd800 && c <= 0xdbff) {\r\n const high = c - 0xd800; // the high 10 bits.\r\n i++;\r\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\r\n const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\r\n c = 0x10000 + (high << 10) + low;\r\n }\r\n if (c < 128) {\r\n out[p++] = c;\r\n }\r\n else if (c < 2048) {\r\n out[p++] = (c >> 6) | 192;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else if (c < 65536) {\r\n out[p++] = (c >> 12) | 224;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n else {\r\n out[p++] = (c >> 18) | 240;\r\n out[p++] = ((c >> 12) & 63) | 128;\r\n out[p++] = ((c >> 6) & 63) | 128;\r\n out[p++] = (c & 63) | 128;\r\n }\r\n }\r\n return out;\r\n};\r\n/**\r\n * Calculate length without actually converting; useful for doing cheaper validation.\r\n * @param {string} str\r\n * @return {number}\r\n */\r\nconst stringLength = function (str) {\r\n let p = 0;\r\n for (let i = 0; i < str.length; i++) {\r\n const c = str.charCodeAt(i);\r\n if (c < 128) {\r\n p++;\r\n }\r\n else if (c < 2048) {\r\n p += 2;\r\n }\r\n else if (c >= 0xd800 && c <= 0xdbff) {\r\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\r\n p += 4;\r\n i++; // skip trail surrogate.\r\n }\r\n else {\r\n p += 3;\r\n }\r\n }\r\n return p;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Copied from https://stackoverflow.com/a/2117523\r\n * Generates a new uuid.\r\n * @public\r\n */\r\nconst uuidv4 = function () {\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {\r\n const r = (Math.random() * 16) | 0, v = c === 'x' ? r : (r & 0x3) | 0x8;\r\n return v.toString(16);\r\n });\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The amount of milliseconds to exponentially increase.\r\n */\r\nconst DEFAULT_INTERVAL_MILLIS = 1000;\r\n/**\r\n * The factor to backoff by.\r\n * Should be a number greater than 1.\r\n */\r\nconst DEFAULT_BACKOFF_FACTOR = 2;\r\n/**\r\n * The maximum milliseconds to increase to.\r\n *\r\n *

Visible for testing\r\n */\r\nconst MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\r\n/**\r\n * The percentage of backoff time to randomize by.\r\n * See\r\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\r\n * for context.\r\n *\r\n *

Visible for testing\r\n */\r\nconst RANDOM_FACTOR = 0.5;\r\n/**\r\n * Based on the backoff method from\r\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\r\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\r\n */\r\nfunction calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {\r\n // Calculates an exponentially increasing value.\r\n // Deviation: calculates value from count and a constant interval, so we only need to save value\r\n // and count to restore state.\r\n const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);\r\n // A random \"fuzz\" to avoid waves of retries.\r\n // Deviation: randomFactor is required.\r\n const randomWait = Math.round(\r\n // A fraction of the backoff value to add/subtract.\r\n // Deviation: changes multiplication order to improve readability.\r\n RANDOM_FACTOR *\r\n currBaseValue *\r\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\r\n // if we add or subtract.\r\n (Math.random() - 0.5) *\r\n 2);\r\n // Limits backoff to max to avoid effectively permanent backoff.\r\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provide English ordinal letters after a number\r\n */\r\nfunction ordinal(i) {\r\n if (!Number.isFinite(i)) {\r\n return `${i}`;\r\n }\r\n return i + indicator(i);\r\n}\r\nfunction indicator(i) {\r\n i = Math.abs(i);\r\n const cent = i % 100;\r\n if (cent >= 10 && cent <= 20) {\r\n return 'th';\r\n }\r\n const dec = i % 10;\r\n if (dec === 1) {\r\n return 'st';\r\n }\r\n if (dec === 2) {\r\n return 'nd';\r\n }\r\n if (dec === 3) {\r\n return 'rd';\r\n }\r\n return 'th';\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getModularInstance(service) {\r\n if (service && service._delegate) {\r\n return service._delegate;\r\n }\r\n else {\r\n return service;\r\n }\r\n}\n\nexport { CONSTANTS, DecodeBase64StringError, Deferred, ErrorFactory, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getDefaultAppConfig, getDefaultEmulatorHost, getDefaultEmulatorHostnameAndPort, getDefaults, getExperimentalSetting, getGlobal, getModularInstance, getUA, isAdmin, isBrowser, isBrowserExtension, isElectron, isEmpty, isIE, isIndexedDBAvailable, isMobileCordova, isNode, isNodeSdk, isReactNative, isSafari, isUWP, isValidFormat, isValidTimestamp, isWebWorker, issuedAtTime, jsonEval, map, ordinal, promiseWithTimeout, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, uuidv4, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace };\n//# sourceMappingURL=index.esm2017.js.map\n","import { Deferred } from '@firebase/util';\n\n/**\r\n * Component for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass Component {\r\n /**\r\n *\r\n * @param name The public service name, e.g. app, auth, firestore, database\r\n * @param instanceFactory Service factory responsible for creating the public interface\r\n * @param type whether the service provided by the component is public or private\r\n */\r\n constructor(name, instanceFactory, type) {\r\n this.name = name;\r\n this.instanceFactory = instanceFactory;\r\n this.type = type;\r\n this.multipleInstances = false;\r\n /**\r\n * Properties to be added to the service namespace\r\n */\r\n this.serviceProps = {};\r\n this.instantiationMode = \"LAZY\" /* InstantiationMode.LAZY */;\r\n this.onInstanceCreated = null;\r\n }\r\n setInstantiationMode(mode) {\r\n this.instantiationMode = mode;\r\n return this;\r\n }\r\n setMultipleInstances(multipleInstances) {\r\n this.multipleInstances = multipleInstances;\r\n return this;\r\n }\r\n setServiceProps(props) {\r\n this.serviceProps = props;\r\n return this;\r\n }\r\n setInstanceCreatedCallback(callback) {\r\n this.onInstanceCreated = callback;\r\n return this;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\r\n * NameServiceMapping[T] is an alias for the type of the instance\r\n */\r\nclass Provider {\r\n constructor(name, container) {\r\n this.name = name;\r\n this.container = container;\r\n this.component = null;\r\n this.instances = new Map();\r\n this.instancesDeferred = new Map();\r\n this.instancesOptions = new Map();\r\n this.onInitCallbacks = new Map();\r\n }\r\n /**\r\n * @param identifier A provider can provide mulitple instances of a service\r\n * if this.component.multipleInstances is true.\r\n */\r\n get(identifier) {\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\r\n const deferred = new Deferred();\r\n this.instancesDeferred.set(normalizedIdentifier, deferred);\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n // initialize the service if it can be auto-initialized\r\n try {\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n if (instance) {\r\n deferred.resolve(instance);\r\n }\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception during get(), it should not cause\r\n // a fatal error. We just return the unresolved promise in this case.\r\n }\r\n }\r\n }\r\n return this.instancesDeferred.get(normalizedIdentifier).promise;\r\n }\r\n getImmediate(options) {\r\n var _a;\r\n // if multipleInstances is not supported, use the default name\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);\r\n const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;\r\n if (this.isInitialized(normalizedIdentifier) ||\r\n this.shouldAutoInitialize()) {\r\n try {\r\n return this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n }\r\n catch (e) {\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n }\r\n else {\r\n // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw\r\n if (optional) {\r\n return null;\r\n }\r\n else {\r\n throw Error(`Service ${this.name} is not available`);\r\n }\r\n }\r\n }\r\n getComponent() {\r\n return this.component;\r\n }\r\n setComponent(component) {\r\n if (component.name !== this.name) {\r\n throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);\r\n }\r\n if (this.component) {\r\n throw Error(`Component for ${this.name} has already been provided`);\r\n }\r\n this.component = component;\r\n // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)\r\n if (!this.shouldAutoInitialize()) {\r\n return;\r\n }\r\n // if the service is eager, initialize the default instance\r\n if (isComponentEager(component)) {\r\n try {\r\n this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME });\r\n }\r\n catch (e) {\r\n // when the instance factory for an eager Component throws an exception during the eager\r\n // initialization, it should not cause a fatal error.\r\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\r\n // a fatal error in this case?\r\n }\r\n }\r\n // Create service instances for the pending promises and resolve them\r\n // NOTE: if this.multipleInstances is false, only the default instance will be created\r\n // and all promises with resolve with it regardless of the identifier.\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n try {\r\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier\r\n });\r\n instanceDeferred.resolve(instance);\r\n }\r\n catch (e) {\r\n // when the instance factory throws an exception, it should not cause\r\n // a fatal error. We just leave the promise unresolved.\r\n }\r\n }\r\n }\r\n clearInstance(identifier = DEFAULT_ENTRY_NAME) {\r\n this.instancesDeferred.delete(identifier);\r\n this.instancesOptions.delete(identifier);\r\n this.instances.delete(identifier);\r\n }\r\n // app.delete() will call this method on every provider to delete the services\r\n // TODO: should we mark the provider as deleted?\r\n async delete() {\r\n const services = Array.from(this.instances.values());\r\n await Promise.all([\r\n ...services\r\n .filter(service => 'INTERNAL' in service) // legacy services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service.INTERNAL.delete()),\r\n ...services\r\n .filter(service => '_delete' in service) // modularized services\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n .map(service => service._delete())\r\n ]);\r\n }\r\n isComponentSet() {\r\n return this.component != null;\r\n }\r\n isInitialized(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instances.has(identifier);\r\n }\r\n getOptions(identifier = DEFAULT_ENTRY_NAME) {\r\n return this.instancesOptions.get(identifier) || {};\r\n }\r\n initialize(opts = {}) {\r\n const { options = {} } = opts;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);\r\n if (this.isInitialized(normalizedIdentifier)) {\r\n throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);\r\n }\r\n if (!this.isComponentSet()) {\r\n throw Error(`Component ${this.name} has not been registered yet`);\r\n }\r\n const instance = this.getOrInitializeService({\r\n instanceIdentifier: normalizedIdentifier,\r\n options\r\n });\r\n // resolve any pending promise waiting for the service instance\r\n for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {\r\n const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);\r\n if (normalizedIdentifier === normalizedDeferredIdentifier) {\r\n instanceDeferred.resolve(instance);\r\n }\r\n }\r\n return instance;\r\n }\r\n /**\r\n *\r\n * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().\r\n * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.\r\n *\r\n * @param identifier An optional instance identifier\r\n * @returns a function to unregister the callback\r\n */\r\n onInit(callback, identifier) {\r\n var _a;\r\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\r\n const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();\r\n existingCallbacks.add(callback);\r\n this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);\r\n const existingInstance = this.instances.get(normalizedIdentifier);\r\n if (existingInstance) {\r\n callback(existingInstance, normalizedIdentifier);\r\n }\r\n return () => {\r\n existingCallbacks.delete(callback);\r\n };\r\n }\r\n /**\r\n * Invoke onInit callbacks synchronously\r\n * @param instance the service instance`\r\n */\r\n invokeOnInitCallbacks(instance, identifier) {\r\n const callbacks = this.onInitCallbacks.get(identifier);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n try {\r\n callback(instance, identifier);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInit callback\r\n }\r\n }\r\n }\r\n getOrInitializeService({ instanceIdentifier, options = {} }) {\r\n let instance = this.instances.get(instanceIdentifier);\r\n if (!instance && this.component) {\r\n instance = this.component.instanceFactory(this.container, {\r\n instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),\r\n options\r\n });\r\n this.instances.set(instanceIdentifier, instance);\r\n this.instancesOptions.set(instanceIdentifier, options);\r\n /**\r\n * Invoke onInit listeners.\r\n * Note this.component.onInstanceCreated is different, which is used by the component creator,\r\n * while onInit listeners are registered by consumers of the provider.\r\n */\r\n this.invokeOnInitCallbacks(instance, instanceIdentifier);\r\n /**\r\n * Order is important\r\n * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which\r\n * makes `isInitialized()` return true.\r\n */\r\n if (this.component.onInstanceCreated) {\r\n try {\r\n this.component.onInstanceCreated(this.container, instanceIdentifier, instance);\r\n }\r\n catch (_a) {\r\n // ignore errors in the onInstanceCreatedCallback\r\n }\r\n }\r\n }\r\n return instance || null;\r\n }\r\n normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {\r\n if (this.component) {\r\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\r\n }\r\n else {\r\n return identifier; // assume multiple instances are supported before the component is provided.\r\n }\r\n }\r\n shouldAutoInitialize() {\r\n return (!!this.component &&\r\n this.component.instantiationMode !== \"EXPLICIT\" /* InstantiationMode.EXPLICIT */);\r\n }\r\n}\r\n// undefined should be passed to the service factory for the default instance\r\nfunction normalizeIdentifierForFactory(identifier) {\r\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\r\n}\r\nfunction isComponentEager(component) {\r\n return component.instantiationMode === \"EAGER\" /* InstantiationMode.EAGER */;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\r\n */\r\nclass ComponentContainer {\r\n constructor(name) {\r\n this.name = name;\r\n this.providers = new Map();\r\n }\r\n /**\r\n *\r\n * @param component Component being added\r\n * @param overwrite When a component with the same name has already been registered,\r\n * if overwrite is true: overwrite the existing component with the new component and create a new\r\n * provider with the new component. It can be useful in tests where you want to use different mocks\r\n * for different tests.\r\n * if overwrite is false: throw an exception\r\n */\r\n addComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n throw new Error(`Component ${component.name} has already been registered with ${this.name}`);\r\n }\r\n provider.setComponent(component);\r\n }\r\n addOrOverwriteComponent(component) {\r\n const provider = this.getProvider(component.name);\r\n if (provider.isComponentSet()) {\r\n // delete the existing provider from the container, so we can register the new component\r\n this.providers.delete(component.name);\r\n }\r\n this.addComponent(component);\r\n }\r\n /**\r\n * getProvider provides a type safe interface where it can only be called with a field name\r\n * present in NameServiceMapping interface.\r\n *\r\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\r\n * themselves.\r\n */\r\n getProvider(name) {\r\n if (this.providers.has(name)) {\r\n return this.providers.get(name);\r\n }\r\n // create a Provider for a service that hasn't registered with Firebase\r\n const provider = new Provider(name, this);\r\n this.providers.set(name, provider);\r\n return provider;\r\n }\r\n getProviders() {\r\n return Array.from(this.providers.values());\r\n }\r\n}\n\nexport { Component, ComponentContainer, Provider };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A container for all of the Logger instances\r\n */\r\nconst instances = [];\r\n/**\r\n * The JS SDK supports 5 log levels and also allows a user the ability to\r\n * silence the logs altogether.\r\n *\r\n * The order is a follows:\r\n * DEBUG < VERBOSE < INFO < WARN < ERROR\r\n *\r\n * All of the log types above the current log level will be captured (i.e. if\r\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\r\n * `VERBOSE` logs will not)\r\n */\r\nvar LogLevel;\r\n(function (LogLevel) {\r\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\r\n LogLevel[LogLevel[\"VERBOSE\"] = 1] = \"VERBOSE\";\r\n LogLevel[LogLevel[\"INFO\"] = 2] = \"INFO\";\r\n LogLevel[LogLevel[\"WARN\"] = 3] = \"WARN\";\r\n LogLevel[LogLevel[\"ERROR\"] = 4] = \"ERROR\";\r\n LogLevel[LogLevel[\"SILENT\"] = 5] = \"SILENT\";\r\n})(LogLevel || (LogLevel = {}));\r\nconst levelStringToEnum = {\r\n 'debug': LogLevel.DEBUG,\r\n 'verbose': LogLevel.VERBOSE,\r\n 'info': LogLevel.INFO,\r\n 'warn': LogLevel.WARN,\r\n 'error': LogLevel.ERROR,\r\n 'silent': LogLevel.SILENT\r\n};\r\n/**\r\n * The default log level\r\n */\r\nconst defaultLogLevel = LogLevel.INFO;\r\n/**\r\n * By default, `console.debug` is not displayed in the developer console (in\r\n * chrome). To avoid forcing users to have to opt-in to these logs twice\r\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\r\n * logs to the `console.log` function.\r\n */\r\nconst ConsoleMethod = {\r\n [LogLevel.DEBUG]: 'log',\r\n [LogLevel.VERBOSE]: 'log',\r\n [LogLevel.INFO]: 'info',\r\n [LogLevel.WARN]: 'warn',\r\n [LogLevel.ERROR]: 'error'\r\n};\r\n/**\r\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\r\n * messages on to their corresponding console counterparts (if the log method\r\n * is supported by the current log level)\r\n */\r\nconst defaultLogHandler = (instance, logType, ...args) => {\r\n if (logType < instance.logLevel) {\r\n return;\r\n }\r\n const now = new Date().toISOString();\r\n const method = ConsoleMethod[logType];\r\n if (method) {\r\n console[method](`[${now}] ${instance.name}:`, ...args);\r\n }\r\n else {\r\n throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);\r\n }\r\n};\r\nclass Logger {\r\n /**\r\n * Gives you an instance of a Logger to capture messages according to\r\n * Firebase's logging scheme.\r\n *\r\n * @param name The name that the logs will be associated with\r\n */\r\n constructor(name) {\r\n this.name = name;\r\n /**\r\n * The log level of the given Logger instance.\r\n */\r\n this._logLevel = defaultLogLevel;\r\n /**\r\n * The main (internal) log handler for the Logger instance.\r\n * Can be set to a new function in internal package code but not by user.\r\n */\r\n this._logHandler = defaultLogHandler;\r\n /**\r\n * The optional, additional, user-defined log handler for the Logger instance.\r\n */\r\n this._userLogHandler = null;\r\n /**\r\n * Capture the current instance for later use\r\n */\r\n instances.push(this);\r\n }\r\n get logLevel() {\r\n return this._logLevel;\r\n }\r\n set logLevel(val) {\r\n if (!(val in LogLevel)) {\r\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\r\n }\r\n this._logLevel = val;\r\n }\r\n // Workaround for setter/getter having to be the same type.\r\n setLogLevel(val) {\r\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\r\n }\r\n get logHandler() {\r\n return this._logHandler;\r\n }\r\n set logHandler(val) {\r\n if (typeof val !== 'function') {\r\n throw new TypeError('Value assigned to `logHandler` must be a function');\r\n }\r\n this._logHandler = val;\r\n }\r\n get userLogHandler() {\r\n return this._userLogHandler;\r\n }\r\n set userLogHandler(val) {\r\n this._userLogHandler = val;\r\n }\r\n /**\r\n * The functions below are all based on the `console` interface\r\n */\r\n debug(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\r\n this._logHandler(this, LogLevel.DEBUG, ...args);\r\n }\r\n log(...args) {\r\n this._userLogHandler &&\r\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\r\n this._logHandler(this, LogLevel.VERBOSE, ...args);\r\n }\r\n info(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\r\n this._logHandler(this, LogLevel.INFO, ...args);\r\n }\r\n warn(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\r\n this._logHandler(this, LogLevel.WARN, ...args);\r\n }\r\n error(...args) {\r\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\r\n this._logHandler(this, LogLevel.ERROR, ...args);\r\n }\r\n}\r\nfunction setLogLevel(level) {\r\n instances.forEach(inst => {\r\n inst.setLogLevel(level);\r\n });\r\n}\r\nfunction setUserLogHandler(logCallback, options) {\r\n for (const instance of instances) {\r\n let customLogLevel = null;\r\n if (options && options.level) {\r\n customLogLevel = levelStringToEnum[options.level];\r\n }\r\n if (logCallback === null) {\r\n instance.userLogHandler = null;\r\n }\r\n else {\r\n instance.userLogHandler = (instance, level, ...args) => {\r\n const message = args\r\n .map(arg => {\r\n if (arg == null) {\r\n return null;\r\n }\r\n else if (typeof arg === 'string') {\r\n return arg;\r\n }\r\n else if (typeof arg === 'number' || typeof arg === 'boolean') {\r\n return arg.toString();\r\n }\r\n else if (arg instanceof Error) {\r\n return arg.message;\r\n }\r\n else {\r\n try {\r\n return JSON.stringify(arg);\r\n }\r\n catch (ignored) {\r\n return null;\r\n }\r\n }\r\n })\r\n .filter(arg => arg)\r\n .join(' ');\r\n if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {\r\n logCallback({\r\n level: LogLevel[level].toLowerCase(),\r\n message,\r\n args,\r\n type: instance.name\r\n });\r\n }\r\n };\r\n }\r\n }\r\n}\n\nexport { LogLevel, Logger, setLogLevel, setUserLogHandler };\n//# sourceMappingURL=index.esm2017.js.map\n","const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);\n\nlet idbProxyableTypes;\nlet cursorAdvanceMethods;\n// This is a function to prevent it throwing up in node environments.\nfunction getIdbProxyableTypes() {\n return (idbProxyableTypes ||\n (idbProxyableTypes = [\n IDBDatabase,\n IDBObjectStore,\n IDBIndex,\n IDBCursor,\n IDBTransaction,\n ]));\n}\n// This is a function to prevent it throwing up in node environments.\nfunction getCursorAdvanceMethods() {\n return (cursorAdvanceMethods ||\n (cursorAdvanceMethods = [\n IDBCursor.prototype.advance,\n IDBCursor.prototype.continue,\n IDBCursor.prototype.continuePrimaryKey,\n ]));\n}\nconst cursorRequestMap = new WeakMap();\nconst transactionDoneMap = new WeakMap();\nconst transactionStoreNamesMap = new WeakMap();\nconst transformCache = new WeakMap();\nconst reverseTransformCache = new WeakMap();\nfunction promisifyRequest(request) {\n const promise = new Promise((resolve, reject) => {\n const unlisten = () => {\n request.removeEventListener('success', success);\n request.removeEventListener('error', error);\n };\n const success = () => {\n resolve(wrap(request.result));\n unlisten();\n };\n const error = () => {\n reject(request.error);\n unlisten();\n };\n request.addEventListener('success', success);\n request.addEventListener('error', error);\n });\n promise\n .then((value) => {\n // Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval\n // (see wrapFunction).\n if (value instanceof IDBCursor) {\n cursorRequestMap.set(value, request);\n }\n // Catching to avoid \"Uncaught Promise exceptions\"\n })\n .catch(() => { });\n // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This\n // is because we create many promises from a single IDBRequest.\n reverseTransformCache.set(promise, request);\n return promise;\n}\nfunction cacheDonePromiseForTransaction(tx) {\n // Early bail if we've already created a done promise for this transaction.\n if (transactionDoneMap.has(tx))\n return;\n const done = new Promise((resolve, reject) => {\n const unlisten = () => {\n tx.removeEventListener('complete', complete);\n tx.removeEventListener('error', error);\n tx.removeEventListener('abort', error);\n };\n const complete = () => {\n resolve();\n unlisten();\n };\n const error = () => {\n reject(tx.error || new DOMException('AbortError', 'AbortError'));\n unlisten();\n };\n tx.addEventListener('complete', complete);\n tx.addEventListener('error', error);\n tx.addEventListener('abort', error);\n });\n // Cache it for later retrieval.\n transactionDoneMap.set(tx, done);\n}\nlet idbProxyTraps = {\n get(target, prop, receiver) {\n if (target instanceof IDBTransaction) {\n // Special handling for transaction.done.\n if (prop === 'done')\n return transactionDoneMap.get(target);\n // Polyfill for objectStoreNames because of Edge.\n if (prop === 'objectStoreNames') {\n return target.objectStoreNames || transactionStoreNamesMap.get(target);\n }\n // Make tx.store return the only store in the transaction, or undefined if there are many.\n if (prop === 'store') {\n return receiver.objectStoreNames[1]\n ? undefined\n : receiver.objectStore(receiver.objectStoreNames[0]);\n }\n }\n // Else transform whatever we get back.\n return wrap(target[prop]);\n },\n set(target, prop, value) {\n target[prop] = value;\n return true;\n },\n has(target, prop) {\n if (target instanceof IDBTransaction &&\n (prop === 'done' || prop === 'store')) {\n return true;\n }\n return prop in target;\n },\n};\nfunction replaceTraps(callback) {\n idbProxyTraps = callback(idbProxyTraps);\n}\nfunction wrapFunction(func) {\n // Due to expected object equality (which is enforced by the caching in `wrap`), we\n // only create one new func per func.\n // Edge doesn't support objectStoreNames (booo), so we polyfill it here.\n if (func === IDBDatabase.prototype.transaction &&\n !('objectStoreNames' in IDBTransaction.prototype)) {\n return function (storeNames, ...args) {\n const tx = func.call(unwrap(this), storeNames, ...args);\n transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);\n return wrap(tx);\n };\n }\n // Cursor methods are special, as the behaviour is a little more different to standard IDB. In\n // IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the\n // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense\n // with real promises, so each advance methods returns a new promise for the cursor object, or\n // undefined if the end of the cursor has been reached.\n if (getCursorAdvanceMethods().includes(func)) {\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n func.apply(unwrap(this), args);\n return wrap(cursorRequestMap.get(this));\n };\n }\n return function (...args) {\n // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use\n // the original object.\n return wrap(func.apply(unwrap(this), args));\n };\n}\nfunction transformCachableValue(value) {\n if (typeof value === 'function')\n return wrapFunction(value);\n // This doesn't return, it just creates a 'done' promise for the transaction,\n // which is later returned for transaction.done (see idbObjectHandler).\n if (value instanceof IDBTransaction)\n cacheDonePromiseForTransaction(value);\n if (instanceOfAny(value, getIdbProxyableTypes()))\n return new Proxy(value, idbProxyTraps);\n // Return the same value back if we're not going to transform it.\n return value;\n}\nfunction wrap(value) {\n // We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because\n // IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.\n if (value instanceof IDBRequest)\n return promisifyRequest(value);\n // If we've already transformed this value before, reuse the transformed value.\n // This is faster, but it also provides object equality.\n if (transformCache.has(value))\n return transformCache.get(value);\n const newValue = transformCachableValue(value);\n // Not all types are transformed.\n // These may be primitive types, so they can't be WeakMap keys.\n if (newValue !== value) {\n transformCache.set(value, newValue);\n reverseTransformCache.set(newValue, value);\n }\n return newValue;\n}\nconst unwrap = (value) => reverseTransformCache.get(value);\n\nexport { reverseTransformCache as a, instanceOfAny as i, replaceTraps as r, unwrap as u, wrap as w };\n","import { w as wrap, r as replaceTraps } from './wrap-idb-value.js';\nexport { u as unwrap, w as wrap } from './wrap-idb-value.js';\n\n/**\n * Open a database.\n *\n * @param name Name of the database.\n * @param version Schema version.\n * @param callbacks Additional callbacks.\n */\nfunction openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {\n const request = indexedDB.open(name, version);\n const openPromise = wrap(request);\n if (upgrade) {\n request.addEventListener('upgradeneeded', (event) => {\n upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);\n });\n }\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event.newVersion, event));\n }\n openPromise\n .then((db) => {\n if (terminated)\n db.addEventListener('close', () => terminated());\n if (blocking) {\n db.addEventListener('versionchange', (event) => blocking(event.oldVersion, event.newVersion, event));\n }\n })\n .catch(() => { });\n return openPromise;\n}\n/**\n * Delete a database.\n *\n * @param name Name of the database.\n */\nfunction deleteDB(name, { blocked } = {}) {\n const request = indexedDB.deleteDatabase(name);\n if (blocked) {\n request.addEventListener('blocked', (event) => blocked(\n // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405\n event.oldVersion, event));\n }\n return wrap(request).then(() => undefined);\n}\n\nconst readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];\nconst writeMethods = ['put', 'add', 'delete', 'clear'];\nconst cachedMethods = new Map();\nfunction getMethod(target, prop) {\n if (!(target instanceof IDBDatabase &&\n !(prop in target) &&\n typeof prop === 'string')) {\n return;\n }\n if (cachedMethods.get(prop))\n return cachedMethods.get(prop);\n const targetFuncName = prop.replace(/FromIndex$/, '');\n const useIndex = prop !== targetFuncName;\n const isWrite = writeMethods.includes(targetFuncName);\n if (\n // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.\n !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||\n !(isWrite || readMethods.includes(targetFuncName))) {\n return;\n }\n const method = async function (storeName, ...args) {\n // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(\n const tx = this.transaction(storeName, isWrite ? 'readwrite' : 'readonly');\n let target = tx.store;\n if (useIndex)\n target = target.index(args.shift());\n // Must reject if op rejects.\n // If it's a write operation, must reject if tx.done rejects.\n // Must reject with op rejection first.\n // Must resolve with op value.\n // Must handle both promises (no unhandled rejections)\n return (await Promise.all([\n target[targetFuncName](...args),\n isWrite && tx.done,\n ]))[0];\n };\n cachedMethods.set(prop, method);\n return method;\n}\nreplaceTraps((oldTraps) => ({\n ...oldTraps,\n get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),\n has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop),\n}));\n\nexport { deleteDB, openDB };\n","import { Component, ComponentContainer } from '@firebase/component';\nimport { Logger, setUserLogHandler, setLogLevel as setLogLevel$1 } from '@firebase/logger';\nimport { ErrorFactory, getDefaultAppConfig, deepEqual, isBrowser, isWebWorker, FirebaseError, base64urlEncodeWithoutPadding, isIndexedDBAvailable, validateIndexedDBOpenable } from '@firebase/util';\nexport { FirebaseError } from '@firebase/util';\nimport { openDB } from 'idb';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PlatformLoggerServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n }\r\n // In initial implementation, this will be called by installations on\r\n // auth token refresh, and installations will send this string.\r\n getPlatformInfoString() {\r\n const providers = this.container.getProviders();\r\n // Loop through providers and get library/version pairs from any that are\r\n // version components.\r\n return providers\r\n .map(provider => {\r\n if (isVersionServiceProvider(provider)) {\r\n const service = provider.getImmediate();\r\n return `${service.library}/${service.version}`;\r\n }\r\n else {\r\n return null;\r\n }\r\n })\r\n .filter(logString => logString)\r\n .join(' ');\r\n }\r\n}\r\n/**\r\n *\r\n * @param provider check if this provider provides a VersionService\r\n *\r\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\r\n * provides VersionService. The provider is not necessarily a 'app-version'\r\n * provider.\r\n */\r\nfunction isVersionServiceProvider(provider) {\r\n const component = provider.getComponent();\r\n return (component === null || component === void 0 ? void 0 : component.type) === \"VERSION\" /* ComponentType.VERSION */;\r\n}\n\nconst name$p = \"@firebase/app\";\nconst version$1 = \"0.10.7\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/app');\n\nconst name$o = \"@firebase/app-compat\";\n\nconst name$n = \"@firebase/analytics-compat\";\n\nconst name$m = \"@firebase/analytics\";\n\nconst name$l = \"@firebase/app-check-compat\";\n\nconst name$k = \"@firebase/app-check\";\n\nconst name$j = \"@firebase/auth\";\n\nconst name$i = \"@firebase/auth-compat\";\n\nconst name$h = \"@firebase/database\";\n\nconst name$g = \"@firebase/database-compat\";\n\nconst name$f = \"@firebase/functions\";\n\nconst name$e = \"@firebase/functions-compat\";\n\nconst name$d = \"@firebase/installations\";\n\nconst name$c = \"@firebase/installations-compat\";\n\nconst name$b = \"@firebase/messaging\";\n\nconst name$a = \"@firebase/messaging-compat\";\n\nconst name$9 = \"@firebase/performance\";\n\nconst name$8 = \"@firebase/performance-compat\";\n\nconst name$7 = \"@firebase/remote-config\";\n\nconst name$6 = \"@firebase/remote-config-compat\";\n\nconst name$5 = \"@firebase/storage\";\n\nconst name$4 = \"@firebase/storage-compat\";\n\nconst name$3 = \"@firebase/firestore\";\n\nconst name$2 = \"@firebase/vertexai-preview\";\n\nconst name$1 = \"@firebase/firestore-compat\";\n\nconst name = \"firebase\";\nconst version = \"10.12.4\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The default app name\r\n *\r\n * @internal\r\n */\r\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\r\nconst PLATFORM_LOG_STRING = {\r\n [name$p]: 'fire-core',\r\n [name$o]: 'fire-core-compat',\r\n [name$m]: 'fire-analytics',\r\n [name$n]: 'fire-analytics-compat',\r\n [name$k]: 'fire-app-check',\r\n [name$l]: 'fire-app-check-compat',\r\n [name$j]: 'fire-auth',\r\n [name$i]: 'fire-auth-compat',\r\n [name$h]: 'fire-rtdb',\r\n [name$g]: 'fire-rtdb-compat',\r\n [name$f]: 'fire-fn',\r\n [name$e]: 'fire-fn-compat',\r\n [name$d]: 'fire-iid',\r\n [name$c]: 'fire-iid-compat',\r\n [name$b]: 'fire-fcm',\r\n [name$a]: 'fire-fcm-compat',\r\n [name$9]: 'fire-perf',\r\n [name$8]: 'fire-perf-compat',\r\n [name$7]: 'fire-rc',\r\n [name$6]: 'fire-rc-compat',\r\n [name$5]: 'fire-gcs',\r\n [name$4]: 'fire-gcs-compat',\r\n [name$3]: 'fire-fst',\r\n [name$1]: 'fire-fst-compat',\r\n [name$2]: 'fire-vertex',\r\n 'fire-js': 'fire-js',\r\n [name]: 'fire-js-all'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nconst _apps = new Map();\r\n/**\r\n * @internal\r\n */\r\nconst _serverApps = new Map();\r\n/**\r\n * Registered components.\r\n *\r\n * @internal\r\n */\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nconst _components = new Map();\r\n/**\r\n * @param component - the component being added to this app's container\r\n *\r\n * @internal\r\n */\r\nfunction _addComponent(app, component) {\r\n try {\r\n app.container.addComponent(component);\r\n }\r\n catch (e) {\r\n logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);\r\n }\r\n}\r\n/**\r\n *\r\n * @internal\r\n */\r\nfunction _addOrOverwriteComponent(app, component) {\r\n app.container.addOrOverwriteComponent(component);\r\n}\r\n/**\r\n *\r\n * @param component - the component to register\r\n * @returns whether or not the component is registered successfully\r\n *\r\n * @internal\r\n */\r\nfunction _registerComponent(component) {\r\n const componentName = component.name;\r\n if (_components.has(componentName)) {\r\n logger.debug(`There were multiple attempts to register component ${componentName}.`);\r\n return false;\r\n }\r\n _components.set(componentName, component);\r\n // add the component to existing app instances\r\n for (const app of _apps.values()) {\r\n _addComponent(app, component);\r\n }\r\n for (const serverApp of _serverApps.values()) {\r\n _addComponent(serverApp, component);\r\n }\r\n return true;\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n *\r\n * @returns the provider for the service with the matching name\r\n *\r\n * @internal\r\n */\r\nfunction _getProvider(app, name) {\r\n const heartbeatController = app.container\r\n .getProvider('heartbeat')\r\n .getImmediate({ optional: true });\r\n if (heartbeatController) {\r\n void heartbeatController.triggerHeartbeat();\r\n }\r\n return app.container.getProvider(name);\r\n}\r\n/**\r\n *\r\n * @param app - FirebaseApp instance\r\n * @param name - service name\r\n * @param instanceIdentifier - service instance identifier in case the service supports multiple instances\r\n *\r\n * @internal\r\n */\r\nfunction _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {\r\n _getProvider(app, name).clearInstance(instanceIdentifier);\r\n}\r\n/**\r\n *\r\n * @param obj - an object of type FirebaseApp or FirebaseOptions.\r\n *\r\n * @returns true if the provide object is of type FirebaseApp.\r\n *\r\n * @internal\r\n */\r\nfunction _isFirebaseApp(obj) {\r\n return obj.options !== undefined;\r\n}\r\n/**\r\n *\r\n * @param obj - an object of type FirebaseApp.\r\n *\r\n * @returns true if the provided object is of type FirebaseServerAppImpl.\r\n *\r\n * @internal\r\n */\r\nfunction _isFirebaseServerApp(obj) {\r\n return obj.settings !== undefined;\r\n}\r\n/**\r\n * Test only\r\n *\r\n * @internal\r\n */\r\nfunction _clearComponents() {\r\n _components.clear();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n [\"no-app\" /* AppError.NO_APP */]: \"No Firebase App '{$appName}' has been created - \" +\r\n 'call initializeApp() first',\r\n [\"bad-app-name\" /* AppError.BAD_APP_NAME */]: \"Illegal App name: '{$appName}'\",\r\n [\"duplicate-app\" /* AppError.DUPLICATE_APP */]: \"Firebase App named '{$appName}' already exists with different options or config\",\r\n [\"app-deleted\" /* AppError.APP_DELETED */]: \"Firebase App named '{$appName}' already deleted\",\r\n [\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */]: 'Firebase Server App has been deleted',\r\n [\"no-options\" /* AppError.NO_OPTIONS */]: 'Need to provide options, when not being deployed to hosting via source.',\r\n [\"invalid-app-argument\" /* AppError.INVALID_APP_ARGUMENT */]: 'firebase.{$appName}() takes either no argument or a ' +\r\n 'Firebase App instance.',\r\n [\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */]: 'First argument to `onLog` must be null or a function.',\r\n [\"idb-open\" /* AppError.IDB_OPEN */]: 'Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-get\" /* AppError.IDB_GET */]: 'Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-set\" /* AppError.IDB_WRITE */]: 'Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"idb-delete\" /* AppError.IDB_DELETE */]: 'Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.',\r\n [\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: 'FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.',\r\n [\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: 'FirebaseServerApp is not for use in browser environments.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('app', 'Firebase', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseAppImpl {\r\n constructor(options, config, container) {\r\n this._isDeleted = false;\r\n this._options = Object.assign({}, options);\r\n this._config = Object.assign({}, config);\r\n this._name = config.name;\r\n this._automaticDataCollectionEnabled =\r\n config.automaticDataCollectionEnabled;\r\n this._container = container;\r\n this.container.addComponent(new Component('app', () => this, \"PUBLIC\" /* ComponentType.PUBLIC */));\r\n }\r\n get automaticDataCollectionEnabled() {\r\n this.checkDestroyed();\r\n return this._automaticDataCollectionEnabled;\r\n }\r\n set automaticDataCollectionEnabled(val) {\r\n this.checkDestroyed();\r\n this._automaticDataCollectionEnabled = val;\r\n }\r\n get name() {\r\n this.checkDestroyed();\r\n return this._name;\r\n }\r\n get options() {\r\n this.checkDestroyed();\r\n return this._options;\r\n }\r\n get config() {\r\n this.checkDestroyed();\r\n return this._config;\r\n }\r\n get container() {\r\n return this._container;\r\n }\r\n get isDeleted() {\r\n return this._isDeleted;\r\n }\r\n set isDeleted(val) {\r\n this._isDeleted = val;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"app-deleted\" /* AppError.APP_DELETED */, { appName: this._name });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FirebaseServerAppImpl extends FirebaseAppImpl {\r\n constructor(options, serverConfig, name, container) {\r\n // Build configuration parameters for the FirebaseAppImpl base class.\r\n const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined\r\n ? serverConfig.automaticDataCollectionEnabled\r\n : false;\r\n // Create the FirebaseAppSettings object for the FirebaseAppImp constructor.\r\n const config = {\r\n name,\r\n automaticDataCollectionEnabled\r\n };\r\n if (options.apiKey !== undefined) {\r\n // Construct the parent FirebaseAppImp object.\r\n super(options, config, container);\r\n }\r\n else {\r\n const appImpl = options;\r\n super(appImpl.options, config, container);\r\n }\r\n // Now construct the data for the FirebaseServerAppImpl.\r\n this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig);\r\n this._finalizationRegistry = null;\r\n if (typeof FinalizationRegistry !== 'undefined') {\r\n this._finalizationRegistry = new FinalizationRegistry(() => {\r\n this.automaticCleanup();\r\n });\r\n }\r\n this._refCount = 0;\r\n this.incRefCount(this._serverConfig.releaseOnDeref);\r\n // Do not retain a hard reference to the dref object, otherwise the FinalizationRegisry\r\n // will never trigger.\r\n this._serverConfig.releaseOnDeref = undefined;\r\n serverConfig.releaseOnDeref = undefined;\r\n registerVersion(name$p, version$1, 'serverapp');\r\n }\r\n toJSON() {\r\n return undefined;\r\n }\r\n get refCount() {\r\n return this._refCount;\r\n }\r\n // Increment the reference count of this server app. If an object is provided, register it\r\n // with the finalization registry.\r\n incRefCount(obj) {\r\n if (this.isDeleted) {\r\n return;\r\n }\r\n this._refCount++;\r\n if (obj !== undefined && this._finalizationRegistry !== null) {\r\n this._finalizationRegistry.register(obj, this);\r\n }\r\n }\r\n // Decrement the reference count.\r\n decRefCount() {\r\n if (this.isDeleted) {\r\n return 0;\r\n }\r\n return --this._refCount;\r\n }\r\n // Invoked by the FinalizationRegistry callback to note that this app should go through its\r\n // reference counts and delete itself if no reference count remain. The coordinating logic that\r\n // handles this is in deleteApp(...).\r\n automaticCleanup() {\r\n void deleteApp(this);\r\n }\r\n get settings() {\r\n this.checkDestroyed();\r\n return this._serverConfig;\r\n }\r\n /**\r\n * This function will throw an Error if the App has already been deleted -\r\n * use before performing API actions on the App.\r\n */\r\n checkDestroyed() {\r\n if (this.isDeleted) {\r\n throw ERROR_FACTORY.create(\"server-app-deleted\" /* AppError.SERVER_APP_DELETED */);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The current SDK version.\r\n *\r\n * @public\r\n */\r\nconst SDK_VERSION = version;\r\nfunction initializeApp(_options, rawConfig = {}) {\r\n let options = _options;\r\n if (typeof rawConfig !== 'object') {\r\n const name = rawConfig;\r\n rawConfig = { name };\r\n }\r\n const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);\r\n const name = config.name;\r\n if (typeof name !== 'string' || !name) {\r\n throw ERROR_FACTORY.create(\"bad-app-name\" /* AppError.BAD_APP_NAME */, {\r\n appName: String(name)\r\n });\r\n }\r\n options || (options = getDefaultAppConfig());\r\n if (!options) {\r\n throw ERROR_FACTORY.create(\"no-options\" /* AppError.NO_OPTIONS */);\r\n }\r\n const existingApp = _apps.get(name);\r\n if (existingApp) {\r\n // return the existing app if options and config deep equal the ones in the existing app.\r\n if (deepEqual(options, existingApp.options) &&\r\n deepEqual(config, existingApp.config)) {\r\n return existingApp;\r\n }\r\n else {\r\n throw ERROR_FACTORY.create(\"duplicate-app\" /* AppError.DUPLICATE_APP */, { appName: name });\r\n }\r\n }\r\n const container = new ComponentContainer(name);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseAppImpl(options, config, container);\r\n _apps.set(name, newApp);\r\n return newApp;\r\n}\r\nfunction initializeServerApp(_options, _serverAppConfig) {\r\n if (isBrowser() && !isWebWorker()) {\r\n // FirebaseServerApp isn't designed to be run in browsers.\r\n throw ERROR_FACTORY.create(\"invalid-server-app-environment\" /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);\r\n }\r\n if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {\r\n _serverAppConfig.automaticDataCollectionEnabled = false;\r\n }\r\n let appOptions;\r\n if (_isFirebaseApp(_options)) {\r\n appOptions = _options.options;\r\n }\r\n else {\r\n appOptions = _options;\r\n }\r\n // Build an app name based on a hash of the configuration options.\r\n const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions);\r\n // However, Do not mangle the name based on releaseOnDeref, since it will vary between the\r\n // construction of FirebaseServerApp instances. For example, if the object is the request headers.\r\n if (nameObj.releaseOnDeref !== undefined) {\r\n delete nameObj.releaseOnDeref;\r\n }\r\n const hashCode = (s) => {\r\n return [...s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);\r\n };\r\n if (_serverAppConfig.releaseOnDeref !== undefined) {\r\n if (typeof FinalizationRegistry === 'undefined') {\r\n throw ERROR_FACTORY.create(\"finalization-registry-not-supported\" /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});\r\n }\r\n }\r\n const nameString = '' + hashCode(JSON.stringify(nameObj));\r\n const existingApp = _serverApps.get(nameString);\r\n if (existingApp) {\r\n existingApp.incRefCount(_serverAppConfig.releaseOnDeref);\r\n return existingApp;\r\n }\r\n const container = new ComponentContainer(nameString);\r\n for (const component of _components.values()) {\r\n container.addComponent(component);\r\n }\r\n const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container);\r\n _serverApps.set(nameString, newApp);\r\n return newApp;\r\n}\r\n/**\r\n * Retrieves a {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * When called with no arguments, the default app is returned. When an app name\r\n * is provided, the app corresponding to that name is returned.\r\n *\r\n * An exception is thrown if the app being retrieved has not yet been\r\n * initialized.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return the default app\r\n * const app = getApp();\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Return a named app\r\n * const otherApp = getApp(\"otherApp\");\r\n * ```\r\n *\r\n * @param name - Optional name of the app to return. If no name is\r\n * provided, the default is `\"[DEFAULT]\"`.\r\n *\r\n * @returns The app corresponding to the provided app name.\r\n * If no app name is provided, the default app is returned.\r\n *\r\n * @public\r\n */\r\nfunction getApp(name = DEFAULT_ENTRY_NAME) {\r\n const app = _apps.get(name);\r\n if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {\r\n return initializeApp();\r\n }\r\n if (!app) {\r\n throw ERROR_FACTORY.create(\"no-app\" /* AppError.NO_APP */, { appName: name });\r\n }\r\n return app;\r\n}\r\n/**\r\n * A (read-only) array of all initialized apps.\r\n * @public\r\n */\r\nfunction getApps() {\r\n return Array.from(_apps.values());\r\n}\r\n/**\r\n * Renders this app unusable and frees the resources of all associated\r\n * services.\r\n *\r\n * @example\r\n * ```javascript\r\n * deleteApp(app)\r\n * .then(function() {\r\n * console.log(\"App deleted successfully\");\r\n * })\r\n * .catch(function(error) {\r\n * console.log(\"Error deleting app:\", error);\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nasync function deleteApp(app) {\r\n let cleanupProviders = false;\r\n const name = app.name;\r\n if (_apps.has(name)) {\r\n cleanupProviders = true;\r\n _apps.delete(name);\r\n }\r\n else if (_serverApps.has(name)) {\r\n const firebaseServerApp = app;\r\n if (firebaseServerApp.decRefCount() <= 0) {\r\n _serverApps.delete(name);\r\n cleanupProviders = true;\r\n }\r\n }\r\n if (cleanupProviders) {\r\n await Promise.all(app.container\r\n .getProviders()\r\n .map(provider => provider.delete()));\r\n app.isDeleted = true;\r\n }\r\n}\r\n/**\r\n * Registers a library's name and version for platform logging purposes.\r\n * @param library - Name of 1p or 3p library (e.g. firestore, angularfire)\r\n * @param version - Current version of that library.\r\n * @param variant - Bundle variant, e.g., node, rn, etc.\r\n *\r\n * @public\r\n */\r\nfunction registerVersion(libraryKeyOrName, version, variant) {\r\n var _a;\r\n // TODO: We can use this check to whitelist strings when/if we set up\r\n // a good whitelist system.\r\n let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;\r\n if (variant) {\r\n library += `-${variant}`;\r\n }\r\n const libraryMismatch = library.match(/\\s|\\//);\r\n const versionMismatch = version.match(/\\s|\\//);\r\n if (libraryMismatch || versionMismatch) {\r\n const warning = [\r\n `Unable to register library \"${library}\" with version \"${version}\":`\r\n ];\r\n if (libraryMismatch) {\r\n warning.push(`library name \"${library}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n if (libraryMismatch && versionMismatch) {\r\n warning.push('and');\r\n }\r\n if (versionMismatch) {\r\n warning.push(`version name \"${version}\" contains illegal characters (whitespace or \"/\")`);\r\n }\r\n logger.warn(warning.join(' '));\r\n return;\r\n }\r\n _registerComponent(new Component(`${library}-version`, () => ({ library, version }), \"VERSION\" /* ComponentType.VERSION */));\r\n}\r\n/**\r\n * Sets log handler for all Firebase SDKs.\r\n * @param logCallback - An optional custom log handler that executes user code whenever\r\n * the Firebase SDK makes a logging call.\r\n *\r\n * @public\r\n */\r\nfunction onLog(logCallback, options) {\r\n if (logCallback !== null && typeof logCallback !== 'function') {\r\n throw ERROR_FACTORY.create(\"invalid-log-argument\" /* AppError.INVALID_LOG_ARGUMENT */);\r\n }\r\n setUserLogHandler(logCallback, options);\r\n}\r\n/**\r\n * Sets log level for all Firebase SDKs.\r\n *\r\n * All of the log types above the current log level are captured (i.e. if\r\n * you set the log level to `info`, errors are logged, but `debug` and\r\n * `verbose` logs are not).\r\n *\r\n * @public\r\n */\r\nfunction setLogLevel(logLevel) {\r\n setLogLevel$1(logLevel);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebase-heartbeat-database';\r\nconst DB_VERSION = 1;\r\nconst STORE_NAME = 'firebase-heartbeat-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DB_NAME, DB_VERSION, {\r\n upgrade: (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n try {\r\n db.createObjectStore(STORE_NAME);\r\n }\r\n catch (e) {\r\n // Safari/iOS browsers throw occasional exceptions on\r\n // db.createObjectStore() that may be a bug. Avoid blocking\r\n // the rest of the app functionality.\r\n console.warn(e);\r\n }\r\n }\r\n }\r\n }).catch(e => {\r\n throw ERROR_FACTORY.create(\"idb-open\" /* AppError.IDB_OPEN */, {\r\n originalErrorMessage: e.message\r\n });\r\n });\r\n }\r\n return dbPromise;\r\n}\r\nasync function readHeartbeatsFromIndexedDB(app) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME);\r\n const result = await tx.objectStore(STORE_NAME).get(computeKey(app));\r\n // We already have the value but tx.done can throw,\r\n // so we need to await it here to catch errors\r\n await tx.done;\r\n return result;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-get\" /* AppError.IDB_GET */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nasync function writeHeartbeatsToIndexedDB(app, heartbeatObject) {\r\n try {\r\n const db = await getDbPromise();\r\n const tx = db.transaction(STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(STORE_NAME);\r\n await objectStore.put(heartbeatObject, computeKey(app));\r\n await tx.done;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n logger.warn(e.message);\r\n }\r\n else {\r\n const idbGetError = ERROR_FACTORY.create(\"idb-set\" /* AppError.IDB_WRITE */, {\r\n originalErrorMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n logger.warn(idbGetError.message);\r\n }\r\n }\r\n}\r\nfunction computeKey(app) {\r\n return `${app.name}!${app.options.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst MAX_HEADER_BYTES = 1024;\r\n// 30 days\r\nconst STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1000;\r\nclass HeartbeatServiceImpl {\r\n constructor(container) {\r\n this.container = container;\r\n /**\r\n * In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate\r\n * the header string.\r\n * Stores one record per date. This will be consolidated into the standard\r\n * format of one record per user agent string before being sent as a header.\r\n * Populated from indexedDB when the controller is instantiated and should\r\n * be kept in sync with indexedDB.\r\n * Leave public for easier testing.\r\n */\r\n this._heartbeatsCache = null;\r\n const app = this.container.getProvider('app').getImmediate();\r\n this._storage = new HeartbeatStorageImpl(app);\r\n this._heartbeatsCachePromise = this._storage.read().then(result => {\r\n this._heartbeatsCache = result;\r\n return result;\r\n });\r\n }\r\n /**\r\n * Called to report a heartbeat. The function will generate\r\n * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it\r\n * to IndexedDB.\r\n * Note that we only store one heartbeat per day. So if a heartbeat for today is\r\n * already logged, subsequent calls to this function in the same day will be ignored.\r\n */\r\n async triggerHeartbeat() {\r\n var _a, _b;\r\n const platformLogger = this.container\r\n .getProvider('platform-logger')\r\n .getImmediate();\r\n // This is the \"Firebase user agent\" string from the platform logger\r\n // service, not the browser user agent.\r\n const agent = platformLogger.getPlatformInfoString();\r\n const date = getUTCDateString();\r\n if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) {\r\n this._heartbeatsCache = await this._heartbeatsCachePromise;\r\n // If we failed to construct a heartbeats cache, then return immediately.\r\n if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {\r\n return;\r\n }\r\n }\r\n // Do not store a heartbeat if one is already stored for this day\r\n // or if a header has already been sent today.\r\n if (this._heartbeatsCache.lastSentHeartbeatDate === date ||\r\n this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {\r\n return;\r\n }\r\n else {\r\n // There is no entry for this date. Create one.\r\n this._heartbeatsCache.heartbeats.push({ date, agent });\r\n }\r\n // Remove entries older than 30 days.\r\n this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter(singleDateHeartbeat => {\r\n const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();\r\n const now = Date.now();\r\n return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;\r\n });\r\n return this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n /**\r\n * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.\r\n * It also clears all heartbeats from memory as well as in IndexedDB.\r\n *\r\n * NOTE: Consuming product SDKs should not send the header if this method\r\n * returns an empty string.\r\n */\r\n async getHeartbeatsHeader() {\r\n var _a;\r\n if (this._heartbeatsCache === null) {\r\n await this._heartbeatsCachePromise;\r\n }\r\n // If it's still null or the array is empty, there is no data to send.\r\n if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null ||\r\n this._heartbeatsCache.heartbeats.length === 0) {\r\n return '';\r\n }\r\n const date = getUTCDateString();\r\n // Extract as many heartbeats from the cache as will fit under the size limit.\r\n const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);\r\n const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));\r\n // Store last sent date to prevent another being logged/sent for the same day.\r\n this._heartbeatsCache.lastSentHeartbeatDate = date;\r\n if (unsentEntries.length > 0) {\r\n // Store any unsent entries if they exist.\r\n this._heartbeatsCache.heartbeats = unsentEntries;\r\n // This seems more likely than emptying the array (below) to lead to some odd state\r\n // since the cache isn't empty and this will be called again on the next request,\r\n // and is probably safest if we await it.\r\n await this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n else {\r\n this._heartbeatsCache.heartbeats = [];\r\n // Do not wait for this, to reduce latency.\r\n void this._storage.overwrite(this._heartbeatsCache);\r\n }\r\n return headerString;\r\n }\r\n}\r\nfunction getUTCDateString() {\r\n const today = new Date();\r\n // Returns date format 'YYYY-MM-DD'\r\n return today.toISOString().substring(0, 10);\r\n}\r\nfunction extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {\r\n // Heartbeats grouped by user agent in the standard format to be sent in\r\n // the header.\r\n const heartbeatsToSend = [];\r\n // Single date format heartbeats that are not sent.\r\n let unsentEntries = heartbeatsCache.slice();\r\n for (const singleDateHeartbeat of heartbeatsCache) {\r\n // Look for an existing entry with the same user agent.\r\n const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);\r\n if (!heartbeatEntry) {\r\n // If no entry for this user agent exists, create one.\r\n heartbeatsToSend.push({\r\n agent: singleDateHeartbeat.agent,\r\n dates: [singleDateHeartbeat.date]\r\n });\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n // If the header would exceed max size, remove the added heartbeat\r\n // entry and stop adding to the header.\r\n heartbeatsToSend.pop();\r\n break;\r\n }\r\n }\r\n else {\r\n heartbeatEntry.dates.push(singleDateHeartbeat.date);\r\n // If the header would exceed max size, remove the added date\r\n // and stop adding to the header.\r\n if (countBytes(heartbeatsToSend) > maxSize) {\r\n heartbeatEntry.dates.pop();\r\n break;\r\n }\r\n }\r\n // Pop unsent entry from queue. (Skipped if adding the entry exceeded\r\n // quota and the loop breaks early.)\r\n unsentEntries = unsentEntries.slice(1);\r\n }\r\n return {\r\n heartbeatsToSend,\r\n unsentEntries\r\n };\r\n}\r\nclass HeartbeatStorageImpl {\r\n constructor(app) {\r\n this.app = app;\r\n this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();\r\n }\r\n async runIndexedDBEnvironmentCheck() {\r\n if (!isIndexedDBAvailable()) {\r\n return false;\r\n }\r\n else {\r\n return validateIndexedDBOpenable()\r\n .then(() => true)\r\n .catch(() => false);\r\n }\r\n }\r\n /**\r\n * Read all heartbeats.\r\n */\r\n async read() {\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return { heartbeats: [] };\r\n }\r\n else {\r\n const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);\r\n if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {\r\n return idbHeartbeatObject;\r\n }\r\n else {\r\n return { heartbeats: [] };\r\n }\r\n }\r\n }\r\n // overwrite the storage with the provided heartbeats\r\n async overwrite(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: heartbeatsObject.heartbeats\r\n });\r\n }\r\n }\r\n // add heartbeats\r\n async add(heartbeatsObject) {\r\n var _a;\r\n const canUseIndexedDB = await this._canUseIndexedDBPromise;\r\n if (!canUseIndexedDB) {\r\n return;\r\n }\r\n else {\r\n const existingHeartbeatsObject = await this.read();\r\n return writeHeartbeatsToIndexedDB(this.app, {\r\n lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,\r\n heartbeats: [\r\n ...existingHeartbeatsObject.heartbeats,\r\n ...heartbeatsObject.heartbeats\r\n ]\r\n });\r\n }\r\n }\r\n}\r\n/**\r\n * Calculate bytes of a HeartbeatsByUserAgent array after being wrapped\r\n * in a platform logging header JSON object, stringified, and converted\r\n * to base 64.\r\n */\r\nfunction countBytes(heartbeatsCache) {\r\n // base64 has a restricted set of characters, all of which should be 1 byte.\r\n return base64urlEncodeWithoutPadding(\r\n // heartbeatsCache wrapper properties\r\n JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerCoreComponents(variant) {\r\n _registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n _registerComponent(new Component('heartbeat', container => new HeartbeatServiceImpl(container), \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n // Register `app` package.\r\n registerVersion(name$p, version$1, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name$p, version$1, 'esm2017');\r\n // Register platform SDK identifier (no version).\r\n registerVersion('fire-js', '');\r\n}\n\n/**\r\n * Firebase App\r\n *\r\n * @remarks This package coordinates the communication between the different Firebase components\r\n * @packageDocumentation\r\n */\r\nregisterCoreComponents('');\n\nexport { SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _isFirebaseApp, _isFirebaseServerApp, _registerComponent, _removeServiceInstance, _serverApps, deleteApp, getApp, getApps, initializeApp, initializeServerApp, onLog, registerVersion, setLogLevel };\n//# sourceMappingURL=index.esm2017.js.map\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n","import { registerVersion } from '@firebase/app';\nexport * from '@firebase/app';\n\nvar name = \"firebase\";\nvar version = \"10.12.4\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nregisterVersion(name, version, 'app');\n//# sourceMappingURL=index.esm.js.map\n","import { SDK_VERSION, _isFirebaseServerApp, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';\nimport { ErrorFactory, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, deepEqual, querystringDecode, extractQuerystring, isEmpty, getExperimentalSetting, getDefaultEmulatorHost } from '@firebase/util';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { __rest } from 'tslib';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An enum of factors that may be used for multifactor authentication.\r\n *\r\n * @public\r\n */\r\nconst FactorId = {\r\n /** Phone as second factor */\r\n PHONE: 'phone',\r\n TOTP: 'totp'\r\n};\r\n/**\r\n * Enumeration of supported providers.\r\n *\r\n * @public\r\n */\r\nconst ProviderId = {\r\n /** Facebook provider ID */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub provider ID */\r\n GITHUB: 'github.com',\r\n /** Google provider ID */\r\n GOOGLE: 'google.com',\r\n /** Password provider */\r\n PASSWORD: 'password',\r\n /** Phone provider */\r\n PHONE: 'phone',\r\n /** Twitter provider ID */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported sign-in methods.\r\n *\r\n * @public\r\n */\r\nconst SignInMethod = {\r\n /** Email link sign in method */\r\n EMAIL_LINK: 'emailLink',\r\n /** Email/password sign in method */\r\n EMAIL_PASSWORD: 'password',\r\n /** Facebook sign in method */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub sign in method */\r\n GITHUB: 'github.com',\r\n /** Google sign in method */\r\n GOOGLE: 'google.com',\r\n /** Phone sign in method */\r\n PHONE: 'phone',\r\n /** Twitter sign in method */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported operation types.\r\n *\r\n * @public\r\n */\r\nconst OperationType = {\r\n /** Operation involving linking an additional provider to an already signed-in user. */\r\n LINK: 'link',\r\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\r\n REAUTHENTICATE: 'reauthenticate',\r\n /** Operation involving signing in a user. */\r\n SIGN_IN: 'signIn'\r\n};\r\n/**\r\n * An enumeration of the possible email action types.\r\n *\r\n * @public\r\n */\r\nconst ActionCodeOperation = {\r\n /** The email link sign-in action. */\r\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\r\n /** The password reset action. */\r\n PASSWORD_RESET: 'PASSWORD_RESET',\r\n /** The email revocation action. */\r\n RECOVER_EMAIL: 'RECOVER_EMAIL',\r\n /** The revert second factor addition email action. */\r\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\r\n /** The revert second factor addition email action. */\r\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\r\n /** The email verification action. */\r\n VERIFY_EMAIL: 'VERIFY_EMAIL'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _debugErrorMap() {\r\n return {\r\n [\"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',\r\n [\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */]: '',\r\n [\"app-not-authorized\" /* AuthErrorCode.APP_NOT_AUTHORIZED */]: \"This app, identified by the domain where it's hosted, is not \" +\r\n 'authorized to use Firebase Authentication with the provided API key. ' +\r\n 'Review your key configuration in the Google API console.',\r\n [\"app-not-installed\" /* AuthErrorCode.APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +\r\n 'Android package name or iOS bundle ID) provided is not installed on ' +\r\n 'this device.',\r\n [\"captcha-check-failed\" /* AuthErrorCode.CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +\r\n 'already used or the domain associated with it does not match the list ' +\r\n 'of whitelisted domains.',\r\n [\"code-expired\" /* AuthErrorCode.CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +\r\n 'again.',\r\n [\"cordova-not-ready\" /* AuthErrorCode.CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',\r\n [\"cors-unsupported\" /* AuthErrorCode.CORS_UNSUPPORTED */]: 'This browser is not supported.',\r\n [\"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',\r\n [\"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',\r\n [\"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +\r\n 'again before retrying this request.',\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.',\r\n [\"dynamic-link-not-activated\" /* AuthErrorCode.DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\r\n 'conditions.',\r\n [\"email-change-needs-verification\" /* AuthErrorCode.EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',\r\n [\"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */]: 'The email address is already in use by another account.',\r\n [\"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +\r\n 'no longer be configured to use the emulator. Try calling ' +\r\n '\"connectAuthEmulator()\" sooner.',\r\n [\"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */]: 'The action code has expired.',\r\n [\"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',\r\n [\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */]: 'An internal AuthError has occurred.',\r\n [\"invalid-app-credential\" /* AuthErrorCode.INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +\r\n ' The reCAPTCHA token response is either invalid or expired.',\r\n [\"invalid-app-id\" /* AuthErrorCode.INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',\r\n [\"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */]: \"This user's credential isn't valid for this project. This can happen \" +\r\n \"if the user's token has been tampered with, or if the user isn't for \" +\r\n 'the project associated with this API key.',\r\n [\"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +\r\n 'invalid. Please resend the verification code sms and be sure to use the ' +\r\n 'verification code provided by the user.',\r\n [\"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',\r\n [\"invalid-cordova-configuration\" /* AuthErrorCode.INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\r\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\r\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\r\n 'cordova-plugin-customurlscheme.',\r\n [\"invalid-custom-token\" /* AuthErrorCode.INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',\r\n [\"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',\r\n [\"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */]: 'The email address is badly formatted.',\r\n [\"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',\r\n [\"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',\r\n [\"invalid-cert-hash\" /* AuthErrorCode.INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',\r\n [\"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */]: 'The supplied auth credential is incorrect, malformed or has expired.',\r\n [\"invalid-message-payload\" /* AuthErrorCode.INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',\r\n [\"invalid-oauth-provider\" /* AuthErrorCode.INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +\r\n 'only supports OAuth providers.',\r\n [\"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +\r\n 'specified API key.',\r\n [\"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +\r\n 'project. Edit the list of authorized domains from the Firebase console.',\r\n [\"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +\r\n 'expired, or has already been used.',\r\n [\"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',\r\n [\"invalid-persistence-type\" /* AuthErrorCode.INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',\r\n [\"invalid-phone-number\" /* AuthErrorCode.INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +\r\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\r\n 'phone numbers are written in the format [+][country code][subscriber ' +\r\n 'number including area code].',\r\n [\"invalid-provider-id\" /* AuthErrorCode.INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',\r\n [\"invalid-recipient-email\" /* AuthErrorCode.INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +\r\n 'recipient email address is invalid.',\r\n [\"invalid-sender\" /* AuthErrorCode.INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',\r\n [\"invalid-tenant-id\" /* AuthErrorCode.INVALID_TENANT_ID */]: \"The Auth instance's tenant ID is invalid.\",\r\n [\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */]: 'Login blocked by user-provided method: {$originalMessage}',\r\n [\"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */]: 'An Android Package Name must be provided if the Android App is required to be installed.',\r\n [\"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\r\n 'by following the instructions in the Firebase console.',\r\n [\"missing-app-credential\" /* AuthErrorCode.MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +\r\n 'assertion. A reCAPTCHA response token needs to be provided.',\r\n [\"missing-verification-code\" /* AuthErrorCode.MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',\r\n [\"missing-continue-uri\" /* AuthErrorCode.MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',\r\n [\"missing-iframe-start\" /* AuthErrorCode.MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',\r\n [\"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',\r\n [\"missing-or-invalid-nonce\" /* AuthErrorCode.MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +\r\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\r\n 'in the ID token payload.',\r\n [\"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */]: 'A non-empty password must be provided',\r\n [\"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */]: 'No second factor identifier is provided.',\r\n [\"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',\r\n [\"missing-phone-number\" /* AuthErrorCode.MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',\r\n [\"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',\r\n [\"app-deleted\" /* AuthErrorCode.MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',\r\n [\"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',\r\n [\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',\r\n [\"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +\r\n 'sign-in credentials. Sign in using a provider associated with this ' +\r\n 'email address.',\r\n [\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\r\n [\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',\r\n [\"null-user\" /* AuthErrorCode.NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +\r\n 'requires a non-null user object.',\r\n [\"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +\r\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\r\n 'Auth section.',\r\n [\"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +\r\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\r\n ' and web storage must be enabled.',\r\n [\"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\r\n [\"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',\r\n [\"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',\r\n [\"quota-exceeded\" /* AuthErrorCode.QUOTA_EXCEEDED */]: \"The project's quota for this operation has been exceeded.\",\r\n [\"redirect-cancelled-by-user\" /* AuthErrorCode.REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',\r\n [\"redirect-operation-pending\" /* AuthErrorCode.REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',\r\n [\"rejected-credential\" /* AuthErrorCode.REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',\r\n [\"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',\r\n [\"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',\r\n [\"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */]: \"The provided tenant ID does not match the Auth instance's tenant ID\",\r\n [\"timeout\" /* AuthErrorCode.TIMEOUT */]: 'The operation has timed out.',\r\n [\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */]: \"The user's credential is no longer valid. The user must sign in again.\",\r\n [\"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +\r\n 'Try again later.',\r\n [\"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +\r\n 'the domain in the Firebase console.',\r\n [\"unsupported-first-factor\" /* AuthErrorCode.UNSUPPORTED_FIRST_FACTOR */]: 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\r\n [\"unsupported-persistence-type\" /* AuthErrorCode.UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',\r\n [\"unsupported-tenant-operation\" /* AuthErrorCode.UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',\r\n [\"unverified-email\" /* AuthErrorCode.UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',\r\n [\"user-cancelled\" /* AuthErrorCode.USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',\r\n [\"user-not-found\" /* AuthErrorCode.USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +\r\n 'have been deleted.',\r\n [\"user-disabled\" /* AuthErrorCode.USER_DISABLED */]: 'The user account has been disabled by an administrator.',\r\n [\"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',\r\n [\"user-signed-out\" /* AuthErrorCode.USER_SIGNED_OUT */]: '',\r\n [\"weak-password\" /* AuthErrorCode.WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',\r\n [\"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',\r\n [\"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +\r\n 'different options. To avoid this error, call initializeAuth() with the ' +\r\n 'same options as when it was originally called, or call getAuth() to return the' +\r\n ' already initialized instance.',\r\n [\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is missing when sending request to the backend.',\r\n [\"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */]: 'The reCAPTCHA token is invalid when sending request to the backend.',\r\n [\"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */]: 'The reCAPTCHA action is invalid when sending request to the backend.',\r\n [\"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */]: 'reCAPTCHA Enterprise integration is not enabled for this project.',\r\n [\"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */]: 'The reCAPTCHA client type is missing when sending request to the backend.',\r\n [\"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is missing when sending request to the backend.',\r\n [\"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */]: 'Invalid request parameters.',\r\n [\"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */]: 'The reCAPTCHA version is invalid when sending request to the backend.',\r\n [\"unsupported-password-policy-schema-version\" /* AuthErrorCode.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.',\r\n [\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: 'The password does not meet the requirements.'\r\n };\r\n}\r\nfunction _prodErrorMap() {\r\n // We will include this one message in the prod error map since by the very\r\n // nature of this error, developers will never be able to see the message\r\n // using the debugErrorMap (which is installed during auth initialization).\r\n return {\r\n [\"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.'\r\n };\r\n}\r\n/**\r\n * A verbose error map with detailed descriptions for most error codes.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst debugErrorMap = _debugErrorMap;\r\n/**\r\n * A minimal error map with all verbose error messages stripped.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst prodErrorMap = _prodErrorMap;\r\nconst _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());\r\n/**\r\n * A map of potential `Auth` error codes, for easier comparison with errors\r\n * thrown by the SDK.\r\n *\r\n * @remarks\r\n * Note that you can't tree-shake individual keys\r\n * in the map, so by using the map you might substantially increase your\r\n * bundle size.\r\n *\r\n * @public\r\n */\r\nconst AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\r\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\r\n ARGUMENT_ERROR: 'auth/argument-error',\r\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\r\n APP_NOT_INSTALLED: 'auth/app-not-installed',\r\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\r\n CODE_EXPIRED: 'auth/code-expired',\r\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\r\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\r\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\r\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\r\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\r\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\r\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\r\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\r\n EMAIL_EXISTS: 'auth/email-already-in-use',\r\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\r\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\r\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\r\n INTERNAL_ERROR: 'auth/internal-error',\r\n INVALID_API_KEY: 'auth/invalid-api-key',\r\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\r\n INVALID_APP_ID: 'auth/invalid-app-id',\r\n INVALID_AUTH: 'auth/invalid-user-token',\r\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\r\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\r\n INVALID_CODE: 'auth/invalid-verification-code',\r\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\r\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\r\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\r\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\r\n INVALID_EMAIL: 'auth/invalid-email',\r\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\r\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\r\n INVALID_LOGIN_CREDENTIALS: 'auth/invalid-credential',\r\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\r\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\r\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\r\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\r\n INVALID_OOB_CODE: 'auth/invalid-action-code',\r\n INVALID_ORIGIN: 'auth/unauthorized-domain',\r\n INVALID_PASSWORD: 'auth/wrong-password',\r\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\r\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\r\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\r\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\r\n INVALID_SENDER: 'auth/invalid-sender',\r\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\r\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\r\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\r\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\r\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\r\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\r\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\r\n MISSING_CODE: 'auth/missing-verification-code',\r\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\r\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\r\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\r\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\r\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\r\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\r\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\r\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\r\n MODULE_DESTROYED: 'auth/app-deleted',\r\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\r\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\r\n NULL_USER: 'auth/null-user',\r\n NO_AUTH_EVENT: 'auth/no-auth-event',\r\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\r\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\r\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\r\n POPUP_BLOCKED: 'auth/popup-blocked',\r\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\r\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\r\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\r\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\r\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\r\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\r\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\r\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\r\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\r\n TIMEOUT: 'auth/timeout',\r\n TOKEN_EXPIRED: 'auth/user-token-expired',\r\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\r\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\r\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\r\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\r\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\r\n UNVERIFIED_EMAIL: 'auth/unverified-email',\r\n USER_CANCELLED: 'auth/user-cancelled',\r\n USER_DELETED: 'auth/user-not-found',\r\n USER_DISABLED: 'auth/user-disabled',\r\n USER_MISMATCH: 'auth/user-mismatch',\r\n USER_SIGNED_OUT: 'auth/user-signed-out',\r\n WEAK_PASSWORD: 'auth/weak-password',\r\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\r\n ALREADY_INITIALIZED: 'auth/already-initialized',\r\n RECAPTCHA_NOT_ENABLED: 'auth/recaptcha-not-enabled',\r\n MISSING_RECAPTCHA_TOKEN: 'auth/missing-recaptcha-token',\r\n INVALID_RECAPTCHA_TOKEN: 'auth/invalid-recaptcha-token',\r\n INVALID_RECAPTCHA_ACTION: 'auth/invalid-recaptcha-action',\r\n MISSING_CLIENT_TYPE: 'auth/missing-client-type',\r\n MISSING_RECAPTCHA_VERSION: 'auth/missing-recaptcha-version',\r\n INVALID_RECAPTCHA_VERSION: 'auth/invalid-recaptcha-version',\r\n INVALID_REQ_TYPE: 'auth/invalid-req-type'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logClient = new Logger('@firebase/auth');\r\nfunction _logWarn(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.WARN) {\r\n logClient.warn(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\r\nfunction _logError(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.ERROR) {\r\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _fail(authOrCode, ...rest) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _createError(authOrCode, ...rest) {\r\n return createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _errorWithCustomMessage(auth, code, message) {\r\n const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });\r\n const factory = new ErrorFactory('auth', 'Firebase', errorMap);\r\n return factory.create(code, {\r\n appName: auth.name\r\n });\r\n}\r\nfunction _serverAppCurrentUserOperationNotSupportedError(auth) {\r\n return _errorWithCustomMessage(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */, 'Operations that alter the current user are not supported in conjunction with FirebaseServerApp');\r\n}\r\nfunction _assertInstanceOf(auth, object, instance) {\r\n const constructorInstance = instance;\r\n if (!(object instanceof constructorInstance)) {\r\n if (constructorInstance.name !== object.constructor.name) {\r\n _fail(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n throw _errorWithCustomMessage(auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +\r\n `Did you pass a reference from a different Auth SDK?`);\r\n }\r\n}\r\nfunction createErrorInternal(authOrCode, ...rest) {\r\n if (typeof authOrCode !== 'string') {\r\n const code = rest[0];\r\n const fullParams = [...rest.slice(1)];\r\n if (fullParams[0]) {\r\n fullParams[0].appName = authOrCode.name;\r\n }\r\n return authOrCode._errorFactory.create(code, ...fullParams);\r\n }\r\n return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);\r\n}\r\nfunction _assert(assertion, authOrCode, ...rest) {\r\n if (!assertion) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n }\r\n}\r\n/**\r\n * Unconditionally fails, throwing an internal error with the given message.\r\n *\r\n * @param failure type of failure encountered\r\n * @throws Error\r\n */\r\nfunction debugFail(failure) {\r\n // Log the failure in addition to throw an exception, just in case the\r\n // exception is swallowed.\r\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\r\n _logError(message);\r\n // NOTE: We don't use FirebaseError here because these are internal failures\r\n // that cannot be handled by the user. (Also it would create a circular\r\n // dependency between the error and assert modules which doesn't work.)\r\n throw new Error(message);\r\n}\r\n/**\r\n * Fails if the given assertion condition is false, throwing an Error with the\r\n * given message if it did.\r\n *\r\n * @param assertion\r\n * @param message\r\n */\r\nfunction debugAssert(assertion, message) {\r\n if (!assertion) {\r\n debugFail(message);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _getCurrentUrl() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';\r\n}\r\nfunction _isHttpOrHttps() {\r\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\r\n}\r\nfunction _getCurrentScheme() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine whether the browser is working online\r\n */\r\nfunction _isOnline() {\r\n if (typeof navigator !== 'undefined' &&\r\n navigator &&\r\n 'onLine' in navigator &&\r\n typeof navigator.onLine === 'boolean' &&\r\n // Apply only for traditional web apps and Chrome extensions.\r\n // This is especially true for Cordova apps which have unreliable\r\n // navigator.onLine behavior unless cordova-plugin-network-information is\r\n // installed which overwrites the native navigator.onLine value and\r\n // defines navigator.connection.\r\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {\r\n return navigator.onLine;\r\n }\r\n // If we can't determine the state, assume it is online.\r\n return true;\r\n}\r\nfunction _getUserLanguage() {\r\n if (typeof navigator === 'undefined') {\r\n return null;\r\n }\r\n const navigatorLanguage = navigator;\r\n return (\r\n // Most reliable, but only supported in Chrome/Firefox.\r\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\r\n // Supported in most browsers, but returns the language of the browser\r\n // UI, not the language set in browser settings.\r\n navigatorLanguage.language ||\r\n // Couldn't determine language.\r\n null);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A structure to help pick between a range of long and short delay durations\r\n * depending on the current environment. In general, the long delay is used for\r\n * mobile environments whereas short delays are used for desktop environments.\r\n */\r\nclass Delay {\r\n constructor(shortDelay, longDelay) {\r\n this.shortDelay = shortDelay;\r\n this.longDelay = longDelay;\r\n // Internal error when improperly initialized.\r\n debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');\r\n this.isMobile = isMobileCordova() || isReactNative();\r\n }\r\n get() {\r\n if (!_isOnline()) {\r\n // Pick the shorter timeout.\r\n return Math.min(5000 /* DelayMin.OFFLINE */, this.shortDelay);\r\n }\r\n // If running in a mobile environment, return the long delay, otherwise\r\n // return the short delay.\r\n // This could be improved in the future to dynamically change based on other\r\n // variables instead of just reading the current environment.\r\n return this.isMobile ? this.longDelay : this.shortDelay;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _emulatorUrl(config, path) {\r\n debugAssert(config.emulator, 'Emulator should always be set here');\r\n const { url } = config.emulator;\r\n if (!path) {\r\n return url;\r\n }\r\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FetchProvider {\r\n static initialize(fetchImpl, headersImpl, responseImpl) {\r\n this.fetchImpl = fetchImpl;\r\n if (headersImpl) {\r\n this.headersImpl = headersImpl;\r\n }\r\n if (responseImpl) {\r\n this.responseImpl = responseImpl;\r\n }\r\n }\r\n static fetch() {\r\n if (this.fetchImpl) {\r\n return this.fetchImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'fetch' in self) {\r\n return self.fetch;\r\n }\r\n if (typeof globalThis !== 'undefined' && globalThis.fetch) {\r\n return globalThis.fetch;\r\n }\r\n if (typeof fetch !== 'undefined') {\r\n return fetch;\r\n }\r\n debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static headers() {\r\n if (this.headersImpl) {\r\n return this.headersImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Headers' in self) {\r\n return self.Headers;\r\n }\r\n if (typeof globalThis !== 'undefined' && globalThis.Headers) {\r\n return globalThis.Headers;\r\n }\r\n if (typeof Headers !== 'undefined') {\r\n return Headers;\r\n }\r\n debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static response() {\r\n if (this.responseImpl) {\r\n return this.responseImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Response' in self) {\r\n return self.Response;\r\n }\r\n if (typeof globalThis !== 'undefined' && globalThis.Response) {\r\n return globalThis.Response;\r\n }\r\n if (typeof Response !== 'undefined') {\r\n return Response;\r\n }\r\n debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Map from errors returned by the server to errors to developer visible errors\r\n */\r\nconst SERVER_ERROR_MAP = {\r\n // Custom token errors.\r\n [\"CREDENTIAL_MISMATCH\" /* ServerError.CREDENTIAL_MISMATCH */]: \"custom-token-mismatch\" /* AuthErrorCode.CREDENTIAL_MISMATCH */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CUSTOM_TOKEN\" /* ServerError.MISSING_CUSTOM_TOKEN */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Create Auth URI errors.\r\n [\"INVALID_IDENTIFIER\" /* ServerError.INVALID_IDENTIFIER */]: \"invalid-email\" /* AuthErrorCode.INVALID_EMAIL */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CONTINUE_URI\" /* ServerError.MISSING_CONTINUE_URI */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Sign in with email and password errors (some apply to sign up too).\r\n [\"INVALID_PASSWORD\" /* ServerError.INVALID_PASSWORD */]: \"wrong-password\" /* AuthErrorCode.INVALID_PASSWORD */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_PASSWORD\" /* ServerError.MISSING_PASSWORD */]: \"missing-password\" /* AuthErrorCode.MISSING_PASSWORD */,\r\n // Thrown if Email Enumeration Protection is enabled in the project and the email or password is\r\n // invalid.\r\n [\"INVALID_LOGIN_CREDENTIALS\" /* ServerError.INVALID_LOGIN_CREDENTIALS */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n // Sign up with email and password errors.\r\n [\"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */]: \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */,\r\n [\"PASSWORD_LOGIN_DISABLED\" /* ServerError.PASSWORD_LOGIN_DISABLED */]: \"operation-not-allowed\" /* AuthErrorCode.OPERATION_NOT_ALLOWED */,\r\n // Verify assertion for sign in with credential errors:\r\n [\"INVALID_IDP_RESPONSE\" /* ServerError.INVALID_IDP_RESPONSE */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n [\"INVALID_PENDING_TOKEN\" /* ServerError.INVALID_PENDING_TOKEN */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n [\"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */]: \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_REQ_TYPE\" /* ServerError.MISSING_REQ_TYPE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Send Password reset email errors:\r\n [\"EMAIL_NOT_FOUND\" /* ServerError.EMAIL_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */,\r\n [\"RESET_PASSWORD_EXCEED_LIMIT\" /* ServerError.RESET_PASSWORD_EXCEED_LIMIT */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n [\"EXPIRED_OOB_CODE\" /* ServerError.EXPIRED_OOB_CODE */]: \"expired-action-code\" /* AuthErrorCode.EXPIRED_OOB_CODE */,\r\n [\"INVALID_OOB_CODE\" /* ServerError.INVALID_OOB_CODE */]: \"invalid-action-code\" /* AuthErrorCode.INVALID_OOB_CODE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_OOB_CODE\" /* ServerError.MISSING_OOB_CODE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Operations that require ID token in request:\r\n [\"CREDENTIAL_TOO_OLD_LOGIN_AGAIN\" /* ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: \"requires-recent-login\" /* AuthErrorCode.CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,\r\n [\"INVALID_ID_TOKEN\" /* ServerError.INVALID_ID_TOKEN */]: \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */,\r\n [\"TOKEN_EXPIRED\" /* ServerError.TOKEN_EXPIRED */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */,\r\n // Other errors.\r\n [\"TOO_MANY_ATTEMPTS_TRY_LATER\" /* ServerError.TOO_MANY_ATTEMPTS_TRY_LATER */]: \"too-many-requests\" /* AuthErrorCode.TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n [\"PASSWORD_DOES_NOT_MEET_REQUIREMENTS\" /* ServerError.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */]: \"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */,\r\n // Phone Auth related errors.\r\n [\"INVALID_CODE\" /* ServerError.INVALID_CODE */]: \"invalid-verification-code\" /* AuthErrorCode.INVALID_CODE */,\r\n [\"INVALID_SESSION_INFO\" /* ServerError.INVALID_SESSION_INFO */]: \"invalid-verification-id\" /* AuthErrorCode.INVALID_SESSION_INFO */,\r\n [\"INVALID_TEMPORARY_PROOF\" /* ServerError.INVALID_TEMPORARY_PROOF */]: \"invalid-credential\" /* AuthErrorCode.INVALID_CREDENTIAL */,\r\n [\"MISSING_SESSION_INFO\" /* ServerError.MISSING_SESSION_INFO */]: \"missing-verification-id\" /* AuthErrorCode.MISSING_SESSION_INFO */,\r\n [\"SESSION_EXPIRED\" /* ServerError.SESSION_EXPIRED */]: \"code-expired\" /* AuthErrorCode.CODE_EXPIRED */,\r\n // Other action code errors when additional settings passed.\r\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\r\n // This is OK as this error will be caught by client side validation.\r\n [\"MISSING_ANDROID_PACKAGE_NAME\" /* ServerError.MISSING_ANDROID_PACKAGE_NAME */]: \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */,\r\n [\"UNAUTHORIZED_DOMAIN\" /* ServerError.UNAUTHORIZED_DOMAIN */]: \"unauthorized-continue-uri\" /* AuthErrorCode.UNAUTHORIZED_DOMAIN */,\r\n // getProjectConfig errors when clientId is passed.\r\n [\"INVALID_OAUTH_CLIENT_ID\" /* ServerError.INVALID_OAUTH_CLIENT_ID */]: \"invalid-oauth-client-id\" /* AuthErrorCode.INVALID_OAUTH_CLIENT_ID */,\r\n // User actions (sign-up or deletion) disabled errors.\r\n [\"ADMIN_ONLY_OPERATION\" /* ServerError.ADMIN_ONLY_OPERATION */]: \"admin-restricted-operation\" /* AuthErrorCode.ADMIN_ONLY_OPERATION */,\r\n // Multi factor related errors.\r\n [\"INVALID_MFA_PENDING_CREDENTIAL\" /* ServerError.INVALID_MFA_PENDING_CREDENTIAL */]: \"invalid-multi-factor-session\" /* AuthErrorCode.INVALID_MFA_SESSION */,\r\n [\"MFA_ENROLLMENT_NOT_FOUND\" /* ServerError.MFA_ENROLLMENT_NOT_FOUND */]: \"multi-factor-info-not-found\" /* AuthErrorCode.MFA_INFO_NOT_FOUND */,\r\n [\"MISSING_MFA_ENROLLMENT_ID\" /* ServerError.MISSING_MFA_ENROLLMENT_ID */]: \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */,\r\n [\"MISSING_MFA_PENDING_CREDENTIAL\" /* ServerError.MISSING_MFA_PENDING_CREDENTIAL */]: \"missing-multi-factor-session\" /* AuthErrorCode.MISSING_MFA_SESSION */,\r\n [\"SECOND_FACTOR_EXISTS\" /* ServerError.SECOND_FACTOR_EXISTS */]: \"second-factor-already-in-use\" /* AuthErrorCode.SECOND_FACTOR_ALREADY_ENROLLED */,\r\n [\"SECOND_FACTOR_LIMIT_EXCEEDED\" /* ServerError.SECOND_FACTOR_LIMIT_EXCEEDED */]: \"maximum-second-factor-count-exceeded\" /* AuthErrorCode.SECOND_FACTOR_LIMIT_EXCEEDED */,\r\n // Blocking functions related errors.\r\n [\"BLOCKING_FUNCTION_ERROR_RESPONSE\" /* ServerError.BLOCKING_FUNCTION_ERROR_RESPONSE */]: \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */,\r\n // Recaptcha related errors.\r\n [\"RECAPTCHA_NOT_ENABLED\" /* ServerError.RECAPTCHA_NOT_ENABLED */]: \"recaptcha-not-enabled\" /* AuthErrorCode.RECAPTCHA_NOT_ENABLED */,\r\n [\"MISSING_RECAPTCHA_TOKEN\" /* ServerError.MISSING_RECAPTCHA_TOKEN */]: \"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_TOKEN\" /* ServerError.INVALID_RECAPTCHA_TOKEN */]: \"invalid-recaptcha-token\" /* AuthErrorCode.INVALID_RECAPTCHA_TOKEN */,\r\n [\"INVALID_RECAPTCHA_ACTION\" /* ServerError.INVALID_RECAPTCHA_ACTION */]: \"invalid-recaptcha-action\" /* AuthErrorCode.INVALID_RECAPTCHA_ACTION */,\r\n [\"MISSING_CLIENT_TYPE\" /* ServerError.MISSING_CLIENT_TYPE */]: \"missing-client-type\" /* AuthErrorCode.MISSING_CLIENT_TYPE */,\r\n [\"MISSING_RECAPTCHA_VERSION\" /* ServerError.MISSING_RECAPTCHA_VERSION */]: \"missing-recaptcha-version\" /* AuthErrorCode.MISSING_RECAPTCHA_VERSION */,\r\n [\"INVALID_RECAPTCHA_VERSION\" /* ServerError.INVALID_RECAPTCHA_VERSION */]: \"invalid-recaptcha-version\" /* AuthErrorCode.INVALID_RECAPTCHA_VERSION */,\r\n [\"INVALID_REQ_TYPE\" /* ServerError.INVALID_REQ_TYPE */]: \"invalid-req-type\" /* AuthErrorCode.INVALID_REQ_TYPE */\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);\r\nfunction _addTidIfNecessary(auth, request) {\r\n if (auth.tenantId && !request.tenantId) {\r\n return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });\r\n }\r\n return request;\r\n}\r\nasync function _performApiRequest(auth, method, path, request, customErrorMap = {}) {\r\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\r\n let body = {};\r\n let params = {};\r\n if (request) {\r\n if (method === \"GET\" /* HttpMethod.GET */) {\r\n params = request;\r\n }\r\n else {\r\n body = {\r\n body: JSON.stringify(request)\r\n };\r\n }\r\n }\r\n const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/json';\r\n if (auth.languageCode) {\r\n headers[\"X-Firebase-Locale\" /* HttpHeader.X_FIREBASE_LOCALE */] = auth.languageCode;\r\n }\r\n return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,\r\n headers, referrerPolicy: 'no-referrer' }, body));\r\n });\r\n}\r\nasync function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {\r\n auth._canInitEmulator = false;\r\n const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);\r\n try {\r\n const networkTimeout = new NetworkTimeout(auth);\r\n const response = await Promise.race([\r\n fetchFn(),\r\n networkTimeout.promise\r\n ]);\r\n // If we've reached this point, the fetch succeeded and the networkTimeout\r\n // didn't throw; clear the network timeout delay so that Node won't hang\r\n networkTimeout.clearNetworkTimeout();\r\n const json = await response.json();\r\n if ('needConfirmation' in json) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, json);\r\n }\r\n if (response.ok && !('errorMessage' in json)) {\r\n return json;\r\n }\r\n else {\r\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\r\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\r\n if (serverErrorCode === \"FEDERATED_USER_ID_ALREADY_LINKED\" /* ServerError.FEDERATED_USER_ID_ALREADY_LINKED */) {\r\n throw _makeTaggedError(auth, \"credential-already-in-use\" /* AuthErrorCode.CREDENTIAL_ALREADY_IN_USE */, json);\r\n }\r\n else if (serverErrorCode === \"EMAIL_EXISTS\" /* ServerError.EMAIL_EXISTS */) {\r\n throw _makeTaggedError(auth, \"email-already-in-use\" /* AuthErrorCode.EMAIL_EXISTS */, json);\r\n }\r\n else if (serverErrorCode === \"USER_DISABLED\" /* ServerError.USER_DISABLED */) {\r\n throw _makeTaggedError(auth, \"user-disabled\" /* AuthErrorCode.USER_DISABLED */, json);\r\n }\r\n const authError = errorMap[serverErrorCode] ||\r\n serverErrorCode\r\n .toLowerCase()\r\n .replace(/[_\\s]+/g, '-');\r\n if (serverErrorMessage) {\r\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\r\n }\r\n else {\r\n _fail(auth, authError);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n throw e;\r\n }\r\n // Changing this to a different error code will log user out when there is a network error\r\n // because we treat any error other than NETWORK_REQUEST_FAILED as token is invalid.\r\n // https://github.com/firebase/firebase-js-sdk/blob/4fbc73610d70be4e0852e7de63a39cb7897e8546/packages/auth/src/core/auth/auth_impl.ts#L309-L316\r\n _fail(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */, { 'message': String(e) });\r\n }\r\n}\r\nasync function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {\r\n const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));\r\n if ('mfaPendingCredential' in serverResponse) {\r\n _fail(auth, \"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */, {\r\n _serverResponse: serverResponse\r\n });\r\n }\r\n return serverResponse;\r\n}\r\nfunction _getFinalTarget(auth, host, path, query) {\r\n const base = `${host}${path}?${query}`;\r\n if (!auth.config.emulator) {\r\n return `${auth.config.apiScheme}://${base}`;\r\n }\r\n return _emulatorUrl(auth.config, base);\r\n}\r\nfunction _parseEnforcementState(enforcementStateStr) {\r\n switch (enforcementStateStr) {\r\n case 'ENFORCE':\r\n return \"ENFORCE\" /* EnforcementState.ENFORCE */;\r\n case 'AUDIT':\r\n return \"AUDIT\" /* EnforcementState.AUDIT */;\r\n case 'OFF':\r\n return \"OFF\" /* EnforcementState.OFF */;\r\n default:\r\n return \"ENFORCEMENT_STATE_UNSPECIFIED\" /* EnforcementState.ENFORCEMENT_STATE_UNSPECIFIED */;\r\n }\r\n}\r\nclass NetworkTimeout {\r\n constructor(auth) {\r\n this.auth = auth;\r\n // Node timers and browser timers are fundamentally incompatible, but we\r\n // don't care about the value here\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timer = null;\r\n this.promise = new Promise((_, reject) => {\r\n this.timer = setTimeout(() => {\r\n return reject(_createError(this.auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, DEFAULT_API_TIMEOUT_MS.get());\r\n });\r\n }\r\n clearNetworkTimeout() {\r\n clearTimeout(this.timer);\r\n }\r\n}\r\nfunction _makeTaggedError(auth, code, response) {\r\n const errorParams = {\r\n appName: auth.name\r\n };\r\n if (response.email) {\r\n errorParams.email = response.email;\r\n }\r\n if (response.phoneNumber) {\r\n errorParams.phoneNumber = response.phoneNumber;\r\n }\r\n const error = _createError(auth, code, errorParams);\r\n // We know customData is defined on error because errorParams is defined\r\n error.customData._tokenResponse = response;\r\n return error;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction isV2(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.getResponse !== undefined);\r\n}\r\nfunction isEnterprise(grecaptcha) {\r\n return (grecaptcha !== undefined &&\r\n grecaptcha.enterprise !== undefined);\r\n}\r\nclass RecaptchaConfig {\r\n constructor(response) {\r\n /**\r\n * The reCAPTCHA site key.\r\n */\r\n this.siteKey = '';\r\n /**\r\n * The list of providers and their enablement status for reCAPTCHA Enterprise.\r\n */\r\n this.recaptchaEnforcementState = [];\r\n if (response.recaptchaKey === undefined) {\r\n throw new Error('recaptchaKey undefined');\r\n }\r\n // Example response.recaptchaKey: \"projects/proj123/keys/sitekey123\"\r\n this.siteKey = response.recaptchaKey.split('/')[3];\r\n this.recaptchaEnforcementState = response.recaptchaEnforcementState;\r\n }\r\n /**\r\n * Returns the reCAPTCHA Enterprise enforcement state for the given provider.\r\n *\r\n * @param providerStr - The provider whose enforcement state is to be returned.\r\n * @returns The reCAPTCHA Enterprise enforcement state for the given provider.\r\n */\r\n getProviderEnforcementState(providerStr) {\r\n if (!this.recaptchaEnforcementState ||\r\n this.recaptchaEnforcementState.length === 0) {\r\n return null;\r\n }\r\n for (const recaptchaEnforcementState of this.recaptchaEnforcementState) {\r\n if (recaptchaEnforcementState.provider &&\r\n recaptchaEnforcementState.provider === providerStr) {\r\n return _parseEnforcementState(recaptchaEnforcementState.enforcementState);\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n * Returns true if the reCAPTCHA Enterprise enforcement state for the provider is set to ENFORCE or AUDIT.\r\n *\r\n * @param providerStr - The provider whose enablement state is to be returned.\r\n * @returns Whether or not reCAPTCHA Enterprise protection is enabled for the given provider.\r\n */\r\n isProviderEnabled(providerStr) {\r\n return (this.getProviderEnforcementState(providerStr) ===\r\n \"ENFORCE\" /* EnforcementState.ENFORCE */ ||\r\n this.getProviderEnforcementState(providerStr) === \"AUDIT\" /* EnforcementState.AUDIT */);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getRecaptchaParams(auth) {\r\n return ((await _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/recaptchaParams\" /* Endpoint.GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');\r\n}\r\nasync function getRecaptchaConfig(auth, request) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/recaptchaConfig\" /* Endpoint.GET_RECAPTCHA_CONFIG */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteAccount(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:delete\" /* Endpoint.DELETE_ACCOUNT */, request);\r\n}\r\nasync function deleteLinkedAccounts(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function getAccountInfo(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:lookup\" /* Endpoint.GET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction utcTimestampToDateString(utcTimestamp) {\r\n if (!utcTimestamp) {\r\n return undefined;\r\n }\r\n try {\r\n // Convert to date object.\r\n const date = new Date(Number(utcTimestamp));\r\n // Test date is valid.\r\n if (!isNaN(date.getTime())) {\r\n // Convert to UTC date string.\r\n return date.toUTCString();\r\n }\r\n }\r\n catch (e) {\r\n // Do nothing. undefined will be returned.\r\n }\r\n return undefined;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nfunction getIdToken(user, forceRefresh = false) {\r\n return getModularInstance(user).getIdToken(forceRefresh);\r\n}\r\n/**\r\n * Returns a deserialized JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getIdTokenResult(user, forceRefresh = false) {\r\n const userInternal = getModularInstance(user);\r\n const token = await userInternal.getIdToken(forceRefresh);\r\n const claims = _parseToken(token);\r\n _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;\r\n const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];\r\n return {\r\n claims,\r\n token,\r\n authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),\r\n issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),\r\n expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),\r\n signInProvider: signInProvider || null,\r\n signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null\r\n };\r\n}\r\nfunction secondsStringToMilliseconds(seconds) {\r\n return Number(seconds) * 1000;\r\n}\r\nfunction _parseToken(token) {\r\n const [algorithm, payload, signature] = token.split('.');\r\n if (algorithm === undefined ||\r\n payload === undefined ||\r\n signature === undefined) {\r\n _logError('JWT malformed, contained fewer than 3 sections');\r\n return null;\r\n }\r\n try {\r\n const decoded = base64Decode(payload);\r\n if (!decoded) {\r\n _logError('Failed to decode base64 JWT payload');\r\n return null;\r\n }\r\n return JSON.parse(decoded);\r\n }\r\n catch (e) {\r\n _logError('Caught error parsing JWT payload as JSON', e === null || e === void 0 ? void 0 : e.toString());\r\n return null;\r\n }\r\n}\r\n/**\r\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\r\n */\r\nfunction _tokenExpiresIn(token) {\r\n const parsedToken = _parseToken(token);\r\n _assert(parsedToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return Number(parsedToken.exp) - Number(parsedToken.iat);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _logoutIfInvalidated(user, promise, bypassAuthState = false) {\r\n if (bypassAuthState) {\r\n return promise;\r\n }\r\n try {\r\n return await promise;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\r\n if (user.auth.currentUser === user) {\r\n await user.auth.signOut();\r\n }\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isUserInvalidated({ code }) {\r\n return (code === `auth/${\"user-disabled\" /* AuthErrorCode.USER_DISABLED */}` ||\r\n code === `auth/${\"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */}`);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ProactiveRefresh {\r\n constructor(user) {\r\n this.user = user;\r\n this.isRunning = false;\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timerId = null;\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n }\r\n _start() {\r\n if (this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = true;\r\n this.schedule();\r\n }\r\n _stop() {\r\n if (!this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = false;\r\n if (this.timerId !== null) {\r\n clearTimeout(this.timerId);\r\n }\r\n }\r\n getInterval(wasError) {\r\n var _a;\r\n if (wasError) {\r\n const interval = this.errorBackoff;\r\n this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* Duration.RETRY_BACKOFF_MAX */);\r\n return interval;\r\n }\r\n else {\r\n // Reset the error backoff\r\n this.errorBackoff = 30000 /* Duration.RETRY_BACKOFF_MIN */;\r\n const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;\r\n const interval = expTime - Date.now() - 300000 /* Duration.OFFSET */;\r\n return Math.max(0, interval);\r\n }\r\n }\r\n schedule(wasError = false) {\r\n if (!this.isRunning) {\r\n // Just in case...\r\n return;\r\n }\r\n const interval = this.getInterval(wasError);\r\n this.timerId = setTimeout(async () => {\r\n await this.iteration();\r\n }, interval);\r\n }\r\n async iteration() {\r\n try {\r\n await this.user.getIdToken(true);\r\n }\r\n catch (e) {\r\n // Only retry on network errors\r\n if ((e === null || e === void 0 ? void 0 : e.code) ===\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n this.schedule(/* wasError */ true);\r\n }\r\n return;\r\n }\r\n this.schedule();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserMetadata {\r\n constructor(createdAt, lastLoginAt) {\r\n this.createdAt = createdAt;\r\n this.lastLoginAt = lastLoginAt;\r\n this._initializeTime();\r\n }\r\n _initializeTime() {\r\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\r\n this.creationTime = utcTimestampToDateString(this.createdAt);\r\n }\r\n _copy(metadata) {\r\n this.createdAt = metadata.createdAt;\r\n this.lastLoginAt = metadata.lastLoginAt;\r\n this._initializeTime();\r\n }\r\n toJSON() {\r\n return {\r\n createdAt: this.createdAt,\r\n lastLoginAt: this.lastLoginAt\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reloadWithoutSaving(user) {\r\n var _a;\r\n const auth = user.auth;\r\n const idToken = await user.getIdToken();\r\n const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));\r\n _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const coreAccount = response.users[0];\r\n user._notifyReloadListener(coreAccount);\r\n const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const providerData = mergeProviderData(user.providerData, newProviderData);\r\n // Preserves the non-nonymous status of the stored user, even if no more\r\n // credentials (federated or email/password) are linked to the user. If\r\n // the user was previously anonymous, then use provider data to update.\r\n // On the other hand, if it was not anonymous before, it should never be\r\n // considered anonymous now.\r\n const oldIsAnonymous = user.isAnonymous;\r\n const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\r\n const updates = {\r\n uid: coreAccount.localId,\r\n displayName: coreAccount.displayName || null,\r\n photoURL: coreAccount.photoUrl || null,\r\n email: coreAccount.email || null,\r\n emailVerified: coreAccount.emailVerified || false,\r\n phoneNumber: coreAccount.phoneNumber || null,\r\n tenantId: coreAccount.tenantId || null,\r\n providerData,\r\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n isAnonymous\r\n };\r\n Object.assign(user, updates);\r\n}\r\n/**\r\n * Reloads user account data, if signed in.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function reload(user) {\r\n const userInternal = getModularInstance(user);\r\n await _reloadWithoutSaving(userInternal);\r\n // Even though the current user hasn't changed, update\r\n // current user will trigger a persistence update w/ the\r\n // new info.\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n userInternal.auth._notifyListenersIfCurrent(userInternal);\r\n}\r\nfunction mergeProviderData(original, newData) {\r\n const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));\r\n return [...deduped, ...newData];\r\n}\r\nfunction extractProviderData(providers) {\r\n return providers.map((_a) => {\r\n var { providerId } = _a, provider = __rest(_a, [\"providerId\"]);\r\n return {\r\n providerId,\r\n uid: provider.rawId || '',\r\n displayName: provider.displayName || null,\r\n email: provider.email || null,\r\n phoneNumber: provider.phoneNumber || null,\r\n photoURL: provider.photoUrl || null\r\n };\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestStsToken(auth, refreshToken) {\r\n const response = await _performFetchWithErrorHandling(auth, {}, async () => {\r\n const body = querystring({\r\n 'grant_type': 'refresh_token',\r\n 'refresh_token': refreshToken\r\n }).slice(1);\r\n const { tokenApiHost, apiKey } = auth.config;\r\n const url = _getFinalTarget(auth, tokenApiHost, \"/v1/token\" /* Endpoint.TOKEN */, `key=${apiKey}`);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* HttpHeader.CONTENT_TYPE */] = 'application/x-www-form-urlencoded';\r\n return FetchProvider.fetch()(url, {\r\n method: \"POST\" /* HttpMethod.POST */,\r\n headers,\r\n body\r\n });\r\n });\r\n // The response comes back in snake_case. Convert to camel:\r\n return {\r\n accessToken: response.access_token,\r\n expiresIn: response.expires_in,\r\n refreshToken: response.refresh_token\r\n };\r\n}\r\nasync function revokeToken(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts:revokeToken\" /* Endpoint.REVOKE_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\r\n * it references AuthInternal which has a circular dependency with UserInternal.\r\n *\r\n * @internal\r\n */\r\nclass StsTokenManager {\r\n constructor() {\r\n this.refreshToken = null;\r\n this.accessToken = null;\r\n this.expirationTime = null;\r\n }\r\n get isExpired() {\r\n return (!this.expirationTime ||\r\n Date.now() > this.expirationTime - 30000 /* Buffer.TOKEN_REFRESH */);\r\n }\r\n updateFromServerResponse(response) {\r\n _assert(response.idToken, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.idToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof response.refreshToken !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\r\n ? Number(response.expiresIn)\r\n : _tokenExpiresIn(response.idToken);\r\n this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);\r\n }\r\n updateFromIdToken(idToken) {\r\n _assert(idToken.length !== 0, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const expiresIn = _tokenExpiresIn(idToken);\r\n this.updateTokensAndExpiration(idToken, null, expiresIn);\r\n }\r\n async getToken(auth, forceRefresh = false) {\r\n if (!forceRefresh && this.accessToken && !this.isExpired) {\r\n return this.accessToken;\r\n }\r\n _assert(this.refreshToken, auth, \"user-token-expired\" /* AuthErrorCode.TOKEN_EXPIRED */);\r\n if (this.refreshToken) {\r\n await this.refresh(auth, this.refreshToken);\r\n return this.accessToken;\r\n }\r\n return null;\r\n }\r\n clearRefreshToken() {\r\n this.refreshToken = null;\r\n }\r\n async refresh(auth, oldToken) {\r\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);\r\n this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));\r\n }\r\n updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {\r\n this.refreshToken = refreshToken || null;\r\n this.accessToken = accessToken || null;\r\n this.expirationTime = Date.now() + expiresInSec * 1000;\r\n }\r\n static fromJSON(appName, object) {\r\n const { refreshToken, accessToken, expirationTime } = object;\r\n const manager = new StsTokenManager();\r\n if (refreshToken) {\r\n _assert(typeof refreshToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.refreshToken = refreshToken;\r\n }\r\n if (accessToken) {\r\n _assert(typeof accessToken === 'string', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.accessToken = accessToken;\r\n }\r\n if (expirationTime) {\r\n _assert(typeof expirationTime === 'number', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.expirationTime = expirationTime;\r\n }\r\n return manager;\r\n }\r\n toJSON() {\r\n return {\r\n refreshToken: this.refreshToken,\r\n accessToken: this.accessToken,\r\n expirationTime: this.expirationTime\r\n };\r\n }\r\n _assign(stsTokenManager) {\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.refreshToken = stsTokenManager.refreshToken;\r\n this.expirationTime = stsTokenManager.expirationTime;\r\n }\r\n _clone() {\r\n return Object.assign(new StsTokenManager(), this.toJSON());\r\n }\r\n _performRefresh() {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction assertStringOrUndefined(assertion, appName) {\r\n _assert(typeof assertion === 'string' || typeof assertion === 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */, { appName });\r\n}\r\nclass UserImpl {\r\n constructor(_a) {\r\n var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, [\"uid\", \"auth\", \"stsTokenManager\"]);\r\n // For the user object, provider is always Firebase.\r\n this.providerId = \"firebase\" /* ProviderId.FIREBASE */;\r\n this.proactiveRefresh = new ProactiveRefresh(this);\r\n this.reloadUserInfo = null;\r\n this.reloadListener = null;\r\n this.uid = uid;\r\n this.auth = auth;\r\n this.stsTokenManager = stsTokenManager;\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.displayName = opt.displayName || null;\r\n this.email = opt.email || null;\r\n this.emailVerified = opt.emailVerified || false;\r\n this.phoneNumber = opt.phoneNumber || null;\r\n this.photoURL = opt.photoURL || null;\r\n this.isAnonymous = opt.isAnonymous || false;\r\n this.tenantId = opt.tenantId || null;\r\n this.providerData = opt.providerData ? [...opt.providerData] : [];\r\n this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);\r\n }\r\n async getIdToken(forceRefresh) {\r\n const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));\r\n _assert(accessToken, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n if (this.accessToken !== accessToken) {\r\n this.accessToken = accessToken;\r\n await this.auth._persistUserIfCurrent(this);\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n return accessToken;\r\n }\r\n getIdTokenResult(forceRefresh) {\r\n return getIdTokenResult(this, forceRefresh);\r\n }\r\n reload() {\r\n return reload(this);\r\n }\r\n _assign(user) {\r\n if (this === user) {\r\n return;\r\n }\r\n _assert(this.uid === user.uid, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.displayName = user.displayName;\r\n this.photoURL = user.photoURL;\r\n this.email = user.email;\r\n this.emailVerified = user.emailVerified;\r\n this.phoneNumber = user.phoneNumber;\r\n this.isAnonymous = user.isAnonymous;\r\n this.tenantId = user.tenantId;\r\n this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n this.metadata._copy(user.metadata);\r\n this.stsTokenManager._assign(user.stsTokenManager);\r\n }\r\n _clone(auth) {\r\n const newUser = new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));\r\n newUser.metadata._copy(this.metadata);\r\n return newUser;\r\n }\r\n _onReload(callback) {\r\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\r\n _assert(!this.reloadListener, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.reloadListener = callback;\r\n if (this.reloadUserInfo) {\r\n this._notifyReloadListener(this.reloadUserInfo);\r\n this.reloadUserInfo = null;\r\n }\r\n }\r\n _notifyReloadListener(userInfo) {\r\n if (this.reloadListener) {\r\n this.reloadListener(userInfo);\r\n }\r\n else {\r\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\r\n this.reloadUserInfo = userInfo;\r\n }\r\n }\r\n _startProactiveRefresh() {\r\n this.proactiveRefresh._start();\r\n }\r\n _stopProactiveRefresh() {\r\n this.proactiveRefresh._stop();\r\n }\r\n async _updateTokensIfNecessary(response, reload = false) {\r\n let tokensRefreshed = false;\r\n if (response.idToken &&\r\n response.idToken !== this.stsTokenManager.accessToken) {\r\n this.stsTokenManager.updateFromServerResponse(response);\r\n tokensRefreshed = true;\r\n }\r\n if (reload) {\r\n await _reloadWithoutSaving(this);\r\n }\r\n await this.auth._persistUserIfCurrent(this);\r\n if (tokensRefreshed) {\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n }\r\n async delete() {\r\n if (_isFirebaseServerApp(this.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));\r\n }\r\n const idToken = await this.getIdToken();\r\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\r\n this.stsTokenManager.clearRefreshToken();\r\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\r\n // cancels pending actions...\r\n return this.auth.signOut();\r\n }\r\n toJSON() {\r\n return Object.assign(Object.assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(userInfo => (Object.assign({}, userInfo))), stsTokenManager: this.stsTokenManager.toJSON(), \r\n // Redirect event ID must be maintained in case there is a pending\r\n // redirect event.\r\n _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), { \r\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\r\n apiKey: this.auth.config.apiKey, appName: this.auth.name });\r\n }\r\n get refreshToken() {\r\n return this.stsTokenManager.refreshToken || '';\r\n }\r\n static _fromJSON(auth, object) {\r\n var _a, _b, _c, _d, _e, _f, _g, _h;\r\n const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;\r\n const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;\r\n const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;\r\n const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;\r\n const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;\r\n const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;\r\n const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;\r\n const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;\r\n const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;\r\n _assert(uid && plainObjectTokenManager, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);\r\n _assert(typeof uid === 'string', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(displayName, auth.name);\r\n assertStringOrUndefined(email, auth.name);\r\n _assert(typeof emailVerified === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n _assert(typeof isAnonymous === 'boolean', auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n assertStringOrUndefined(phoneNumber, auth.name);\r\n assertStringOrUndefined(photoURL, auth.name);\r\n assertStringOrUndefined(tenantId, auth.name);\r\n assertStringOrUndefined(_redirectEventId, auth.name);\r\n assertStringOrUndefined(createdAt, auth.name);\r\n assertStringOrUndefined(lastLoginAt, auth.name);\r\n const user = new UserImpl({\r\n uid,\r\n auth,\r\n email,\r\n emailVerified,\r\n displayName,\r\n isAnonymous,\r\n photoURL,\r\n phoneNumber,\r\n tenantId,\r\n stsTokenManager,\r\n createdAt,\r\n lastLoginAt\r\n });\r\n if (providerData && Array.isArray(providerData)) {\r\n user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n }\r\n if (_redirectEventId) {\r\n user._redirectEventId = _redirectEventId;\r\n }\r\n return user;\r\n }\r\n /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromServerResponse(idTokenResponse);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: idTokenResponse.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // Updates the user info and data and resolves with a user instance.\r\n await _reloadWithoutSaving(user);\r\n return user;\r\n }\r\n /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromGetAccountInfoResponse(auth, response, idToken) {\r\n const coreAccount = response.users[0];\r\n _assert(coreAccount.localId !== undefined, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const providerData = coreAccount.providerUserInfo !== undefined\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const isAnonymous = !(coreAccount.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromIdToken(idToken);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: coreAccount.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // update the user with data from the GetAccountInfo response.\r\n const updates = {\r\n uid: coreAccount.localId,\r\n displayName: coreAccount.displayName || null,\r\n photoURL: coreAccount.photoUrl || null,\r\n email: coreAccount.email || null,\r\n emailVerified: coreAccount.emailVerified || false,\r\n phoneNumber: coreAccount.phoneNumber || null,\r\n tenantId: coreAccount.tenantId || null,\r\n providerData,\r\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n isAnonymous: !(coreAccount.email && coreAccount.passwordHash) &&\r\n !(providerData === null || providerData === void 0 ? void 0 : providerData.length)\r\n };\r\n Object.assign(user, updates);\r\n return user;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst instanceCache = new Map();\r\nfunction _getInstance(cls) {\r\n debugAssert(cls instanceof Function, 'Expected a class definition');\r\n let instance = instanceCache.get(cls);\r\n if (instance) {\r\n debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');\r\n return instance;\r\n }\r\n instance = new cls();\r\n instanceCache.set(cls, instance);\r\n return instance;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass InMemoryPersistence {\r\n constructor() {\r\n this.type = \"NONE\" /* PersistenceType.NONE */;\r\n this.storage = {};\r\n }\r\n async _isAvailable() {\r\n return true;\r\n }\r\n async _set(key, value) {\r\n this.storage[key] = value;\r\n }\r\n async _get(key) {\r\n const value = this.storage[key];\r\n return value === undefined ? null : value;\r\n }\r\n async _remove(key) {\r\n delete this.storage[key];\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n}\r\nInMemoryPersistence.type = 'NONE';\r\n/**\r\n * An implementation of {@link Persistence} of type 'NONE'.\r\n *\r\n * @public\r\n */\r\nconst inMemoryPersistence = InMemoryPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _persistenceKeyName(key, apiKey, appName) {\r\n return `${\"firebase\" /* Namespace.PERSISTENCE */}:${key}:${apiKey}:${appName}`;\r\n}\r\nclass PersistenceUserManager {\r\n constructor(persistence, auth, userKey) {\r\n this.persistence = persistence;\r\n this.auth = auth;\r\n this.userKey = userKey;\r\n const { config, name } = this.auth;\r\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\r\n this.fullPersistenceKey = _persistenceKeyName(\"persistence\" /* KeyName.PERSISTENCE_USER */, config.apiKey, name);\r\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\r\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n setCurrentUser(user) {\r\n return this.persistence._set(this.fullUserKey, user.toJSON());\r\n }\r\n async getCurrentUser() {\r\n const blob = await this.persistence._get(this.fullUserKey);\r\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\r\n }\r\n removeCurrentUser() {\r\n return this.persistence._remove(this.fullUserKey);\r\n }\r\n savePersistenceForRedirect() {\r\n return this.persistence._set(this.fullPersistenceKey, this.persistence.type);\r\n }\r\n async setPersistence(newPersistence) {\r\n if (this.persistence === newPersistence) {\r\n return;\r\n }\r\n const currentUser = await this.getCurrentUser();\r\n await this.removeCurrentUser();\r\n this.persistence = newPersistence;\r\n if (currentUser) {\r\n return this.setCurrentUser(currentUser);\r\n }\r\n }\r\n delete() {\r\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n static async create(auth, persistenceHierarchy, userKey = \"authUser\" /* KeyName.AUTH_USER */) {\r\n if (!persistenceHierarchy.length) {\r\n return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);\r\n }\r\n // Eliminate any persistences that are not available\r\n const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (await persistence._isAvailable()) {\r\n return persistence;\r\n }\r\n return undefined;\r\n }))).filter(persistence => persistence);\r\n // Fall back to the first persistence listed, or in memory if none available\r\n let selectedPersistence = availablePersistences[0] ||\r\n _getInstance(inMemoryPersistence);\r\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\r\n // Pull out the existing user, setting the chosen persistence to that\r\n // persistence if the user exists.\r\n let userToMigrate = null;\r\n // Note, here we check for a user in _all_ persistences, not just the\r\n // ones deemed available. If we can migrate a user out of a broken\r\n // persistence, we will (but only if that persistence supports migration).\r\n for (const persistence of persistenceHierarchy) {\r\n try {\r\n const blob = await persistence._get(key);\r\n if (blob) {\r\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\r\n if (persistence !== selectedPersistence) {\r\n userToMigrate = user;\r\n }\r\n selectedPersistence = persistence;\r\n break;\r\n }\r\n }\r\n catch (_a) { }\r\n }\r\n // If we find the user in a persistence that does support migration, use\r\n // that migration path (of only persistences that support migration)\r\n const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);\r\n // If the persistence does _not_ allow migration, just finish off here\r\n if (!selectedPersistence._shouldAllowMigration ||\r\n !migrationHierarchy.length) {\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n selectedPersistence = migrationHierarchy[0];\r\n if (userToMigrate) {\r\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\r\n // we'll just let it bubble to surface the error.\r\n await selectedPersistence._set(key, userToMigrate.toJSON());\r\n }\r\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\r\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\r\n await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (persistence !== selectedPersistence) {\r\n try {\r\n await persistence._remove(key);\r\n }\r\n catch (_a) { }\r\n }\r\n }));\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine the browser for the purposes of reporting usage to the API\r\n */\r\nfunction _getBrowserName(userAgent) {\r\n const ua = userAgent.toLowerCase();\r\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\r\n return \"Opera\" /* BrowserName.OPERA */;\r\n }\r\n else if (_isIEMobile(ua)) {\r\n // Windows phone IEMobile browser.\r\n return \"IEMobile\" /* BrowserName.IEMOBILE */;\r\n }\r\n else if (ua.includes('msie') || ua.includes('trident/')) {\r\n return \"IE\" /* BrowserName.IE */;\r\n }\r\n else if (ua.includes('edge/')) {\r\n return \"Edge\" /* BrowserName.EDGE */;\r\n }\r\n else if (_isFirefox(ua)) {\r\n return \"Firefox\" /* BrowserName.FIREFOX */;\r\n }\r\n else if (ua.includes('silk/')) {\r\n return \"Silk\" /* BrowserName.SILK */;\r\n }\r\n else if (_isBlackBerry(ua)) {\r\n // Blackberry browser.\r\n return \"Blackberry\" /* BrowserName.BLACKBERRY */;\r\n }\r\n else if (_isWebOS(ua)) {\r\n // WebOS default browser.\r\n return \"Webos\" /* BrowserName.WEBOS */;\r\n }\r\n else if (_isSafari(ua)) {\r\n return \"Safari\" /* BrowserName.SAFARI */;\r\n }\r\n else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&\r\n !ua.includes('edge/')) {\r\n return \"Chrome\" /* BrowserName.CHROME */;\r\n }\r\n else if (_isAndroid(ua)) {\r\n // Android stock browser.\r\n return \"Android\" /* BrowserName.ANDROID */;\r\n }\r\n else {\r\n // Most modern browsers have name/version at end of user agent string.\r\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\r\n const matches = userAgent.match(re);\r\n if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {\r\n return matches[1];\r\n }\r\n }\r\n return \"Other\" /* BrowserName.OTHER */;\r\n}\r\nfunction _isFirefox(ua = getUA()) {\r\n return /firefox\\//i.test(ua);\r\n}\r\nfunction _isSafari(userAgent = getUA()) {\r\n const ua = userAgent.toLowerCase();\r\n return (ua.includes('safari/') &&\r\n !ua.includes('chrome/') &&\r\n !ua.includes('crios/') &&\r\n !ua.includes('android'));\r\n}\r\nfunction _isChromeIOS(ua = getUA()) {\r\n return /crios\\//i.test(ua);\r\n}\r\nfunction _isIEMobile(ua = getUA()) {\r\n return /iemobile/i.test(ua);\r\n}\r\nfunction _isAndroid(ua = getUA()) {\r\n return /android/i.test(ua);\r\n}\r\nfunction _isBlackBerry(ua = getUA()) {\r\n return /blackberry/i.test(ua);\r\n}\r\nfunction _isWebOS(ua = getUA()) {\r\n return /webos/i.test(ua);\r\n}\r\nfunction _isIOS(ua = getUA()) {\r\n return (/iphone|ipad|ipod/i.test(ua) ||\r\n (/macintosh/i.test(ua) && /mobile/i.test(ua)));\r\n}\r\nfunction _isIOS7Or8(ua = getUA()) {\r\n return (/(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\r\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua));\r\n}\r\nfunction _isIOSStandalone(ua = getUA()) {\r\n var _a;\r\n return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);\r\n}\r\nfunction _isIE10() {\r\n return isIE() && document.documentMode === 10;\r\n}\r\nfunction _isMobileBrowser(ua = getUA()) {\r\n // TODO: implement getBrowserName equivalent for OS.\r\n return (_isIOS(ua) ||\r\n _isAndroid(ua) ||\r\n _isWebOS(ua) ||\r\n _isBlackBerry(ua) ||\r\n /windows phone/i.test(ua) ||\r\n _isIEMobile(ua));\r\n}\r\nfunction _isIframe() {\r\n try {\r\n // Check that the current window is not the top window.\r\n // If so, return true.\r\n return !!(window && window !== window.top);\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/*\r\n * Determine the SDK version string\r\n */\r\nfunction _getClientVersion(clientPlatform, frameworks = []) {\r\n let reportedPlatform;\r\n switch (clientPlatform) {\r\n case \"Browser\" /* ClientPlatform.BROWSER */:\r\n // In a browser environment, report the browser name.\r\n reportedPlatform = _getBrowserName(getUA());\r\n break;\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n // Technically a worker runs from a browser but we need to differentiate a\r\n // worker from a browser.\r\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\r\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\r\n break;\r\n default:\r\n reportedPlatform = clientPlatform;\r\n }\r\n const reportedFrameworks = frameworks.length\r\n ? frameworks.join(',')\r\n : 'FirebaseCore-web'; /* default value if no other framework is used */\r\n return `${reportedPlatform}/${\"JsCore\" /* ClientImplementation.CORE */}/${SDK_VERSION}/${reportedFrameworks}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2022 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthMiddlewareQueue {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.queue = [];\r\n }\r\n pushCallback(callback, onAbort) {\r\n // The callback could be sync or async. Wrap it into a\r\n // function that is always async.\r\n const wrappedCallback = (user) => new Promise((resolve, reject) => {\r\n try {\r\n const result = callback(user);\r\n // Either resolve with existing promise or wrap a non-promise\r\n // return value into a promise.\r\n resolve(result);\r\n }\r\n catch (e) {\r\n // Sync callback throws.\r\n reject(e);\r\n }\r\n });\r\n // Attach the onAbort if present\r\n wrappedCallback.onAbort = onAbort;\r\n this.queue.push(wrappedCallback);\r\n const index = this.queue.length - 1;\r\n return () => {\r\n // Unsubscribe. Replace with no-op. Do not remove from array, or it will disturb\r\n // indexing of other elements.\r\n this.queue[index] = () => Promise.resolve();\r\n };\r\n }\r\n async runMiddleware(nextUser) {\r\n if (this.auth.currentUser === nextUser) {\r\n return;\r\n }\r\n // While running the middleware, build a temporary stack of onAbort\r\n // callbacks to call if one middleware callback rejects.\r\n const onAbortStack = [];\r\n try {\r\n for (const beforeStateCallback of this.queue) {\r\n await beforeStateCallback(nextUser);\r\n // Only push the onAbort if the callback succeeds\r\n if (beforeStateCallback.onAbort) {\r\n onAbortStack.push(beforeStateCallback.onAbort);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n // Run all onAbort, with separate try/catch to ignore any errors and\r\n // continue\r\n onAbortStack.reverse();\r\n for (const onAbort of onAbortStack) {\r\n try {\r\n onAbort();\r\n }\r\n catch (_) {\r\n /* swallow error */\r\n }\r\n }\r\n throw this.auth._errorFactory.create(\"login-blocked\" /* AuthErrorCode.LOGIN_BLOCKED */, {\r\n originalMessage: e === null || e === void 0 ? void 0 : e.message\r\n });\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Fetches the password policy for the currently set tenant or the project if no tenant is set.\r\n *\r\n * @param auth Auth object.\r\n * @param request Password policy request.\r\n * @returns Password policy response.\r\n */\r\nasync function _getPasswordPolicy(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v2/passwordPolicy\" /* Endpoint.GET_PASSWORD_POLICY */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Minimum min password length enforced by the backend, even if no minimum length is set.\r\nconst MINIMUM_MIN_PASSWORD_LENGTH = 6;\r\n/**\r\n * Stores password policy requirements and provides password validation against the policy.\r\n *\r\n * @internal\r\n */\r\nclass PasswordPolicyImpl {\r\n constructor(response) {\r\n var _a, _b, _c, _d;\r\n // Only include custom strength options defined in the response.\r\n const responseOptions = response.customStrengthOptions;\r\n this.customStrengthOptions = {};\r\n // TODO: Remove once the backend is updated to include the minimum min password length instead of undefined when there is no minimum length set.\r\n this.customStrengthOptions.minPasswordLength =\r\n (_a = responseOptions.minPasswordLength) !== null && _a !== void 0 ? _a : MINIMUM_MIN_PASSWORD_LENGTH;\r\n if (responseOptions.maxPasswordLength) {\r\n this.customStrengthOptions.maxPasswordLength =\r\n responseOptions.maxPasswordLength;\r\n }\r\n if (responseOptions.containsLowercaseCharacter !== undefined) {\r\n this.customStrengthOptions.containsLowercaseLetter =\r\n responseOptions.containsLowercaseCharacter;\r\n }\r\n if (responseOptions.containsUppercaseCharacter !== undefined) {\r\n this.customStrengthOptions.containsUppercaseLetter =\r\n responseOptions.containsUppercaseCharacter;\r\n }\r\n if (responseOptions.containsNumericCharacter !== undefined) {\r\n this.customStrengthOptions.containsNumericCharacter =\r\n responseOptions.containsNumericCharacter;\r\n }\r\n if (responseOptions.containsNonAlphanumericCharacter !== undefined) {\r\n this.customStrengthOptions.containsNonAlphanumericCharacter =\r\n responseOptions.containsNonAlphanumericCharacter;\r\n }\r\n this.enforcementState = response.enforcementState;\r\n if (this.enforcementState === 'ENFORCEMENT_STATE_UNSPECIFIED') {\r\n this.enforcementState = 'OFF';\r\n }\r\n // Use an empty string if no non-alphanumeric characters are specified in the response.\r\n this.allowedNonAlphanumericCharacters =\r\n (_c = (_b = response.allowedNonAlphanumericCharacters) === null || _b === void 0 ? void 0 : _b.join('')) !== null && _c !== void 0 ? _c : '';\r\n this.forceUpgradeOnSignin = (_d = response.forceUpgradeOnSignin) !== null && _d !== void 0 ? _d : false;\r\n this.schemaVersion = response.schemaVersion;\r\n }\r\n validatePassword(password) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const status = {\r\n isValid: true,\r\n passwordPolicy: this\r\n };\r\n // Check the password length and character options.\r\n this.validatePasswordLengthOptions(password, status);\r\n this.validatePasswordCharacterOptions(password, status);\r\n // Combine the status into single isValid property.\r\n status.isValid && (status.isValid = (_a = status.meetsMinPasswordLength) !== null && _a !== void 0 ? _a : true);\r\n status.isValid && (status.isValid = (_b = status.meetsMaxPasswordLength) !== null && _b !== void 0 ? _b : true);\r\n status.isValid && (status.isValid = (_c = status.containsLowercaseLetter) !== null && _c !== void 0 ? _c : true);\r\n status.isValid && (status.isValid = (_d = status.containsUppercaseLetter) !== null && _d !== void 0 ? _d : true);\r\n status.isValid && (status.isValid = (_e = status.containsNumericCharacter) !== null && _e !== void 0 ? _e : true);\r\n status.isValid && (status.isValid = (_f = status.containsNonAlphanumericCharacter) !== null && _f !== void 0 ? _f : true);\r\n return status;\r\n }\r\n /**\r\n * Validates that the password meets the length options for the policy.\r\n *\r\n * @param password Password to validate.\r\n * @param status Validation status.\r\n */\r\n validatePasswordLengthOptions(password, status) {\r\n const minPasswordLength = this.customStrengthOptions.minPasswordLength;\r\n const maxPasswordLength = this.customStrengthOptions.maxPasswordLength;\r\n if (minPasswordLength) {\r\n status.meetsMinPasswordLength = password.length >= minPasswordLength;\r\n }\r\n if (maxPasswordLength) {\r\n status.meetsMaxPasswordLength = password.length <= maxPasswordLength;\r\n }\r\n }\r\n /**\r\n * Validates that the password meets the character options for the policy.\r\n *\r\n * @param password Password to validate.\r\n * @param status Validation status.\r\n */\r\n validatePasswordCharacterOptions(password, status) {\r\n // Assign statuses for requirements even if the password is an empty string.\r\n this.updatePasswordCharacterOptionsStatuses(status, \r\n /* containsLowercaseCharacter= */ false, \r\n /* containsUppercaseCharacter= */ false, \r\n /* containsNumericCharacter= */ false, \r\n /* containsNonAlphanumericCharacter= */ false);\r\n let passwordChar;\r\n for (let i = 0; i < password.length; i++) {\r\n passwordChar = password.charAt(i);\r\n this.updatePasswordCharacterOptionsStatuses(status, \r\n /* containsLowercaseCharacter= */ passwordChar >= 'a' &&\r\n passwordChar <= 'z', \r\n /* containsUppercaseCharacter= */ passwordChar >= 'A' &&\r\n passwordChar <= 'Z', \r\n /* containsNumericCharacter= */ passwordChar >= '0' &&\r\n passwordChar <= '9', \r\n /* containsNonAlphanumericCharacter= */ this.allowedNonAlphanumericCharacters.includes(passwordChar));\r\n }\r\n }\r\n /**\r\n * Updates the running validation status with the statuses for the character options.\r\n * Expected to be called each time a character is processed to update each option status\r\n * based on the current character.\r\n *\r\n * @param status Validation status.\r\n * @param containsLowercaseCharacter Whether the character is a lowercase letter.\r\n * @param containsUppercaseCharacter Whether the character is an uppercase letter.\r\n * @param containsNumericCharacter Whether the character is a numeric character.\r\n * @param containsNonAlphanumericCharacter Whether the character is a non-alphanumeric character.\r\n */\r\n updatePasswordCharacterOptionsStatuses(status, containsLowercaseCharacter, containsUppercaseCharacter, containsNumericCharacter, containsNonAlphanumericCharacter) {\r\n if (this.customStrengthOptions.containsLowercaseLetter) {\r\n status.containsLowercaseLetter || (status.containsLowercaseLetter = containsLowercaseCharacter);\r\n }\r\n if (this.customStrengthOptions.containsUppercaseLetter) {\r\n status.containsUppercaseLetter || (status.containsUppercaseLetter = containsUppercaseCharacter);\r\n }\r\n if (this.customStrengthOptions.containsNumericCharacter) {\r\n status.containsNumericCharacter || (status.containsNumericCharacter = containsNumericCharacter);\r\n }\r\n if (this.customStrengthOptions.containsNonAlphanumericCharacter) {\r\n status.containsNonAlphanumericCharacter || (status.containsNonAlphanumericCharacter = containsNonAlphanumericCharacter);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthImpl {\r\n constructor(app, heartbeatServiceProvider, appCheckServiceProvider, config) {\r\n this.app = app;\r\n this.heartbeatServiceProvider = heartbeatServiceProvider;\r\n this.appCheckServiceProvider = appCheckServiceProvider;\r\n this.config = config;\r\n this.currentUser = null;\r\n this.emulatorConfig = null;\r\n this.operations = Promise.resolve();\r\n this.authStateSubscription = new Subscription(this);\r\n this.idTokenSubscription = new Subscription(this);\r\n this.beforeStateQueue = new AuthMiddlewareQueue(this);\r\n this.redirectUser = null;\r\n this.isProactiveRefreshEnabled = false;\r\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION = 1;\r\n // Any network calls will set this to true and prevent subsequent emulator\r\n // initialization\r\n this._canInitEmulator = true;\r\n this._isInitialized = false;\r\n this._deleted = false;\r\n this._initializationPromise = null;\r\n this._popupRedirectResolver = null;\r\n this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;\r\n this._agentRecaptchaConfig = null;\r\n this._tenantRecaptchaConfigs = {};\r\n this._projectPasswordPolicy = null;\r\n this._tenantPasswordPolicies = {};\r\n // Tracks the last notified UID for state change listeners to prevent\r\n // repeated calls to the callbacks. Undefined means it's never been\r\n // called, whereas null means it's been called with a signed out user\r\n this.lastNotifiedUid = undefined;\r\n this.languageCode = null;\r\n this.tenantId = null;\r\n this.settings = { appVerificationDisabledForTesting: false };\r\n this.frameworks = [];\r\n this.name = app.name;\r\n this.clientVersion = config.sdkClientVersion;\r\n }\r\n _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {\r\n if (popupRedirectResolver) {\r\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\r\n }\r\n // Have to check for app deletion throughout initialization (after each\r\n // promise resolution)\r\n this._initializationPromise = this.queue(async () => {\r\n var _a, _b;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);\r\n if (this._deleted) {\r\n return;\r\n }\r\n // Initialize the resolver early if necessary (only applicable to web:\r\n // this will cause the iframe to load immediately in certain cases)\r\n if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {\r\n // If this fails, don't halt auth loading\r\n try {\r\n await this._popupRedirectResolver._initialize(this);\r\n }\r\n catch (e) {\r\n /* Ignore the error */\r\n }\r\n }\r\n await this.initializeCurrentUser(popupRedirectResolver);\r\n this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this._isInitialized = true;\r\n });\r\n return this._initializationPromise;\r\n }\r\n /**\r\n * If the persistence is changed in another window, the user manager will let us know\r\n */\r\n async _onStorageEvent() {\r\n if (this._deleted) {\r\n return;\r\n }\r\n const user = await this.assertedPersistence.getCurrentUser();\r\n if (!this.currentUser && !user) {\r\n // No change, do nothing (was signed out and remained signed out).\r\n return;\r\n }\r\n // If the same user is to be synchronized.\r\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\r\n // Data update, simply copy data changes.\r\n this._currentUser._assign(user);\r\n // If tokens changed from previous user tokens, this will trigger\r\n // notifyAuthListeners_.\r\n await this.currentUser.getIdToken();\r\n return;\r\n }\r\n // Update current Auth state. Either a new login or logout.\r\n // Skip blocking callbacks, they should not apply to a change in another tab.\r\n await this._updateCurrentUser(user, /* skipBeforeStateCallbacks */ true);\r\n }\r\n async initializeCurrentUserFromIdToken(idToken) {\r\n try {\r\n const response = await getAccountInfo(this, { idToken });\r\n const user = await UserImpl._fromGetAccountInfoResponse(this, response, idToken);\r\n await this.directlySetCurrentUser(user);\r\n }\r\n catch (err) {\r\n console.warn('FirebaseServerApp could not login user with provided authIdToken: ', err);\r\n await this.directlySetCurrentUser(null);\r\n }\r\n }\r\n async initializeCurrentUser(popupRedirectResolver) {\r\n var _a;\r\n if (_isFirebaseServerApp(this.app)) {\r\n const idToken = this.app.settings.authIdToken;\r\n if (idToken) {\r\n // Start the auth operation in the next tick to allow a moment for the customer's app to\r\n // attach an emulator, if desired.\r\n return new Promise(resolve => {\r\n setTimeout(() => this.initializeCurrentUserFromIdToken(idToken).then(resolve, resolve));\r\n });\r\n }\r\n else {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n // First check to see if we have a pending redirect event.\r\n const previouslyStoredUser = (await this.assertedPersistence.getCurrentUser());\r\n let futureCurrentUser = previouslyStoredUser;\r\n let needsTocheckMiddleware = false;\r\n if (popupRedirectResolver && this.config.authDomain) {\r\n await this.getOrInitRedirectPersistenceManager();\r\n const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;\r\n const storedUserEventId = futureCurrentUser === null || futureCurrentUser === void 0 ? void 0 : futureCurrentUser._redirectEventId;\r\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\r\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\r\n // matches the redirect user, then we want to initially sign in with the\r\n // new user object from result.\r\n // TODO(samgho): More thoroughly test all of this\r\n if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\r\n (result === null || result === void 0 ? void 0 : result.user)) {\r\n futureCurrentUser = result.user;\r\n needsTocheckMiddleware = true;\r\n }\r\n }\r\n // If no user in persistence, there is no current user. Set to null.\r\n if (!futureCurrentUser) {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n if (!futureCurrentUser._redirectEventId) {\r\n // This isn't a redirect link operation, we can reload and bail.\r\n // First though, ensure that we check the middleware is happy.\r\n if (needsTocheckMiddleware) {\r\n try {\r\n await this.beforeStateQueue.runMiddleware(futureCurrentUser);\r\n }\r\n catch (e) {\r\n futureCurrentUser = previouslyStoredUser;\r\n // We know this is available since the bit is only set when the\r\n // resolver is available\r\n this._popupRedirectResolver._overrideRedirectResult(this, () => Promise.reject(e));\r\n }\r\n }\r\n if (futureCurrentUser) {\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n else {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n _assert(this._popupRedirectResolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n await this.getOrInitRedirectPersistenceManager();\r\n // If the redirect user's event ID matches the current user's event ID,\r\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\r\n // This is important for the reauthenticateWithRedirect() flow.\r\n if (this.redirectUser &&\r\n this.redirectUser._redirectEventId === futureCurrentUser._redirectEventId) {\r\n return this.directlySetCurrentUser(futureCurrentUser);\r\n }\r\n return this.reloadAndSetCurrentUserOrClear(futureCurrentUser);\r\n }\r\n async tryRedirectSignIn(redirectResolver) {\r\n // The redirect user needs to be checked (and signed in if available)\r\n // during auth initialization. All of the normal sign in and link/reauth\r\n // flows call back into auth and push things onto the promise queue. We\r\n // need to await the result of the redirect sign in *inside the promise\r\n // queue*. This presents a problem: we run into deadlock. See:\r\n // ┌> [Initialization] ─────┐\r\n // ┌> [] │\r\n // └─ [getRedirectResult] <─┘\r\n // where [] are tasks on the queue and arrows denote awaits\r\n // Initialization will never complete because it's waiting on something\r\n // that's waiting for initialization to complete!\r\n //\r\n // Instead, this method calls getRedirectResult() (stored in\r\n // _completeRedirectFn) with an optional parameter that instructs all of\r\n // the underlying auth operations to skip anything that mutates auth state.\r\n let result = null;\r\n try {\r\n // We know this._popupRedirectResolver is set since redirectResolver\r\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\r\n result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);\r\n }\r\n catch (e) {\r\n // Swallow any errors here; the code can retrieve them in\r\n // getRedirectResult().\r\n await this._setRedirectUser(null);\r\n }\r\n return result;\r\n }\r\n async reloadAndSetCurrentUserOrClear(user) {\r\n try {\r\n await _reloadWithoutSaving(user);\r\n }\r\n catch (e) {\r\n if ((e === null || e === void 0 ? void 0 : e.code) !==\r\n `auth/${\"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */}`) {\r\n // Something's wrong with the user's token. Log them out and remove\r\n // them from storage\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n return this.directlySetCurrentUser(user);\r\n }\r\n useDeviceLanguage() {\r\n this.languageCode = _getUserLanguage();\r\n }\r\n async _delete() {\r\n this._deleted = true;\r\n }\r\n async updateCurrentUser(userExtern) {\r\n if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n // The public updateCurrentUser method needs to make a copy of the user,\r\n // and also check that the project matches\r\n const user = userExtern\r\n ? getModularInstance(userExtern)\r\n : null;\r\n if (user) {\r\n _assert(user.auth.config.apiKey === this.config.apiKey, this, \"invalid-user-token\" /* AuthErrorCode.INVALID_AUTH */);\r\n }\r\n return this._updateCurrentUser(user && user._clone(this));\r\n }\r\n async _updateCurrentUser(user, skipBeforeStateCallbacks = false) {\r\n if (this._deleted) {\r\n return;\r\n }\r\n if (user) {\r\n _assert(this.tenantId === user.tenantId, this, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n }\r\n if (!skipBeforeStateCallbacks) {\r\n await this.beforeStateQueue.runMiddleware(user);\r\n }\r\n return this.queue(async () => {\r\n await this.directlySetCurrentUser(user);\r\n this.notifyAuthListeners();\r\n });\r\n }\r\n async signOut() {\r\n if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n // Run first, to block _setRedirectUser() if any callbacks fail.\r\n await this.beforeStateQueue.runMiddleware(null);\r\n // Clear the redirect user when signOut is called\r\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\r\n await this._setRedirectUser(null);\r\n }\r\n // Prevent callbacks from being called again in _updateCurrentUser, as\r\n // they were already called in the first line.\r\n return this._updateCurrentUser(null, /* skipBeforeStateCallbacks */ true);\r\n }\r\n setPersistence(persistence) {\r\n if (_isFirebaseServerApp(this.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));\r\n }\r\n return this.queue(async () => {\r\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\r\n });\r\n }\r\n _getRecaptchaConfig() {\r\n if (this.tenantId == null) {\r\n return this._agentRecaptchaConfig;\r\n }\r\n else {\r\n return this._tenantRecaptchaConfigs[this.tenantId];\r\n }\r\n }\r\n async validatePassword(password) {\r\n if (!this._getPasswordPolicyInternal()) {\r\n await this._updatePasswordPolicy();\r\n }\r\n // Password policy will be defined after fetching.\r\n const passwordPolicy = this._getPasswordPolicyInternal();\r\n // Check that the policy schema version is supported by the SDK.\r\n // TODO: Update this logic to use a max supported policy schema version once we have multiple schema versions.\r\n if (passwordPolicy.schemaVersion !==\r\n this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION) {\r\n return Promise.reject(this._errorFactory.create(\"unsupported-password-policy-schema-version\" /* AuthErrorCode.UNSUPPORTED_PASSWORD_POLICY_SCHEMA_VERSION */, {}));\r\n }\r\n return passwordPolicy.validatePassword(password);\r\n }\r\n _getPasswordPolicyInternal() {\r\n if (this.tenantId === null) {\r\n return this._projectPasswordPolicy;\r\n }\r\n else {\r\n return this._tenantPasswordPolicies[this.tenantId];\r\n }\r\n }\r\n async _updatePasswordPolicy() {\r\n const response = await _getPasswordPolicy(this);\r\n const passwordPolicy = new PasswordPolicyImpl(response);\r\n if (this.tenantId === null) {\r\n this._projectPasswordPolicy = passwordPolicy;\r\n }\r\n else {\r\n this._tenantPasswordPolicies[this.tenantId] = passwordPolicy;\r\n }\r\n }\r\n _getPersistence() {\r\n return this.assertedPersistence.persistence.type;\r\n }\r\n _updateErrorMap(errorMap) {\r\n this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());\r\n }\r\n onAuthStateChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);\r\n }\r\n beforeAuthStateChanged(callback, onAbort) {\r\n return this.beforeStateQueue.pushCallback(callback, onAbort);\r\n }\r\n onIdTokenChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);\r\n }\r\n authStateReady() {\r\n return new Promise((resolve, reject) => {\r\n if (this.currentUser) {\r\n resolve();\r\n }\r\n else {\r\n const unsubscribe = this.onAuthStateChanged(() => {\r\n unsubscribe();\r\n resolve();\r\n }, reject);\r\n }\r\n });\r\n }\r\n /**\r\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\r\n */\r\n async revokeAccessToken(token) {\r\n if (this.currentUser) {\r\n const idToken = await this.currentUser.getIdToken();\r\n // Generalize this to accept other providers once supported.\r\n const request = {\r\n providerId: 'apple.com',\r\n tokenType: \"ACCESS_TOKEN\" /* TokenType.ACCESS_TOKEN */,\r\n token,\r\n idToken\r\n };\r\n if (this.tenantId != null) {\r\n request.tenantId = this.tenantId;\r\n }\r\n await revokeToken(this, request);\r\n }\r\n }\r\n toJSON() {\r\n var _a;\r\n return {\r\n apiKey: this.config.apiKey,\r\n authDomain: this.config.authDomain,\r\n appName: this.name,\r\n currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()\r\n };\r\n }\r\n async _setRedirectUser(user, popupRedirectResolver) {\r\n const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);\r\n return user === null\r\n ? redirectManager.removeCurrentUser()\r\n : redirectManager.setCurrentUser(user);\r\n }\r\n async getOrInitRedirectPersistenceManager(popupRedirectResolver) {\r\n if (!this.redirectPersistenceManager) {\r\n const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\r\n this._popupRedirectResolver;\r\n _assert(resolver, this, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], \"redirectUser\" /* KeyName.REDIRECT_USER */);\r\n this.redirectUser =\r\n await this.redirectPersistenceManager.getCurrentUser();\r\n }\r\n return this.redirectPersistenceManager;\r\n }\r\n async _redirectUserForId(id) {\r\n var _a, _b;\r\n // Make sure we've cleared any pending persistence actions if we're not in\r\n // the initializer\r\n if (this._isInitialized) {\r\n await this.queue(async () => { });\r\n }\r\n if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {\r\n return this._currentUser;\r\n }\r\n if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {\r\n return this.redirectUser;\r\n }\r\n return null;\r\n }\r\n async _persistUserIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n return this.queue(async () => this.directlySetCurrentUser(user));\r\n }\r\n }\r\n /** Notifies listeners only if the user is current */\r\n _notifyListenersIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n this.notifyAuthListeners();\r\n }\r\n }\r\n _key() {\r\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\r\n }\r\n _startProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = true;\r\n if (this.currentUser) {\r\n this._currentUser._startProactiveRefresh();\r\n }\r\n }\r\n _stopProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = false;\r\n if (this.currentUser) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n }\r\n /** Returns the current user cast as the internal type */\r\n get _currentUser() {\r\n return this.currentUser;\r\n }\r\n notifyAuthListeners() {\r\n var _a, _b;\r\n if (!this._isInitialized) {\r\n return;\r\n }\r\n this.idTokenSubscription.next(this.currentUser);\r\n const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;\r\n if (this.lastNotifiedUid !== currentUid) {\r\n this.lastNotifiedUid = currentUid;\r\n this.authStateSubscription.next(this.currentUser);\r\n }\r\n }\r\n registerStateListener(subscription, nextOrObserver, error, completed) {\r\n if (this._deleted) {\r\n return () => { };\r\n }\r\n const cb = typeof nextOrObserver === 'function'\r\n ? nextOrObserver\r\n : nextOrObserver.next.bind(nextOrObserver);\r\n let isUnsubscribed = false;\r\n const promise = this._isInitialized\r\n ? Promise.resolve()\r\n : this._initializationPromise;\r\n _assert(promise, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // The callback needs to be called asynchronously per the spec.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n promise.then(() => {\r\n if (isUnsubscribed) {\r\n return;\r\n }\r\n cb(this.currentUser);\r\n });\r\n if (typeof nextOrObserver === 'function') {\r\n const unsubscribe = subscription.addObserver(nextOrObserver, error, completed);\r\n return () => {\r\n isUnsubscribed = true;\r\n unsubscribe();\r\n };\r\n }\r\n else {\r\n const unsubscribe = subscription.addObserver(nextOrObserver);\r\n return () => {\r\n isUnsubscribed = true;\r\n unsubscribe();\r\n };\r\n }\r\n }\r\n /**\r\n * Unprotected (from race conditions) method to set the current user. This\r\n * should only be called from within a queued callback. This is necessary\r\n * because the queue shouldn't rely on another queued callback.\r\n */\r\n async directlySetCurrentUser(user) {\r\n if (this.currentUser && this.currentUser !== user) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n if (user && this.isProactiveRefreshEnabled) {\r\n user._startProactiveRefresh();\r\n }\r\n this.currentUser = user;\r\n if (user) {\r\n await this.assertedPersistence.setCurrentUser(user);\r\n }\r\n else {\r\n await this.assertedPersistence.removeCurrentUser();\r\n }\r\n }\r\n queue(action) {\r\n // In case something errors, the callback still should be called in order\r\n // to keep the promise chain alive\r\n this.operations = this.operations.then(action, action);\r\n return this.operations;\r\n }\r\n get assertedPersistence() {\r\n _assert(this.persistenceManager, this, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.persistenceManager;\r\n }\r\n _logFramework(framework) {\r\n if (!framework || this.frameworks.includes(framework)) {\r\n return;\r\n }\r\n this.frameworks.push(framework);\r\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\r\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\r\n this.frameworks.sort();\r\n this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());\r\n }\r\n _getFrameworks() {\r\n return this.frameworks;\r\n }\r\n async _getAdditionalHeaders() {\r\n var _a;\r\n // Additional headers on every request\r\n const headers = {\r\n [\"X-Client-Version\" /* HttpHeader.X_CLIENT_VERSION */]: this.clientVersion\r\n };\r\n if (this.app.options.appId) {\r\n headers[\"X-Firebase-gmpid\" /* HttpHeader.X_FIREBASE_GMPID */] = this.app.options.appId;\r\n }\r\n // If the heartbeat service exists, add the heartbeat string\r\n const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider\r\n .getImmediate({\r\n optional: true\r\n })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());\r\n if (heartbeatsHeader) {\r\n headers[\"X-Firebase-Client\" /* HttpHeader.X_FIREBASE_CLIENT */] = heartbeatsHeader;\r\n }\r\n // If the App Check service exists, add the App Check token in the headers\r\n const appCheckToken = await this._getAppCheckToken();\r\n if (appCheckToken) {\r\n headers[\"X-Firebase-AppCheck\" /* HttpHeader.X_FIREBASE_APP_CHECK */] = appCheckToken;\r\n }\r\n return headers;\r\n }\r\n async _getAppCheckToken() {\r\n var _a;\r\n const appCheckTokenResult = await ((_a = this.appCheckServiceProvider\r\n .getImmediate({ optional: true })) === null || _a === void 0 ? void 0 : _a.getToken());\r\n if (appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.error) {\r\n // Context: appCheck.getToken() will never throw even if an error happened.\r\n // In the error case, a dummy token will be returned along with an error field describing\r\n // the error. In general, we shouldn't care about the error condition and just use\r\n // the token (actual or dummy) to send requests.\r\n _logWarn(`Error while retrieving App Check token: ${appCheckTokenResult.error}`);\r\n }\r\n return appCheckTokenResult === null || appCheckTokenResult === void 0 ? void 0 : appCheckTokenResult.token;\r\n }\r\n}\r\n/**\r\n * Method to be used to cast down to our private implmentation of Auth.\r\n * It will also handle unwrapping from the compat type if necessary\r\n *\r\n * @param auth Auth object passed in from developer\r\n */\r\nfunction _castAuth(auth) {\r\n return getModularInstance(auth);\r\n}\r\n/** Helper class to wrap subscriber logic */\r\nclass Subscription {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.observer = null;\r\n this.addObserver = createSubscribe(observer => (this.observer = observer));\r\n }\r\n get next() {\r\n _assert(this.observer, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.observer.next.bind(this.observer);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet externalJSProvider = {\r\n async loadJS() {\r\n throw new Error('Unable to load external scripts');\r\n },\r\n recaptchaV2Script: '',\r\n recaptchaEnterpriseScript: '',\r\n gapiScript: ''\r\n};\r\nfunction _setExternalJSProvider(p) {\r\n externalJSProvider = p;\r\n}\r\nfunction _loadJS(url) {\r\n return externalJSProvider.loadJS(url);\r\n}\r\nfunction _recaptchaV2ScriptUrl() {\r\n return externalJSProvider.recaptchaV2Script;\r\n}\r\nfunction _recaptchaEnterpriseScriptUrl() {\r\n return externalJSProvider.recaptchaEnterpriseScript;\r\n}\r\nfunction _gapiScriptUrl() {\r\n return externalJSProvider.gapiScript;\r\n}\r\nfunction _generateCallbackName(prefix) {\r\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\r\n}\n\n/* eslint-disable @typescript-eslint/no-require-imports */\r\nconst RECAPTCHA_ENTERPRISE_VERIFIER_TYPE = 'recaptcha-enterprise';\r\nconst FAKE_TOKEN = 'NO_RECAPTCHA';\r\nclass RecaptchaEnterpriseVerifier {\r\n /**\r\n *\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n *\r\n */\r\n constructor(authExtern) {\r\n /**\r\n * Identifies the type of application verifier (e.g. \"recaptcha-enterprise\").\r\n */\r\n this.type = RECAPTCHA_ENTERPRISE_VERIFIER_TYPE;\r\n this.auth = _castAuth(authExtern);\r\n }\r\n /**\r\n * Executes the verification process.\r\n *\r\n * @returns A Promise for a token that can be used to assert the validity of a request.\r\n */\r\n async verify(action = 'verify', forceRefresh = false) {\r\n async function retrieveSiteKey(auth) {\r\n if (!forceRefresh) {\r\n if (auth.tenantId == null && auth._agentRecaptchaConfig != null) {\r\n return auth._agentRecaptchaConfig.siteKey;\r\n }\r\n if (auth.tenantId != null &&\r\n auth._tenantRecaptchaConfigs[auth.tenantId] !== undefined) {\r\n return auth._tenantRecaptchaConfigs[auth.tenantId].siteKey;\r\n }\r\n }\r\n return new Promise(async (resolve, reject) => {\r\n getRecaptchaConfig(auth, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n })\r\n .then(response => {\r\n if (response.recaptchaKey === undefined) {\r\n reject(new Error('recaptcha Enterprise site key undefined'));\r\n }\r\n else {\r\n const config = new RecaptchaConfig(response);\r\n if (auth.tenantId == null) {\r\n auth._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n auth._tenantRecaptchaConfigs[auth.tenantId] = config;\r\n }\r\n return resolve(config.siteKey);\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n function retrieveRecaptchaToken(siteKey, resolve, reject) {\r\n const grecaptcha = window.grecaptcha;\r\n if (isEnterprise(grecaptcha)) {\r\n grecaptcha.enterprise.ready(() => {\r\n grecaptcha.enterprise\r\n .execute(siteKey, { action })\r\n .then(token => {\r\n resolve(token);\r\n })\r\n .catch(() => {\r\n resolve(FAKE_TOKEN);\r\n });\r\n });\r\n }\r\n else {\r\n reject(Error('No reCAPTCHA enterprise script loaded.'));\r\n }\r\n }\r\n return new Promise((resolve, reject) => {\r\n retrieveSiteKey(this.auth)\r\n .then(siteKey => {\r\n if (!forceRefresh && isEnterprise(window.grecaptcha)) {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n }\r\n else {\r\n if (typeof window === 'undefined') {\r\n reject(new Error('RecaptchaVerifier is only supported in browser'));\r\n return;\r\n }\r\n let url = _recaptchaEnterpriseScriptUrl();\r\n if (url.length !== 0) {\r\n url += siteKey;\r\n }\r\n _loadJS(url)\r\n .then(() => {\r\n retrieveRecaptchaToken(siteKey, resolve, reject);\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n }\r\n })\r\n .catch(error => {\r\n reject(error);\r\n });\r\n });\r\n }\r\n}\r\nasync function injectRecaptchaFields(auth, request, action, captchaResp = false) {\r\n const verifier = new RecaptchaEnterpriseVerifier(auth);\r\n let captchaResponse;\r\n try {\r\n captchaResponse = await verifier.verify(action);\r\n }\r\n catch (error) {\r\n captchaResponse = await verifier.verify(action, true);\r\n }\r\n const newRequest = Object.assign({}, request);\r\n if (!captchaResp) {\r\n Object.assign(newRequest, { captchaResponse });\r\n }\r\n else {\r\n Object.assign(newRequest, { 'captchaResp': captchaResponse });\r\n }\r\n Object.assign(newRequest, { 'clientType': \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */ });\r\n Object.assign(newRequest, {\r\n 'recaptchaVersion': \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n return newRequest;\r\n}\r\nasync function handleRecaptchaFlow(authInstance, request, actionName, actionMethod) {\r\n var _a;\r\n if ((_a = authInstance\r\n ._getRecaptchaConfig()) === null || _a === void 0 ? void 0 : _a.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaProvider.EMAIL_PASSWORD_PROVIDER */)) {\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\r\n return actionMethod(authInstance, requestWithRecaptcha);\r\n }\r\n else {\r\n return actionMethod(authInstance, request).catch(async (error) => {\r\n if (error.code === `auth/${\"missing-recaptcha-token\" /* AuthErrorCode.MISSING_RECAPTCHA_TOKEN */}`) {\r\n console.log(`${actionName} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);\r\n const requestWithRecaptcha = await injectRecaptchaFields(authInstance, request, actionName, actionName === \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */);\r\n return actionMethod(authInstance, requestWithRecaptcha);\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n}\r\nasync function _initializeRecaptchaConfig(auth) {\r\n const authInternal = _castAuth(auth);\r\n const response = await getRecaptchaConfig(authInternal, {\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */,\r\n version: \"RECAPTCHA_ENTERPRISE\" /* RecaptchaVersion.ENTERPRISE */\r\n });\r\n const config = new RecaptchaConfig(response);\r\n if (authInternal.tenantId == null) {\r\n authInternal._agentRecaptchaConfig = config;\r\n }\r\n else {\r\n authInternal._tenantRecaptchaConfigs[authInternal.tenantId] = config;\r\n }\r\n if (config.isProviderEnabled(\"EMAIL_PASSWORD_PROVIDER\" /* RecaptchaProvider.EMAIL_PASSWORD_PROVIDER */)) {\r\n const verifier = new RecaptchaEnterpriseVerifier(authInternal);\r\n void verifier.verify();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Initializes an {@link Auth} instance with fine-grained control over\r\n * {@link Dependencies}.\r\n *\r\n * @remarks\r\n *\r\n * This function allows more control over the {@link Auth} instance than\r\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\r\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\r\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\r\n * need control over which persistence layer is used, or to minimize bundle\r\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\r\n *\r\n * For example, if your app only uses anonymous accounts and you only want\r\n * accounts saved for the current session, initialize `Auth` with:\r\n *\r\n * ```js\r\n * const auth = initializeAuth(app, {\r\n * persistence: browserSessionPersistence,\r\n * popupRedirectResolver: undefined,\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nfunction initializeAuth(app, deps) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n const auth = provider.getImmediate();\r\n const initialOptions = provider.getOptions();\r\n if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {\r\n return auth;\r\n }\r\n else {\r\n _fail(auth, \"already-initialized\" /* AuthErrorCode.ALREADY_INITIALIZED */);\r\n }\r\n }\r\n const auth = provider.initialize({ options: deps });\r\n return auth;\r\n}\r\nfunction _initializeAuthInstance(auth, deps) {\r\n const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];\r\n const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);\r\n if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {\r\n auth._updateErrorMap(deps.errorMap);\r\n }\r\n // This promise is intended to float; auth initialization happens in the\r\n // background, meanwhile the auth object may be used by the app.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);\r\n}\n\n/**\r\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\r\n * Firebase Auth services.\r\n *\r\n * @remarks\r\n * This must be called synchronously immediately following the first call to\r\n * {@link initializeAuth}. Do not use with production credentials as emulator\r\n * traffic is not encrypted.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\r\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\r\n * `true` to disable the warning banner attached to the DOM.\r\n *\r\n * @public\r\n */\r\nfunction connectAuthEmulator(auth, url, options) {\r\n const authInternal = _castAuth(auth);\r\n _assert(authInternal._canInitEmulator, authInternal, \"emulator-config-failed\" /* AuthErrorCode.EMULATOR_CONFIG_FAILED */);\r\n _assert(/^https?:\\/\\//.test(url), authInternal, \"invalid-emulator-scheme\" /* AuthErrorCode.INVALID_EMULATOR_SCHEME */);\r\n const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);\r\n const protocol = extractProtocol(url);\r\n const { host, port } = extractHostAndPort(url);\r\n const portStr = port === null ? '' : `:${port}`;\r\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\r\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\r\n authInternal.settings.appVerificationDisabledForTesting = true;\r\n authInternal.emulatorConfig = Object.freeze({\r\n host,\r\n port,\r\n protocol: protocol.replace(':', ''),\r\n options: Object.freeze({ disableWarnings })\r\n });\r\n if (!disableWarnings) {\r\n emitEmulatorWarning();\r\n }\r\n}\r\nfunction extractProtocol(url) {\r\n const protocolEnd = url.indexOf(':');\r\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\r\n}\r\nfunction extractHostAndPort(url) {\r\n const protocol = extractProtocol(url);\r\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\r\n if (!authority) {\r\n return { host: '', port: null };\r\n }\r\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\r\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\r\n if (bracketedIPv6) {\r\n const host = bracketedIPv6[1];\r\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\r\n }\r\n else {\r\n const [host, port] = hostAndPort.split(':');\r\n return { host, port: parsePort(port) };\r\n }\r\n}\r\nfunction parsePort(portStr) {\r\n if (!portStr) {\r\n return null;\r\n }\r\n const port = Number(portStr);\r\n if (isNaN(port)) {\r\n return null;\r\n }\r\n return port;\r\n}\r\nfunction emitEmulatorWarning() {\r\n function attachBanner() {\r\n const el = document.createElement('p');\r\n const sty = el.style;\r\n el.innerText =\r\n 'Running in emulator mode. Do not use with production credentials.';\r\n sty.position = 'fixed';\r\n sty.width = '100%';\r\n sty.backgroundColor = '#ffffff';\r\n sty.border = '.1em solid #000000';\r\n sty.color = '#b50000';\r\n sty.bottom = '0px';\r\n sty.left = '0px';\r\n sty.margin = '0px';\r\n sty.zIndex = '10000';\r\n sty.textAlign = 'center';\r\n el.classList.add('firebase-emulator-warning');\r\n document.body.appendChild(el);\r\n }\r\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\r\n console.info('WARNING: You are using the Auth Emulator,' +\r\n ' which is intended for local testing only. Do not use with' +\r\n ' production credentials.');\r\n }\r\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\r\n if (document.readyState === 'loading') {\r\n window.addEventListener('DOMContentLoaded', attachBanner);\r\n }\r\n else {\r\n attachBanner();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by an {@link AuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /**\r\n * The authentication provider ID for the credential.\r\n *\r\n * @remarks\r\n * For example, 'facebook.com', or 'google.com'.\r\n */\r\n providerId, \r\n /**\r\n * The authentication sign in method for the credential.\r\n *\r\n * @remarks\r\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\r\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\r\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\r\n */\r\n signInMethod) {\r\n this.providerId = providerId;\r\n this.signInMethod = signInMethod;\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n *\r\n * @returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _linkToIdToken(_auth, _idToken) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function resetPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:resetPassword\" /* Endpoint.RESET_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function updateEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\r\n// Used for linking an email/password account to an existing idToken. Uses the same request/response\r\n// format as updateEmailPassword.\r\nasync function linkEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, request);\r\n}\r\nasync function applyActionCode$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithPassword(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPassword\" /* Endpoint.SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendOobCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendOobCode\" /* Endpoint.SEND_OOB_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendEmailVerification$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendPasswordResetEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendSignInLinkToEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function verifyAndChangeEmail(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithEmailLink$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithEmailLinkForLinking(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithEmailLink\" /* Endpoint.SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\r\n * {@link ProviderId}.PASSWORD\r\n *\r\n * @remarks\r\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /** @internal */\r\n _email, \r\n /** @internal */\r\n _password, signInMethod, \r\n /** @internal */\r\n _tenantId = null) {\r\n super(\"password\" /* ProviderId.PASSWORD */, signInMethod);\r\n this._email = _email;\r\n this._password = _password;\r\n this._tenantId = _tenantId;\r\n }\r\n /** @internal */\r\n static _fromEmailAndPassword(email, password) {\r\n return new EmailAuthCredential(email, password, \"password\" /* SignInMethod.EMAIL_PASSWORD */);\r\n }\r\n /** @internal */\r\n static _fromEmailAndCode(email, oobCode, tenantId = null) {\r\n return new EmailAuthCredential(email, oobCode, \"emailLink\" /* SignInMethod.EMAIL_LINK */, tenantId);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n email: this._email,\r\n password: this._password,\r\n signInMethod: this.signInMethod,\r\n tenantId: this._tenantId\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\r\n *\r\n * @param json - Either `object` or the stringified representation of the object. When string is\r\n * provided, `JSON.parse` would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {\r\n if (obj.signInMethod === \"password\" /* SignInMethod.EMAIL_PASSWORD */) {\r\n return this._fromEmailAndPassword(obj.email, obj.password);\r\n }\r\n else if (obj.signInMethod === \"emailLink\" /* SignInMethod.EMAIL_LINK */) {\r\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\r\n }\r\n }\r\n return null;\r\n }\r\n /** @internal */\r\n async _getIdTokenResponse(auth) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n const request = {\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n return handleRecaptchaFlow(auth, request, \"signInWithPassword\" /* RecaptchaActionName.SIGN_IN_WITH_PASSWORD */, signInWithPassword);\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLink$1(auth, {\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n async _linkToIdToken(auth, idToken) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* SignInMethod.EMAIL_PASSWORD */:\r\n const request = {\r\n idToken,\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n return handleRecaptchaFlow(auth, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, linkEmailPassword);\r\n case \"emailLink\" /* SignInMethod.EMAIL_LINK */:\r\n return signInWithEmailLinkForLinking(auth, {\r\n idToken,\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return this._getIdTokenResponse(auth);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithIdp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithIdp\" /* Endpoint.SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI$1 = 'http://localhost';\r\n/**\r\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass OAuthCredential extends AuthCredential {\r\n constructor() {\r\n super(...arguments);\r\n this.pendingToken = null;\r\n }\r\n /** @internal */\r\n static _fromParams(params) {\r\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\r\n if (params.idToken || params.accessToken) {\r\n // OAuth 2 and either ID token or access token.\r\n if (params.idToken) {\r\n cred.idToken = params.idToken;\r\n }\r\n if (params.accessToken) {\r\n cred.accessToken = params.accessToken;\r\n }\r\n // Add nonce if available and no pendingToken is present.\r\n if (params.nonce && !params.pendingToken) {\r\n cred.nonce = params.nonce;\r\n }\r\n if (params.pendingToken) {\r\n cred.pendingToken = params.pendingToken;\r\n }\r\n }\r\n else if (params.oauthToken && params.oauthTokenSecret) {\r\n // OAuth 1 and OAuth token with token secret\r\n cred.accessToken = params.oauthToken;\r\n cred.secret = params.oauthTokenSecret;\r\n }\r\n else {\r\n _fail(\"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n }\r\n return cred;\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n idToken: this.idToken,\r\n accessToken: this.accessToken,\r\n secret: this.secret,\r\n nonce: this.nonce,\r\n pendingToken: this.pendingToken,\r\n providerId: this.providerId,\r\n signInMethod: this.signInMethod\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod } = obj, rest = __rest(obj, [\"providerId\", \"signInMethod\"]);\r\n if (!providerId || !signInMethod) {\r\n return null;\r\n }\r\n const cred = new OAuthCredential(providerId, signInMethod);\r\n cred.idToken = rest.idToken || undefined;\r\n cred.accessToken = rest.accessToken || undefined;\r\n cred.secret = rest.secret;\r\n cred.nonce = rest.nonce;\r\n cred.pendingToken = rest.pendingToken || null;\r\n return cred;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n buildRequest() {\r\n const request = {\r\n requestUri: IDP_REQUEST_URI$1,\r\n returnSecureToken: true\r\n };\r\n if (this.pendingToken) {\r\n request.pendingToken = this.pendingToken;\r\n }\r\n else {\r\n const postBody = {};\r\n if (this.idToken) {\r\n postBody['id_token'] = this.idToken;\r\n }\r\n if (this.accessToken) {\r\n postBody['access_token'] = this.accessToken;\r\n }\r\n if (this.secret) {\r\n postBody['oauth_token_secret'] = this.secret;\r\n }\r\n postBody['providerId'] = this.providerId;\r\n if (this.nonce && !this.pendingToken) {\r\n postBody['nonce'] = this.nonce;\r\n }\r\n request.postBody = querystring(postBody);\r\n }\r\n return request;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function sendPhoneVerificationCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:sendVerificationCode\" /* Endpoint.SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithPhoneNumber$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function linkWithPhoneNumber$1(auth, request) {\r\n const response = await _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n if (response.temporaryProof) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* AuthErrorCode.NEED_CONFIRMATION */, response);\r\n }\r\n return response;\r\n}\r\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {\r\n [\"USER_NOT_FOUND\" /* ServerError.USER_NOT_FOUND */]: \"user-not-found\" /* AuthErrorCode.USER_DELETED */\r\n};\r\nasync function verifyPhoneNumberForExisting(auth, request) {\r\n const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithPhoneNumber\" /* Endpoint.SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents the credentials returned by {@link PhoneAuthProvider}.\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"phone\" /* ProviderId.PHONE */, \"phone\" /* SignInMethod.PHONE */);\r\n this.params = params;\r\n }\r\n /** @internal */\r\n static _fromVerification(verificationId, verificationCode) {\r\n return new PhoneAuthCredential({ verificationId, verificationCode });\r\n }\r\n /** @internal */\r\n static _fromTokenResponse(phoneNumber, temporaryProof) {\r\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _makeVerificationRequest() {\r\n const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;\r\n if (temporaryProof && phoneNumber) {\r\n return { temporaryProof, phoneNumber };\r\n }\r\n return {\r\n sessionInfo: verificationId,\r\n code: verificationCode\r\n };\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n const obj = {\r\n providerId: this.providerId\r\n };\r\n if (this.params.phoneNumber) {\r\n obj.phoneNumber = this.params.phoneNumber;\r\n }\r\n if (this.params.temporaryProof) {\r\n obj.temporaryProof = this.params.temporaryProof;\r\n }\r\n if (this.params.verificationCode) {\r\n obj.verificationCode = this.params.verificationCode;\r\n }\r\n if (this.params.verificationId) {\r\n obj.verificationId = this.params.verificationId;\r\n }\r\n return obj;\r\n }\r\n /** Generates a phone credential based on a plain object or a JSON string. */\r\n static fromJSON(json) {\r\n if (typeof json === 'string') {\r\n json = JSON.parse(json);\r\n }\r\n const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;\r\n if (!verificationCode &&\r\n !verificationId &&\r\n !phoneNumber &&\r\n !temporaryProof) {\r\n return null;\r\n }\r\n return new PhoneAuthCredential({\r\n verificationId,\r\n verificationCode,\r\n phoneNumber,\r\n temporaryProof\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Maps the mode string in action code URL to Action Code Info operation.\r\n *\r\n * @param mode\r\n */\r\nfunction parseMode(mode) {\r\n switch (mode) {\r\n case 'recoverEmail':\r\n return \"RECOVER_EMAIL\" /* ActionCodeOperation.RECOVER_EMAIL */;\r\n case 'resetPassword':\r\n return \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */;\r\n case 'signIn':\r\n return \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n case 'verifyEmail':\r\n return \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */;\r\n case 'verifyAndChangeEmail':\r\n return \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */;\r\n case 'revertSecondFactorAddition':\r\n return \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */;\r\n default:\r\n return null;\r\n }\r\n}\r\n/**\r\n * Helper to parse FDL links\r\n *\r\n * @param url\r\n */\r\nfunction parseDeepLink(url) {\r\n const link = querystringDecode(extractQuerystring(url))['link'];\r\n // Double link case (automatic redirect).\r\n const doubleDeepLink = link\r\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\r\n : null;\r\n // iOS custom scheme links.\r\n const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];\r\n const iOSDoubleDeepLink = iOSDeepLink\r\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\r\n : null;\r\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\r\n}\r\n/**\r\n * A utility class to parse email action URLs such as password reset, email verification,\r\n * email link sign in, etc.\r\n *\r\n * @public\r\n */\r\nclass ActionCodeURL {\r\n /**\r\n * @param actionLink - The link from which to extract the URL.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @internal\r\n */\r\n constructor(actionLink) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const searchParams = querystringDecode(extractQuerystring(actionLink));\r\n const apiKey = (_a = searchParams[\"apiKey\" /* QueryField.API_KEY */]) !== null && _a !== void 0 ? _a : null;\r\n const code = (_b = searchParams[\"oobCode\" /* QueryField.CODE */]) !== null && _b !== void 0 ? _b : null;\r\n const operation = parseMode((_c = searchParams[\"mode\" /* QueryField.MODE */]) !== null && _c !== void 0 ? _c : null);\r\n // Validate API key, code and mode.\r\n _assert(apiKey && code && operation, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.apiKey = apiKey;\r\n this.operation = operation;\r\n this.code = code;\r\n this.continueUrl = (_d = searchParams[\"continueUrl\" /* QueryField.CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;\r\n this.languageCode = (_e = searchParams[\"languageCode\" /* QueryField.LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;\r\n this.tenantId = (_f = searchParams[\"tenantId\" /* QueryField.TENANT_ID */]) !== null && _f !== void 0 ? _f : null;\r\n }\r\n /**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\r\n * otherwise returns null.\r\n *\r\n * @param link - The email action link string.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @public\r\n */\r\n static parseLink(link) {\r\n const actionLink = parseDeepLink(link);\r\n try {\r\n return new ActionCodeURL(actionLink);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if\r\n * the link is valid, otherwise returns null.\r\n *\r\n * @public\r\n */\r\nfunction parseActionCodeURL(link) {\r\n return ActionCodeURL.parseLink(link);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating {@link EmailAuthCredential}.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthProvider {\r\n constructor() {\r\n /**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\n this.providerId = EmailAuthProvider.PROVIDER_ID;\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and password.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credential(email, password);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\r\n * ```\r\n *\r\n * @param email - Email address.\r\n * @param password - User account password.\r\n * @returns The auth provider credential.\r\n */\r\n static credential(email, password) {\r\n return EmailAuthCredential._fromEmailAndPassword(email, password);\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\r\n * email link operation.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * await sendSignInLinkToEmail(auth, email);\r\n * // Obtain emailLink from user.\r\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance used to verify the link.\r\n * @param email - Email address.\r\n * @param emailLink - Sign-in email link.\r\n * @returns - The auth provider credential.\r\n */\r\n static credentialWithLink(email, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n _assert(actionCodeUrl, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);\r\n }\r\n}\r\n/**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\nEmailAuthProvider.PROVIDER_ID = \"password\" /* ProviderId.PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\r\n */\r\nEmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = \"password\" /* SignInMethod.EMAIL_PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_LINK.\r\n */\r\nEmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = \"emailLink\" /* SignInMethod.EMAIL_LINK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\r\n *\r\n * This class is not meant to be instantiated directly.\r\n *\r\n * @public\r\n */\r\nclass FederatedAuthProvider {\r\n /**\r\n * Constructor for generic OAuth providers.\r\n *\r\n * @param providerId - Provider for which credentials should be generated.\r\n */\r\n constructor(providerId) {\r\n this.providerId = providerId;\r\n /** @internal */\r\n this.defaultLanguageCode = null;\r\n /** @internal */\r\n this.customParameters = {};\r\n }\r\n /**\r\n * Set the language gode.\r\n *\r\n * @param languageCode - language code\r\n */\r\n setDefaultLanguage(languageCode) {\r\n this.defaultLanguageCode = languageCode;\r\n }\r\n /**\r\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\r\n * operations.\r\n *\r\n * @remarks\r\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\r\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\r\n *\r\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\r\n */\r\n setCustomParameters(customOAuthParameters) {\r\n this.customParameters = customOAuthParameters;\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of {@link CustomParameters}.\r\n */\r\n getCustomParameters() {\r\n return this.customParameters;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Common code to all OAuth providers. This is separate from the\r\n * {@link OAuthProvider} so that child providers (like\r\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\r\n * Instead, they rely on a static `credential` method.\r\n */\r\nclass BaseOAuthProvider extends FederatedAuthProvider {\r\n constructor() {\r\n super(...arguments);\r\n /** @internal */\r\n this.scopes = [];\r\n }\r\n /**\r\n * Add an OAuth scope to the credential.\r\n *\r\n * @param scope - Provider OAuth scope to add.\r\n */\r\n addScope(scope) {\r\n // If not already added, add scope to list.\r\n if (!this.scopes.includes(scope)) {\r\n this.scopes.push(scope);\r\n }\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of OAuth scopes.\r\n */\r\n getScopes() {\r\n return [...this.scopes];\r\n }\r\n}\r\n/**\r\n * Provider for generating generic {@link OAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new OAuthProvider('google.com');\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new OAuthProvider('google.com');\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass OAuthProvider extends BaseOAuthProvider {\r\n /**\r\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n _assert('providerId' in obj && 'signInMethod' in obj, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return OAuthCredential._fromParams(obj);\r\n }\r\n /**\r\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\r\n *\r\n * @remarks\r\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\r\n * the raw nonce must match the nonce field in the ID token.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `googleUser` from the onsuccess Google Sign In callback.\r\n * // Initialize a generate OAuth provider with a `google.com` providerId.\r\n * const provider = new OAuthProvider('google.com');\r\n * const credential = provider.credential({\r\n * idToken: googleUser.getAuthResponse().id_token,\r\n * });\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param params - Either the options object containing the ID token, access token and raw nonce\r\n * or the ID token string.\r\n */\r\n credential(params) {\r\n return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));\r\n }\r\n /** An internal credential method that accepts more permissive options */\r\n _credential(params) {\r\n _assert(params.idToken || params.accessToken, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n // For OAuthCredential, sign in method is same as providerId.\r\n return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;\r\n if (!oauthAccessToken &&\r\n !oauthTokenSecret &&\r\n !oauthIdToken &&\r\n !pendingToken) {\r\n return null;\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n try {\r\n return new OAuthProvider(providerId)._credential({\r\n idToken: oauthIdToken,\r\n accessToken: oauthAccessToken,\r\n nonce,\r\n pendingToken\r\n });\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('user_birthday');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * provider.addScope('user_birthday');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass FacebookAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"facebook.com\" /* ProviderId.FACEBOOK */);\r\n }\r\n /**\r\n * Creates a credential for Facebook.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `event` from the Facebook auth.authResponseChange callback.\r\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param accessToken - Facebook access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: FacebookAuthProvider.PROVIDER_ID,\r\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return FacebookAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.FACEBOOK. */\r\nFacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = \"facebook.com\" /* SignInMethod.FACEBOOK */;\r\n/** Always set to {@link ProviderId}.FACEBOOK. */\r\nFacebookAuthProvider.PROVIDER_ID = \"facebook.com\" /* ProviderId.FACEBOOK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GoogleAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GoogleAuthProvider();\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass GoogleAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"google.com\" /* ProviderId.GOOGLE */);\r\n this.addScope('profile');\r\n }\r\n /**\r\n * Creates a credential for Google. At least one of ID token and access token is required.\r\n *\r\n * @example\r\n * ```javascript\r\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\r\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param idToken - Google ID token.\r\n * @param accessToken - Google access token.\r\n */\r\n static credential(idToken, accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GoogleAuthProvider.PROVIDER_ID,\r\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\r\n idToken,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GoogleAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken } = tokenResponse;\r\n if (!oauthIdToken && !oauthAccessToken) {\r\n // This could be an oauth 1 credential or a phone credential\r\n return null;\r\n }\r\n try {\r\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GOOGLE. */\r\nGoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = \"google.com\" /* SignInMethod.GOOGLE */;\r\n/** Always set to {@link ProviderId}.GOOGLE. */\r\nGoogleAuthProvider.PROVIDER_ID = \"google.com\" /* ProviderId.GOOGLE */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\r\n *\r\n * @remarks\r\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\r\n * the {@link signInWithPopup} handler:\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GithubAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('repo');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GithubAuthProvider();\r\n * provider.addScope('repo');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass GithubAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"github.com\" /* ProviderId.GITHUB */);\r\n }\r\n /**\r\n * Creates a credential for Github.\r\n *\r\n * @param accessToken - Github access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GithubAuthProvider.PROVIDER_ID,\r\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GithubAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GITHUB. */\r\nGithubAuthProvider.GITHUB_SIGN_IN_METHOD = \"github.com\" /* SignInMethod.GITHUB */;\r\n/** Always set to {@link ProviderId}.GITHUB. */\r\nGithubAuthProvider.PROVIDER_ID = \"github.com\" /* ProviderId.GITHUB */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI = 'http://localhost';\r\n/**\r\n * @public\r\n */\r\nclass SAMLAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(providerId, pendingToken) {\r\n super(providerId, providerId);\r\n this.pendingToken = pendingToken;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n signInMethod: this.signInMethod,\r\n providerId: this.providerId,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod, pendingToken } = obj;\r\n if (!providerId ||\r\n !signInMethod ||\r\n !pendingToken ||\r\n providerId !== signInMethod) {\r\n return null;\r\n }\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n /**\r\n * Helper static method to avoid exposing the constructor to end users.\r\n *\r\n * @internal\r\n */\r\n static _create(providerId, pendingToken) {\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n buildRequest() {\r\n return {\r\n requestUri: IDP_REQUEST_URI,\r\n returnSecureToken: true,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SAML_PROVIDER_PREFIX = 'saml.';\r\n/**\r\n * An {@link AuthProvider} for SAML.\r\n *\r\n * @public\r\n */\r\nclass SAMLAuthProvider extends FederatedAuthProvider {\r\n /**\r\n * Constructor. The providerId must start with \"saml.\"\r\n * @param providerId - SAML provider ID.\r\n */\r\n constructor(providerId) {\r\n _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n super(providerId);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\r\n * successful SAML flow completes.\r\n *\r\n * @remarks\r\n *\r\n * For example, to get an {@link AuthCredential}, you could write the\r\n * following code:\r\n *\r\n * ```js\r\n * const userCredential = await signInWithPopup(auth, samlProvider);\r\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\r\n * ```\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n /**\r\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const credential = SAMLAuthCredential.fromJSON(json);\r\n _assert(credential, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return credential;\r\n }\r\n static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { pendingToken, providerId } = tokenResponse;\r\n if (!pendingToken || !providerId) {\r\n return null;\r\n }\r\n try {\r\n return SAMLAuthCredential._create(providerId, pendingToken);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new TwitterAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new TwitterAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass TwitterAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"twitter.com\" /* ProviderId.TWITTER */);\r\n }\r\n /**\r\n * Creates a credential for Twitter.\r\n *\r\n * @param token - Twitter access token.\r\n * @param secret - Twitter secret.\r\n */\r\n static credential(token, secret) {\r\n return OAuthCredential._fromParams({\r\n providerId: TwitterAuthProvider.PROVIDER_ID,\r\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\r\n oauthToken: token,\r\n oauthTokenSecret: secret\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return TwitterAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthAccessToken, oauthTokenSecret } = tokenResponse;\r\n if (!oauthAccessToken || !oauthTokenSecret) {\r\n return null;\r\n }\r\n try {\r\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.TWITTER. */\r\nTwitterAuthProvider.TWITTER_SIGN_IN_METHOD = \"twitter.com\" /* SignInMethod.TWITTER */;\r\n/** Always set to {@link ProviderId}.TWITTER. */\r\nTwitterAuthProvider.PROVIDER_ID = \"twitter.com\" /* ProviderId.TWITTER */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signUp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signUp\" /* Endpoint.SIGN_UP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserCredentialImpl {\r\n constructor(params) {\r\n this.user = params.user;\r\n this.providerId = params.providerId;\r\n this._tokenResponse = params._tokenResponse;\r\n this.operationType = params.operationType;\r\n }\r\n static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {\r\n const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);\r\n const providerId = providerIdForResponse(idTokenResponse);\r\n const userCred = new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: idTokenResponse,\r\n operationType\r\n });\r\n return userCred;\r\n }\r\n static async _forOperation(user, operationType, response) {\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n const providerId = providerIdForResponse(response);\r\n return new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: response,\r\n operationType\r\n });\r\n }\r\n}\r\nfunction providerIdForResponse(response) {\r\n if (response.providerId) {\r\n return response.providerId;\r\n }\r\n if ('phoneNumber' in response) {\r\n return \"phone\" /* ProviderId.PHONE */;\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in as an anonymous user.\r\n *\r\n * @remarks\r\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\r\n * new anonymous user identity will be created and returned.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nasync function signInAnonymously(auth) {\r\n var _a;\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n await authInternal._initializationPromise;\r\n if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {\r\n // If an anonymous user is already signed in, no need to sign them in again.\r\n return new UserCredentialImpl({\r\n user: authInternal.currentUser,\r\n providerId: null,\r\n operationType: \"signIn\" /* OperationType.SIGN_IN */\r\n });\r\n }\r\n const response = await signUp(authInternal, {\r\n returnSecureToken: true\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response, true);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorError extends FirebaseError {\r\n constructor(auth, error, operationType, user) {\r\n var _a;\r\n super(error.code, error.message);\r\n this.operationType = operationType;\r\n this.user = user;\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, MultiFactorError.prototype);\r\n this.customData = {\r\n appName: auth.name,\r\n tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,\r\n _serverResponse: error.customData._serverResponse,\r\n operationType\r\n };\r\n }\r\n static _fromErrorAndOperation(auth, error, operationType, user) {\r\n return new MultiFactorError(auth, error, operationType, user);\r\n }\r\n}\r\nfunction _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {\r\n const idTokenProvider = operationType === \"reauthenticate\" /* OperationType.REAUTHENTICATE */\r\n ? credential._getReauthenticationResolver(auth)\r\n : credential._getIdTokenResponse(auth);\r\n return idTokenProvider.catch(error => {\r\n if (error.code === `auth/${\"multi-factor-auth-required\" /* AuthErrorCode.MFA_REQUIRED */}`) {\r\n throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);\r\n }\r\n throw error;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Takes a set of UserInfo provider data and converts it to a set of names\r\n */\r\nfunction providerDataAsNames(providerData) {\r\n return new Set(providerData\r\n .map(({ providerId }) => providerId)\r\n .filter(pid => !!pid));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Unlinks a provider from a user account.\r\n *\r\n * @param user - The user.\r\n * @param providerId - The provider to unlink.\r\n *\r\n * @public\r\n */\r\nasync function unlink(user, providerId) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(true, userInternal, providerId);\r\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\r\n idToken: await userInternal.getIdToken(),\r\n deleteProvider: [providerId]\r\n });\r\n const providersLeft = providerDataAsNames(providerUserInfo || []);\r\n userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));\r\n if (!providersLeft.has(\"phone\" /* ProviderId.PHONE */)) {\r\n userInternal.phoneNumber = null;\r\n }\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n return userInternal;\r\n}\r\nasync function _link$1(user, credential, bypassAuthState = false) {\r\n const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);\r\n return UserCredentialImpl._forOperation(user, \"link\" /* OperationType.LINK */, response);\r\n}\r\nasync function _assertLinkedStatus(expected, user, provider) {\r\n await _reloadWithoutSaving(user);\r\n const providerIds = providerDataAsNames(user.providerData);\r\n const code = expected === false\r\n ? \"provider-already-linked\" /* AuthErrorCode.PROVIDER_ALREADY_LINKED */\r\n : \"no-such-provider\" /* AuthErrorCode.NO_SUCH_PROVIDER */;\r\n _assert(providerIds.has(provider) === expected, user.auth, code);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reauthenticate(user, credential, bypassAuthState = false) {\r\n const { auth } = user;\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const operationType = \"reauthenticate\" /* OperationType.REAUTHENTICATE */;\r\n try {\r\n const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);\r\n _assert(response.idToken, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const parsed = _parseToken(response.idToken);\r\n _assert(parsed, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const { sub: localId } = parsed;\r\n _assert(user.uid === localId, auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n return UserCredentialImpl._forOperation(user, operationType, response);\r\n }\r\n catch (e) {\r\n // Convert user deleted error into user mismatch\r\n if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${\"user-not-found\" /* AuthErrorCode.USER_DELETED */}`) {\r\n _fail(auth, \"user-mismatch\" /* AuthErrorCode.USER_MISMATCH */);\r\n }\r\n throw e;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _signInWithCredential(auth, credential, bypassAuthState = false) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const operationType = \"signIn\" /* OperationType.SIGN_IN */;\r\n const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);\r\n if (!bypassAuthState) {\r\n await auth._updateCurrentUser(userCredential.user);\r\n }\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCredential(auth, credential) {\r\n return _signInWithCredential(_castAuth(auth), credential);\r\n}\r\n/**\r\n * Links the user account with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function linkWithCredential(user, credential) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, credential.providerId);\r\n return _link$1(userInternal, credential);\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\r\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error\r\n * or a `TOKEN_EXPIRED` error.\r\n *\r\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithCredential(user, credential) {\r\n return _reauthenticate(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithCustomToken$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:signInWithCustomToken\" /* Endpoint.SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in using a custom token.\r\n *\r\n * @remarks\r\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\r\n * be generated by an auth backend using the\r\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\r\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\r\n *\r\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param customToken - The custom token to sign in with.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCustomToken(auth, customToken) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const response = await signInWithCustomToken$1(authInternal, {\r\n token: customToken,\r\n returnSecureToken: true\r\n });\r\n const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(cred.user);\r\n return cred;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorInfoImpl {\r\n constructor(factorId, response) {\r\n this.factorId = factorId;\r\n this.uid = response.mfaEnrollmentId;\r\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\r\n this.displayName = response.displayName;\r\n }\r\n static _fromServerResponse(auth, enrollment) {\r\n if ('phoneInfo' in enrollment) {\r\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n else if ('totpInfo' in enrollment) {\r\n return TotpMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n return _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n}\r\nclass PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"phone\" /* FactorId.PHONE */, response);\r\n this.phoneNumber = response.phoneInfo;\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new PhoneMultiFactorInfoImpl(enrollment);\r\n }\r\n}\r\nclass TotpMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"totp\" /* FactorId.TOTP */, response);\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new TotpMultiFactorInfoImpl(enrollment);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {\r\n var _a;\r\n _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, \"invalid-continue-uri\" /* AuthErrorCode.INVALID_CONTINUE_URI */);\r\n _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\r\n actionCodeSettings.dynamicLinkDomain.length > 0, auth, \"invalid-dynamic-link-domain\" /* AuthErrorCode.INVALID_DYNAMIC_LINK_DOMAIN */);\r\n request.continueUrl = actionCodeSettings.url;\r\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\r\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\r\n if (actionCodeSettings.iOS) {\r\n _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, \"missing-ios-bundle-id\" /* AuthErrorCode.MISSING_IOS_BUNDLE_ID */);\r\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\r\n }\r\n if (actionCodeSettings.android) {\r\n _assert(actionCodeSettings.android.packageName.length > 0, auth, \"missing-android-pkg-name\" /* AuthErrorCode.MISSING_ANDROID_PACKAGE_NAME */);\r\n request.androidInstallApp = actionCodeSettings.android.installApp;\r\n request.androidMinimumVersionCode =\r\n actionCodeSettings.android.minimumVersion;\r\n request.androidPackageName = actionCodeSettings.android.packageName;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates the password policy cached in the {@link Auth} instance if a policy is already\r\n * cached for the project or tenant.\r\n *\r\n * @remarks\r\n * We only fetch the password policy if the password did not meet policy requirements and\r\n * there is an existing policy cached. A developer must call validatePassword at least\r\n * once for the cache to be automatically updated.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @private\r\n */\r\nasync function recachePasswordPolicy(auth) {\r\n const authInternal = _castAuth(auth);\r\n if (authInternal._getPasswordPolicyInternal()) {\r\n await authInternal._updatePasswordPolicy();\r\n }\r\n}\r\n/**\r\n * Sends a password reset email to the given email address. This method does not throw an error when\r\n * there's no user account with the given email address and\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled.\r\n *\r\n * @remarks\r\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\r\n * the email sent to the user, along with the new password specified by the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain code from user.\r\n * await confirmPasswordReset('user@example.com', code);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendPasswordResetEmail(auth, email, actionCodeSettings) {\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"PASSWORD_RESET\" /* ActionCodeOperation.PASSWORD_RESET */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendPasswordResetEmail$1);\r\n}\r\n/**\r\n * Completes the password reset process, given a confirmation code and new password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A confirmation code sent to the user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nasync function confirmPasswordReset(auth, oobCode, newPassword) {\r\n await resetPassword(getModularInstance(auth), {\r\n oobCode,\r\n newPassword\r\n })\r\n .catch(async (error) => {\r\n if (error.code ===\r\n `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\r\n });\r\n // Do not return the email.\r\n}\r\n/**\r\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function applyActionCode(auth, oobCode) {\r\n await applyActionCode$1(getModularInstance(auth), { oobCode });\r\n}\r\n/**\r\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns metadata about the code.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function checkActionCode(auth, oobCode) {\r\n const authModular = getModularInstance(auth);\r\n const response = await resetPassword(authModular, { oobCode });\r\n // Email could be empty only if the request type is EMAIL_SIGNIN or\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // New email should not be empty if the request type is\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // Multi-factor info could not be empty if the request type is\r\n // REVERT_SECOND_FACTOR_ADDITION.\r\n const operation = response.requestType;\r\n _assert(operation, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n switch (operation) {\r\n case \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */:\r\n break;\r\n case \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */:\r\n _assert(response.newEmail, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n break;\r\n case \"REVERT_SECOND_FACTOR_ADDITION\" /* ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION */:\r\n _assert(response.mfaInfo, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n // fall through\r\n default:\r\n _assert(response.email, authModular, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n // The multi-factor info for revert second factor addition\r\n let multiFactorInfo = null;\r\n if (response.mfaInfo) {\r\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);\r\n }\r\n return {\r\n data: {\r\n email: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.newEmail\r\n : response.email) || null,\r\n previousEmail: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */\r\n ? response.email\r\n : response.newEmail) || null,\r\n multiFactorInfo\r\n },\r\n operation\r\n };\r\n}\r\n/**\r\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns the user's email address if valid.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param code - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function verifyPasswordResetCode(auth, code) {\r\n const { data } = await checkActionCode(getModularInstance(auth), code);\r\n // Email should always be present since a code was sent to it\r\n return data.email;\r\n}\r\n/**\r\n * Creates a new user account associated with the specified email address and password.\r\n *\r\n * @remarks\r\n * On successful creation of the user account, this user will also be signed in to your application.\r\n *\r\n * User account creation can fail if the account already exists or the password is invalid.\r\n *\r\n * This method is not supported on {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Note: The email address acts as a unique identifier for the user and enables an email-based\r\n * password reset. This function will create a new user account and set the initial user password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param password - The user's chosen password.\r\n *\r\n * @public\r\n */\r\nasync function createUserWithEmailAndPassword(auth, email, password) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n returnSecureToken: true,\r\n email,\r\n password,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n const signUpResponse = handleRecaptchaFlow(authInternal, request, \"signUpPassword\" /* RecaptchaActionName.SIGN_UP_PASSWORD */, signUp);\r\n const response = await signUpResponse.catch(error => {\r\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* OperationType.SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and password.\r\n *\r\n * @remarks\r\n * Fails with an error if the email address and password do not match. When\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled, this method fails with \"auth/invalid-credential\" in case of an invalid\r\n * email/password.\r\n *\r\n * This method is not supported on {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Note: The user's password is NOT the password used to access the user's email account. The\r\n * email address serves as a unique identifier for the user, and the password is used to access\r\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\r\n *\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The users email address.\r\n * @param password - The users password.\r\n *\r\n * @public\r\n */\r\nfunction signInWithEmailAndPassword(auth, email, password) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password)).catch(async (error) => {\r\n if (error.code === `auth/${\"password-does-not-meet-requirements\" /* AuthErrorCode.PASSWORD_DOES_NOT_MEET_REQUIREMENTS */}`) {\r\n void recachePasswordPolicy(auth);\r\n }\r\n throw error;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a sign-in email link to the user with the specified email.\r\n *\r\n * @remarks\r\n * The sign-in operation has to always be completed in the app unlike other out of band email\r\n * actions (password reset and email verifications). This is because, at the end of the flow,\r\n * the user is expected to be signed in and their Auth state persisted within the app.\r\n *\r\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\r\n * address and the email link supplied in the email sent to the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param authInternal - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendSignInLinkToEmail(auth, email, actionCodeSettings) {\r\n const authInternal = _castAuth(auth);\r\n const request = {\r\n requestType: \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */,\r\n email,\r\n clientType: \"CLIENT_TYPE_WEB\" /* RecaptchaClientType.WEB */\r\n };\r\n function setActionCodeSettings(request, actionCodeSettings) {\r\n _assert(actionCodeSettings.handleCodeInApp, authInternal, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authInternal, request, actionCodeSettings);\r\n }\r\n }\r\n setActionCodeSettings(request, actionCodeSettings);\r\n await handleRecaptchaFlow(authInternal, request, \"getOobCode\" /* RecaptchaActionName.GET_OOB_CODE */, sendSignInLinkToEmail$1);\r\n}\r\n/**\r\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nfunction isSignInWithEmailLink(auth, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === \"EMAIL_SIGNIN\" /* ActionCodeOperation.EMAIL_SIGNIN */;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and sign-in email link.\r\n *\r\n * @remarks\r\n * If no link is passed, the link is inferred from the current URL.\r\n *\r\n * Fails with an error if the email address is invalid or OTP in email link expires.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nasync function signInWithEmailLink(auth, email, emailLink) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authModular = getModularInstance(auth);\r\n const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());\r\n // Check if the tenant ID in the email link matches the tenant ID on Auth\r\n // instance.\r\n _assert(credential._tenantId === (authModular.tenantId || null), authModular, \"tenant-id-mismatch\" /* AuthErrorCode.TENANT_ID_MISMATCH */);\r\n return signInWithCredential(authModular, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createAuthUri(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:createAuthUri\" /* Endpoint.CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Gets the list of possible sign in methods for the given email address. This method returns an\r\n * empty list when\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled, irrespective of the number of authentication methods available for the given email.\r\n *\r\n * @remarks\r\n * This is useful to differentiate methods of sign-in for the same provider, eg.\r\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\r\n * {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n *\r\n * Deprecated. Migrating off of this method is recommended as a security best-practice.\r\n * Learn more in the Identity Platform documentation for\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}.\r\n * @public\r\n */\r\nasync function fetchSignInMethodsForEmail(auth, email) {\r\n // createAuthUri returns an error if continue URI is not http or https.\r\n // For environments like Cordova, Chrome extensions, native frameworks, file\r\n // systems, etc, use http://localhost as continue URL.\r\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\r\n const request = {\r\n identifier: email,\r\n continueUri\r\n };\r\n const { signinMethods } = await createAuthUri(getModularInstance(auth), request);\r\n return signinMethods || [];\r\n}\r\n/**\r\n * Sends a verification email to a user.\r\n *\r\n * @remarks\r\n * The verification process is completed by calling {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendEmailVerification(user, actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendEmailVerification(user, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_EMAIL\" /* ActionCodeOperation.VERIFY_EMAIL */,\r\n idToken\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await sendEmailVerification$1(userInternal.auth, request);\r\n if (email !== user.email) {\r\n await user.reload();\r\n }\r\n}\r\n/**\r\n * Sends a verification email to a new email address.\r\n *\r\n * @remarks\r\n * The user's email will be updated to the new one after being verified.\r\n *\r\n * If you have a custom email action handler, you can complete the verification process by calling\r\n * {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address to be verified before update.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_AND_CHANGE_EMAIL\" /* ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL */,\r\n idToken,\r\n newEmail\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await verifyAndChangeEmail(userInternal.auth, request);\r\n if (email !== user.email) {\r\n // If the local copy of the email on user is outdated, reload the\r\n // user.\r\n await user.reload();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateProfile$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v1/accounts:update\" /* Endpoint.SET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates a user's profile data.\r\n *\r\n * @param user - The user.\r\n * @param profile - The profile's `displayName` and `photoURL` to update.\r\n *\r\n * @public\r\n */\r\nasync function updateProfile(user, { displayName, photoURL: photoUrl }) {\r\n if (displayName === undefined && photoUrl === undefined) {\r\n return;\r\n }\r\n const userInternal = getModularInstance(user);\r\n const idToken = await userInternal.getIdToken();\r\n const profileRequest = {\r\n idToken,\r\n displayName,\r\n photoUrl,\r\n returnSecureToken: true\r\n };\r\n const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));\r\n userInternal.displayName = response.displayName || null;\r\n userInternal.photoURL = response.photoUrl || null;\r\n // Update the password provider as well\r\n const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === \"password\" /* ProviderId.PASSWORD */);\r\n if (passwordProvider) {\r\n passwordProvider.displayName = userInternal.displayName;\r\n passwordProvider.photoURL = userInternal.photoURL;\r\n }\r\n await userInternal._updateTokensIfNecessary(response);\r\n}\r\n/**\r\n * Updates the user's email address.\r\n *\r\n * @remarks\r\n * An email will be sent to the original email address (if it was set) that allows to revoke the\r\n * email address change, in order to protect them from account hijacking.\r\n *\r\n * This method is not supported on any {@link User} signed in by {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address.\r\n *\r\n * Throws \"auth/operation-not-allowed\" error when\r\n * {@link https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection | Email Enumeration Protection}\r\n * is enabled.\r\n * Deprecated - Use {@link verifyBeforeUpdateEmail} instead.\r\n *\r\n * @public\r\n */\r\nfunction updateEmail(user, newEmail) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n return updateEmailOrPassword(userInternal, newEmail, null);\r\n}\r\n/**\r\n * Updates the user's password.\r\n *\r\n * @remarks\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nfunction updatePassword(user, newPassword) {\r\n return updateEmailOrPassword(getModularInstance(user), null, newPassword);\r\n}\r\nasync function updateEmailOrPassword(user, email, password) {\r\n const { auth } = user;\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n idToken,\r\n returnSecureToken: true\r\n };\r\n if (email) {\r\n request.email = email;\r\n }\r\n if (password) {\r\n request.password = password;\r\n }\r\n const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Parse the `AdditionalUserInfo` from the ID token response.\r\n *\r\n */\r\nfunction _fromIdTokenResponse(idTokenResponse) {\r\n var _a, _b;\r\n if (!idTokenResponse) {\r\n return null;\r\n }\r\n const { providerId } = idTokenResponse;\r\n const profile = idTokenResponse.rawUserInfo\r\n ? JSON.parse(idTokenResponse.rawUserInfo)\r\n : {};\r\n const isNewUser = idTokenResponse.isNewUser ||\r\n idTokenResponse.kind === \"identitytoolkit#SignupNewUserResponse\" /* IdTokenResponseKind.SignupNewUser */;\r\n if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {\r\n const signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];\r\n if (signInProvider) {\r\n const filteredProviderId = signInProvider !== \"anonymous\" /* ProviderId.ANONYMOUS */ &&\r\n signInProvider !== \"custom\" /* ProviderId.CUSTOM */\r\n ? signInProvider\r\n : null;\r\n // Uses generic class in accordance with the legacy SDK.\r\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\r\n }\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n switch (providerId) {\r\n case \"facebook.com\" /* ProviderId.FACEBOOK */:\r\n return new FacebookAdditionalUserInfo(isNewUser, profile);\r\n case \"github.com\" /* ProviderId.GITHUB */:\r\n return new GithubAdditionalUserInfo(isNewUser, profile);\r\n case \"google.com\" /* ProviderId.GOOGLE */:\r\n return new GoogleAdditionalUserInfo(isNewUser, profile);\r\n case \"twitter.com\" /* ProviderId.TWITTER */:\r\n return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);\r\n case \"custom\" /* ProviderId.CUSTOM */:\r\n case \"anonymous\" /* ProviderId.ANONYMOUS */:\r\n return new GenericAdditionalUserInfo(isNewUser, null);\r\n default:\r\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\r\n }\r\n}\r\nclass GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile = {}) {\r\n this.isNewUser = isNewUser;\r\n this.providerId = providerId;\r\n this.profile = profile;\r\n }\r\n}\r\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile, username) {\r\n super(isNewUser, providerId, profile);\r\n this.username = username;\r\n }\r\n}\r\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"facebook.com\" /* ProviderId.FACEBOOK */, profile);\r\n }\r\n}\r\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"github.com\" /* ProviderId.GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null);\r\n }\r\n}\r\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"google.com\" /* ProviderId.GOOGLE */, profile);\r\n }\r\n}\r\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile, screenName) {\r\n super(isNewUser, \"twitter.com\" /* ProviderId.TWITTER */, profile, screenName);\r\n }\r\n}\r\n/**\r\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\r\n *\r\n * @param userCredential - The user credential.\r\n *\r\n * @public\r\n */\r\nfunction getAdditionalUserInfo(userCredential) {\r\n const { user, _tokenResponse } = userCredential;\r\n if (user.isAnonymous && !_tokenResponse) {\r\n // Handle the special case where signInAnonymously() gets called twice.\r\n // No network call is made so there's nothing to actually fill this in\r\n return {\r\n providerId: null,\r\n isNewUser: false,\r\n profile: null\r\n };\r\n }\r\n return _fromIdTokenResponse(_tokenResponse);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Non-optional auth methods.\r\n/**\r\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\r\n * `Auth` session and applies this type of persistence for future sign-in requests, including\r\n * sign-in with redirect requests.\r\n *\r\n * @remarks\r\n * This makes it easy for a user signing in to specify whether their session should be\r\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\r\n * that are shared by other users or have sensitive data.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * setPersistence(auth, browserSessionPersistence);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param persistence - The {@link Persistence} to use.\r\n * @returns A `Promise` that resolves once the persistence change has completed\r\n *\r\n * @public\r\n */\r\nfunction setPersistence(auth, persistence) {\r\n return getModularInstance(auth).setPersistence(persistence);\r\n}\r\n/**\r\n * Loads the reCAPTCHA configuration into the `Auth` instance.\r\n *\r\n * @remarks\r\n * This will load the reCAPTCHA config, which indicates whether the reCAPTCHA\r\n * verification flow should be triggered for each auth provider, into the\r\n * current Auth session.\r\n *\r\n * If initializeRecaptchaConfig() is not invoked, the auth flow will always start\r\n * without reCAPTCHA verification. If the provider is configured to require reCAPTCHA\r\n * verification, the SDK will transparently load the reCAPTCHA config and restart the\r\n * auth flows.\r\n *\r\n * Thus, by calling this optional method, you will reduce the latency of future auth flows.\r\n * Loading the reCAPTCHA config early will also enhance the signal collected by reCAPTCHA.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * initializeRecaptchaConfig(auth);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction initializeRecaptchaConfig(auth) {\r\n return _initializeRecaptchaConfig(auth);\r\n}\r\n/**\r\n * Validates the password against the password policy configured for the project or tenant.\r\n *\r\n * @remarks\r\n * If no tenant ID is set on the `Auth` instance, then this method will use the password\r\n * policy configured for the project. Otherwise, this method will use the policy configured\r\n * for the tenant. If a password policy has not been configured, then the default policy\r\n * configured for all projects will be used.\r\n *\r\n * If an auth flow fails because a submitted password does not meet the password policy\r\n * requirements and this method has previously been called, then this method will use the\r\n * most recent policy available when called again.\r\n *\r\n * @example\r\n * ```javascript\r\n * validatePassword(auth, 'some-password');\r\n * ```\r\n *\r\n * @param auth The {@link Auth} instance.\r\n * @param password The password to validate.\r\n *\r\n * @public\r\n */\r\nasync function validatePassword(auth, password) {\r\n const authInternal = _castAuth(auth);\r\n return authInternal.validatePassword(password);\r\n}\r\n/**\r\n * Adds an observer for changes to the signed-in user's ID token.\r\n *\r\n * @remarks\r\n * This includes sign-in, sign-out, and token refresh events.\r\n * This will not be triggered automatically upon ID token expiration. Use {@link User.getIdToken} to refresh the ID token.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onIdTokenChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Adds a blocking callback that runs before an auth state change\r\n * sets a new user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param callback - callback triggered before new user value is set.\r\n * If this throws, it blocks the user from being set.\r\n * @param onAbort - callback triggered if a later `beforeAuthStateChanged()`\r\n * callback throws, allowing you to undo any side effects.\r\n */\r\nfunction beforeAuthStateChanged(auth, callback, onAbort) {\r\n return getModularInstance(auth).beforeAuthStateChanged(callback, onAbort);\r\n}\r\n/**\r\n * Adds an observer for changes to the user's sign-in state.\r\n *\r\n * @remarks\r\n * To keep the old behavior, see {@link onIdTokenChanged}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - Deprecated. This callback is never triggered. Errors\r\n * on signing in/out can be caught in promises returned from\r\n * sign-in/sign-out functions.\r\n * @param completed - Deprecated. This callback is never triggered.\r\n *\r\n * @public\r\n */\r\nfunction onAuthStateChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Sets the current language to the default device/browser preference.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction useDeviceLanguage(auth) {\r\n getModularInstance(auth).useDeviceLanguage();\r\n}\r\n/**\r\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\r\n * {@link Auth} instance.\r\n *\r\n * @remarks\r\n * A new instance copy of the user provided will be made and set as currentUser.\r\n *\r\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\r\n * like other sign in methods.\r\n *\r\n * The operation fails with an error if the user to be updated belongs to a different Firebase\r\n * project.\r\n *\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param user - The new {@link User}.\r\n *\r\n * @public\r\n */\r\nfunction updateCurrentUser(auth, user) {\r\n return getModularInstance(auth).updateCurrentUser(user);\r\n}\r\n/**\r\n * Signs out the current user.\r\n *\r\n * @remarks\r\n * This method is not supported by {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction signOut(auth) {\r\n return getModularInstance(auth).signOut();\r\n}\r\n/**\r\n * Revokes the given access token. Currently only supports Apple OAuth access tokens.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param token - The Apple OAuth access token.\r\n *\r\n * @public\r\n */\r\nfunction revokeAccessToken(auth, token) {\r\n const authInternal = _castAuth(auth);\r\n return authInternal.revokeAccessToken(token);\r\n}\r\n/**\r\n * Deletes and signs out the user.\r\n *\r\n * @remarks\r\n * Important: this is a security-sensitive operation that requires the user to have recently\r\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function deleteUser(user) {\r\n return getModularInstance(user).delete();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorSessionImpl {\r\n constructor(type, credential, user) {\r\n this.type = type;\r\n this.credential = credential;\r\n this.user = user;\r\n }\r\n static _fromIdtoken(idToken, user) {\r\n return new MultiFactorSessionImpl(\"enroll\" /* MultiFactorSessionType.ENROLL */, idToken, user);\r\n }\r\n static _fromMfaPendingCredential(mfaPendingCredential) {\r\n return new MultiFactorSessionImpl(\"signin\" /* MultiFactorSessionType.SIGN_IN */, mfaPendingCredential);\r\n }\r\n toJSON() {\r\n const key = this.type === \"enroll\" /* MultiFactorSessionType.ENROLL */\r\n ? 'idToken'\r\n : 'pendingCredential';\r\n return {\r\n multiFactorSession: {\r\n [key]: this.credential\r\n }\r\n };\r\n }\r\n static fromJSON(obj) {\r\n var _a, _b;\r\n if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {\r\n if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {\r\n return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);\r\n }\r\n else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {\r\n return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);\r\n }\r\n }\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorResolverImpl {\r\n constructor(session, hints, signInResolver) {\r\n this.session = session;\r\n this.hints = hints;\r\n this.signInResolver = signInResolver;\r\n }\r\n /** @internal */\r\n static _fromError(authExtern, error) {\r\n const auth = _castAuth(authExtern);\r\n const serverResponse = error.customData._serverResponse;\r\n const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));\r\n _assert(serverResponse.mfaPendingCredential, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);\r\n return new MultiFactorResolverImpl(session, hints, async (assertion) => {\r\n const mfaResponse = await assertion._process(auth, session);\r\n // Clear out the unneeded fields from the old login response\r\n delete serverResponse.mfaInfo;\r\n delete serverResponse.mfaPendingCredential;\r\n // Use in the new token & refresh token in the old response\r\n const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });\r\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\r\n switch (error.operationType) {\r\n case \"signIn\" /* OperationType.SIGN_IN */:\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);\r\n await auth._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n case \"reauthenticate\" /* OperationType.REAUTHENTICATE */:\r\n _assert(error.user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);\r\n default:\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n });\r\n }\r\n async resolveSignIn(assertionExtern) {\r\n const assertion = assertionExtern;\r\n return this.signInResolver(assertion);\r\n }\r\n}\r\n/**\r\n * Provides a {@link MultiFactorResolver} suitable for completion of a\r\n * multi-factor flow.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\r\n * reauthentication operation.\r\n *\r\n * @public\r\n */\r\nfunction getMultiFactorResolver(auth, error) {\r\n var _a;\r\n const authModular = getModularInstance(auth);\r\n const errorInternal = error;\r\n _assert(error.customData.operationType, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction startEnrollTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:start\" /* Endpoint.START_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* Endpoint.FINALIZE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction withdrawMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaEnrollment:withdraw\" /* Endpoint.WITHDRAW_MFA */, _addTidIfNecessary(auth, request));\r\n}\n\nclass MultiFactorUserImpl {\r\n constructor(user) {\r\n this.user = user;\r\n this.enrolledFactors = [];\r\n user._onReload(userInfo => {\r\n if (userInfo.mfaInfo) {\r\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));\r\n }\r\n });\r\n }\r\n static _fromUser(user) {\r\n return new MultiFactorUserImpl(user);\r\n }\r\n async getSession() {\r\n return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(), this.user);\r\n }\r\n async enroll(assertionExtern, displayName) {\r\n const assertion = assertionExtern;\r\n const session = (await this.getSession());\r\n const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));\r\n // New tokens will be issued after enrollment of the new second factors.\r\n // They need to be updated on the user.\r\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\r\n // The user needs to be reloaded to get the new multi-factor information\r\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\r\n // will be updated.\r\n return this.user.reload();\r\n }\r\n async unenroll(infoOrUid) {\r\n const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\r\n const idToken = await this.user.getIdToken();\r\n try {\r\n const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {\r\n idToken,\r\n mfaEnrollmentId\r\n }));\r\n // Remove the second factor from the user's list.\r\n this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);\r\n // Depending on whether the backend decided to revoke the user's session,\r\n // the tokenResponse may be empty. If the tokens were not updated (and they\r\n // are now invalid), reloading the user will discover this and invalidate\r\n // the user's state accordingly.\r\n await this.user._updateTokensIfNecessary(idTokenResponse);\r\n await this.user.reload();\r\n }\r\n catch (e) {\r\n throw e;\r\n }\r\n }\r\n}\r\nconst multiFactorUserCache = new WeakMap();\r\n/**\r\n * The {@link MultiFactorUser} corresponding to the user.\r\n *\r\n * @remarks\r\n * This is used to access all multi-factor properties and operations related to the user.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nfunction multiFactor(user) {\r\n const userModular = getModularInstance(user);\r\n if (!multiFactorUserCache.has(userModular)) {\r\n multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));\r\n }\r\n return multiFactorUserCache.get(userModular);\r\n}\n\nconst STORAGE_AVAILABLE_KEY = '__sak';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// There are two different browser persistence types: local and session.\r\n// Both have the same implementation but use a different underlying storage\r\n// object.\r\nclass BrowserPersistenceClass {\r\n constructor(storageRetriever, type) {\r\n this.storageRetriever = storageRetriever;\r\n this.type = type;\r\n }\r\n _isAvailable() {\r\n try {\r\n if (!this.storage) {\r\n return Promise.resolve(false);\r\n }\r\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\r\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\r\n return Promise.resolve(true);\r\n }\r\n catch (_a) {\r\n return Promise.resolve(false);\r\n }\r\n }\r\n _set(key, value) {\r\n this.storage.setItem(key, JSON.stringify(value));\r\n return Promise.resolve();\r\n }\r\n _get(key) {\r\n const json = this.storage.getItem(key);\r\n return Promise.resolve(json ? JSON.parse(json) : null);\r\n }\r\n _remove(key) {\r\n this.storage.removeItem(key);\r\n return Promise.resolve();\r\n }\r\n get storage() {\r\n return this.storageRetriever();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _iframeCannotSyncWebStorage() {\r\n const ua = getUA();\r\n return _isSafari(ua) || _isIOS(ua);\r\n}\r\n// The polling period in case events are not supported\r\nconst _POLLING_INTERVAL_MS$1 = 1000;\r\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\r\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\r\nclass BrowserLocalPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.localStorage, \"LOCAL\" /* PersistenceType.LOCAL */);\r\n this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n // Safari or iOS browser and embedded in an iframe.\r\n this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();\r\n // Whether to use polling instead of depending on window events\r\n this.fallbackToPolling = _isMobileBrowser();\r\n this._shouldAllowMigration = true;\r\n }\r\n forAllChangedKeys(cb) {\r\n // Check all keys with listeners on them.\r\n for (const key of Object.keys(this.listeners)) {\r\n // Get value from localStorage.\r\n const newValue = this.storage.getItem(key);\r\n const oldValue = this.localCache[key];\r\n // If local map value does not match, trigger listener with storage event.\r\n // Differentiate this simulated event from the real storage event.\r\n if (newValue !== oldValue) {\r\n cb(key, oldValue, newValue);\r\n }\r\n }\r\n }\r\n onStorageEvent(event, poll = false) {\r\n // Key would be null in some situations, like when localStorage is cleared\r\n if (!event.key) {\r\n this.forAllChangedKeys((key, _oldValue, newValue) => {\r\n this.notifyListeners(key, newValue);\r\n });\r\n return;\r\n }\r\n const key = event.key;\r\n // Check the mechanism how this event was detected.\r\n // The first event will dictate the mechanism to be used.\r\n if (poll) {\r\n // Environment detects storage changes via polling.\r\n // Remove storage event listener to prevent possible event duplication.\r\n this.detachListener();\r\n }\r\n else {\r\n // Environment detects storage changes via storage event listener.\r\n // Remove polling listener to prevent possible event duplication.\r\n this.stopPolling();\r\n }\r\n // Safari embedded iframe. Storage event will trigger with the delta\r\n // changes but no changes will be applied to the iframe localStorage.\r\n if (this.safariLocalStorageNotSynced) {\r\n // Get current iframe page value.\r\n const storedValue = this.storage.getItem(key);\r\n // Value not synchronized, synchronize manually.\r\n if (event.newValue !== storedValue) {\r\n if (event.newValue !== null) {\r\n // Value changed from current value.\r\n this.storage.setItem(key, event.newValue);\r\n }\r\n else {\r\n // Current value deleted.\r\n this.storage.removeItem(key);\r\n }\r\n }\r\n else if (this.localCache[key] === event.newValue && !poll) {\r\n // Already detected and processed, do not trigger listeners again.\r\n return;\r\n }\r\n }\r\n const triggerListeners = () => {\r\n // Keep local map up to date in case storage event is triggered before\r\n // poll.\r\n const storedValue = this.storage.getItem(key);\r\n if (!poll && this.localCache[key] === storedValue) {\r\n // Real storage event which has already been detected, do nothing.\r\n // This seems to trigger in some IE browsers for some reason.\r\n return;\r\n }\r\n this.notifyListeners(key, storedValue);\r\n };\r\n const storedValue = this.storage.getItem(key);\r\n if (_isIE10() &&\r\n storedValue !== event.newValue &&\r\n event.newValue !== event.oldValue) {\r\n // IE 10 has this weird bug where a storage event would trigger with the\r\n // correct key, oldValue and newValue but localStorage.getItem(key) does\r\n // not yield the updated value until a few milliseconds. This ensures\r\n // this recovers from that situation.\r\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\r\n }\r\n else {\r\n triggerListeners();\r\n }\r\n }\r\n notifyListeners(key, value) {\r\n this.localCache[key] = value;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(value ? JSON.parse(value) : value);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(() => {\r\n this.forAllChangedKeys((key, oldValue, newValue) => {\r\n this.onStorageEvent(new StorageEvent('storage', {\r\n key,\r\n oldValue,\r\n newValue\r\n }), \r\n /* poll */ true);\r\n });\r\n }, _POLLING_INTERVAL_MS$1);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n attachListener() {\r\n window.addEventListener('storage', this.boundEventHandler);\r\n }\r\n detachListener() {\r\n window.removeEventListener('storage', this.boundEventHandler);\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n // Whether browser can detect storage event when it had already been pushed to the background.\r\n // This may happen in some mobile browsers. A localStorage change in the foreground window\r\n // will not be detected in the background window via the storage event.\r\n // This was detected in iOS 7.x mobile browsers\r\n if (this.fallbackToPolling) {\r\n this.startPolling();\r\n }\r\n else {\r\n this.attachListener();\r\n }\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n this.localCache[key] = this.storage.getItem(key);\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.detachListener();\r\n this.stopPolling();\r\n }\r\n }\r\n // Update local cache on base operations:\r\n async _set(key, value) {\r\n await super._set(key, value);\r\n this.localCache[key] = JSON.stringify(value);\r\n }\r\n async _get(key) {\r\n const value = await super._get(key);\r\n this.localCache[key] = JSON.stringify(value);\r\n return value;\r\n }\r\n async _remove(key) {\r\n await super._remove(key);\r\n delete this.localCache[key];\r\n }\r\n}\r\nBrowserLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserLocalPersistence = BrowserLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass BrowserSessionPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.sessionStorage, \"SESSION\" /* PersistenceType.SESSION */);\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n}\r\nBrowserSessionPersistence.type = 'SESSION';\r\n/**\r\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserSessionPersistence = BrowserSessionPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\r\n *\r\n * @param promises - Array of promises to wait on.\r\n */\r\nfunction _allSettled(promises) {\r\n return Promise.all(promises.map(async (promise) => {\r\n try {\r\n const value = await promise;\r\n return {\r\n fulfilled: true,\r\n value\r\n };\r\n }\r\n catch (reason) {\r\n return {\r\n fulfilled: false,\r\n reason\r\n };\r\n }\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface class for receiving messages.\r\n *\r\n */\r\nclass Receiver {\r\n constructor(eventTarget) {\r\n this.eventTarget = eventTarget;\r\n this.handlersMap = {};\r\n this.boundEventHandler = this.handleEvent.bind(this);\r\n }\r\n /**\r\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\r\n *\r\n * @param eventTarget - An event target (such as window or self) through which the underlying\r\n * messages will be received.\r\n */\r\n static _getInstance(eventTarget) {\r\n // The results are stored in an array since objects can't be keys for other\r\n // objects. In addition, setting a unique property on an event target as a\r\n // hash map key may not be allowed due to CORS restrictions.\r\n const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));\r\n if (existingInstance) {\r\n return existingInstance;\r\n }\r\n const newInstance = new Receiver(eventTarget);\r\n this.receivers.push(newInstance);\r\n return newInstance;\r\n }\r\n isListeningto(eventTarget) {\r\n return this.eventTarget === eventTarget;\r\n }\r\n /**\r\n * Fans out a MessageEvent to the appropriate listeners.\r\n *\r\n * @remarks\r\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\r\n * finished processing.\r\n *\r\n * @param event - The MessageEvent.\r\n *\r\n */\r\n async handleEvent(event) {\r\n const messageEvent = event;\r\n const { eventId, eventType, data } = messageEvent.data;\r\n const handlers = this.handlersMap[eventType];\r\n if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {\r\n return;\r\n }\r\n messageEvent.ports[0].postMessage({\r\n status: \"ack\" /* _Status.ACK */,\r\n eventId,\r\n eventType\r\n });\r\n const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));\r\n const response = await _allSettled(promises);\r\n messageEvent.ports[0].postMessage({\r\n status: \"done\" /* _Status.DONE */,\r\n eventId,\r\n eventType,\r\n response\r\n });\r\n }\r\n /**\r\n * Subscribe an event handler for a particular event.\r\n *\r\n * @param eventType - Event name to subscribe to.\r\n * @param eventHandler - The event handler which should receive the events.\r\n *\r\n */\r\n _subscribe(eventType, eventHandler) {\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.addEventListener('message', this.boundEventHandler);\r\n }\r\n if (!this.handlersMap[eventType]) {\r\n this.handlersMap[eventType] = new Set();\r\n }\r\n this.handlersMap[eventType].add(eventHandler);\r\n }\r\n /**\r\n * Unsubscribe an event handler from a particular event.\r\n *\r\n * @param eventType - Event name to unsubscribe from.\r\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\r\n *\r\n */\r\n _unsubscribe(eventType, eventHandler) {\r\n if (this.handlersMap[eventType] && eventHandler) {\r\n this.handlersMap[eventType].delete(eventHandler);\r\n }\r\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\r\n delete this.handlersMap[eventType];\r\n }\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\r\n }\r\n }\r\n}\r\nReceiver.receivers = [];\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _generateEventId(prefix = '', digits = 10) {\r\n let random = '';\r\n for (let i = 0; i < digits; i++) {\r\n random += Math.floor(Math.random() * 10);\r\n }\r\n return prefix + random;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface for sending messages and waiting for a completion response.\r\n *\r\n */\r\nclass Sender {\r\n constructor(target) {\r\n this.target = target;\r\n this.handlers = new Set();\r\n }\r\n /**\r\n * Unsubscribe the handler and remove it from our tracking Set.\r\n *\r\n * @param handler - The handler to unsubscribe.\r\n */\r\n removeMessageHandler(handler) {\r\n if (handler.messageChannel) {\r\n handler.messageChannel.port1.removeEventListener('message', handler.onMessage);\r\n handler.messageChannel.port1.close();\r\n }\r\n this.handlers.delete(handler);\r\n }\r\n /**\r\n * Send a message to the Receiver located at {@link target}.\r\n *\r\n * @remarks\r\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\r\n * receiver has had a chance to fully process the event.\r\n *\r\n * @param eventType - Type of event to send.\r\n * @param data - The payload of the event.\r\n * @param timeout - Timeout for waiting on an ACK from the receiver.\r\n *\r\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\r\n */\r\n async _send(eventType, data, timeout = 50 /* _TimeoutDuration.ACK */) {\r\n const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\r\n if (!messageChannel) {\r\n throw new Error(\"connection_unavailable\" /* _MessageError.CONNECTION_UNAVAILABLE */);\r\n }\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n let completionTimer;\r\n let handler;\r\n return new Promise((resolve, reject) => {\r\n const eventId = _generateEventId('', 20);\r\n messageChannel.port1.start();\r\n const ackTimer = setTimeout(() => {\r\n reject(new Error(\"unsupported_event\" /* _MessageError.UNSUPPORTED_EVENT */));\r\n }, timeout);\r\n handler = {\r\n messageChannel,\r\n onMessage(event) {\r\n const messageEvent = event;\r\n if (messageEvent.data.eventId !== eventId) {\r\n return;\r\n }\r\n switch (messageEvent.data.status) {\r\n case \"ack\" /* _Status.ACK */:\r\n // The receiver should ACK first.\r\n clearTimeout(ackTimer);\r\n completionTimer = setTimeout(() => {\r\n reject(new Error(\"timeout\" /* _MessageError.TIMEOUT */));\r\n }, 3000 /* _TimeoutDuration.COMPLETION */);\r\n break;\r\n case \"done\" /* _Status.DONE */:\r\n // Once the receiver's handlers are finished we will get the results.\r\n clearTimeout(completionTimer);\r\n resolve(messageEvent.data.response);\r\n break;\r\n default:\r\n clearTimeout(ackTimer);\r\n clearTimeout(completionTimer);\r\n reject(new Error(\"invalid_response\" /* _MessageError.INVALID_RESPONSE */));\r\n break;\r\n }\r\n }\r\n };\r\n this.handlers.add(handler);\r\n messageChannel.port1.addEventListener('message', handler.onMessage);\r\n this.target.postMessage({\r\n eventType,\r\n eventId,\r\n data\r\n }, [messageChannel.port2]);\r\n }).finally(() => {\r\n if (handler) {\r\n this.removeMessageHandler(handler);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Lazy accessor for window, since the compat layer won't tree shake this out,\r\n * we need to make sure not to mess with window unless we have to\r\n */\r\nfunction _window() {\r\n return window;\r\n}\r\nfunction _setWindowLocation(url) {\r\n _window().location.href = url;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _isWorker() {\r\n return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\r\n typeof _window()['importScripts'] === 'function');\r\n}\r\nasync function _getActiveServiceWorker() {\r\n if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {\r\n return null;\r\n }\r\n try {\r\n const registration = await navigator.serviceWorker.ready;\r\n return registration.active;\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n}\r\nfunction _getServiceWorkerController() {\r\n var _a;\r\n return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;\r\n}\r\nfunction _getWorkerGlobalScope() {\r\n return _isWorker() ? self : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebaseLocalStorageDb';\r\nconst DB_VERSION = 1;\r\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\r\nconst DB_DATA_KEYPATH = 'fbase_key';\r\n/**\r\n * Promise wrapper for IDBRequest\r\n *\r\n * Unfortunately we can't cleanly extend Promise since promises are not callable in ES6\r\n *\r\n */\r\nclass DBPromise {\r\n constructor(request) {\r\n this.request = request;\r\n }\r\n toPromise() {\r\n return new Promise((resolve, reject) => {\r\n this.request.addEventListener('success', () => {\r\n resolve(this.request.result);\r\n });\r\n this.request.addEventListener('error', () => {\r\n reject(this.request.error);\r\n });\r\n });\r\n }\r\n}\r\nfunction getObjectStore(db, isReadWrite) {\r\n return db\r\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\r\n .objectStore(DB_OBJECTSTORE_NAME);\r\n}\r\nfunction _deleteDatabase() {\r\n const request = indexedDB.deleteDatabase(DB_NAME);\r\n return new DBPromise(request).toPromise();\r\n}\r\nfunction _openDatabase() {\r\n const request = indexedDB.open(DB_NAME, DB_VERSION);\r\n return new Promise((resolve, reject) => {\r\n request.addEventListener('error', () => {\r\n reject(request.error);\r\n });\r\n request.addEventListener('upgradeneeded', () => {\r\n const db = request.result;\r\n try {\r\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n });\r\n request.addEventListener('success', async () => {\r\n const db = request.result;\r\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\r\n // same time. The only way to recover seems to be deleting the database\r\n // and re-initializing it.\r\n // https://github.com/firebase/firebase-js-sdk/issues/634\r\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\r\n // Need to close the database or else you get a `blocked` event\r\n db.close();\r\n await _deleteDatabase();\r\n resolve(await _openDatabase());\r\n }\r\n else {\r\n resolve(db);\r\n }\r\n });\r\n });\r\n}\r\nasync function _putObject(db, key, value) {\r\n const request = getObjectStore(db, true).put({\r\n [DB_DATA_KEYPATH]: key,\r\n value\r\n });\r\n return new DBPromise(request).toPromise();\r\n}\r\nasync function getObject(db, key) {\r\n const request = getObjectStore(db, false).get(key);\r\n const data = await new DBPromise(request).toPromise();\r\n return data === undefined ? null : data.value;\r\n}\r\nfunction _deleteObject(db, key) {\r\n const request = getObjectStore(db, true).delete(key);\r\n return new DBPromise(request).toPromise();\r\n}\r\nconst _POLLING_INTERVAL_MS = 800;\r\nconst _TRANSACTION_RETRY_COUNT = 3;\r\nclass IndexedDBLocalPersistence {\r\n constructor() {\r\n this.type = \"LOCAL\" /* PersistenceType.LOCAL */;\r\n this._shouldAllowMigration = true;\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n this.pendingWrites = 0;\r\n this.receiver = null;\r\n this.sender = null;\r\n this.serviceWorkerReceiverAvailable = false;\r\n this.activeServiceWorker = null;\r\n // Fire & forget the service worker registration as it may never resolve\r\n this._workerInitializationPromise =\r\n this.initializeServiceWorkerMessaging().then(() => { }, () => { });\r\n }\r\n async _openDb() {\r\n if (this.db) {\r\n return this.db;\r\n }\r\n this.db = await _openDatabase();\r\n return this.db;\r\n }\r\n async _withRetries(op) {\r\n let numAttempts = 0;\r\n while (true) {\r\n try {\r\n const db = await this._openDb();\r\n return await op(db);\r\n }\r\n catch (e) {\r\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\r\n throw e;\r\n }\r\n if (this.db) {\r\n this.db.close();\r\n this.db = undefined;\r\n }\r\n // TODO: consider adding exponential backoff\r\n }\r\n }\r\n }\r\n /**\r\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\r\n * postMessage interface to send these events to the worker ourselves.\r\n */\r\n async initializeServiceWorkerMessaging() {\r\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\r\n }\r\n /**\r\n * As the worker we should listen to events from the main window.\r\n */\r\n async initializeReceiver() {\r\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\r\n // Refresh from persistence if we receive a KeyChanged message.\r\n this.receiver._subscribe(\"keyChanged\" /* _EventType.KEY_CHANGED */, async (_origin, data) => {\r\n const keys = await this._poll();\r\n return {\r\n keyProcessed: keys.includes(data.key)\r\n };\r\n });\r\n // Let the sender know that we are listening so they give us more timeout.\r\n this.receiver._subscribe(\"ping\" /* _EventType.PING */, async (_origin, _data) => {\r\n return [\"keyChanged\" /* _EventType.KEY_CHANGED */];\r\n });\r\n }\r\n /**\r\n * As the main window, we should let the worker know when keys change (set and remove).\r\n *\r\n * @remarks\r\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\r\n * may not resolve.\r\n */\r\n async initializeSender() {\r\n var _a, _b;\r\n // Check to see if there's an active service worker.\r\n this.activeServiceWorker = await _getActiveServiceWorker();\r\n if (!this.activeServiceWorker) {\r\n return;\r\n }\r\n this.sender = new Sender(this.activeServiceWorker);\r\n // Ping the service worker to check what events they can handle.\r\n const results = await this.sender._send(\"ping\" /* _EventType.PING */, {}, 800 /* _TimeoutDuration.LONG_ACK */);\r\n if (!results) {\r\n return;\r\n }\r\n if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&\r\n ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes(\"keyChanged\" /* _EventType.KEY_CHANGED */))) {\r\n this.serviceWorkerReceiverAvailable = true;\r\n }\r\n }\r\n /**\r\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\r\n * worker will just trigger a full sync anyway.\r\n *\r\n * @remarks\r\n * For now, we only support one service worker per page.\r\n *\r\n * @param key - Storage key which changed.\r\n */\r\n async notifyServiceWorker(key) {\r\n if (!this.sender ||\r\n !this.activeServiceWorker ||\r\n _getServiceWorkerController() !== this.activeServiceWorker) {\r\n return;\r\n }\r\n try {\r\n await this.sender._send(\"keyChanged\" /* _EventType.KEY_CHANGED */, { key }, \r\n // Use long timeout if receiver has previously responded to a ping from us.\r\n this.serviceWorkerReceiverAvailable\r\n ? 800 /* _TimeoutDuration.LONG_ACK */\r\n : 50 /* _TimeoutDuration.ACK */);\r\n }\r\n catch (_a) {\r\n // This is a best effort approach. Ignore errors.\r\n }\r\n }\r\n async _isAvailable() {\r\n try {\r\n if (!indexedDB) {\r\n return false;\r\n }\r\n const db = await _openDatabase();\r\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\r\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\r\n return true;\r\n }\r\n catch (_a) { }\r\n return false;\r\n }\r\n async _withPendingWrite(write) {\r\n this.pendingWrites++;\r\n try {\r\n await write();\r\n }\r\n finally {\r\n this.pendingWrites--;\r\n }\r\n }\r\n async _set(key, value) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _putObject(db, key, value));\r\n this.localCache[key] = value;\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _get(key) {\r\n const obj = (await this._withRetries((db) => getObject(db, key)));\r\n this.localCache[key] = obj;\r\n return obj;\r\n }\r\n async _remove(key) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _deleteObject(db, key));\r\n delete this.localCache[key];\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _poll() {\r\n // TODO: check if we need to fallback if getAll is not supported\r\n const result = await this._withRetries((db) => {\r\n const getAllRequest = getObjectStore(db, false).getAll();\r\n return new DBPromise(getAllRequest).toPromise();\r\n });\r\n if (!result) {\r\n return [];\r\n }\r\n // If we have pending writes in progress abort, we'll get picked up on the next poll\r\n if (this.pendingWrites !== 0) {\r\n return [];\r\n }\r\n const keys = [];\r\n const keysInResult = new Set();\r\n if (result.length !== 0) {\r\n for (const { fbase_key: key, value } of result) {\r\n keysInResult.add(key);\r\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\r\n this.notifyListeners(key, value);\r\n keys.push(key);\r\n }\r\n }\r\n }\r\n for (const localKey of Object.keys(this.localCache)) {\r\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\r\n // Deleted\r\n this.notifyListeners(localKey, null);\r\n keys.push(localKey);\r\n }\r\n }\r\n return keys;\r\n }\r\n notifyListeners(key, newValue) {\r\n this.localCache[key] = newValue;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(newValue);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.startPolling();\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n void this._get(key); // This can happen in the background async and we can return immediately.\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.stopPolling();\r\n }\r\n }\r\n}\r\nIndexedDBLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst indexedDBLocalPersistence = IndexedDBLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:start\" /* Endpoint.START_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInTotpMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* HttpMethod.POST */, \"/v2/accounts/mfaSignIn:finalize\" /* Endpoint.FINALIZE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _SOLVE_TIME_MS = 500;\r\nconst _EXPIRATION_TIME_MS = 60000;\r\nconst _WIDGET_ID_START = 1000000000000;\r\nclass MockReCaptcha {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.counter = _WIDGET_ID_START;\r\n this._widgets = new Map();\r\n }\r\n render(container, parameters) {\r\n const id = this.counter;\r\n this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));\r\n this.counter++;\r\n return id;\r\n }\r\n reset(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());\r\n this._widgets.delete(id);\r\n }\r\n getResponse(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';\r\n }\r\n async execute(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());\r\n return '';\r\n }\r\n}\r\nclass MockWidget {\r\n constructor(containerOrId, appName, params) {\r\n this.params = params;\r\n this.timerId = null;\r\n this.deleted = false;\r\n this.responseToken = null;\r\n this.clickHandler = () => {\r\n this.execute();\r\n };\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */, { appName });\r\n this.container = container;\r\n this.isVisible = this.params.size !== 'invisible';\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n else {\r\n this.container.addEventListener('click', this.clickHandler);\r\n }\r\n }\r\n getResponse() {\r\n this.checkIfDeleted();\r\n return this.responseToken;\r\n }\r\n delete() {\r\n this.checkIfDeleted();\r\n this.deleted = true;\r\n if (this.timerId) {\r\n clearTimeout(this.timerId);\r\n this.timerId = null;\r\n }\r\n this.container.removeEventListener('click', this.clickHandler);\r\n }\r\n execute() {\r\n this.checkIfDeleted();\r\n if (this.timerId) {\r\n return;\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.responseToken = generateRandomAlphaNumericString(50);\r\n const { callback, 'expired-callback': expiredCallback } = this.params;\r\n if (callback) {\r\n try {\r\n callback(this.responseToken);\r\n }\r\n catch (e) { }\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.timerId = null;\r\n this.responseToken = null;\r\n if (expiredCallback) {\r\n try {\r\n expiredCallback();\r\n }\r\n catch (e) { }\r\n }\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n }, _EXPIRATION_TIME_MS);\r\n }, _SOLVE_TIME_MS);\r\n }\r\n checkIfDeleted() {\r\n if (this.deleted) {\r\n throw new Error('reCAPTCHA mock was already deleted!');\r\n }\r\n }\r\n}\r\nfunction generateRandomAlphaNumericString(len) {\r\n const chars = [];\r\n const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n for (let i = 0; i < len; i++) {\r\n chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));\r\n }\r\n return chars.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// ReCaptcha will load using the same callback, so the callback function needs\r\n// to be kept around\r\nconst _JSLOAD_CALLBACK = _generateCallbackName('rcb');\r\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\r\n/**\r\n * Loader for the GReCaptcha library. There should only ever be one of this.\r\n */\r\nclass ReCaptchaLoaderImpl {\r\n constructor() {\r\n var _a;\r\n this.hostLanguage = '';\r\n this.counter = 0;\r\n /**\r\n * Check for `render()` method. `window.grecaptcha` will exist if the Enterprise\r\n * version of the ReCAPTCHA script was loaded by someone else (e.g. App Check) but\r\n * `window.grecaptcha.render()` will not. Another load will add it.\r\n */\r\n this.librarySeparatelyLoaded = !!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render);\r\n }\r\n load(auth, hl = '') {\r\n _assert(isHostLanguageValid(hl), auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n if (this.shouldResolveImmediately(hl) && isV2(_window().grecaptcha)) {\r\n return Promise.resolve(_window().grecaptcha);\r\n }\r\n return new Promise((resolve, reject) => {\r\n const networkTimeout = _window().setTimeout(() => {\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }, NETWORK_TIMEOUT_DELAY.get());\r\n _window()[_JSLOAD_CALLBACK] = () => {\r\n _window().clearTimeout(networkTimeout);\r\n delete _window()[_JSLOAD_CALLBACK];\r\n const recaptcha = _window().grecaptcha;\r\n if (!recaptcha || !isV2(recaptcha)) {\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n return;\r\n }\r\n // Wrap the greptcha render function so that we know if the developer has\r\n // called it separately\r\n const render = recaptcha.render;\r\n recaptcha.render = (container, params) => {\r\n const widgetId = render(container, params);\r\n this.counter++;\r\n return widgetId;\r\n };\r\n this.hostLanguage = hl;\r\n resolve(recaptcha);\r\n };\r\n const url = `${_recaptchaV2ScriptUrl()}?${querystring({\r\n onload: _JSLOAD_CALLBACK,\r\n render: 'explicit',\r\n hl\r\n })}`;\r\n _loadJS(url).catch(() => {\r\n clearTimeout(networkTimeout);\r\n reject(_createError(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */));\r\n });\r\n });\r\n }\r\n clearedOneInstance() {\r\n this.counter--;\r\n }\r\n shouldResolveImmediately(hl) {\r\n var _a;\r\n // We can resolve immediately if:\r\n // • grecaptcha is already defined AND (\r\n // 1. the requested language codes are the same OR\r\n // 2. there exists already a ReCaptcha on the page\r\n // 3. the library was already loaded by the app\r\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\r\n // that are already in the page\r\n return (!!((_a = _window().grecaptcha) === null || _a === void 0 ? void 0 : _a.render) &&\r\n (hl === this.hostLanguage ||\r\n this.counter > 0 ||\r\n this.librarySeparatelyLoaded));\r\n }\r\n}\r\nfunction isHostLanguageValid(hl) {\r\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\r\n}\r\nclass MockReCaptchaLoaderImpl {\r\n async load(auth) {\r\n return new MockReCaptcha(auth);\r\n }\r\n clearedOneInstance() { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\r\nconst DEFAULT_PARAMS = {\r\n theme: 'light',\r\n type: 'image'\r\n};\r\n/**\r\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\r\n *\r\n * @remarks\r\n * `RecaptchaVerifier` does not work in a Node.js environment.\r\n *\r\n * @public\r\n */\r\nclass RecaptchaVerifier {\r\n /**\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n *\r\n * @param containerOrId - The reCAPTCHA container parameter.\r\n *\r\n * @remarks\r\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\r\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\r\n * an element ID. The corresponding element must also must be in the DOM at the time of\r\n * initialization.\r\n *\r\n * @param parameters - The optional reCAPTCHA parameters.\r\n *\r\n * @remarks\r\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\r\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\r\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\r\n * 'invisible'.\r\n */\r\n constructor(authExtern, containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS)) {\r\n this.parameters = parameters;\r\n /**\r\n * The application verifier type.\r\n *\r\n * @remarks\r\n * For a reCAPTCHA verifier, this is 'recaptcha'.\r\n */\r\n this.type = RECAPTCHA_VERIFIER_TYPE;\r\n this.destroyed = false;\r\n this.widgetId = null;\r\n this.tokenChangeListeners = new Set();\r\n this.renderPromise = null;\r\n this.recaptcha = null;\r\n this.auth = _castAuth(authExtern);\r\n this.isInvisible = this.parameters.size === 'invisible';\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n this.container = container;\r\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\r\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\r\n ? new MockReCaptchaLoaderImpl()\r\n : new ReCaptchaLoaderImpl();\r\n this.validateStartingState();\r\n // TODO: Figure out if sdk version is needed\r\n }\r\n /**\r\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\r\n *\r\n * @returns A Promise for the reCAPTCHA token.\r\n */\r\n async verify() {\r\n this.assertNotDestroyed();\r\n const id = await this.render();\r\n const recaptcha = this.getAssertedRecaptcha();\r\n const response = recaptcha.getResponse(id);\r\n if (response) {\r\n return response;\r\n }\r\n return new Promise(resolve => {\r\n const tokenChange = (token) => {\r\n if (!token) {\r\n return; // Ignore token expirations.\r\n }\r\n this.tokenChangeListeners.delete(tokenChange);\r\n resolve(token);\r\n };\r\n this.tokenChangeListeners.add(tokenChange);\r\n if (this.isInvisible) {\r\n recaptcha.execute(id);\r\n }\r\n });\r\n }\r\n /**\r\n * Renders the reCAPTCHA widget on the page.\r\n *\r\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\r\n */\r\n render() {\r\n try {\r\n this.assertNotDestroyed();\r\n }\r\n catch (e) {\r\n // This method returns a promise. Since it's not async (we want to return the\r\n // _same_ promise if rendering is still occurring), the API surface should\r\n // reject with the error rather than just throw\r\n return Promise.reject(e);\r\n }\r\n if (this.renderPromise) {\r\n return this.renderPromise;\r\n }\r\n this.renderPromise = this.makeRenderPromise().catch(e => {\r\n this.renderPromise = null;\r\n throw e;\r\n });\r\n return this.renderPromise;\r\n }\r\n /** @internal */\r\n _reset() {\r\n this.assertNotDestroyed();\r\n if (this.widgetId !== null) {\r\n this.getAssertedRecaptcha().reset(this.widgetId);\r\n }\r\n }\r\n /**\r\n * Clears the reCAPTCHA widget from the page and destroys the instance.\r\n */\r\n clear() {\r\n this.assertNotDestroyed();\r\n this.destroyed = true;\r\n this._recaptchaLoader.clearedOneInstance();\r\n if (!this.isInvisible) {\r\n this.container.childNodes.forEach(node => {\r\n this.container.removeChild(node);\r\n });\r\n }\r\n }\r\n validateStartingState() {\r\n _assert(!this.parameters.sitekey, this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */);\r\n }\r\n makeTokenCallback(existing) {\r\n return token => {\r\n this.tokenChangeListeners.forEach(listener => listener(token));\r\n if (typeof existing === 'function') {\r\n existing(token);\r\n }\r\n else if (typeof existing === 'string') {\r\n const globalFunc = _window()[existing];\r\n if (typeof globalFunc === 'function') {\r\n globalFunc(token);\r\n }\r\n }\r\n };\r\n }\r\n assertNotDestroyed() {\r\n _assert(!this.destroyed, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n async makeRenderPromise() {\r\n await this.init();\r\n if (!this.widgetId) {\r\n let container = this.container;\r\n if (!this.isInvisible) {\r\n const guaranteedEmpty = document.createElement('div');\r\n container.appendChild(guaranteedEmpty);\r\n container = guaranteedEmpty;\r\n }\r\n this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);\r\n }\r\n return this.widgetId;\r\n }\r\n async init() {\r\n _assert(_isHttpOrHttps() && !_isWorker(), this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n await domReady();\r\n this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);\r\n const siteKey = await getRecaptchaParams(this.auth);\r\n _assert(siteKey, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n this.parameters.sitekey = siteKey;\r\n }\r\n getAssertedRecaptcha() {\r\n _assert(this.recaptcha, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return this.recaptcha;\r\n }\r\n}\r\nfunction domReady() {\r\n let resolver = null;\r\n return new Promise(resolve => {\r\n if (document.readyState === 'complete') {\r\n resolve();\r\n return;\r\n }\r\n // Document not ready, wait for load before resolving.\r\n // Save resolver, so we can remove listener in case it was externally\r\n // cancelled.\r\n resolver = () => resolve();\r\n window.addEventListener('load', resolver);\r\n }).catch(e => {\r\n if (resolver) {\r\n window.removeEventListener('load', resolver);\r\n }\r\n throw e;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ConfirmationResultImpl {\r\n constructor(verificationId, onConfirmation) {\r\n this.verificationId = verificationId;\r\n this.onConfirmation = onConfirmation;\r\n }\r\n confirm(verificationCode) {\r\n const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);\r\n return this.onConfirmation(authCredential);\r\n }\r\n}\r\n/**\r\n * Asynchronously signs in using a phone number.\r\n *\r\n * @remarks\r\n * This method sends a code via SMS to the given\r\n * phone number, and returns a {@link ConfirmationResult}. After the user\r\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\r\n * with the code to sign the user in.\r\n *\r\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\r\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\r\n * This function can work on other platforms that do not support the\r\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\r\n * third-party {@link ApplicationVerifier} implementation.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain a verificationCode from the user.\r\n * const credential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));\r\n}\r\n/**\r\n * Links the user account with the given phone number.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, \"phone\" /* ProviderId.PHONE */);\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh phone credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\r\n *\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\r\n *\r\n */\r\nasync function _verifyPhoneNumber(auth, options, verifier) {\r\n var _a;\r\n const recaptchaToken = await verifier.verify();\r\n try {\r\n _assert(typeof recaptchaToken === 'string', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n let phoneInfoOptions;\r\n if (typeof options === 'string') {\r\n phoneInfoOptions = {\r\n phoneNumber: options\r\n };\r\n }\r\n else {\r\n phoneInfoOptions = options;\r\n }\r\n if ('session' in phoneInfoOptions) {\r\n const session = phoneInfoOptions.session;\r\n if ('phoneNumber' in phoneInfoOptions) {\r\n _assert(session.type === \"enroll\" /* MultiFactorSessionType.ENROLL */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollPhoneMfa(auth, {\r\n idToken: session.credential,\r\n phoneEnrollmentInfo: {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneSessionInfo.sessionInfo;\r\n }\r\n else {\r\n _assert(session.type === \"signin\" /* MultiFactorSessionType.SIGN_IN */, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||\r\n phoneInfoOptions.multiFactorUid;\r\n _assert(mfaEnrollmentId, auth, \"missing-multi-factor-info\" /* AuthErrorCode.MISSING_MFA_INFO */);\r\n const response = await startSignInPhoneMfa(auth, {\r\n mfaPendingCredential: session.credential,\r\n mfaEnrollmentId,\r\n phoneSignInInfo: {\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneResponseInfo.sessionInfo;\r\n }\r\n }\r\n else {\r\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n });\r\n return sessionInfo;\r\n }\r\n }\r\n finally {\r\n verifier._reset();\r\n }\r\n}\r\n/**\r\n * Updates the user's phone number.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * await updatePhoneNumber(user, phoneCredential);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param credential - A credential authenticating the new phone number.\r\n *\r\n * @public\r\n */\r\nasync function updatePhoneNumber(user, credential) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n await _link$1(userInternal, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link PhoneAuthCredential}.\r\n *\r\n * @remarks\r\n * `PhoneAuthProvider` does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, phoneCredential);\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthProvider {\r\n /**\r\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\r\n *\r\n */\r\n constructor(auth) {\r\n /** Always set to {@link ProviderId}.PHONE. */\r\n this.providerId = PhoneAuthProvider.PROVIDER_ID;\r\n this.auth = _castAuth(auth);\r\n }\r\n /**\r\n *\r\n * Starts a phone number authentication flow by sending a verification code to the given phone\r\n * number.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\r\n * E.164 format (e.g. +16505550101).\r\n * @param applicationVerifier - For abuse prevention, this method also requires a\r\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\r\n * {@link RecaptchaVerifier}.\r\n *\r\n * @returns A Promise for a verification ID that can be passed to\r\n * {@link PhoneAuthProvider.credential} to identify this flow..\r\n */\r\n verifyPhoneNumber(phoneOptions, applicationVerifier) {\r\n return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));\r\n }\r\n /**\r\n * Creates a phone auth credential, given the verification ID from\r\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\r\n * mobile device.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\r\n * @param verificationCode - The verification code sent to the user's mobile device.\r\n *\r\n * @returns The auth provider credential.\r\n */\r\n static credential(verificationId, verificationCode) {\r\n return PhoneAuthCredential._fromVerification(verificationId, verificationCode);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n const credential = userCredential;\r\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\r\n }\r\n /**\r\n * Returns an {@link AuthCredential} when passed an error.\r\n *\r\n * @remarks\r\n *\r\n * This method works for errors like\r\n * `auth/account-exists-with-different-credentials`. This is useful for\r\n * recovering when attempting to set a user's phone number but the number\r\n * in question is already tied to another account. For example, the following\r\n * code tries to update the current user's phone number, and if that\r\n * fails, links the user with the account associated with that number:\r\n *\r\n * ```js\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\r\n * try {\r\n * const code = ''; // Prompt the user for the verification code\r\n * await updatePhoneNumber(\r\n * auth.currentUser,\r\n * PhoneAuthProvider.credential(verificationId, code));\r\n * } catch (e) {\r\n * if ((e as FirebaseError)?.code === 'auth/account-exists-with-different-credential') {\r\n * const cred = PhoneAuthProvider.credentialFromError(e);\r\n * await linkWithCredential(auth.currentUser, cred);\r\n * }\r\n * }\r\n *\r\n * // At this point, auth.currentUser.phoneNumber === number.\r\n * ```\r\n *\r\n * @param error - The error to generate a credential from.\r\n */\r\n static credentialFromError(error) {\r\n return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { phoneNumber, temporaryProof } = tokenResponse;\r\n if (phoneNumber && temporaryProof) {\r\n return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);\r\n }\r\n return null;\r\n }\r\n}\r\n/** Always set to {@link ProviderId}.PHONE. */\r\nPhoneAuthProvider.PROVIDER_ID = \"phone\" /* ProviderId.PHONE */;\r\n/** Always set to {@link SignInMethod}.PHONE. */\r\nPhoneAuthProvider.PHONE_SIGN_IN_METHOD = \"phone\" /* SignInMethod.PHONE */;\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Chooses a popup/redirect resolver to use. This prefers the override (which\r\n * is directly passed in), and falls back to the property set on the auth\r\n * object. If neither are available, this function errors w/ an argument error.\r\n */\r\nfunction _withDefaultResolver(auth, resolverOverride) {\r\n if (resolverOverride) {\r\n return _getInstance(resolverOverride);\r\n }\r\n _assert(auth._popupRedirectResolver, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return auth._popupRedirectResolver;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass IdpCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"custom\" /* ProviderId.CUSTOM */, \"custom\" /* ProviderId.CUSTOM */);\r\n this.params = params;\r\n }\r\n _getIdTokenResponse(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _linkToIdToken(auth, idToken) {\r\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\r\n }\r\n _getReauthenticationResolver(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _buildIdpRequest(idToken) {\r\n const request = {\r\n requestUri: this.params.requestUri,\r\n sessionId: this.params.sessionId,\r\n postBody: this.params.postBody,\r\n tenantId: this.params.tenantId,\r\n pendingToken: this.params.pendingToken,\r\n returnSecureToken: true,\r\n returnIdpCredential: true\r\n };\r\n if (idToken) {\r\n request.idToken = idToken;\r\n }\r\n return request;\r\n }\r\n}\r\nfunction _signIn(params) {\r\n return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nfunction _reauth(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nasync function _link(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return _link$1(user, new IdpCredential(params), params.bypassAuthState);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n */\r\nclass AbstractPopupRedirectOperation {\r\n constructor(auth, filter, resolver, user, bypassAuthState = false) {\r\n this.auth = auth;\r\n this.resolver = resolver;\r\n this.user = user;\r\n this.bypassAuthState = bypassAuthState;\r\n this.pendingPromise = null;\r\n this.eventManager = null;\r\n this.filter = Array.isArray(filter) ? filter : [filter];\r\n }\r\n execute() {\r\n return new Promise(async (resolve, reject) => {\r\n this.pendingPromise = { resolve, reject };\r\n try {\r\n this.eventManager = await this.resolver._initialize(this.auth);\r\n await this.onExecution();\r\n this.eventManager.registerConsumer(this);\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n });\r\n }\r\n async onAuthEvent(event) {\r\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\r\n if (error) {\r\n this.reject(error);\r\n return;\r\n }\r\n const params = {\r\n auth: this.auth,\r\n requestUri: urlResponse,\r\n sessionId: sessionId,\r\n tenantId: tenantId || undefined,\r\n postBody: postBody || undefined,\r\n user: this.user,\r\n bypassAuthState: this.bypassAuthState\r\n };\r\n try {\r\n this.resolve(await this.getIdpTask(type)(params));\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n }\r\n onError(error) {\r\n this.reject(error);\r\n }\r\n getIdpTask(type) {\r\n switch (type) {\r\n case \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */:\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n return _signIn;\r\n case \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n return _link;\r\n case \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return _reauth;\r\n default:\r\n _fail(this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }\r\n }\r\n resolve(cred) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.resolve(cred);\r\n this.unregisterAndCleanUp();\r\n }\r\n reject(error) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.reject(error);\r\n this.unregisterAndCleanUp();\r\n }\r\n unregisterAndCleanUp() {\r\n if (this.eventManager) {\r\n this.eventManager.unregisterConsumer(this);\r\n }\r\n this.pendingPromise = null;\r\n this.cleanUp();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\r\n/**\r\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\r\n *\r\n * @remarks\r\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\r\n * unsuccessful, returns an error object containing additional information about the error.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPopup(auth, provider, resolver) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_createError(auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\r\n }\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n const action = new PopupOperation(authInternal, \"signInViaPopup\" /* AuthEventType.SIGN_IN_VIA_POPUP */, provider, resolverInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\r\n * OAuth flow.\r\n *\r\n * @remarks\r\n * If the reauthentication is successful, the returned result will contain the user and the\r\n * provider's credential.\r\n *\r\n * This method does not work in a Node.js environment or on any {@link User} signed in by\r\n * {@link Auth} instances created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n * // Reauthenticate using a popup.\r\n * await reauthenticateWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_createError(userInternal.auth, \"operation-not-supported-in-this-environment\" /* AuthErrorCode.OPERATION_NOT_SUPPORTED */));\r\n }\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"reauthViaPopup\" /* AuthEventType.REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\r\n *\r\n * @remarks\r\n * If the linking is successful, the returned result will contain the user and the provider's credential.\r\n *\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"linkViaPopup\" /* AuthEventType.LINK_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n *\r\n */\r\nclass PopupOperation extends AbstractPopupRedirectOperation {\r\n constructor(auth, filter, provider, resolver, user) {\r\n super(auth, filter, resolver, user);\r\n this.provider = provider;\r\n this.authWindow = null;\r\n this.pollId = null;\r\n if (PopupOperation.currentPopupAction) {\r\n PopupOperation.currentPopupAction.cancel();\r\n }\r\n PopupOperation.currentPopupAction = this;\r\n }\r\n async executeNotNull() {\r\n const result = await this.execute();\r\n _assert(result, this.auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return result;\r\n }\r\n async onExecution() {\r\n debugAssert(this.filter.length === 1, 'Popup operations only handle one event');\r\n const eventId = _generateEventId();\r\n this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor\r\n eventId);\r\n this.authWindow.associatedEvent = eventId;\r\n // Check for web storage support and origin validation _after_ the popup is\r\n // loaded. These operations are slow (~1 second or so) Rather than\r\n // waiting on them before opening the window, optimistically open the popup\r\n // and check for storage support at the same time. If storage support is\r\n // not available, this will cause the whole thing to reject properly. It\r\n // will also close the popup, but since the promise has already rejected,\r\n // the popup closed by user poll will reject into the void.\r\n this.resolver._originValidation(this.auth).catch(e => {\r\n this.reject(e);\r\n });\r\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\r\n if (!isSupported) {\r\n this.reject(_createError(this.auth, \"web-storage-unsupported\" /* AuthErrorCode.WEB_STORAGE_UNSUPPORTED */));\r\n }\r\n });\r\n // Handle user closure. Notice this does *not* use await\r\n this.pollUserCancellation();\r\n }\r\n get eventId() {\r\n var _a;\r\n return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;\r\n }\r\n cancel() {\r\n this.reject(_createError(this.auth, \"cancelled-popup-request\" /* AuthErrorCode.EXPIRED_POPUP_REQUEST */));\r\n }\r\n cleanUp() {\r\n if (this.authWindow) {\r\n this.authWindow.close();\r\n }\r\n if (this.pollId) {\r\n window.clearTimeout(this.pollId);\r\n }\r\n this.authWindow = null;\r\n this.pollId = null;\r\n PopupOperation.currentPopupAction = null;\r\n }\r\n pollUserCancellation() {\r\n const poll = () => {\r\n var _a, _b;\r\n if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {\r\n // Make sure that there is sufficient time for whatever action to\r\n // complete. The window could have closed but the sign in network\r\n // call could still be in flight. This is specifically true for\r\n // Firefox or if the opener is in an iframe, in which case the oauth\r\n // helper closes the popup.\r\n this.pollId = window.setTimeout(() => {\r\n this.pollId = null;\r\n this.reject(_createError(this.auth, \"popup-closed-by-user\" /* AuthErrorCode.POPUP_CLOSED_BY_USER */));\r\n }, 8000 /* _Timeout.AUTH_EVENT */);\r\n return;\r\n }\r\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\r\n };\r\n poll();\r\n }\r\n}\r\n// Only one popup is ever shown at once. The lifecycle of the current popup\r\n// can be managed / cancelled by the constructor.\r\nPopupOperation.currentPopupAction = null;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\r\n// We only get one redirect outcome for any one auth, so just store it\r\n// in here.\r\nconst redirectOutcomeMap = new Map();\r\nclass RedirectAction extends AbstractPopupRedirectOperation {\r\n constructor(auth, resolver, bypassAuthState = false) {\r\n super(auth, [\r\n \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */,\r\n \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */,\r\n \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */,\r\n \"unknown\" /* AuthEventType.UNKNOWN */\r\n ], resolver, undefined, bypassAuthState);\r\n this.eventId = null;\r\n }\r\n /**\r\n * Override the execute function; if we already have a redirect result, then\r\n * just return it.\r\n */\r\n async execute() {\r\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\r\n if (!readyOutcome) {\r\n try {\r\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);\r\n const result = hasPendingRedirect ? await super.execute() : null;\r\n readyOutcome = () => Promise.resolve(result);\r\n }\r\n catch (e) {\r\n readyOutcome = () => Promise.reject(e);\r\n }\r\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\r\n }\r\n // If we're not bypassing auth state, the ready outcome should be set to\r\n // null.\r\n if (!this.bypassAuthState) {\r\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\r\n }\r\n return readyOutcome();\r\n }\r\n async onAuthEvent(event) {\r\n if (event.type === \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */) {\r\n return super.onAuthEvent(event);\r\n }\r\n else if (event.type === \"unknown\" /* AuthEventType.UNKNOWN */) {\r\n // This is a sentinel value indicating there's no pending redirect\r\n this.resolve(null);\r\n return;\r\n }\r\n if (event.eventId) {\r\n const user = await this.auth._redirectUserForId(event.eventId);\r\n if (user) {\r\n this.user = user;\r\n return super.onAuthEvent(event);\r\n }\r\n else {\r\n this.resolve(null);\r\n }\r\n }\r\n }\r\n async onExecution() { }\r\n cleanUp() { }\r\n}\r\nasync function _getAndClearPendingRedirectStatus(resolver, auth) {\r\n const key = pendingRedirectKey(auth);\r\n const persistence = resolverPersistence(resolver);\r\n if (!(await persistence._isAvailable())) {\r\n return false;\r\n }\r\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\r\n await persistence._remove(key);\r\n return hasPendingRedirect;\r\n}\r\nasync function _setPendingRedirectStatus(resolver, auth) {\r\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\r\n}\r\nfunction _clearRedirectOutcomes() {\r\n redirectOutcomeMap.clear();\r\n}\r\nfunction _overrideRedirectResult(auth, result) {\r\n redirectOutcomeMap.set(auth._key(), result);\r\n}\r\nfunction resolverPersistence(resolver) {\r\n return _getInstance(resolver._redirectPersistence);\r\n}\r\nfunction pendingRedirectKey(auth) {\r\n return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Authenticates a Firebase client using a full-page redirect flow.\r\n *\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link signInWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction signInWithRedirect(auth, provider, resolver) {\r\n return _signInWithRedirect(auth, provider, resolver);\r\n}\r\nasync function _signInWithRedirect(auth, provider, resolver) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await authInternal._initializationPromise;\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, authInternal);\r\n return resolverInternal._openRedirect(authInternal, provider, \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */);\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link reauthenticateWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * // Reauthenticate using a redirect.\r\n * await reauthenticateWithRedirect(result.user, provider);\r\n * // This will again trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction reauthenticateWithRedirect(user, provider, resolver) {\r\n return _reauthenticateWithRedirect(user, provider, resolver);\r\n}\r\nasync function _reauthenticateWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n if (_isFirebaseServerApp(userInternal.auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(userInternal.auth));\r\n }\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n * Follow the {@link https://firebase.google.com/docs/auth/web/redirect-best-practices\r\n * | best practices} when using {@link linkWithRedirect}.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances\r\n * created with a {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithRedirect(result.user, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction linkWithRedirect(user, provider, resolver) {\r\n return _linkWithRedirect(user, provider, resolver);\r\n}\r\nasync function _linkWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n // Wait for auth initialization to complete, this will process pending redirects and clear the\r\n // PENDING_REDIRECT_KEY in persistence. This should be completed before starting a new\r\n // redirect and creating a PENDING_REDIRECT_KEY entry.\r\n await userInternal.auth._initializationPromise;\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _assertLinkedStatus(false, userInternal, provider.providerId);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\r\n *\r\n * @remarks\r\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\r\n * error. If no redirect operation was called, returns `null`.\r\n *\r\n * This method does not work in a Node.js environment or with {@link Auth} instances created with a\r\n * {@link @firebase/app#FirebaseServerApp}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function getRedirectResult(auth, resolver) {\r\n await _castAuth(auth)._initializationPromise;\r\n return _getRedirectResult(auth, resolver, false);\r\n}\r\nasync function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {\r\n if (_isFirebaseServerApp(auth.app)) {\r\n return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(auth));\r\n }\r\n const authInternal = _castAuth(auth);\r\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\r\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\r\n const result = await action.execute();\r\n if (result && !bypassAuthState) {\r\n delete result.user._redirectEventId;\r\n await authInternal._persistUserIfCurrent(result.user);\r\n await authInternal._setRedirectUser(null, resolverExtern);\r\n }\r\n return result;\r\n}\r\nasync function prepareUserForRedirect(user) {\r\n const eventId = _generateEventId(`${user.uid}:::`);\r\n user._redirectEventId = eventId;\r\n await user.auth._setRedirectUser(user);\r\n await user.auth._persistUserIfCurrent(user);\r\n return eventId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// The amount of time to store the UIDs of seen events; this is\r\n// set to 10 min by default\r\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\r\nclass AuthEventManager {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.cachedEventUids = new Set();\r\n this.consumers = new Set();\r\n this.queuedRedirectEvent = null;\r\n this.hasHandledPotentialRedirect = false;\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n registerConsumer(authEventConsumer) {\r\n this.consumers.add(authEventConsumer);\r\n if (this.queuedRedirectEvent &&\r\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {\r\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\r\n this.saveEventToCache(this.queuedRedirectEvent);\r\n this.queuedRedirectEvent = null;\r\n }\r\n }\r\n unregisterConsumer(authEventConsumer) {\r\n this.consumers.delete(authEventConsumer);\r\n }\r\n onEvent(event) {\r\n // Check if the event has already been handled\r\n if (this.hasEventBeenHandled(event)) {\r\n return false;\r\n }\r\n let handled = false;\r\n this.consumers.forEach(consumer => {\r\n if (this.isEventForConsumer(event, consumer)) {\r\n handled = true;\r\n this.sendToConsumer(event, consumer);\r\n this.saveEventToCache(event);\r\n }\r\n });\r\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\r\n // If we've already seen a redirect before, or this is a popup event,\r\n // bail now\r\n return handled;\r\n }\r\n this.hasHandledPotentialRedirect = true;\r\n // If the redirect wasn't handled, hang on to it\r\n if (!handled) {\r\n this.queuedRedirectEvent = event;\r\n handled = true;\r\n }\r\n return handled;\r\n }\r\n sendToConsumer(event, consumer) {\r\n var _a;\r\n if (event.error && !isNullRedirectEvent(event)) {\r\n const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||\r\n \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */;\r\n consumer.onError(_createError(this.auth, code));\r\n }\r\n else {\r\n consumer.onAuthEvent(event);\r\n }\r\n }\r\n isEventForConsumer(event, consumer) {\r\n const eventIdMatches = consumer.eventId === null ||\r\n (!!event.eventId && event.eventId === consumer.eventId);\r\n return consumer.filter.includes(event.type) && eventIdMatches;\r\n }\r\n hasEventBeenHandled(event) {\r\n if (Date.now() - this.lastProcessedEventTime >=\r\n EVENT_DUPLICATION_CACHE_DURATION_MS) {\r\n this.cachedEventUids.clear();\r\n }\r\n return this.cachedEventUids.has(eventUid(event));\r\n }\r\n saveEventToCache(event) {\r\n this.cachedEventUids.add(eventUid(event));\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n}\r\nfunction eventUid(e) {\r\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\r\n}\r\nfunction isNullRedirectEvent({ type, error }) {\r\n return (type === \"unknown\" /* AuthEventType.UNKNOWN */ &&\r\n (error === null || error === void 0 ? void 0 : error.code) === `auth/${\"no-auth-event\" /* AuthErrorCode.NO_AUTH_EVENT */}`);\r\n}\r\nfunction isRedirectEvent(event) {\r\n switch (event.type) {\r\n case \"signInViaRedirect\" /* AuthEventType.SIGN_IN_VIA_REDIRECT */:\r\n case \"linkViaRedirect\" /* AuthEventType.LINK_VIA_REDIRECT */:\r\n case \"reauthViaRedirect\" /* AuthEventType.REAUTH_VIA_REDIRECT */:\r\n return true;\r\n case \"unknown\" /* AuthEventType.UNKNOWN */:\r\n return isNullRedirectEvent(event);\r\n default:\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _getProjectConfig(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* HttpMethod.GET */, \"/v1/projects\" /* Endpoint.GET_PROJECT_CONFIG */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\r\nconst HTTP_REGEX = /^https?/;\r\nasync function _validateOrigin(auth) {\r\n // Skip origin validation if we are in an emulated environment\r\n if (auth.config.emulator) {\r\n return;\r\n }\r\n const { authorizedDomains } = await _getProjectConfig(auth);\r\n for (const domain of authorizedDomains) {\r\n try {\r\n if (matchDomain(domain)) {\r\n return;\r\n }\r\n }\r\n catch (_a) {\r\n // Do nothing if there's a URL error; just continue searching\r\n }\r\n }\r\n // In the old SDK, this error also provides helpful messages.\r\n _fail(auth, \"unauthorized-domain\" /* AuthErrorCode.INVALID_ORIGIN */);\r\n}\r\nfunction matchDomain(expected) {\r\n const currentUrl = _getCurrentUrl();\r\n const { protocol, hostname } = new URL(currentUrl);\r\n if (expected.startsWith('chrome-extension://')) {\r\n const ceUrl = new URL(expected);\r\n if (ceUrl.hostname === '' && hostname === '') {\r\n // For some reason we're not parsing chrome URLs properly\r\n return (protocol === 'chrome-extension:' &&\r\n expected.replace('chrome-extension://', '') ===\r\n currentUrl.replace('chrome-extension://', ''));\r\n }\r\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\r\n }\r\n if (!HTTP_REGEX.test(protocol)) {\r\n return false;\r\n }\r\n if (IP_ADDRESS_REGEX.test(expected)) {\r\n // The domain has to be exactly equal to the pattern, as an IP domain will\r\n // only contain the IP, no extra character.\r\n return hostname === expected;\r\n }\r\n // Dots in pattern should be escaped.\r\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\r\n // Non ip address domains.\r\n // domain.com = *.domain.com OR domain.com\r\n const re = new RegExp('^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');\r\n return re.test(hostname);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\r\n/**\r\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\r\n * it will stop working after a retrial. This is a hack to fix this issue.\r\n */\r\nfunction resetUnloadedGapiModules() {\r\n // Clear last failed gapi.load state to force next gapi.load to first\r\n // load the failed gapi.iframes module.\r\n // Get gapix.beacon context.\r\n const beacon = _window().___jsl;\r\n // Get current hint.\r\n if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {\r\n // Get gapi hint.\r\n for (const hint of Object.keys(beacon.H)) {\r\n // Requested modules.\r\n beacon.H[hint].r = beacon.H[hint].r || [];\r\n // Loaded modules.\r\n beacon.H[hint].L = beacon.H[hint].L || [];\r\n // Set requested modules to a copy of the loaded modules.\r\n beacon.H[hint].r = [...beacon.H[hint].L];\r\n // Clear pending callbacks.\r\n if (beacon.CP) {\r\n for (let i = 0; i < beacon.CP.length; i++) {\r\n // Remove all failed pending callbacks.\r\n beacon.CP[i] = null;\r\n }\r\n }\r\n }\r\n }\r\n}\r\nfunction loadGapi(auth) {\r\n return new Promise((resolve, reject) => {\r\n var _a, _b, _c;\r\n // Function to run when gapi.load is ready.\r\n function loadGapiIframe() {\r\n // The developer may have tried to previously run gapi.load and failed.\r\n // Run this to fix that.\r\n resetUnloadedGapiModules();\r\n gapi.load('gapi.iframes', {\r\n callback: () => {\r\n resolve(gapi.iframes.getContext());\r\n },\r\n ontimeout: () => {\r\n // The above reset may be sufficient, but having this reset after\r\n // failure ensures that if the developer calls gapi.load after the\r\n // connection is re-established and before another attempt to embed\r\n // the iframe, it would work and would not be broken because of our\r\n // failed attempt.\r\n // Timeout when gapi.iframes.Iframe not loaded.\r\n resetUnloadedGapiModules();\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n },\r\n timeout: NETWORK_TIMEOUT.get()\r\n });\r\n }\r\n if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {\r\n // If gapi.iframes.Iframe available, resolve.\r\n resolve(gapi.iframes.getContext());\r\n }\r\n else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {\r\n // Gapi loader ready, load gapi.iframes.\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Create a new iframe callback when this is called so as not to overwrite\r\n // any previous defined callback. This happens if this method is called\r\n // multiple times in parallel and could result in the later callback\r\n // overwriting the previous one. This would end up with a iframe\r\n // timeout.\r\n const cbName = _generateCallbackName('iframefcb');\r\n // GApi loader not available, dynamically load platform.js.\r\n _window()[cbName] = () => {\r\n // GApi loader should be ready.\r\n if (!!gapi.load) {\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Gapi loader failed, throw error.\r\n reject(_createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */));\r\n }\r\n };\r\n // Load GApi loader.\r\n return _loadJS(`${_gapiScriptUrl()}?onload=${cbName}`)\r\n .catch(e => reject(e));\r\n }\r\n }).catch(error => {\r\n // Reset cached promise to allow for retrial.\r\n cachedGApiLoader = null;\r\n throw error;\r\n });\r\n}\r\nlet cachedGApiLoader = null;\r\nfunction _loadGapi(auth) {\r\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\r\n return cachedGApiLoader;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PING_TIMEOUT = new Delay(5000, 15000);\r\nconst IFRAME_PATH = '__/auth/iframe';\r\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\r\nconst IFRAME_ATTRIBUTES = {\r\n style: {\r\n position: 'absolute',\r\n top: '-100px',\r\n width: '1px',\r\n height: '1px'\r\n },\r\n 'aria-hidden': 'true',\r\n tabindex: '-1'\r\n};\r\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\r\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\r\nconst EID_FROM_APIHOST = new Map([\r\n [\"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */, 'p'],\r\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'],\r\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\r\n]);\r\nfunction getIframeUrl(auth) {\r\n const config = auth.config;\r\n _assert(config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n const url = config.emulator\r\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\r\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\r\n const params = {\r\n apiKey: config.apiKey,\r\n appName: auth.name,\r\n v: SDK_VERSION\r\n };\r\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\r\n if (eid) {\r\n params.eid = eid;\r\n }\r\n const frameworks = auth._getFrameworks();\r\n if (frameworks.length) {\r\n params.fw = frameworks.join(',');\r\n }\r\n return `${url}?${querystring(params).slice(1)}`;\r\n}\r\nasync function _openIframe(auth) {\r\n const context = await _loadGapi(auth);\r\n const gapi = _window().gapi;\r\n _assert(gapi, auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n return context.open({\r\n where: document.body,\r\n url: getIframeUrl(auth),\r\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\r\n attributes: IFRAME_ATTRIBUTES,\r\n dontclear: true\r\n }, (iframe) => new Promise(async (resolve, reject) => {\r\n await iframe.restyle({\r\n // Prevent iframe from closing on mouse out.\r\n setHideOnLeave: false\r\n });\r\n const networkError = _createError(auth, \"network-request-failed\" /* AuthErrorCode.NETWORK_REQUEST_FAILED */);\r\n // Confirm iframe is correctly loaded.\r\n // To fallback on failure, set a timeout.\r\n const networkErrorTimer = _window().setTimeout(() => {\r\n reject(networkError);\r\n }, PING_TIMEOUT.get());\r\n // Clear timer and resolve pending iframe ready promise.\r\n function clearTimerAndResolve() {\r\n _window().clearTimeout(networkErrorTimer);\r\n resolve(iframe);\r\n }\r\n // This returns an IThenable. However the reject part does not call\r\n // when the iframe is not loaded.\r\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\r\n reject(networkError);\r\n });\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst BASE_POPUP_OPTIONS = {\r\n location: 'yes',\r\n resizable: 'yes',\r\n statusbar: 'yes',\r\n toolbar: 'no'\r\n};\r\nconst DEFAULT_WIDTH = 500;\r\nconst DEFAULT_HEIGHT = 600;\r\nconst TARGET_BLANK = '_blank';\r\nconst FIREFOX_EMPTY_URL = 'http://localhost';\r\nclass AuthPopup {\r\n constructor(window) {\r\n this.window = window;\r\n this.associatedEvent = null;\r\n }\r\n close() {\r\n if (this.window) {\r\n try {\r\n this.window.close();\r\n }\r\n catch (e) { }\r\n }\r\n }\r\n}\r\nfunction _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {\r\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\r\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\r\n let target = '';\r\n const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top,\r\n left });\r\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\r\n // specified, even though the popup is not necessarily blocked.\r\n const ua = getUA().toLowerCase();\r\n if (name) {\r\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\r\n }\r\n if (_isFirefox(ua)) {\r\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\r\n url = url || FIREFOX_EMPTY_URL;\r\n // Firefox disables by default scrolling on popup windows, which can create\r\n // issues when the user has many Google accounts, for instance.\r\n options.scrollbars = 'yes';\r\n }\r\n const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');\r\n if (_isIOSStandalone(ua) && target !== '_self') {\r\n openAsNewWindowIOS(url || '', target);\r\n return new AuthPopup(null);\r\n }\r\n // about:blank getting sanitized causing browsers like IE/Edge to display\r\n // brief error message before redirecting to handler.\r\n const newWin = window.open(url || '', target, optionsString);\r\n _assert(newWin, auth, \"popup-blocked\" /* AuthErrorCode.POPUP_BLOCKED */);\r\n // Flaky on IE edge, encapsulate with a try and catch.\r\n try {\r\n newWin.focus();\r\n }\r\n catch (e) { }\r\n return new AuthPopup(newWin);\r\n}\r\nfunction openAsNewWindowIOS(url, target) {\r\n const el = document.createElement('a');\r\n el.href = url;\r\n el.target = target;\r\n const click = document.createEvent('MouseEvent');\r\n click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);\r\n el.dispatchEvent(click);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * URL for Authentication widget which will initiate the OAuth handshake\r\n *\r\n * @internal\r\n */\r\nconst WIDGET_PATH = '__/auth/handler';\r\n/**\r\n * URL for emulated environment\r\n *\r\n * @internal\r\n */\r\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\r\n/**\r\n * Fragment name for the App Check token that gets passed to the widget\r\n *\r\n * @internal\r\n */\r\nconst FIREBASE_APP_CHECK_FRAGMENT_ID = encodeURIComponent('fac');\r\nasync function _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {\r\n _assert(auth.config.authDomain, auth, \"auth-domain-config-required\" /* AuthErrorCode.MISSING_AUTH_DOMAIN */);\r\n _assert(auth.config.apiKey, auth, \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */);\r\n const params = {\r\n apiKey: auth.config.apiKey,\r\n appName: auth.name,\r\n authType,\r\n redirectUrl,\r\n v: SDK_VERSION,\r\n eventId\r\n };\r\n if (provider instanceof FederatedAuthProvider) {\r\n provider.setDefaultLanguage(auth.languageCode);\r\n params.providerId = provider.providerId || '';\r\n if (!isEmpty(provider.getCustomParameters())) {\r\n params.customParameters = JSON.stringify(provider.getCustomParameters());\r\n }\r\n // TODO set additionalParams from the provider as well?\r\n for (const [key, value] of Object.entries(additionalParams || {})) {\r\n params[key] = value;\r\n }\r\n }\r\n if (provider instanceof BaseOAuthProvider) {\r\n const scopes = provider.getScopes().filter(scope => scope !== '');\r\n if (scopes.length > 0) {\r\n params.scopes = scopes.join(',');\r\n }\r\n }\r\n if (auth.tenantId) {\r\n params.tid = auth.tenantId;\r\n }\r\n // TODO: maybe set eid as endipointId\r\n // TODO: maybe set fw as Frameworks.join(\",\")\r\n const paramsDict = params;\r\n for (const key of Object.keys(paramsDict)) {\r\n if (paramsDict[key] === undefined) {\r\n delete paramsDict[key];\r\n }\r\n }\r\n // Sets the App Check token to pass to the widget\r\n const appCheckToken = await auth._getAppCheckToken();\r\n const appCheckTokenFragment = appCheckToken\r\n ? `#${FIREBASE_APP_CHECK_FRAGMENT_ID}=${encodeURIComponent(appCheckToken)}`\r\n : '';\r\n // Start at index 1 to skip the leading '&' in the query string\r\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}${appCheckTokenFragment}`;\r\n}\r\nfunction getHandlerBase({ config }) {\r\n if (!config.emulator) {\r\n return `https://${config.authDomain}/${WIDGET_PATH}`;\r\n }\r\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The special web storage event\r\n *\r\n */\r\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\r\nclass BrowserPopupRedirectResolver {\r\n constructor() {\r\n this.eventManagers = {};\r\n this.iframes = {};\r\n this.originValidationPromises = {};\r\n this._redirectPersistence = browserSessionPersistence;\r\n this._completeRedirectFn = _getRedirectResult;\r\n this._overrideRedirectResult = _overrideRedirectResult;\r\n }\r\n // Wrapping in async even though we don't await anywhere in order\r\n // to make sure errors are raised as promise rejections\r\n async _openPopup(auth, provider, authType, eventId) {\r\n var _a;\r\n debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');\r\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n return _open(auth, url, _generateEventId());\r\n }\r\n async _openRedirect(auth, provider, authType, eventId) {\r\n await this._originValidation(auth);\r\n const url = await _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n _setWindowLocation(url);\r\n return new Promise(() => { });\r\n }\r\n _initialize(auth) {\r\n const key = auth._key();\r\n if (this.eventManagers[key]) {\r\n const { manager, promise } = this.eventManagers[key];\r\n if (manager) {\r\n return Promise.resolve(manager);\r\n }\r\n else {\r\n debugAssert(promise, 'If manager is not set, promise should be');\r\n return promise;\r\n }\r\n }\r\n const promise = this.initAndGetManager(auth);\r\n this.eventManagers[key] = { promise };\r\n // If the promise is rejected, the key should be removed so that the\r\n // operation can be retried later.\r\n promise.catch(() => {\r\n delete this.eventManagers[key];\r\n });\r\n return promise;\r\n }\r\n async initAndGetManager(auth) {\r\n const iframe = await _openIframe(auth);\r\n const manager = new AuthEventManager(auth);\r\n iframe.register('authEvent', (iframeEvent) => {\r\n _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, \"invalid-auth-event\" /* AuthErrorCode.INVALID_AUTH_EVENT */);\r\n // TODO: Consider splitting redirect and popup events earlier on\r\n const handled = manager.onEvent(iframeEvent.authEvent);\r\n return { status: handled ? \"ACK\" /* GapiOutcome.ACK */ : \"ERROR\" /* GapiOutcome.ERROR */ };\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n this.eventManagers[auth._key()] = { manager };\r\n this.iframes[auth._key()] = iframe;\r\n return manager;\r\n }\r\n _isIframeWebStorageSupported(auth, cb) {\r\n const iframe = this.iframes[auth._key()];\r\n iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {\r\n var _a;\r\n const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];\r\n if (isSupported !== undefined) {\r\n cb(!!isSupported);\r\n }\r\n _fail(auth, \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n }\r\n _originValidation(auth) {\r\n const key = auth._key();\r\n if (!this.originValidationPromises[key]) {\r\n this.originValidationPromises[key] = _validateOrigin(auth);\r\n }\r\n return this.originValidationPromises[key];\r\n }\r\n get _shouldInitProactively() {\r\n // Mobile browsers and Safari need to optimistically initialize\r\n return _isMobileBrowser() || _isSafari() || _isIOS();\r\n }\r\n}\r\n/**\r\n * An implementation of {@link PopupRedirectResolver} suitable for browser\r\n * based applications.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @public\r\n */\r\nconst browserPopupRedirectResolver = BrowserPopupRedirectResolver;\n\nclass MultiFactorAssertionImpl {\r\n constructor(factorId) {\r\n this.factorId = factorId;\r\n }\r\n _process(auth, session, displayName) {\r\n switch (session.type) {\r\n case \"enroll\" /* MultiFactorSessionType.ENROLL */:\r\n return this._finalizeEnroll(auth, session.credential, displayName);\r\n case \"signin\" /* MultiFactorSessionType.SIGN_IN */:\r\n return this._finalizeSignIn(auth, session.credential);\r\n default:\r\n return debugFail('unexpected MultiFactorSessionType');\r\n }\r\n }\r\n}\n\n/**\r\n * {@inheritdoc PhoneMultiFactorAssertion}\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(credential) {\r\n super(\"phone\" /* FactorId.PHONE */);\r\n this.credential = credential;\r\n }\r\n /** @internal */\r\n static _fromCredential(credential) {\r\n return new PhoneMultiFactorAssertionImpl(credential);\r\n }\r\n /** @internal */\r\n _finalizeEnroll(auth, idToken, displayName) {\r\n return finalizeEnrollPhoneMfa(auth, {\r\n idToken,\r\n displayName,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n /** @internal */\r\n _finalizeSignIn(auth, mfaPendingCredential) {\r\n return finalizeSignInPhoneMfa(auth, {\r\n mfaPendingCredential,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorGenerator {\r\n constructor() { }\r\n /**\r\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\r\n *\r\n * @remarks\r\n * This method does not work in a Node.js environment.\r\n *\r\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\r\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}\r\n */\r\n static assertion(credential) {\r\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\r\n }\r\n}\r\n/**\r\n * The identifier of the phone second factor: `phone`.\r\n */\r\nPhoneMultiFactorGenerator.FACTOR_ID = 'phone';\n\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass TotpMultiFactorGenerator {\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of\r\n * the TOTP (time-based one-time password) second factor.\r\n * This assertion is used to complete enrollment in TOTP second factor.\r\n *\r\n * @param secret A {@link TotpSecret} containing the shared secret key and other TOTP parameters.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorUser.enroll}.\r\n */\r\n static assertionForEnrollment(secret, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromSecret(secret, oneTimePassword);\r\n }\r\n /**\r\n * Provides a {@link TotpMultiFactorAssertion} to confirm ownership of the TOTP second factor.\r\n * This assertion is used to complete signIn with TOTP as the second factor.\r\n *\r\n * @param enrollmentId identifies the enrolled TOTP second factor.\r\n * @param oneTimePassword One-time password from TOTP App.\r\n * @returns A {@link TotpMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}.\r\n */\r\n static assertionForSignIn(enrollmentId, oneTimePassword) {\r\n return TotpMultiFactorAssertionImpl._fromEnrollmentId(enrollmentId, oneTimePassword);\r\n }\r\n /**\r\n * Returns a promise to {@link TotpSecret} which contains the TOTP shared secret key and other parameters.\r\n * Creates a TOTP secret as part of enrolling a TOTP second factor.\r\n * Used for generating a QR code URL or inputting into a TOTP app.\r\n * This method uses the auth instance corresponding to the user in the multiFactorSession.\r\n *\r\n * @param session The {@link MultiFactorSession} that the user is part of.\r\n * @returns A promise to {@link TotpSecret}.\r\n */\r\n static async generateSecret(session) {\r\n var _a;\r\n const mfaSession = session;\r\n _assert(typeof ((_a = mfaSession.user) === null || _a === void 0 ? void 0 : _a.auth) !== 'undefined', \"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n const response = await startEnrollTotpMfa(mfaSession.user.auth, {\r\n idToken: mfaSession.credential,\r\n totpEnrollmentInfo: {}\r\n });\r\n return TotpSecret._fromStartTotpMfaEnrollmentResponse(response, mfaSession.user.auth);\r\n }\r\n}\r\n/**\r\n * The identifier of the TOTP second factor: `totp`.\r\n */\r\nTotpMultiFactorGenerator.FACTOR_ID = \"totp\" /* FactorId.TOTP */;\r\nclass TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(otp, enrollmentId, secret) {\r\n super(\"totp\" /* FactorId.TOTP */);\r\n this.otp = otp;\r\n this.enrollmentId = enrollmentId;\r\n this.secret = secret;\r\n }\r\n /** @internal */\r\n static _fromSecret(secret, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, undefined, secret);\r\n }\r\n /** @internal */\r\n static _fromEnrollmentId(enrollmentId, otp) {\r\n return new TotpMultiFactorAssertionImpl(otp, enrollmentId);\r\n }\r\n /** @internal */\r\n async _finalizeEnroll(auth, idToken, displayName) {\r\n _assert(typeof this.secret !== 'undefined', auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n return finalizeEnrollTotpMfa(auth, {\r\n idToken,\r\n displayName,\r\n totpVerificationInfo: this.secret._makeTotpVerificationInfo(this.otp)\r\n });\r\n }\r\n /** @internal */\r\n async _finalizeSignIn(auth, mfaPendingCredential) {\r\n _assert(this.enrollmentId !== undefined && this.otp !== undefined, auth, \"argument-error\" /* AuthErrorCode.ARGUMENT_ERROR */);\r\n const totpVerificationInfo = { verificationCode: this.otp };\r\n return finalizeSignInTotpMfa(auth, {\r\n mfaPendingCredential,\r\n mfaEnrollmentId: this.enrollmentId,\r\n totpVerificationInfo\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link TotpMultiFactorAssertion}.\r\n *\r\n * Stores the shared secret key and other parameters to generate time-based OTPs.\r\n * Implements methods to retrieve the shared secret key and generate a QR code URL.\r\n * @public\r\n */\r\nclass TotpSecret {\r\n // The public members are declared outside the constructor so the docs can be generated.\r\n constructor(secretKey, hashingAlgorithm, codeLength, codeIntervalSeconds, enrollmentCompletionDeadline, sessionInfo, auth) {\r\n this.sessionInfo = sessionInfo;\r\n this.auth = auth;\r\n this.secretKey = secretKey;\r\n this.hashingAlgorithm = hashingAlgorithm;\r\n this.codeLength = codeLength;\r\n this.codeIntervalSeconds = codeIntervalSeconds;\r\n this.enrollmentCompletionDeadline = enrollmentCompletionDeadline;\r\n }\r\n /** @internal */\r\n static _fromStartTotpMfaEnrollmentResponse(response, auth) {\r\n return new TotpSecret(response.totpSessionInfo.sharedSecretKey, response.totpSessionInfo.hashingAlgorithm, response.totpSessionInfo.verificationCodeLength, response.totpSessionInfo.periodSec, new Date(response.totpSessionInfo.finalizeEnrollmentTime).toUTCString(), response.totpSessionInfo.sessionInfo, auth);\r\n }\r\n /** @internal */\r\n _makeTotpVerificationInfo(otp) {\r\n return { sessionInfo: this.sessionInfo, verificationCode: otp };\r\n }\r\n /**\r\n * Returns a QR code URL as described in\r\n * https://github.com/google/google-authenticator/wiki/Key-Uri-Format\r\n * This can be displayed to the user as a QR code to be scanned into a TOTP app like Google Authenticator.\r\n * If the optional parameters are unspecified, an accountName of and issuer of are used.\r\n *\r\n * @param accountName the name of the account/app along with a user identifier.\r\n * @param issuer issuer of the TOTP (likely the app name).\r\n * @returns A QR code URL string.\r\n */\r\n generateQrCodeUrl(accountName, issuer) {\r\n var _a;\r\n let useDefaults = false;\r\n if (_isEmptyString(accountName) || _isEmptyString(issuer)) {\r\n useDefaults = true;\r\n }\r\n if (useDefaults) {\r\n if (_isEmptyString(accountName)) {\r\n accountName = ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.email) || 'unknownuser';\r\n }\r\n if (_isEmptyString(issuer)) {\r\n issuer = this.auth.name;\r\n }\r\n }\r\n return `otpauth://totp/${issuer}:${accountName}?secret=${this.secretKey}&issuer=${issuer}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`;\r\n }\r\n}\r\n/** @internal */\r\nfunction _isEmptyString(input) {\r\n return typeof input === 'undefined' || (input === null || input === void 0 ? void 0 : input.length) === 0;\r\n}\n\nvar name = \"@firebase/auth\";\nvar version = \"1.7.5\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthInterop {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.internalListeners = new Map();\r\n }\r\n getUid() {\r\n var _a;\r\n this.assertAuthConfigured();\r\n return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;\r\n }\r\n async getToken(forceRefresh) {\r\n this.assertAuthConfigured();\r\n await this.auth._initializationPromise;\r\n if (!this.auth.currentUser) {\r\n return null;\r\n }\r\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\r\n return { accessToken };\r\n }\r\n addAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n if (this.internalListeners.has(listener)) {\r\n return;\r\n }\r\n const unsubscribe = this.auth.onIdTokenChanged(user => {\r\n listener((user === null || user === void 0 ? void 0 : user.stsTokenManager.accessToken) || null);\r\n });\r\n this.internalListeners.set(listener, unsubscribe);\r\n this.updateProactiveRefresh();\r\n }\r\n removeAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n const unsubscribe = this.internalListeners.get(listener);\r\n if (!unsubscribe) {\r\n return;\r\n }\r\n this.internalListeners.delete(listener);\r\n unsubscribe();\r\n this.updateProactiveRefresh();\r\n }\r\n assertAuthConfigured() {\r\n _assert(this.auth._initializationPromise, \"dependent-sdk-initialized-before-auth\" /* AuthErrorCode.DEPENDENT_SDK_INIT_BEFORE_AUTH */);\r\n }\r\n updateProactiveRefresh() {\r\n if (this.internalListeners.size > 0) {\r\n this.auth._startProactiveRefresh();\r\n }\r\n else {\r\n this.auth._stopProactiveRefresh();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getVersionForPlatform(clientPlatform) {\r\n switch (clientPlatform) {\r\n case \"Node\" /* ClientPlatform.NODE */:\r\n return 'node';\r\n case \"ReactNative\" /* ClientPlatform.REACT_NATIVE */:\r\n return 'rn';\r\n case \"Worker\" /* ClientPlatform.WORKER */:\r\n return 'webworker';\r\n case \"Cordova\" /* ClientPlatform.CORDOVA */:\r\n return 'cordova';\r\n case \"WebExtension\" /* ClientPlatform.WEB_EXTENSION */:\r\n return 'web-extension';\r\n default:\r\n return undefined;\r\n }\r\n}\r\n/** @internal */\r\nfunction registerAuth(clientPlatform) {\r\n _registerComponent(new Component(\"auth\" /* _ComponentName.AUTH */, (container, { options: deps }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const heartbeatServiceProvider = container.getProvider('heartbeat');\r\n const appCheckServiceProvider = container.getProvider('app-check-internal');\r\n const { apiKey, authDomain } = app.options;\r\n _assert(apiKey && !apiKey.includes(':'), \"invalid-api-key\" /* AuthErrorCode.INVALID_API_KEY */, { appName: app.name });\r\n const config = {\r\n apiKey,\r\n authDomain,\r\n clientPlatform,\r\n apiHost: \"identitytoolkit.googleapis.com\" /* DefaultConfig.API_HOST */,\r\n tokenApiHost: \"securetoken.googleapis.com\" /* DefaultConfig.TOKEN_API_HOST */,\r\n apiScheme: \"https\" /* DefaultConfig.API_SCHEME */,\r\n sdkClientVersion: _getClientVersion(clientPlatform)\r\n };\r\n const authInstance = new AuthImpl(app, heartbeatServiceProvider, appCheckServiceProvider, config);\r\n _initializeAuthInstance(authInstance, deps);\r\n return authInstance;\r\n }, \"PUBLIC\" /* ComponentType.PUBLIC */)\r\n /**\r\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\r\n * For why we do this, See go/firebase-next-auth-init\r\n */\r\n .setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */)\r\n /**\r\n * Because all firebase products that depend on auth depend on auth-internal directly,\r\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\r\n */\r\n .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {\r\n const authInternalProvider = container.getProvider(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */);\r\n authInternalProvider.initialize();\r\n }));\r\n _registerComponent(new Component(\"auth-internal\" /* _ComponentName.AUTH_INTERNAL */, container => {\r\n const auth = _castAuth(container.getProvider(\"auth\" /* _ComponentName.AUTH */).getImmediate());\r\n return (auth => new AuthInterop(auth))(auth);\r\n }, \"PRIVATE\" /* ComponentType.PRIVATE */).setInstantiationMode(\"EXPLICIT\" /* InstantiationMode.EXPLICIT */));\r\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_ID_TOKEN_MAX_AGE = 5 * 60;\r\nconst authIdTokenMaxAge = getExperimentalSetting('authIdTokenMaxAge') || DEFAULT_ID_TOKEN_MAX_AGE;\r\nlet lastPostedIdToken = null;\r\nconst mintCookieFactory = (url) => async (user) => {\r\n const idTokenResult = user && (await user.getIdTokenResult());\r\n const idTokenAge = idTokenResult &&\r\n (new Date().getTime() - Date.parse(idTokenResult.issuedAtTime)) / 1000;\r\n if (idTokenAge && idTokenAge > authIdTokenMaxAge) {\r\n return;\r\n }\r\n // Specifically trip null => undefined when logged out, to delete any existing cookie\r\n const idToken = idTokenResult === null || idTokenResult === void 0 ? void 0 : idTokenResult.token;\r\n if (lastPostedIdToken === idToken) {\r\n return;\r\n }\r\n lastPostedIdToken = idToken;\r\n await fetch(url, {\r\n method: idToken ? 'POST' : 'DELETE',\r\n headers: idToken\r\n ? {\r\n 'Authorization': `Bearer ${idToken}`\r\n }\r\n : {}\r\n });\r\n};\r\n/**\r\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\r\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\r\n *\r\n * @param app - The Firebase App.\r\n *\r\n * @public\r\n */\r\nfunction getAuth(app = getApp()) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n return provider.getImmediate();\r\n }\r\n const auth = initializeAuth(app, {\r\n popupRedirectResolver: browserPopupRedirectResolver,\r\n persistence: [\r\n indexedDBLocalPersistence,\r\n browserLocalPersistence,\r\n browserSessionPersistence\r\n ]\r\n });\r\n const authTokenSyncPath = getExperimentalSetting('authTokenSyncURL');\r\n // Only do the Cookie exchange in a secure context\r\n if (authTokenSyncPath &&\r\n typeof isSecureContext === 'boolean' &&\r\n isSecureContext) {\r\n // Don't allow urls (XSS possibility), only paths on the same domain\r\n const authTokenSyncUrl = new URL(authTokenSyncPath, location.origin);\r\n if (location.origin === authTokenSyncUrl.origin) {\r\n const mintCookie = mintCookieFactory(authTokenSyncUrl.toString());\r\n beforeAuthStateChanged(auth, mintCookie, () => mintCookie(auth.currentUser));\r\n onIdTokenChanged(auth, user => mintCookie(user));\r\n }\r\n }\r\n const authEmulatorHost = getDefaultEmulatorHost('auth');\r\n if (authEmulatorHost) {\r\n connectAuthEmulator(auth, `http://${authEmulatorHost}`);\r\n }\r\n return auth;\r\n}\r\nfunction getScriptParentElement() {\r\n var _a, _b;\r\n return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;\r\n}\r\n_setExternalJSProvider({\r\n loadJS(url) {\r\n // TODO: consider adding timeout support & cancellation\r\n return new Promise((resolve, reject) => {\r\n const el = document.createElement('script');\r\n el.setAttribute('src', url);\r\n el.onload = resolve;\r\n el.onerror = e => {\r\n const error = _createError(\"internal-error\" /* AuthErrorCode.INTERNAL_ERROR */);\r\n error.customData = e;\r\n reject(error);\r\n };\r\n el.type = 'text/javascript';\r\n el.charset = 'UTF-8';\r\n getScriptParentElement().appendChild(el);\r\n });\r\n },\r\n gapiScript: 'https://apis.google.com/js/api.js',\r\n recaptchaV2Script: 'https://www.google.com/recaptcha/api.js',\r\n recaptchaEnterpriseScript: 'https://www.google.com/recaptcha/enterprise.js?render='\r\n});\r\nregisterAuth(\"Browser\" /* ClientPlatform.BROWSER */);\n\nexport { TwitterAuthProvider as $, ActionCodeOperation as A, updateCurrentUser as B, signOut as C, revokeAccessToken as D, deleteUser as E, FactorId as F, debugErrorMap as G, prodErrorMap as H, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as I, initializeAuth as J, connectAuthEmulator as K, AuthCredential as L, EmailAuthCredential as M, OAuthCredential as N, OperationType as O, PhoneAuthProvider as P, PhoneAuthCredential as Q, RecaptchaVerifier as R, SignInMethod as S, TotpMultiFactorGenerator as T, inMemoryPersistence as U, EmailAuthProvider as V, FacebookAuthProvider as W, GoogleAuthProvider as X, GithubAuthProvider as Y, OAuthProvider as Z, SAMLAuthProvider as _, browserSessionPersistence as a, signInAnonymously as a0, signInWithCredential as a1, linkWithCredential as a2, reauthenticateWithCredential as a3, signInWithCustomToken as a4, sendPasswordResetEmail as a5, confirmPasswordReset as a6, applyActionCode as a7, checkActionCode as a8, verifyPasswordResetCode as a9, _isIOS7Or8 as aA, _createError as aB, _assert as aC, AuthEventManager as aD, _getInstance as aE, _persistenceKeyName as aF, _getRedirectResult as aG, _overrideRedirectResult as aH, _clearRedirectOutcomes as aI, _castAuth as aJ, UserImpl as aK, AuthImpl as aL, _getClientVersion as aM, _generateEventId as aN, AuthPopup as aO, FetchProvider as aP, SAMLAuthCredential as aQ, createUserWithEmailAndPassword as aa, signInWithEmailAndPassword as ab, sendSignInLinkToEmail as ac, isSignInWithEmailLink as ad, signInWithEmailLink as ae, fetchSignInMethodsForEmail as af, sendEmailVerification as ag, verifyBeforeUpdateEmail as ah, ActionCodeURL as ai, parseActionCodeURL as aj, updateProfile as ak, updateEmail as al, updatePassword as am, getIdToken as an, getIdTokenResult as ao, unlink as ap, getAdditionalUserInfo as aq, reload as ar, getMultiFactorResolver as as, multiFactor as at, debugAssert as au, _isIOS as av, _isAndroid as aw, _fail as ax, _getRedirectUrl as ay, _getProjectConfig as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, TotpSecret as n, getAuth as o, ProviderId as p, setPersistence as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, initializeRecaptchaConfig as t, updatePhoneNumber as u, validatePassword as v, onIdTokenChanged as w, beforeAuthStateChanged as x, onAuthStateChanged as y, useDeviceLanguage as z };\n//# sourceMappingURL=index-54738136.js.map\n","import { _getProvider, getApp, SDK_VERSION as SDK_VERSION$1, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component, ComponentContainer, Provider } from '@firebase/component';\nimport { stringify, jsonEval, contains, assert, isNodeSdk, stringToByteArray, Sha1, base64, deepCopy, base64Encode, isMobileCordova, stringLength, Deferred, safeGet, isAdmin, isValidFormat, isEmpty, isReactNative, assertionError, map, querystring, errorPrefix, getModularInstance, getDefaultEmulatorHostnameAndPort, createMockUserToken } from '@firebase/util';\nimport { Logger, LogLevel } from '@firebase/logger';\n\nconst name = \"@firebase/database\";\nconst version = \"1.0.6\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** The semver (www.semver.org) version of the SDK. */\r\nlet SDK_VERSION = '';\r\n/**\r\n * SDK_VERSION should be set before any database instance is created\r\n * @internal\r\n */\r\nfunction setSDKVersion(version) {\r\n SDK_VERSION = version;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Wraps a DOM Storage object and:\r\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\r\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\r\n *\r\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\r\n * and one for localStorage.\r\n *\r\n */\r\nclass DOMStorageWrapper {\r\n /**\r\n * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)\r\n */\r\n constructor(domStorage_) {\r\n this.domStorage_ = domStorage_;\r\n // Use a prefix to avoid collisions with other stuff saved by the app.\r\n this.prefix_ = 'firebase:';\r\n }\r\n /**\r\n * @param key - The key to save the value under\r\n * @param value - The value being stored, or null to remove the key.\r\n */\r\n set(key, value) {\r\n if (value == null) {\r\n this.domStorage_.removeItem(this.prefixedName_(key));\r\n }\r\n else {\r\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\r\n }\r\n }\r\n /**\r\n * @returns The value that was stored under this key, or null\r\n */\r\n get(key) {\r\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\r\n if (storedVal == null) {\r\n return null;\r\n }\r\n else {\r\n return jsonEval(storedVal);\r\n }\r\n }\r\n remove(key) {\r\n this.domStorage_.removeItem(this.prefixedName_(key));\r\n }\r\n prefixedName_(name) {\r\n return this.prefix_ + name;\r\n }\r\n toString() {\r\n return this.domStorage_.toString();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\r\n * (TODO: create interface for both to implement).\r\n */\r\nclass MemoryStorage {\r\n constructor() {\r\n this.cache_ = {};\r\n this.isInMemoryStorage = true;\r\n }\r\n set(key, value) {\r\n if (value == null) {\r\n delete this.cache_[key];\r\n }\r\n else {\r\n this.cache_[key] = value;\r\n }\r\n }\r\n get(key) {\r\n if (contains(this.cache_, key)) {\r\n return this.cache_[key];\r\n }\r\n return null;\r\n }\r\n remove(key) {\r\n delete this.cache_[key];\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\r\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\r\n * to reflect this type\r\n *\r\n * @param domStorageName - Name of the underlying storage object\r\n * (e.g. 'localStorage' or 'sessionStorage').\r\n * @returns Turning off type information until a common interface is defined.\r\n */\r\nconst createStoragefor = function (domStorageName) {\r\n try {\r\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\r\n // so it must be inside the try/catch.\r\n if (typeof window !== 'undefined' &&\r\n typeof window[domStorageName] !== 'undefined') {\r\n // Need to test cache. Just because it's here doesn't mean it works\r\n const domStorage = window[domStorageName];\r\n domStorage.setItem('firebase:sentinel', 'cache');\r\n domStorage.removeItem('firebase:sentinel');\r\n return new DOMStorageWrapper(domStorage);\r\n }\r\n }\r\n catch (e) { }\r\n // Failed to create wrapper. Just return in-memory storage.\r\n // TODO: log?\r\n return new MemoryStorage();\r\n};\r\n/** A storage object that lasts across sessions */\r\nconst PersistentStorage = createStoragefor('localStorage');\r\n/** A storage object that only lasts one session */\r\nconst SessionStorage = createStoragefor('sessionStorage');\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logClient = new Logger('@firebase/database');\r\n/**\r\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\r\n */\r\nconst LUIDGenerator = (function () {\r\n let id = 1;\r\n return function () {\r\n return id++;\r\n };\r\n})();\r\n/**\r\n * Sha1 hash of the input string\r\n * @param str - The string to hash\r\n * @returns {!string} The resulting hash\r\n */\r\nconst sha1 = function (str) {\r\n const utf8Bytes = stringToByteArray(str);\r\n const sha1 = new Sha1();\r\n sha1.update(utf8Bytes);\r\n const sha1Bytes = sha1.digest();\r\n return base64.encodeByteArray(sha1Bytes);\r\n};\r\nconst buildLogMessage_ = function (...varArgs) {\r\n let message = '';\r\n for (let i = 0; i < varArgs.length; i++) {\r\n const arg = varArgs[i];\r\n if (Array.isArray(arg) ||\r\n (arg &&\r\n typeof arg === 'object' &&\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n typeof arg.length === 'number')) {\r\n message += buildLogMessage_.apply(null, arg);\r\n }\r\n else if (typeof arg === 'object') {\r\n message += stringify(arg);\r\n }\r\n else {\r\n message += arg;\r\n }\r\n message += ' ';\r\n }\r\n return message;\r\n};\r\n/**\r\n * Use this for all debug messages in Firebase.\r\n */\r\nlet logger = null;\r\n/**\r\n * Flag to check for log availability on first log message\r\n */\r\nlet firstLog_ = true;\r\n/**\r\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\r\n * @param logger_ - A flag to turn on logging, or a custom logger\r\n * @param persistent - Whether or not to persist logging settings across refreshes\r\n */\r\nconst enableLogging$1 = function (logger_, persistent) {\r\n assert(!persistent || logger_ === true || logger_ === false, \"Can't turn on custom loggers persistently.\");\r\n if (logger_ === true) {\r\n logClient.logLevel = LogLevel.VERBOSE;\r\n logger = logClient.log.bind(logClient);\r\n if (persistent) {\r\n SessionStorage.set('logging_enabled', true);\r\n }\r\n }\r\n else if (typeof logger_ === 'function') {\r\n logger = logger_;\r\n }\r\n else {\r\n logger = null;\r\n SessionStorage.remove('logging_enabled');\r\n }\r\n};\r\nconst log = function (...varArgs) {\r\n if (firstLog_ === true) {\r\n firstLog_ = false;\r\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\r\n enableLogging$1(true);\r\n }\r\n }\r\n if (logger) {\r\n const message = buildLogMessage_.apply(null, varArgs);\r\n logger(message);\r\n }\r\n};\r\nconst logWrapper = function (prefix) {\r\n return function (...varArgs) {\r\n log(prefix, ...varArgs);\r\n };\r\n};\r\nconst error = function (...varArgs) {\r\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\r\n logClient.error(message);\r\n};\r\nconst fatal = function (...varArgs) {\r\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\r\n logClient.error(message);\r\n throw new Error(message);\r\n};\r\nconst warn = function (...varArgs) {\r\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\r\n logClient.warn(message);\r\n};\r\n/**\r\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\r\n * does not use https.\r\n */\r\nconst warnIfPageIsSecure = function () {\r\n // Be very careful accessing browser globals. Who knows what may or may not exist.\r\n if (typeof window !== 'undefined' &&\r\n window.location &&\r\n window.location.protocol &&\r\n window.location.protocol.indexOf('https:') !== -1) {\r\n warn('Insecure Firebase access from a secure page. ' +\r\n 'Please use https in calls to new Firebase().');\r\n }\r\n};\r\n/**\r\n * Returns true if data is NaN, or +/- Infinity.\r\n */\r\nconst isInvalidJSONNumber = function (data) {\r\n return (typeof data === 'number' &&\r\n (data !== data || // NaN\r\n data === Number.POSITIVE_INFINITY ||\r\n data === Number.NEGATIVE_INFINITY));\r\n};\r\nconst executeWhenDOMReady = function (fn) {\r\n if (isNodeSdk() || document.readyState === 'complete') {\r\n fn();\r\n }\r\n else {\r\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\r\n // fire before onload), but fall back to onload.\r\n let called = false;\r\n const wrappedFn = function () {\r\n if (!document.body) {\r\n setTimeout(wrappedFn, Math.floor(10));\r\n return;\r\n }\r\n if (!called) {\r\n called = true;\r\n fn();\r\n }\r\n };\r\n if (document.addEventListener) {\r\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\r\n // fallback to onload.\r\n window.addEventListener('load', wrappedFn, false);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (document.attachEvent) {\r\n // IE.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n document.attachEvent('onreadystatechange', () => {\r\n if (document.readyState === 'complete') {\r\n wrappedFn();\r\n }\r\n });\r\n // fallback to onload.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n window.attachEvent('onload', wrappedFn);\r\n // jQuery has an extra hack for IE that we could employ (based on\r\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\r\n // I'm hoping we don't need it.\r\n }\r\n }\r\n};\r\n/**\r\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\r\n */\r\nconst MIN_NAME = '[MIN_NAME]';\r\n/**\r\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\r\n */\r\nconst MAX_NAME = '[MAX_NAME]';\r\n/**\r\n * Compares valid Firebase key names, plus min and max name\r\n */\r\nconst nameCompare = function (a, b) {\r\n if (a === b) {\r\n return 0;\r\n }\r\n else if (a === MIN_NAME || b === MAX_NAME) {\r\n return -1;\r\n }\r\n else if (b === MIN_NAME || a === MAX_NAME) {\r\n return 1;\r\n }\r\n else {\r\n const aAsInt = tryParseInt(a), bAsInt = tryParseInt(b);\r\n if (aAsInt !== null) {\r\n if (bAsInt !== null) {\r\n return aAsInt - bAsInt === 0 ? a.length - b.length : aAsInt - bAsInt;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (bAsInt !== null) {\r\n return 1;\r\n }\r\n else {\r\n return a < b ? -1 : 1;\r\n }\r\n }\r\n};\r\n/**\r\n * @returns {!number} comparison result.\r\n */\r\nconst stringCompare = function (a, b) {\r\n if (a === b) {\r\n return 0;\r\n }\r\n else if (a < b) {\r\n return -1;\r\n }\r\n else {\r\n return 1;\r\n }\r\n};\r\nconst requireKey = function (key, obj) {\r\n if (obj && key in obj) {\r\n return obj[key];\r\n }\r\n else {\r\n throw new Error('Missing required key (' + key + ') in object: ' + stringify(obj));\r\n }\r\n};\r\nconst ObjectToUniqueKey = function (obj) {\r\n if (typeof obj !== 'object' || obj === null) {\r\n return stringify(obj);\r\n }\r\n const keys = [];\r\n // eslint-disable-next-line guard-for-in\r\n for (const k in obj) {\r\n keys.push(k);\r\n }\r\n // Export as json, but with the keys sorted.\r\n keys.sort();\r\n let key = '{';\r\n for (let i = 0; i < keys.length; i++) {\r\n if (i !== 0) {\r\n key += ',';\r\n }\r\n key += stringify(keys[i]);\r\n key += ':';\r\n key += ObjectToUniqueKey(obj[keys[i]]);\r\n }\r\n key += '}';\r\n return key;\r\n};\r\n/**\r\n * Splits a string into a number of smaller segments of maximum size\r\n * @param str - The string\r\n * @param segsize - The maximum number of chars in the string.\r\n * @returns The string, split into appropriately-sized chunks\r\n */\r\nconst splitStringBySize = function (str, segsize) {\r\n const len = str.length;\r\n if (len <= segsize) {\r\n return [str];\r\n }\r\n const dataSegs = [];\r\n for (let c = 0; c < len; c += segsize) {\r\n if (c + segsize > len) {\r\n dataSegs.push(str.substring(c, len));\r\n }\r\n else {\r\n dataSegs.push(str.substring(c, c + segsize));\r\n }\r\n }\r\n return dataSegs;\r\n};\r\n/**\r\n * Apply a function to each (key, value) pair in an object or\r\n * apply a function to each (index, value) pair in an array\r\n * @param obj - The object or array to iterate over\r\n * @param fn - The function to apply\r\n */\r\nfunction each(obj, fn) {\r\n for (const key in obj) {\r\n if (obj.hasOwnProperty(key)) {\r\n fn(key, obj[key]);\r\n }\r\n }\r\n}\r\n/**\r\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\r\n * I made one modification at the end and removed the NaN / Infinity\r\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\r\n * @param v - A double\r\n *\r\n */\r\nconst doubleToIEEE754String = function (v) {\r\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\r\n const ebits = 11, fbits = 52;\r\n const bias = (1 << (ebits - 1)) - 1;\r\n let s, e, f, ln, i;\r\n // Compute sign, exponent, fraction\r\n // Skip NaN / Infinity handling --MJL.\r\n if (v === 0) {\r\n e = 0;\r\n f = 0;\r\n s = 1 / v === -Infinity ? 1 : 0;\r\n }\r\n else {\r\n s = v < 0;\r\n v = Math.abs(v);\r\n if (v >= Math.pow(2, 1 - bias)) {\r\n // Normalized\r\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\r\n e = ln + bias;\r\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\r\n }\r\n else {\r\n // Denormalized\r\n e = 0;\r\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\r\n }\r\n }\r\n // Pack sign, exponent, fraction\r\n const bits = [];\r\n for (i = fbits; i; i -= 1) {\r\n bits.push(f % 2 ? 1 : 0);\r\n f = Math.floor(f / 2);\r\n }\r\n for (i = ebits; i; i -= 1) {\r\n bits.push(e % 2 ? 1 : 0);\r\n e = Math.floor(e / 2);\r\n }\r\n bits.push(s ? 1 : 0);\r\n bits.reverse();\r\n const str = bits.join('');\r\n // Return the data as a hex string. --MJL\r\n let hexByteString = '';\r\n for (i = 0; i < 64; i += 8) {\r\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\r\n if (hexByte.length === 1) {\r\n hexByte = '0' + hexByte;\r\n }\r\n hexByteString = hexByteString + hexByte;\r\n }\r\n return hexByteString.toLowerCase();\r\n};\r\n/**\r\n * Used to detect if we're in a Chrome content script (which executes in an\r\n * isolated environment where long-polling doesn't work).\r\n */\r\nconst isChromeExtensionContentScript = function () {\r\n return !!(typeof window === 'object' &&\r\n window['chrome'] &&\r\n window['chrome']['extension'] &&\r\n !/^chrome/.test(window.location.href));\r\n};\r\n/**\r\n * Used to detect if we're in a Windows 8 Store app.\r\n */\r\nconst isWindowsStoreApp = function () {\r\n // Check for the presence of a couple WinRT globals\r\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\r\n};\r\n/**\r\n * Converts a server error code to a Javascript Error\r\n */\r\nfunction errorForServerCode(code, query) {\r\n let reason = 'Unknown Error';\r\n if (code === 'too_big') {\r\n reason =\r\n 'The data requested exceeds the maximum size ' +\r\n 'that can be accessed with a single request.';\r\n }\r\n else if (code === 'permission_denied') {\r\n reason = \"Client doesn't have permission to access the desired data.\";\r\n }\r\n else if (code === 'unavailable') {\r\n reason = 'The service is unavailable';\r\n }\r\n const error = new Error(code + ' at ' + query._path.toString() + ': ' + reason);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n error.code = code.toUpperCase();\r\n return error;\r\n}\r\n/**\r\n * Used to test for integer-looking strings\r\n */\r\nconst INTEGER_REGEXP_ = new RegExp('^-?(0*)\\\\d{1,10}$');\r\n/**\r\n * For use in keys, the minimum possible 32-bit integer.\r\n */\r\nconst INTEGER_32_MIN = -2147483648;\r\n/**\r\n * For use in kyes, the maximum possible 32-bit integer.\r\n */\r\nconst INTEGER_32_MAX = 2147483647;\r\n/**\r\n * If the string contains a 32-bit integer, return it. Else return null.\r\n */\r\nconst tryParseInt = function (str) {\r\n if (INTEGER_REGEXP_.test(str)) {\r\n const intVal = Number(str);\r\n if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {\r\n return intVal;\r\n }\r\n }\r\n return null;\r\n};\r\n/**\r\n * Helper to run some code but catch any exceptions and re-throw them later.\r\n * Useful for preventing user callbacks from breaking internal code.\r\n *\r\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\r\n * convenient (we don't have to try to figure out when is a safe point to\r\n * re-throw it), and the behavior seems reasonable:\r\n *\r\n * * If you aren't pausing on exceptions, you get an error in the console with\r\n * the correct stack trace.\r\n * * If you're pausing on all exceptions, the debugger will pause on your\r\n * exception and then again when we rethrow it.\r\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\r\n * on us re-throwing it.\r\n *\r\n * @param fn - The code to guard.\r\n */\r\nconst exceptionGuard = function (fn) {\r\n try {\r\n fn();\r\n }\r\n catch (e) {\r\n // Re-throw exception when it's safe.\r\n setTimeout(() => {\r\n // It used to be that \"throw e\" would result in a good console error with\r\n // relevant context, but as of Chrome 39, you just get the firebase.js\r\n // file/line number where we re-throw it, which is useless. So we log\r\n // e.stack explicitly.\r\n const stack = e.stack || '';\r\n warn('Exception was thrown by user callback.', stack);\r\n throw e;\r\n }, Math.floor(0));\r\n }\r\n};\r\n/**\r\n * @returns {boolean} true if we think we're currently being crawled.\r\n */\r\nconst beingCrawled = function () {\r\n const userAgent = (typeof window === 'object' &&\r\n window['navigator'] &&\r\n window['navigator']['userAgent']) ||\r\n '';\r\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\r\n // believe to support JavaScript/AJAX rendering.\r\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\r\n // would have seen the page\" is flaky if we don't treat it as a crawler.\r\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\r\n};\r\n/**\r\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\r\n *\r\n * It is removed with clearTimeout() as normal.\r\n *\r\n * @param fn - Function to run.\r\n * @param time - Milliseconds to wait before running.\r\n * @returns The setTimeout() return value.\r\n */\r\nconst setTimeoutNonBlocking = function (fn, time) {\r\n const timeout = setTimeout(fn, time);\r\n // Note: at the time of this comment, unrefTimer is under the unstable set of APIs. Run with --unstable to enable the API.\r\n if (typeof timeout === 'number' &&\r\n // @ts-ignore Is only defined in Deno environments.\r\n typeof Deno !== 'undefined' &&\r\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\r\n Deno['unrefTimer']) {\r\n // @ts-ignore Deno and unrefTimer are only defined in Deno environments.\r\n Deno.unrefTimer(timeout);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (typeof timeout === 'object' && timeout['unref']) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n timeout['unref']();\r\n }\r\n return timeout;\r\n};\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Abstraction around AppCheck's token fetching capabilities.\r\n */\r\nclass AppCheckTokenProvider {\r\n constructor(appName_, appCheckProvider) {\r\n this.appName_ = appName_;\r\n this.appCheckProvider = appCheckProvider;\r\n this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });\r\n if (!this.appCheck) {\r\n appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck));\r\n }\r\n }\r\n getToken(forceRefresh) {\r\n if (!this.appCheck) {\r\n return new Promise((resolve, reject) => {\r\n // Support delayed initialization of FirebaseAppCheck. This allows our\r\n // customers to initialize the RTDB SDK before initializing Firebase\r\n // AppCheck and ensures that all requests are authenticated if a token\r\n // becomes available before the timoeout below expires.\r\n setTimeout(() => {\r\n if (this.appCheck) {\r\n this.getToken(forceRefresh).then(resolve, reject);\r\n }\r\n else {\r\n resolve(null);\r\n }\r\n }, 0);\r\n });\r\n }\r\n return this.appCheck.getToken(forceRefresh);\r\n }\r\n addTokenChangeListener(listener) {\r\n var _a;\r\n (_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener));\r\n }\r\n notifyForInvalidToken() {\r\n warn(`Provided AppCheck credentials for the app named \"${this.appName_}\" ` +\r\n 'are invalid. This usually indicates your app was not initialized correctly.');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Abstraction around FirebaseApp's token fetching capabilities.\r\n */\r\nclass FirebaseAuthTokenProvider {\r\n constructor(appName_, firebaseOptions_, authProvider_) {\r\n this.appName_ = appName_;\r\n this.firebaseOptions_ = firebaseOptions_;\r\n this.authProvider_ = authProvider_;\r\n this.auth_ = null;\r\n this.auth_ = authProvider_.getImmediate({ optional: true });\r\n if (!this.auth_) {\r\n authProvider_.onInit(auth => (this.auth_ = auth));\r\n }\r\n }\r\n getToken(forceRefresh) {\r\n if (!this.auth_) {\r\n return new Promise((resolve, reject) => {\r\n // Support delayed initialization of FirebaseAuth. This allows our\r\n // customers to initialize the RTDB SDK before initializing Firebase\r\n // Auth and ensures that all requests are authenticated if a token\r\n // becomes available before the timoeout below expires.\r\n setTimeout(() => {\r\n if (this.auth_) {\r\n this.getToken(forceRefresh).then(resolve, reject);\r\n }\r\n else {\r\n resolve(null);\r\n }\r\n }, 0);\r\n });\r\n }\r\n return this.auth_.getToken(forceRefresh).catch(error => {\r\n // TODO: Need to figure out all the cases this is raised and whether\r\n // this makes sense.\r\n if (error && error.code === 'auth/token-not-initialized') {\r\n log('Got auth/token-not-initialized error. Treating as null token.');\r\n return null;\r\n }\r\n else {\r\n return Promise.reject(error);\r\n }\r\n });\r\n }\r\n addTokenChangeListener(listener) {\r\n // TODO: We might want to wrap the listener and call it with no args to\r\n // avoid a leaky abstraction, but that makes removing the listener harder.\r\n if (this.auth_) {\r\n this.auth_.addAuthTokenListener(listener);\r\n }\r\n else {\r\n this.authProvider_\r\n .get()\r\n .then(auth => auth.addAuthTokenListener(listener));\r\n }\r\n }\r\n removeTokenChangeListener(listener) {\r\n this.authProvider_\r\n .get()\r\n .then(auth => auth.removeAuthTokenListener(listener));\r\n }\r\n notifyForInvalidToken() {\r\n let errorMessage = 'Provided authentication credentials for the app named \"' +\r\n this.appName_ +\r\n '\" are invalid. This usually indicates your app was not ' +\r\n 'initialized correctly. ';\r\n if ('credential' in this.firebaseOptions_) {\r\n errorMessage +=\r\n 'Make sure the \"credential\" property provided to initializeApp() ' +\r\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\r\n 'project.';\r\n }\r\n else if ('serviceAccount' in this.firebaseOptions_) {\r\n errorMessage +=\r\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\r\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\r\n 'project.';\r\n }\r\n else {\r\n errorMessage +=\r\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\r\n 'initializeApp() match the values provided for your app at ' +\r\n 'https://console.firebase.google.com/.';\r\n }\r\n warn(errorMessage);\r\n }\r\n}\r\n/* AuthTokenProvider that supplies a constant token. Used by Admin SDK or mockUserToken with emulators. */\r\nclass EmulatorTokenProvider {\r\n constructor(accessToken) {\r\n this.accessToken = accessToken;\r\n }\r\n getToken(forceRefresh) {\r\n return Promise.resolve({\r\n accessToken: this.accessToken\r\n });\r\n }\r\n addTokenChangeListener(listener) {\r\n // Invoke the listener immediately to match the behavior in Firebase Auth\r\n // (see packages/auth/src/auth.js#L1807)\r\n listener(this.accessToken);\r\n }\r\n removeTokenChangeListener(listener) { }\r\n notifyForInvalidToken() { }\r\n}\r\n/** A string that is treated as an admin access token by the RTDB emulator. Used by Admin SDK. */\r\nEmulatorTokenProvider.OWNER = 'owner';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PROTOCOL_VERSION = '5';\r\nconst VERSION_PARAM = 'v';\r\nconst TRANSPORT_SESSION_PARAM = 's';\r\nconst REFERER_PARAM = 'r';\r\nconst FORGE_REF = 'f';\r\n// Matches console.firebase.google.com, firebase-console-*.corp.google.com and\r\n// firebase.corp.google.com\r\nconst FORGE_DOMAIN_RE = /(console\\.firebase|firebase-console-\\w+\\.corp|firebase\\.corp)\\.google\\.com/;\r\nconst LAST_SESSION_PARAM = 'ls';\r\nconst APPLICATION_ID_PARAM = 'p';\r\nconst APP_CHECK_TOKEN_PARAM = 'ac';\r\nconst WEBSOCKET = 'websocket';\r\nconst LONG_POLLING = 'long_polling';\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A class that holds metadata about a Repo object\r\n */\r\nclass RepoInfo {\r\n /**\r\n * @param host - Hostname portion of the url for the repo\r\n * @param secure - Whether or not this repo is accessed over ssl\r\n * @param namespace - The namespace represented by the repo\r\n * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).\r\n * @param nodeAdmin - Whether this instance uses Admin SDK credentials\r\n * @param persistenceKey - Override the default session persistence storage key\r\n */\r\n constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = '', includeNamespaceInQueryParams = false, isUsingEmulator = false) {\r\n this.secure = secure;\r\n this.namespace = namespace;\r\n this.webSocketOnly = webSocketOnly;\r\n this.nodeAdmin = nodeAdmin;\r\n this.persistenceKey = persistenceKey;\r\n this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;\r\n this.isUsingEmulator = isUsingEmulator;\r\n this._host = host.toLowerCase();\r\n this._domain = this._host.substr(this._host.indexOf('.') + 1);\r\n this.internalHost =\r\n PersistentStorage.get('host:' + host) || this._host;\r\n }\r\n isCacheableHost() {\r\n return this.internalHost.substr(0, 2) === 's-';\r\n }\r\n isCustomHost() {\r\n return (this._domain !== 'firebaseio.com' &&\r\n this._domain !== 'firebaseio-demo.com');\r\n }\r\n get host() {\r\n return this._host;\r\n }\r\n set host(newHost) {\r\n if (newHost !== this.internalHost) {\r\n this.internalHost = newHost;\r\n if (this.isCacheableHost()) {\r\n PersistentStorage.set('host:' + this._host, this.internalHost);\r\n }\r\n }\r\n }\r\n toString() {\r\n let str = this.toURLString();\r\n if (this.persistenceKey) {\r\n str += '<' + this.persistenceKey + '>';\r\n }\r\n return str;\r\n }\r\n toURLString() {\r\n const protocol = this.secure ? 'https://' : 'http://';\r\n const query = this.includeNamespaceInQueryParams\r\n ? `?ns=${this.namespace}`\r\n : '';\r\n return `${protocol}${this.host}/${query}`;\r\n }\r\n}\r\nfunction repoInfoNeedsQueryParam(repoInfo) {\r\n return (repoInfo.host !== repoInfo.internalHost ||\r\n repoInfo.isCustomHost() ||\r\n repoInfo.includeNamespaceInQueryParams);\r\n}\r\n/**\r\n * Returns the websocket URL for this repo\r\n * @param repoInfo - RepoInfo object\r\n * @param type - of connection\r\n * @param params - list\r\n * @returns The URL for this repo\r\n */\r\nfunction repoInfoConnectionURL(repoInfo, type, params) {\r\n assert(typeof type === 'string', 'typeof type must == string');\r\n assert(typeof params === 'object', 'typeof params must == object');\r\n let connURL;\r\n if (type === WEBSOCKET) {\r\n connURL =\r\n (repoInfo.secure ? 'wss://' : 'ws://') + repoInfo.internalHost + '/.ws?';\r\n }\r\n else if (type === LONG_POLLING) {\r\n connURL =\r\n (repoInfo.secure ? 'https://' : 'http://') +\r\n repoInfo.internalHost +\r\n '/.lp?';\r\n }\r\n else {\r\n throw new Error('Unknown connection type: ' + type);\r\n }\r\n if (repoInfoNeedsQueryParam(repoInfo)) {\r\n params['ns'] = repoInfo.namespace;\r\n }\r\n const pairs = [];\r\n each(params, (key, value) => {\r\n pairs.push(key + '=' + value);\r\n });\r\n return connURL + pairs.join('&');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Tracks a collection of stats.\r\n */\r\nclass StatsCollection {\r\n constructor() {\r\n this.counters_ = {};\r\n }\r\n incrementCounter(name, amount = 1) {\r\n if (!contains(this.counters_, name)) {\r\n this.counters_[name] = 0;\r\n }\r\n this.counters_[name] += amount;\r\n }\r\n get() {\r\n return deepCopy(this.counters_);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst collections = {};\r\nconst reporters = {};\r\nfunction statsManagerGetCollection(repoInfo) {\r\n const hashString = repoInfo.toString();\r\n if (!collections[hashString]) {\r\n collections[hashString] = new StatsCollection();\r\n }\r\n return collections[hashString];\r\n}\r\nfunction statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {\r\n const hashString = repoInfo.toString();\r\n if (!reporters[hashString]) {\r\n reporters[hashString] = creatorFunction();\r\n }\r\n return reporters[hashString];\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class ensures the packets from the server arrive in order\r\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\r\n */\r\nclass PacketReceiver {\r\n /**\r\n * @param onMessage_\r\n */\r\n constructor(onMessage_) {\r\n this.onMessage_ = onMessage_;\r\n this.pendingResponses = [];\r\n this.currentResponseNum = 0;\r\n this.closeAfterResponse = -1;\r\n this.onClose = null;\r\n }\r\n closeAfter(responseNum, callback) {\r\n this.closeAfterResponse = responseNum;\r\n this.onClose = callback;\r\n if (this.closeAfterResponse < this.currentResponseNum) {\r\n this.onClose();\r\n this.onClose = null;\r\n }\r\n }\r\n /**\r\n * Each message from the server comes with a response number, and an array of data. The responseNumber\r\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\r\n * browsers will respond in the same order as the requests we sent\r\n */\r\n handleResponse(requestNum, data) {\r\n this.pendingResponses[requestNum] = data;\r\n while (this.pendingResponses[this.currentResponseNum]) {\r\n const toProcess = this.pendingResponses[this.currentResponseNum];\r\n delete this.pendingResponses[this.currentResponseNum];\r\n for (let i = 0; i < toProcess.length; ++i) {\r\n if (toProcess[i]) {\r\n exceptionGuard(() => {\r\n this.onMessage_(toProcess[i]);\r\n });\r\n }\r\n }\r\n if (this.currentResponseNum === this.closeAfterResponse) {\r\n if (this.onClose) {\r\n this.onClose();\r\n this.onClose = null;\r\n }\r\n break;\r\n }\r\n this.currentResponseNum++;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// URL query parameters associated with longpolling\r\nconst FIREBASE_LONGPOLL_START_PARAM = 'start';\r\nconst FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\r\nconst FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\r\nconst FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\r\nconst FIREBASE_LONGPOLL_ID_PARAM = 'id';\r\nconst FIREBASE_LONGPOLL_PW_PARAM = 'pw';\r\nconst FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\r\nconst FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\r\nconst FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\r\nconst FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\r\nconst FIREBASE_LONGPOLL_DATA_PARAM = 'd';\r\nconst FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\r\n//Data size constants.\r\n//TODO: Perf: the maximum length actually differs from browser to browser.\r\n// We should check what browser we're on and set accordingly.\r\nconst MAX_URL_DATA_SIZE = 1870;\r\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\r\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\r\n/**\r\n * Keepalive period\r\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\r\n * length of 30 seconds that we can't exceed.\r\n */\r\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\r\n/**\r\n * How long to wait before aborting a long-polling connection attempt.\r\n */\r\nconst LP_CONNECT_TIMEOUT = 30000;\r\n/**\r\n * This class manages a single long-polling connection.\r\n */\r\nclass BrowserPollConnection {\r\n /**\r\n * @param connId An identifier for this connection, used for logging\r\n * @param repoInfo The info for the endpoint to send data to.\r\n * @param applicationId The Firebase App ID for this project.\r\n * @param appCheckToken The AppCheck token for this client.\r\n * @param authToken The AuthToken to use for this connection.\r\n * @param transportSessionId Optional transportSessionid if we are\r\n * reconnecting for an existing transport session\r\n * @param lastSessionId Optional lastSessionId if the PersistentConnection has\r\n * already created a connection previously\r\n */\r\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.repoInfo = repoInfo;\r\n this.applicationId = applicationId;\r\n this.appCheckToken = appCheckToken;\r\n this.authToken = authToken;\r\n this.transportSessionId = transportSessionId;\r\n this.lastSessionId = lastSessionId;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.everConnected_ = false;\r\n this.log_ = logWrapper(connId);\r\n this.stats_ = statsManagerGetCollection(repoInfo);\r\n this.urlFn = (params) => {\r\n // Always add the token if we have one.\r\n if (this.appCheckToken) {\r\n params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\r\n }\r\n return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);\r\n };\r\n }\r\n /**\r\n * @param onMessage - Callback when messages arrive\r\n * @param onDisconnect - Callback with connection lost.\r\n */\r\n open(onMessage, onDisconnect) {\r\n this.curSegmentNum = 0;\r\n this.onDisconnect_ = onDisconnect;\r\n this.myPacketOrderer = new PacketReceiver(onMessage);\r\n this.isClosed_ = false;\r\n this.connectTimeoutTimer_ = setTimeout(() => {\r\n this.log_('Timed out trying to connect.');\r\n // Make sure we clear the host cache\r\n this.onClosed_();\r\n this.connectTimeoutTimer_ = null;\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(LP_CONNECT_TIMEOUT));\r\n // Ensure we delay the creation of the iframe until the DOM is loaded.\r\n executeWhenDOMReady(() => {\r\n if (this.isClosed_) {\r\n return;\r\n }\r\n //Set up a callback that gets triggered once a connection is set up.\r\n this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {\r\n const [command, arg1, arg2, arg3, arg4] = args;\r\n this.incrementIncomingBytes_(args);\r\n if (!this.scriptTagHolder) {\r\n return; // we closed the connection.\r\n }\r\n if (this.connectTimeoutTimer_) {\r\n clearTimeout(this.connectTimeoutTimer_);\r\n this.connectTimeoutTimer_ = null;\r\n }\r\n this.everConnected_ = true;\r\n if (command === FIREBASE_LONGPOLL_START_PARAM) {\r\n this.id = arg1;\r\n this.password = arg2;\r\n }\r\n else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {\r\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\r\n if (arg1) {\r\n // We aren't expecting any more data (other than what the server's already in the process of sending us\r\n // through our already open polls), so don't send any more.\r\n this.scriptTagHolder.sendNewPolls = false;\r\n // arg1 in this case is the last response number sent by the server. We should try to receive\r\n // all of the responses up to this one before closing\r\n this.myPacketOrderer.closeAfter(arg1, () => {\r\n this.onClosed_();\r\n });\r\n }\r\n else {\r\n this.onClosed_();\r\n }\r\n }\r\n else {\r\n throw new Error('Unrecognized command received: ' + command);\r\n }\r\n }, (...args) => {\r\n const [pN, data] = args;\r\n this.incrementIncomingBytes_(args);\r\n this.myPacketOrderer.handleResponse(pN, data);\r\n }, () => {\r\n this.onClosed_();\r\n }, this.urlFn);\r\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\r\n //from cache.\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\r\n if (this.scriptTagHolder.uniqueCallbackIdentifier) {\r\n urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] =\r\n this.scriptTagHolder.uniqueCallbackIdentifier;\r\n }\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (this.transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\r\n }\r\n if (this.lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\r\n }\r\n if (this.applicationId) {\r\n urlParams[APPLICATION_ID_PARAM] = this.applicationId;\r\n }\r\n if (this.appCheckToken) {\r\n urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;\r\n }\r\n if (typeof location !== 'undefined' &&\r\n location.hostname &&\r\n FORGE_DOMAIN_RE.test(location.hostname)) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n const connectURL = this.urlFn(urlParams);\r\n this.log_('Connecting via long-poll to ' + connectURL);\r\n this.scriptTagHolder.addTag(connectURL, () => {\r\n /* do nothing */\r\n });\r\n });\r\n }\r\n /**\r\n * Call this when a handshake has completed successfully and we want to consider the connection established\r\n */\r\n start() {\r\n this.scriptTagHolder.startLongPoll(this.id, this.password);\r\n this.addDisconnectPingFrame(this.id, this.password);\r\n }\r\n /**\r\n * Forces long polling to be considered as a potential transport\r\n */\r\n static forceAllow() {\r\n BrowserPollConnection.forceAllow_ = true;\r\n }\r\n /**\r\n * Forces longpolling to not be considered as a potential transport\r\n */\r\n static forceDisallow() {\r\n BrowserPollConnection.forceDisallow_ = true;\r\n }\r\n // Static method, use string literal so it can be accessed in a generic way\r\n static isAvailable() {\r\n if (isNodeSdk()) {\r\n return false;\r\n }\r\n else if (BrowserPollConnection.forceAllow_) {\r\n return true;\r\n }\r\n else {\r\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\r\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\r\n return (!BrowserPollConnection.forceDisallow_ &&\r\n typeof document !== 'undefined' &&\r\n document.createElement != null &&\r\n !isChromeExtensionContentScript() &&\r\n !isWindowsStoreApp());\r\n }\r\n }\r\n /**\r\n * No-op for polling\r\n */\r\n markConnectionHealthy() { }\r\n /**\r\n * Stops polling and cleans up the iframe\r\n */\r\n shutdown_() {\r\n this.isClosed_ = true;\r\n if (this.scriptTagHolder) {\r\n this.scriptTagHolder.close();\r\n this.scriptTagHolder = null;\r\n }\r\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\r\n if (this.myDisconnFrame) {\r\n document.body.removeChild(this.myDisconnFrame);\r\n this.myDisconnFrame = null;\r\n }\r\n if (this.connectTimeoutTimer_) {\r\n clearTimeout(this.connectTimeoutTimer_);\r\n this.connectTimeoutTimer_ = null;\r\n }\r\n }\r\n /**\r\n * Triggered when this transport is closed\r\n */\r\n onClosed_() {\r\n if (!this.isClosed_) {\r\n this.log_('Longpoll is closing itself');\r\n this.shutdown_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_(this.everConnected_);\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n }\r\n /**\r\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\r\n * that we've left.\r\n */\r\n close() {\r\n if (!this.isClosed_) {\r\n this.log_('Longpoll is being closed.');\r\n this.shutdown_();\r\n }\r\n }\r\n /**\r\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\r\n * broken into chunks (since URLs have a small maximum length).\r\n * @param data - The JSON data to transmit.\r\n */\r\n send(data) {\r\n const dataStr = stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //first, lets get the base64-encoded data\r\n const base64data = base64Encode(dataStr);\r\n //We can only fit a certain amount in each URL, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\r\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\r\n //of segments so that we can reassemble the packet on the server.\r\n for (let i = 0; i < dataSegs.length; i++) {\r\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\r\n this.curSegmentNum++;\r\n }\r\n }\r\n /**\r\n * This is how we notify the server that we're leaving.\r\n * We aren't able to send requests with DHTML on a window close event, but we can\r\n * trigger XHR requests in some browsers (everything but Opera basically).\r\n */\r\n addDisconnectPingFrame(id, pw) {\r\n if (isNodeSdk()) {\r\n return;\r\n }\r\n this.myDisconnFrame = document.createElement('iframe');\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\r\n this.myDisconnFrame.src = this.urlFn(urlParams);\r\n this.myDisconnFrame.style.display = 'none';\r\n document.body.appendChild(this.myDisconnFrame);\r\n }\r\n /**\r\n * Used to track the bytes received by this client\r\n */\r\n incrementIncomingBytes_(args) {\r\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\r\n const bytesReceived = stringify(args).length;\r\n this.bytesReceived += bytesReceived;\r\n this.stats_.incrementCounter('bytes_received', bytesReceived);\r\n }\r\n}\r\n/*********************************************************************************************\r\n * A wrapper around an iframe that is used as a long-polling script holder.\r\n *********************************************************************************************/\r\nclass FirebaseIFrameScriptHolder {\r\n /**\r\n * @param commandCB - The callback to be called when control commands are recevied from the server.\r\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\r\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\r\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\r\n */\r\n constructor(commandCB, onMessageCB, onDisconnect, urlFn) {\r\n this.onDisconnect = onDisconnect;\r\n this.urlFn = urlFn;\r\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\r\n //problems in some browsers.\r\n this.outstandingRequests = new Set();\r\n //A queue of the pending segments waiting for transmission to the server.\r\n this.pendingSegs = [];\r\n //A serial number. We use this for two things:\r\n // 1) A way to ensure the browser doesn't cache responses to polls\r\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\r\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\r\n // JSONP code in the order it was added to the iframe.\r\n this.currentSerial = Math.floor(Math.random() * 100000000);\r\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\r\n // incoming data from the server that we're waiting for).\r\n this.sendNewPolls = true;\r\n if (!isNodeSdk()) {\r\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\r\n //iframes where we put the long-polling script tags. We have two callbacks:\r\n // 1) Command Callback - Triggered for control issues, like starting a connection.\r\n // 2) Message Callback - Triggered when new data arrives.\r\n this.uniqueCallbackIdentifier = LUIDGenerator();\r\n window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\r\n window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] =\r\n onMessageCB;\r\n //Create an iframe for us to add script tags to.\r\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\r\n // Set the iframe's contents.\r\n let script = '';\r\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\r\n // for ie9, but ie8 needs to do it again in the document itself.\r\n if (this.myIFrame.src &&\r\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\r\n const currentDomain = document.domain;\r\n script = '';\r\n }\r\n const iframeContents = '' + script + '';\r\n try {\r\n this.myIFrame.doc.open();\r\n this.myIFrame.doc.write(iframeContents);\r\n this.myIFrame.doc.close();\r\n }\r\n catch (e) {\r\n log('frame writing exception');\r\n if (e.stack) {\r\n log(e.stack);\r\n }\r\n log(e);\r\n }\r\n }\r\n else {\r\n this.commandCB = commandCB;\r\n this.onMessageCB = onMessageCB;\r\n }\r\n }\r\n /**\r\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\r\n * actually use.\r\n */\r\n static createIFrame_() {\r\n const iframe = document.createElement('iframe');\r\n iframe.style.display = 'none';\r\n // This is necessary in order to initialize the document inside the iframe\r\n if (document.body) {\r\n document.body.appendChild(iframe);\r\n try {\r\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\r\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\r\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\r\n const a = iframe.contentWindow.document;\r\n if (!a) {\r\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\r\n log('No IE domain setting required');\r\n }\r\n }\r\n catch (e) {\r\n const domain = document.domain;\r\n iframe.src =\r\n \"javascript:void((function(){document.open();document.domain='\" +\r\n domain +\r\n \"';document.close();})())\";\r\n }\r\n }\r\n else {\r\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\r\n // never gets hit.\r\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\r\n }\r\n // Get the document of the iframe in a browser-specific way.\r\n if (iframe.contentDocument) {\r\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\r\n }\r\n else if (iframe.contentWindow) {\r\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (iframe.document) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n iframe.doc = iframe.document; //others?\r\n }\r\n return iframe;\r\n }\r\n /**\r\n * Cancel all outstanding queries and remove the frame.\r\n */\r\n close() {\r\n //Mark this iframe as dead, so no new requests are sent.\r\n this.alive = false;\r\n if (this.myIFrame) {\r\n //We have to actually remove all of the html inside this iframe before removing it from the\r\n //window, or IE will continue loading and executing the script tags we've already added, which\r\n //can lead to some errors being thrown. Setting textContent seems to be the safest way to do this.\r\n this.myIFrame.doc.body.textContent = '';\r\n setTimeout(() => {\r\n if (this.myIFrame !== null) {\r\n document.body.removeChild(this.myIFrame);\r\n this.myIFrame = null;\r\n }\r\n }, Math.floor(0));\r\n }\r\n // Protect from being called recursively.\r\n const onDisconnect = this.onDisconnect;\r\n if (onDisconnect) {\r\n this.onDisconnect = null;\r\n onDisconnect();\r\n }\r\n }\r\n /**\r\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\r\n * @param id - The ID of this connection\r\n * @param pw - The password for this connection\r\n */\r\n startLongPoll(id, pw) {\r\n this.myID = id;\r\n this.myPW = pw;\r\n this.alive = true;\r\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\r\n while (this.newRequest_()) { }\r\n }\r\n /**\r\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\r\n * too many outstanding requests and we are still alive.\r\n *\r\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\r\n * needed.\r\n */\r\n newRequest_() {\r\n // We keep one outstanding request open all the time to receive data, but if we need to send data\r\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\r\n // close the old request.\r\n if (this.alive &&\r\n this.sendNewPolls &&\r\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {\r\n //construct our url\r\n this.currentSerial++;\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\r\n let theURL = this.urlFn(urlParams);\r\n //Now add as much data as we can.\r\n let curDataString = '';\r\n let i = 0;\r\n while (this.pendingSegs.length > 0) {\r\n //first, lets see if the next segment will fit.\r\n const nextSeg = this.pendingSegs[0];\r\n if (nextSeg.d.length +\r\n SEG_HEADER_SIZE +\r\n curDataString.length <=\r\n MAX_URL_DATA_SIZE) {\r\n //great, the segment will fit. Lets append it.\r\n const theSeg = this.pendingSegs.shift();\r\n curDataString =\r\n curDataString +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\r\n i +\r\n '=' +\r\n theSeg.seg +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\r\n i +\r\n '=' +\r\n theSeg.ts +\r\n '&' +\r\n FIREBASE_LONGPOLL_DATA_PARAM +\r\n i +\r\n '=' +\r\n theSeg.d;\r\n i++;\r\n }\r\n else {\r\n break;\r\n }\r\n }\r\n theURL = theURL + curDataString;\r\n this.addLongPollTag_(theURL, this.currentSerial);\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n /**\r\n * Queue a packet for transmission to the server.\r\n * @param segnum - A sequential id for this packet segment used for reassembly\r\n * @param totalsegs - The total number of segments in this packet\r\n * @param data - The data for this segment.\r\n */\r\n enqueueSegment(segnum, totalsegs, data) {\r\n //add this to the queue of segments to send.\r\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\r\n //send the data immediately if there isn't already data being transmitted, unless\r\n //startLongPoll hasn't been called yet.\r\n if (this.alive) {\r\n this.newRequest_();\r\n }\r\n }\r\n /**\r\n * Add a script tag for a regular long-poll request.\r\n * @param url - The URL of the script tag.\r\n * @param serial - The serial number of the request.\r\n */\r\n addLongPollTag_(url, serial) {\r\n //remember that we sent this request.\r\n this.outstandingRequests.add(serial);\r\n const doNewRequest = () => {\r\n this.outstandingRequests.delete(serial);\r\n this.newRequest_();\r\n };\r\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\r\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\r\n const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\r\n const readyStateCB = () => {\r\n // Request completed. Cancel the keepalive.\r\n clearTimeout(keepaliveTimeout);\r\n // Trigger a new request so we can continue receiving data.\r\n doNewRequest();\r\n };\r\n this.addTag(url, readyStateCB);\r\n }\r\n /**\r\n * Add an arbitrary script tag to the iframe.\r\n * @param url - The URL for the script tag source.\r\n * @param loadCB - A callback to be triggered once the script has loaded.\r\n */\r\n addTag(url, loadCB) {\r\n if (isNodeSdk()) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.doNodeLongPoll(url, loadCB);\r\n }\r\n else {\r\n setTimeout(() => {\r\n try {\r\n // if we're already closed, don't add this poll\r\n if (!this.sendNewPolls) {\r\n return;\r\n }\r\n const newScript = this.myIFrame.doc.createElement('script');\r\n newScript.type = 'text/javascript';\r\n newScript.async = true;\r\n newScript.src = url;\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange =\r\n function () {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const rstate = newScript.readyState;\r\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange = null;\r\n if (newScript.parentNode) {\r\n newScript.parentNode.removeChild(newScript);\r\n }\r\n loadCB();\r\n }\r\n };\r\n newScript.onerror = () => {\r\n log('Long-poll script failed to load: ' + url);\r\n this.sendNewPolls = false;\r\n this.close();\r\n };\r\n this.myIFrame.doc.body.appendChild(newScript);\r\n }\r\n catch (e) {\r\n // TODO: we should make this error visible somehow\r\n }\r\n }, Math.floor(1));\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\r\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\r\nlet WebSocketImpl = null;\r\nif (typeof MozWebSocket !== 'undefined') {\r\n WebSocketImpl = MozWebSocket;\r\n}\r\nelse if (typeof WebSocket !== 'undefined') {\r\n WebSocketImpl = WebSocket;\r\n}\r\n/**\r\n * Create a new websocket connection with the given callbacks.\r\n */\r\nclass WebSocketConnection {\r\n /**\r\n * @param connId identifier for this transport\r\n * @param repoInfo The info for the websocket endpoint.\r\n * @param applicationId The Firebase App ID for this project.\r\n * @param appCheckToken The App Check Token for this client.\r\n * @param authToken The Auth Token for this client.\r\n * @param transportSessionId Optional transportSessionId if this is connecting\r\n * to an existing transport session\r\n * @param lastSessionId Optional lastSessionId if there was a previous\r\n * connection\r\n */\r\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.applicationId = applicationId;\r\n this.appCheckToken = appCheckToken;\r\n this.authToken = authToken;\r\n this.keepaliveTimer = null;\r\n this.frames = null;\r\n this.totalFrames = 0;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.log_ = logWrapper(this.connId);\r\n this.stats_ = statsManagerGetCollection(repoInfo);\r\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);\r\n this.nodeAdmin = repoInfo.nodeAdmin;\r\n }\r\n /**\r\n * @param repoInfo - The info for the websocket endpoint.\r\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\r\n * @returns connection url\r\n */\r\n static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {\r\n const urlParams = {};\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (!isNodeSdk() &&\r\n typeof location !== 'undefined' &&\r\n location.hostname &&\r\n FORGE_DOMAIN_RE.test(location.hostname)) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n if (transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\r\n }\r\n if (lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\r\n }\r\n if (appCheckToken) {\r\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\r\n }\r\n if (applicationId) {\r\n urlParams[APPLICATION_ID_PARAM] = applicationId;\r\n }\r\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\r\n }\r\n /**\r\n * @param onMessage - Callback when messages arrive\r\n * @param onDisconnect - Callback with connection lost.\r\n */\r\n open(onMessage, onDisconnect) {\r\n this.onDisconnect = onDisconnect;\r\n this.onMessage = onMessage;\r\n this.log_('Websocket connecting to ' + this.connURL);\r\n this.everConnected_ = false;\r\n // Assume failure until proven otherwise.\r\n PersistentStorage.set('previous_websocket_failure', true);\r\n try {\r\n let options;\r\n if (isNodeSdk()) {\r\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\r\n // UA Format: Firebase////\r\n options = {\r\n headers: {\r\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\r\n 'X-Firebase-GMPID': this.applicationId || ''\r\n }\r\n };\r\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\r\n // Note that we send the credentials here even if they aren't admin credentials, which is\r\n // not a problem.\r\n // Note that this header is just used to bypass appcheck, and the token should still be sent\r\n // through the websocket connection once it is established.\r\n if (this.authToken) {\r\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\r\n }\r\n if (this.appCheckToken) {\r\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\r\n }\r\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\r\n const env = process['env'];\r\n const proxy = this.connURL.indexOf('wss://') === 0\r\n ? env['HTTPS_PROXY'] || env['https_proxy']\r\n : env['HTTP_PROXY'] || env['http_proxy'];\r\n if (proxy) {\r\n options['proxy'] = { origin: proxy };\r\n }\r\n }\r\n this.mySock = new WebSocketImpl(this.connURL, [], options);\r\n }\r\n catch (e) {\r\n this.log_('Error instantiating WebSocket.');\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n return;\r\n }\r\n this.mySock.onopen = () => {\r\n this.log_('Websocket connected.');\r\n this.everConnected_ = true;\r\n };\r\n this.mySock.onclose = () => {\r\n this.log_('Websocket connection was disconnected.');\r\n this.mySock = null;\r\n this.onClosed_();\r\n };\r\n this.mySock.onmessage = m => {\r\n this.handleIncomingFrame(m);\r\n };\r\n this.mySock.onerror = e => {\r\n this.log_('WebSocket error. Closing connection.');\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n };\r\n }\r\n /**\r\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\r\n */\r\n start() { }\r\n static forceDisallow() {\r\n WebSocketConnection.forceDisallow_ = true;\r\n }\r\n static isAvailable() {\r\n let isOldAndroid = false;\r\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\r\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\r\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\r\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\r\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\r\n isOldAndroid = true;\r\n }\r\n }\r\n }\r\n return (!isOldAndroid &&\r\n WebSocketImpl !== null &&\r\n !WebSocketConnection.forceDisallow_);\r\n }\r\n /**\r\n * Returns true if we previously failed to connect with this transport.\r\n */\r\n static previouslyFailed() {\r\n // If our persistent storage is actually only in-memory storage,\r\n // we default to assuming that it previously failed to be safe.\r\n return (PersistentStorage.isInMemoryStorage ||\r\n PersistentStorage.get('previous_websocket_failure') === true);\r\n }\r\n markConnectionHealthy() {\r\n PersistentStorage.remove('previous_websocket_failure');\r\n }\r\n appendFrame_(data) {\r\n this.frames.push(data);\r\n if (this.frames.length === this.totalFrames) {\r\n const fullMess = this.frames.join('');\r\n this.frames = null;\r\n const jsonMess = jsonEval(fullMess);\r\n //handle the message\r\n this.onMessage(jsonMess);\r\n }\r\n }\r\n /**\r\n * @param frameCount - The number of frames we are expecting from the server\r\n */\r\n handleNewFrameCount_(frameCount) {\r\n this.totalFrames = frameCount;\r\n this.frames = [];\r\n }\r\n /**\r\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\r\n * @returns Any remaining data to be process, or null if there is none\r\n */\r\n extractFrameCount_(data) {\r\n assert(this.frames === null, 'We already have a frame buffer');\r\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\r\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\r\n if (data.length <= 6) {\r\n const frameCount = Number(data);\r\n if (!isNaN(frameCount)) {\r\n this.handleNewFrameCount_(frameCount);\r\n return null;\r\n }\r\n }\r\n this.handleNewFrameCount_(1);\r\n return data;\r\n }\r\n /**\r\n * Process a websocket frame that has arrived from the server.\r\n * @param mess - The frame data\r\n */\r\n handleIncomingFrame(mess) {\r\n if (this.mySock === null) {\r\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\r\n }\r\n const data = mess['data'];\r\n this.bytesReceived += data.length;\r\n this.stats_.incrementCounter('bytes_received', data.length);\r\n this.resetKeepAlive();\r\n if (this.frames !== null) {\r\n // we're buffering\r\n this.appendFrame_(data);\r\n }\r\n else {\r\n // try to parse out a frame count, otherwise, assume 1 and process it\r\n const remainingData = this.extractFrameCount_(data);\r\n if (remainingData !== null) {\r\n this.appendFrame_(remainingData);\r\n }\r\n }\r\n }\r\n /**\r\n * Send a message to the server\r\n * @param data - The JSON object to transmit\r\n */\r\n send(data) {\r\n this.resetKeepAlive();\r\n const dataStr = stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //We can only fit a certain amount in each websocket frame, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\r\n //Send the length header\r\n if (dataSegs.length > 1) {\r\n this.sendString_(String(dataSegs.length));\r\n }\r\n //Send the actual data in segments.\r\n for (let i = 0; i < dataSegs.length; i++) {\r\n this.sendString_(dataSegs[i]);\r\n }\r\n }\r\n shutdown_() {\r\n this.isClosed_ = true;\r\n if (this.keepaliveTimer) {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = null;\r\n }\r\n if (this.mySock) {\r\n this.mySock.close();\r\n this.mySock = null;\r\n }\r\n }\r\n onClosed_() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is closing itself');\r\n this.shutdown_();\r\n // since this is an internal close, trigger the close listener\r\n if (this.onDisconnect) {\r\n this.onDisconnect(this.everConnected_);\r\n this.onDisconnect = null;\r\n }\r\n }\r\n }\r\n /**\r\n * External-facing close handler.\r\n * Close the websocket and kill the connection.\r\n */\r\n close() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is being closed');\r\n this.shutdown_();\r\n }\r\n }\r\n /**\r\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\r\n * the last activity.\r\n */\r\n resetKeepAlive() {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = setInterval(() => {\r\n //If there has been no websocket activity for a while, send a no-op\r\n if (this.mySock) {\r\n this.sendString_('0');\r\n }\r\n this.resetKeepAlive();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\r\n }\r\n /**\r\n * Send a string over the websocket.\r\n *\r\n * @param str - String to send.\r\n */\r\n sendString_(str) {\r\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\r\n // calls for some unknown reason. We treat these as an error and disconnect.\r\n // See https://app.asana.com/0/58926111402292/68021340250410\r\n try {\r\n this.mySock.send(str);\r\n }\r\n catch (e) {\r\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\r\n setTimeout(this.onClosed_.bind(this), 0);\r\n }\r\n }\r\n}\r\n/**\r\n * Number of response before we consider the connection \"healthy.\"\r\n */\r\nWebSocketConnection.responsesRequiredToBeHealthy = 2;\r\n/**\r\n * Time to wait for the connection te become healthy before giving up.\r\n */\r\nWebSocketConnection.healthyTimeout = 30000;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\r\n * lifecycle.\r\n *\r\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\r\n * they are available.\r\n */\r\nclass TransportManager {\r\n /**\r\n * @param repoInfo - Metadata around the namespace we're connecting to\r\n */\r\n constructor(repoInfo) {\r\n this.initTransports_(repoInfo);\r\n }\r\n static get ALL_TRANSPORTS() {\r\n return [BrowserPollConnection, WebSocketConnection];\r\n }\r\n /**\r\n * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after\r\n * TransportManager has already set up transports_\r\n */\r\n static get IS_TRANSPORT_INITIALIZED() {\r\n return this.globalTransportInitialized_;\r\n }\r\n initTransports_(repoInfo) {\r\n const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();\r\n let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\r\n if (repoInfo.webSocketOnly) {\r\n if (!isWebSocketsAvailable) {\r\n warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\r\n }\r\n isSkipPollConnection = true;\r\n }\r\n if (isSkipPollConnection) {\r\n this.transports_ = [WebSocketConnection];\r\n }\r\n else {\r\n const transports = (this.transports_ = []);\r\n for (const transport of TransportManager.ALL_TRANSPORTS) {\r\n if (transport && transport['isAvailable']()) {\r\n transports.push(transport);\r\n }\r\n }\r\n TransportManager.globalTransportInitialized_ = true;\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the initial transport to use\r\n */\r\n initialTransport() {\r\n if (this.transports_.length > 0) {\r\n return this.transports_[0];\r\n }\r\n else {\r\n throw new Error('No transports available');\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the next transport, or null\r\n */\r\n upgradeTransport() {\r\n if (this.transports_.length > 1) {\r\n return this.transports_[1];\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\r\n// Keeps track of whether the TransportManager has already chosen a transport to use\r\nTransportManager.globalTransportInitialized_ = false;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Abort upgrade attempt if it takes longer than 60s.\r\nconst UPGRADE_TIMEOUT = 60000;\r\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\r\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\r\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\r\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\r\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\r\n// but we've sent/received enough bytes, we don't cancel the connection.\r\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\r\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\r\nconst MESSAGE_TYPE = 't';\r\nconst MESSAGE_DATA = 'd';\r\nconst CONTROL_SHUTDOWN = 's';\r\nconst CONTROL_RESET = 'r';\r\nconst CONTROL_ERROR = 'e';\r\nconst CONTROL_PONG = 'o';\r\nconst SWITCH_ACK = 'a';\r\nconst END_TRANSMISSION = 'n';\r\nconst PING = 'p';\r\nconst SERVER_HELLO = 'h';\r\n/**\r\n * Creates a new real-time connection to the server using whichever method works\r\n * best in the current browser.\r\n */\r\nclass Connection {\r\n /**\r\n * @param id - an id for this connection\r\n * @param repoInfo_ - the info for the endpoint to connect to\r\n * @param applicationId_ - the Firebase App ID for this project\r\n * @param appCheckToken_ - The App Check Token for this device.\r\n * @param authToken_ - The auth token for this session.\r\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\r\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\r\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\r\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\r\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\r\n */\r\n constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\r\n this.id = id;\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.appCheckToken_ = appCheckToken_;\r\n this.authToken_ = authToken_;\r\n this.onMessage_ = onMessage_;\r\n this.onReady_ = onReady_;\r\n this.onDisconnect_ = onDisconnect_;\r\n this.onKill_ = onKill_;\r\n this.lastSessionId = lastSessionId;\r\n this.connectionCount = 0;\r\n this.pendingDataMessages = [];\r\n this.state_ = 0 /* RealtimeState.CONNECTING */;\r\n this.log_ = logWrapper('c:' + this.id + ':');\r\n this.transportManager_ = new TransportManager(repoInfo_);\r\n this.log_('Connection created');\r\n this.start_();\r\n }\r\n /**\r\n * Starts a connection attempt\r\n */\r\n start_() {\r\n const conn = this.transportManager_.initialTransport();\r\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessageReceived = this.connReceiver_(this.conn_);\r\n const onConnectionLost = this.disconnReceiver_(this.conn_);\r\n this.tx_ = this.conn_;\r\n this.rx_ = this.conn_;\r\n this.secondaryConn_ = null;\r\n this.isHealthy_ = false;\r\n /*\r\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\r\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\r\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\r\n * still have the context of your originating frame.\r\n */\r\n setTimeout(() => {\r\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\r\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\r\n }, Math.floor(0));\r\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\r\n if (healthyTimeoutMS > 0) {\r\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\r\n this.healthyTimeout_ = null;\r\n if (!this.isHealthy_) {\r\n if (this.conn_ &&\r\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has received ' +\r\n this.conn_.bytesReceived +\r\n ' bytes. Marking connection healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n else if (this.conn_ &&\r\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has sent ' +\r\n this.conn_.bytesSent +\r\n ' bytes. Leaving connection alive.');\r\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\r\n // the server.\r\n }\r\n else {\r\n this.log_('Closing unhealthy connection after timeout.');\r\n this.close();\r\n }\r\n }\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(healthyTimeoutMS));\r\n }\r\n }\r\n nextTransportId_() {\r\n return 'c:' + this.id + ':' + this.connectionCount++;\r\n }\r\n disconnReceiver_(conn) {\r\n return everConnected => {\r\n if (conn === this.conn_) {\r\n this.onConnectionLost_(everConnected);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.log_('Secondary connection lost.');\r\n this.onSecondaryConnectionLost_();\r\n }\r\n else {\r\n this.log_('closing an old connection');\r\n }\r\n };\r\n }\r\n connReceiver_(conn) {\r\n return (message) => {\r\n if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\r\n if (conn === this.rx_) {\r\n this.onPrimaryMessageReceived_(message);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.onSecondaryMessageReceived_(message);\r\n }\r\n else {\r\n this.log_('message on old connection');\r\n }\r\n }\r\n };\r\n }\r\n /**\r\n * @param dataMsg - An arbitrary data message to be sent to the server\r\n */\r\n sendRequest(dataMsg) {\r\n // wrap in a data message envelope and send it on\r\n const msg = { t: 'd', d: dataMsg };\r\n this.sendData_(msg);\r\n }\r\n tryCleanupConnection() {\r\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\r\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\r\n this.conn_ = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n // the server will shutdown the old connection\r\n }\r\n }\r\n onSecondaryControl_(controlData) {\r\n if (MESSAGE_TYPE in controlData) {\r\n const cmd = controlData[MESSAGE_TYPE];\r\n if (cmd === SWITCH_ACK) {\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // Most likely the session wasn't valid. Abandon the switch attempt\r\n this.log_('Got a reset on secondary, closing it');\r\n this.secondaryConn_.close();\r\n // If we were already using this connection for something, than we need to fully close\r\n if (this.tx_ === this.secondaryConn_ ||\r\n this.rx_ === this.secondaryConn_) {\r\n this.close();\r\n }\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on secondary.');\r\n this.secondaryResponsesRequired_--;\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n }\r\n }\r\n onSecondaryMessageReceived_(parsedData) {\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onSecondaryControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n // got a data message, but we're still second connection. Need to buffer it up\r\n this.pendingDataMessages.push(data);\r\n }\r\n else {\r\n throw new Error('Unknown protocol layer: ' + layer);\r\n }\r\n }\r\n upgradeIfSecondaryHealthy_() {\r\n if (this.secondaryResponsesRequired_ <= 0) {\r\n this.log_('Secondary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.secondaryConn_.markConnectionHealthy();\r\n this.proceedWithUpgrade_();\r\n }\r\n else {\r\n // Send a ping to make sure the connection is healthy.\r\n this.log_('sending ping on secondary.');\r\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n proceedWithUpgrade_() {\r\n // tell this connection to consider itself open\r\n this.secondaryConn_.start();\r\n // send ack\r\n this.log_('sending client ack on secondary');\r\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\r\n // send end packet on primary transport, switch to sending on this one\r\n // can receive on this one, buffer responses until end received on primary transport\r\n this.log_('Ending transmission on primary');\r\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\r\n this.tx_ = this.secondaryConn_;\r\n this.tryCleanupConnection();\r\n }\r\n onPrimaryMessageReceived_(parsedData) {\r\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n this.onDataMessage_(data);\r\n }\r\n }\r\n onDataMessage_(message) {\r\n this.onPrimaryResponse_();\r\n // We don't do anything with data messages, just kick them up a level\r\n this.onMessage_(message);\r\n }\r\n onPrimaryResponse_() {\r\n if (!this.isHealthy_) {\r\n this.primaryResponsesRequired_--;\r\n if (this.primaryResponsesRequired_ <= 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n }\r\n }\r\n onControl_(controlData) {\r\n const cmd = requireKey(MESSAGE_TYPE, controlData);\r\n if (MESSAGE_DATA in controlData) {\r\n const payload = controlData[MESSAGE_DATA];\r\n if (cmd === SERVER_HELLO) {\r\n const handshakePayload = Object.assign({}, payload);\r\n if (this.repoInfo_.isUsingEmulator) {\r\n // Upon connecting, the emulator will pass the hostname that it's aware of, but we prefer the user's set hostname via `connectDatabaseEmulator` over what the emulator passes.\r\n handshakePayload.h = this.repoInfo_.host;\r\n }\r\n this.onHandshake_(handshakePayload);\r\n }\r\n else if (cmd === END_TRANSMISSION) {\r\n this.log_('recvd end transmission on primary');\r\n this.rx_ = this.secondaryConn_;\r\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\r\n this.onDataMessage_(this.pendingDataMessages[i]);\r\n }\r\n this.pendingDataMessages = [];\r\n this.tryCleanupConnection();\r\n }\r\n else if (cmd === CONTROL_SHUTDOWN) {\r\n // This was previously the 'onKill' callback passed to the lower-level connection\r\n // payload in this case is the reason for the shutdown. Generally a human-readable error\r\n this.onConnectionShutdown_(payload);\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // payload in this case is the host we should contact\r\n this.onReset_(payload);\r\n }\r\n else if (cmd === CONTROL_ERROR) {\r\n error('Server Error: ' + payload);\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on primary.');\r\n this.onPrimaryResponse_();\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }\r\n else {\r\n error('Unknown control packet command: ' + cmd);\r\n }\r\n }\r\n }\r\n /**\r\n * @param handshake - The handshake data returned from the server\r\n */\r\n onHandshake_(handshake) {\r\n const timestamp = handshake.ts;\r\n const version = handshake.v;\r\n const host = handshake.h;\r\n this.sessionId = handshake.s;\r\n this.repoInfo_.host = host;\r\n // if we've already closed the connection, then don't bother trying to progress further\r\n if (this.state_ === 0 /* RealtimeState.CONNECTING */) {\r\n this.conn_.start();\r\n this.onConnectionEstablished_(this.conn_, timestamp);\r\n if (PROTOCOL_VERSION !== version) {\r\n warn('Protocol version mismatch detected');\r\n }\r\n // TODO: do we want to upgrade? when? maybe a delay?\r\n this.tryStartUpgrade_();\r\n }\r\n }\r\n tryStartUpgrade_() {\r\n const conn = this.transportManager_.upgradeTransport();\r\n if (conn) {\r\n this.startUpgrade_(conn);\r\n }\r\n }\r\n startUpgrade_(conn) {\r\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.secondaryResponsesRequired_ =\r\n conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessage = this.connReceiver_(this.secondaryConn_);\r\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\r\n this.secondaryConn_.open(onMessage, onDisconnect);\r\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\r\n setTimeoutNonBlocking(() => {\r\n if (this.secondaryConn_) {\r\n this.log_('Timed out trying to upgrade.');\r\n this.secondaryConn_.close();\r\n }\r\n }, Math.floor(UPGRADE_TIMEOUT));\r\n }\r\n onReset_(host) {\r\n this.log_('Reset packet received. New host: ' + host);\r\n this.repoInfo_.host = host;\r\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\r\n // We don't currently support resets after the connection has already been established\r\n if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\r\n this.close();\r\n }\r\n else {\r\n // Close whatever connections we have open and start again.\r\n this.closeConnections_();\r\n this.start_();\r\n }\r\n }\r\n onConnectionEstablished_(conn, timestamp) {\r\n this.log_('Realtime connection established.');\r\n this.conn_ = conn;\r\n this.state_ = 1 /* RealtimeState.CONNECTED */;\r\n if (this.onReady_) {\r\n this.onReady_(timestamp, this.sessionId);\r\n this.onReady_ = null;\r\n }\r\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\r\n // send some pings.\r\n if (this.primaryResponsesRequired_ === 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n }\r\n else {\r\n setTimeoutNonBlocking(() => {\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\r\n }\r\n }\r\n sendPingOnPrimaryIfNecessary_() {\r\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\r\n if (!this.isHealthy_ && this.state_ === 1 /* RealtimeState.CONNECTED */) {\r\n this.log_('sending ping on primary.');\r\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n onSecondaryConnectionLost_() {\r\n const conn = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n if (this.tx_ === conn || this.rx_ === conn) {\r\n // we are relying on this connection already in some capacity. Therefore, a failure is real\r\n this.close();\r\n }\r\n }\r\n /**\r\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\r\n * we should flush the host cache\r\n */\r\n onConnectionLost_(everConnected) {\r\n this.conn_ = null;\r\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\r\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\r\n if (!everConnected && this.state_ === 0 /* RealtimeState.CONNECTING */) {\r\n this.log_('Realtime connection failed.');\r\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\r\n if (this.repoInfo_.isCacheableHost()) {\r\n PersistentStorage.remove('host:' + this.repoInfo_.host);\r\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\r\n this.repoInfo_.internalHost = this.repoInfo_.host;\r\n }\r\n }\r\n else if (this.state_ === 1 /* RealtimeState.CONNECTED */) {\r\n this.log_('Realtime connection lost.');\r\n }\r\n this.close();\r\n }\r\n onConnectionShutdown_(reason) {\r\n this.log_('Connection shutdown command received. Shutting down...');\r\n if (this.onKill_) {\r\n this.onKill_(reason);\r\n this.onKill_ = null;\r\n }\r\n // We intentionally don't want to fire onDisconnect (kill is a different case),\r\n // so clear the callback.\r\n this.onDisconnect_ = null;\r\n this.close();\r\n }\r\n sendData_(data) {\r\n if (this.state_ !== 1 /* RealtimeState.CONNECTED */) {\r\n throw 'Connection is not connected';\r\n }\r\n else {\r\n this.tx_.send(data);\r\n }\r\n }\r\n /**\r\n * Cleans up this connection, calling the appropriate callbacks\r\n */\r\n close() {\r\n if (this.state_ !== 2 /* RealtimeState.DISCONNECTED */) {\r\n this.log_('Closing realtime connection.');\r\n this.state_ = 2 /* RealtimeState.DISCONNECTED */;\r\n this.closeConnections_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_();\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n }\r\n closeConnections_() {\r\n this.log_('Shutting down all connections');\r\n if (this.conn_) {\r\n this.conn_.close();\r\n this.conn_ = null;\r\n }\r\n if (this.secondaryConn_) {\r\n this.secondaryConn_.close();\r\n this.secondaryConn_ = null;\r\n }\r\n if (this.healthyTimeout_) {\r\n clearTimeout(this.healthyTimeout_);\r\n this.healthyTimeout_ = null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface defining the set of actions that can be performed against the Firebase server\r\n * (basically corresponds to our wire protocol).\r\n *\r\n * @interface\r\n */\r\nclass ServerActions {\r\n put(pathString, data, onComplete, hash) { }\r\n merge(pathString, data, onComplete, hash) { }\r\n /**\r\n * Refreshes the auth token for the current connection.\r\n * @param token - The authentication token\r\n */\r\n refreshAuthToken(token) { }\r\n /**\r\n * Refreshes the app check token for the current connection.\r\n * @param token The app check token\r\n */\r\n refreshAppCheckToken(token) { }\r\n onDisconnectPut(pathString, data, onComplete) { }\r\n onDisconnectMerge(pathString, data, onComplete) { }\r\n onDisconnectCancel(pathString, onComplete) { }\r\n reportStats(stats) { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Base class to be used if you want to emit events. Call the constructor with\r\n * the set of allowed event names.\r\n */\r\nclass EventEmitter {\r\n constructor(allowedEvents_) {\r\n this.allowedEvents_ = allowedEvents_;\r\n this.listeners_ = {};\r\n assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\r\n }\r\n /**\r\n * To be called by derived classes to trigger events.\r\n */\r\n trigger(eventType, ...varArgs) {\r\n if (Array.isArray(this.listeners_[eventType])) {\r\n // Clone the list, since callbacks could add/remove listeners.\r\n const listeners = [...this.listeners_[eventType]];\r\n for (let i = 0; i < listeners.length; i++) {\r\n listeners[i].callback.apply(listeners[i].context, varArgs);\r\n }\r\n }\r\n }\r\n on(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n this.listeners_[eventType] = this.listeners_[eventType] || [];\r\n this.listeners_[eventType].push({ callback, context });\r\n const eventData = this.getInitialEvent(eventType);\r\n if (eventData) {\r\n callback.apply(context, eventData);\r\n }\r\n }\r\n off(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n const listeners = this.listeners_[eventType] || [];\r\n for (let i = 0; i < listeners.length; i++) {\r\n if (listeners[i].callback === callback &&\r\n (!context || context === listeners[i].context)) {\r\n listeners.splice(i, 1);\r\n return;\r\n }\r\n }\r\n }\r\n validateEventType_(eventType) {\r\n assert(this.allowedEvents_.find(et => {\r\n return et === eventType;\r\n }), 'Unknown event: ' + eventType);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Monitors online state (as reported by window.online/offline events).\r\n *\r\n * The expectation is that this could have many false positives (thinks we are online\r\n * when we're not), but no false negatives. So we can safely use it to determine when\r\n * we definitely cannot reach the internet.\r\n */\r\nclass OnlineMonitor extends EventEmitter {\r\n constructor() {\r\n super(['online']);\r\n this.online_ = true;\r\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\r\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\r\n // It would seem that the 'online' event does not always fire consistently. So we disable it\r\n // for Cordova.\r\n if (typeof window !== 'undefined' &&\r\n typeof window.addEventListener !== 'undefined' &&\r\n !isMobileCordova()) {\r\n window.addEventListener('online', () => {\r\n if (!this.online_) {\r\n this.online_ = true;\r\n this.trigger('online', true);\r\n }\r\n }, false);\r\n window.addEventListener('offline', () => {\r\n if (this.online_) {\r\n this.online_ = false;\r\n this.trigger('online', false);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new OnlineMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\r\n return [this.online_];\r\n }\r\n currentlyOnline() {\r\n return this.online_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Maximum key depth. */\r\nconst MAX_PATH_DEPTH = 32;\r\n/** Maximum number of (UTF8) bytes in a Firebase path. */\r\nconst MAX_PATH_LENGTH_BYTES = 768;\r\n/**\r\n * An immutable object representing a parsed path. It's immutable so that you\r\n * can pass them around to other functions without worrying about them changing\r\n * it.\r\n */\r\nclass Path {\r\n /**\r\n * @param pathOrString - Path string to parse, or another path, or the raw\r\n * tokens array\r\n */\r\n constructor(pathOrString, pieceNum) {\r\n if (pieceNum === void 0) {\r\n this.pieces_ = pathOrString.split('/');\r\n // Remove empty pieces.\r\n let copyTo = 0;\r\n for (let i = 0; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i].length > 0) {\r\n this.pieces_[copyTo] = this.pieces_[i];\r\n copyTo++;\r\n }\r\n }\r\n this.pieces_.length = copyTo;\r\n this.pieceNum_ = 0;\r\n }\r\n else {\r\n this.pieces_ = pathOrString;\r\n this.pieceNum_ = pieceNum;\r\n }\r\n }\r\n toString() {\r\n let pathString = '';\r\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i] !== '') {\r\n pathString += '/' + this.pieces_[i];\r\n }\r\n }\r\n return pathString || '/';\r\n }\r\n}\r\nfunction newEmptyPath() {\r\n return new Path('');\r\n}\r\nfunction pathGetFront(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n return path.pieces_[path.pieceNum_];\r\n}\r\n/**\r\n * @returns The number of segments in this path\r\n */\r\nfunction pathGetLength(path) {\r\n return path.pieces_.length - path.pieceNum_;\r\n}\r\nfunction pathPopFront(path) {\r\n let pieceNum = path.pieceNum_;\r\n if (pieceNum < path.pieces_.length) {\r\n pieceNum++;\r\n }\r\n return new Path(path.pieces_, pieceNum);\r\n}\r\nfunction pathGetBack(path) {\r\n if (path.pieceNum_ < path.pieces_.length) {\r\n return path.pieces_[path.pieces_.length - 1];\r\n }\r\n return null;\r\n}\r\nfunction pathToUrlEncodedString(path) {\r\n let pathString = '';\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n if (path.pieces_[i] !== '') {\r\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\r\n }\r\n }\r\n return pathString || '/';\r\n}\r\n/**\r\n * Shallow copy of the parts of the path.\r\n *\r\n */\r\nfunction pathSlice(path, begin = 0) {\r\n return path.pieces_.slice(path.pieceNum_ + begin);\r\n}\r\nfunction pathParent(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n return new Path(pieces, 0);\r\n}\r\nfunction pathChild(path, childPathObj) {\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n if (childPathObj instanceof Path) {\r\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\r\n pieces.push(childPathObj.pieces_[i]);\r\n }\r\n }\r\n else {\r\n const childPieces = childPathObj.split('/');\r\n for (let i = 0; i < childPieces.length; i++) {\r\n if (childPieces[i].length > 0) {\r\n pieces.push(childPieces[i]);\r\n }\r\n }\r\n }\r\n return new Path(pieces, 0);\r\n}\r\n/**\r\n * @returns True if there are no segments in this path\r\n */\r\nfunction pathIsEmpty(path) {\r\n return path.pieceNum_ >= path.pieces_.length;\r\n}\r\n/**\r\n * @returns The path from outerPath to innerPath\r\n */\r\nfunction newRelativePath(outerPath, innerPath) {\r\n const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);\r\n if (outer === null) {\r\n return innerPath;\r\n }\r\n else if (outer === inner) {\r\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\r\n }\r\n else {\r\n throw new Error('INTERNAL ERROR: innerPath (' +\r\n innerPath +\r\n ') is not within ' +\r\n 'outerPath (' +\r\n outerPath +\r\n ')');\r\n }\r\n}\r\n/**\r\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\r\n */\r\nfunction pathCompare(left, right) {\r\n const leftKeys = pathSlice(left, 0);\r\n const rightKeys = pathSlice(right, 0);\r\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\r\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\r\n if (cmp !== 0) {\r\n return cmp;\r\n }\r\n }\r\n if (leftKeys.length === rightKeys.length) {\r\n return 0;\r\n }\r\n return leftKeys.length < rightKeys.length ? -1 : 1;\r\n}\r\n/**\r\n * @returns true if paths are the same.\r\n */\r\nfunction pathEquals(path, other) {\r\n if (pathGetLength(path) !== pathGetLength(other)) {\r\n return false;\r\n }\r\n for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * @returns True if this path is a parent of (or the same as) other\r\n */\r\nfunction pathContains(path, other) {\r\n let i = path.pieceNum_;\r\n let j = other.pieceNum_;\r\n if (pathGetLength(path) > pathGetLength(other)) {\r\n return false;\r\n }\r\n while (i < path.pieces_.length) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n ++i;\r\n ++j;\r\n }\r\n return true;\r\n}\r\n/**\r\n * Dynamic (mutable) path used to count path lengths.\r\n *\r\n * This class is used to efficiently check paths for valid\r\n * length (in UTF8 bytes) and depth (used in path validation).\r\n *\r\n * Throws Error exception if path is ever invalid.\r\n *\r\n * The definition of a path always begins with '/'.\r\n */\r\nclass ValidationPath {\r\n /**\r\n * @param path - Initial Path.\r\n * @param errorPrefix_ - Prefix for any error messages.\r\n */\r\n constructor(path, errorPrefix_) {\r\n this.errorPrefix_ = errorPrefix_;\r\n this.parts_ = pathSlice(path, 0);\r\n /** Initialize to number of '/' chars needed in path. */\r\n this.byteLength_ = Math.max(1, this.parts_.length);\r\n for (let i = 0; i < this.parts_.length; i++) {\r\n this.byteLength_ += stringLength(this.parts_[i]);\r\n }\r\n validationPathCheckValid(this);\r\n }\r\n}\r\nfunction validationPathPush(validationPath, child) {\r\n // Count the needed '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ += 1;\r\n }\r\n validationPath.parts_.push(child);\r\n validationPath.byteLength_ += stringLength(child);\r\n validationPathCheckValid(validationPath);\r\n}\r\nfunction validationPathPop(validationPath) {\r\n const last = validationPath.parts_.pop();\r\n validationPath.byteLength_ -= stringLength(last);\r\n // Un-count the previous '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ -= 1;\r\n }\r\n}\r\nfunction validationPathCheckValid(validationPath) {\r\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'has a key path longer than ' +\r\n MAX_PATH_LENGTH_BYTES +\r\n ' bytes (' +\r\n validationPath.byteLength_ +\r\n ').');\r\n }\r\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'path specified exceeds the maximum depth that can be written (' +\r\n MAX_PATH_DEPTH +\r\n ') or object contains a cycle ' +\r\n validationPathToErrorString(validationPath));\r\n }\r\n}\r\n/**\r\n * String for use in error messages - uses '.' notation for path.\r\n */\r\nfunction validationPathToErrorString(validationPath) {\r\n if (validationPath.parts_.length === 0) {\r\n return '';\r\n }\r\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass VisibilityMonitor extends EventEmitter {\r\n constructor() {\r\n super(['visible']);\r\n let hidden;\r\n let visibilityChange;\r\n if (typeof document !== 'undefined' &&\r\n typeof document.addEventListener !== 'undefined') {\r\n if (typeof document['hidden'] !== 'undefined') {\r\n // Opera 12.10 and Firefox 18 and later support\r\n visibilityChange = 'visibilitychange';\r\n hidden = 'hidden';\r\n }\r\n else if (typeof document['mozHidden'] !== 'undefined') {\r\n visibilityChange = 'mozvisibilitychange';\r\n hidden = 'mozHidden';\r\n }\r\n else if (typeof document['msHidden'] !== 'undefined') {\r\n visibilityChange = 'msvisibilitychange';\r\n hidden = 'msHidden';\r\n }\r\n else if (typeof document['webkitHidden'] !== 'undefined') {\r\n visibilityChange = 'webkitvisibilitychange';\r\n hidden = 'webkitHidden';\r\n }\r\n }\r\n // Initially, we always assume we are visible. This ensures that in browsers\r\n // without page visibility support or in cases where we are never visible\r\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\r\n // reconnects\r\n this.visible_ = true;\r\n if (visibilityChange) {\r\n document.addEventListener(visibilityChange, () => {\r\n const visible = !document[hidden];\r\n if (visible !== this.visible_) {\r\n this.visible_ = visible;\r\n this.trigger('visible', visible);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new VisibilityMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\r\n return [this.visible_];\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECONNECT_MIN_DELAY = 1000;\r\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\r\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\r\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\r\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\r\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\r\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\r\nconst INVALID_TOKEN_THRESHOLD = 3;\r\n/**\r\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\r\n *\r\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\r\n * in quotes to make sure the closure compiler does not minify them.\r\n */\r\nclass PersistentConnection extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param applicationId_ - The Firebase App ID for this project\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.onConnectStatus_ = onConnectStatus_;\r\n this.onServerInfoUpdate_ = onServerInfoUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n this.authOverride_ = authOverride_;\r\n // Used for diagnostic logging.\r\n this.id = PersistentConnection.nextPersistentConnectionId_++;\r\n this.log_ = logWrapper('p:' + this.id + ':');\r\n this.interruptReasons_ = {};\r\n this.listens = new Map();\r\n this.outstandingPuts_ = [];\r\n this.outstandingGets_ = [];\r\n this.outstandingPutCount_ = 0;\r\n this.outstandingGetCount_ = 0;\r\n this.onDisconnectRequestQueue_ = [];\r\n this.connected_ = false;\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\r\n this.securityDebugCallback_ = null;\r\n this.lastSessionId = null;\r\n this.establishConnectionTimer_ = null;\r\n this.visible_ = false;\r\n // Before we get connected, we keep a queue of pending messages to send.\r\n this.requestCBHash_ = {};\r\n this.requestNumber_ = 0;\r\n this.realtime_ = null;\r\n this.authToken_ = null;\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = false;\r\n this.invalidAuthTokenCount_ = 0;\r\n this.invalidAppCheckTokenCount_ = 0;\r\n this.firstConnection_ = true;\r\n this.lastConnectionAttemptTime_ = null;\r\n this.lastConnectionEstablishedTime_ = null;\r\n if (authOverride_ && !isNodeSdk()) {\r\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\r\n }\r\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\r\n if (repoInfo_.host.indexOf('fblocal') === -1) {\r\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\r\n }\r\n }\r\n sendRequest(action, body, onResponse) {\r\n const curReqNum = ++this.requestNumber_;\r\n const msg = { r: curReqNum, a: action, b: body };\r\n this.log_(stringify(msg));\r\n assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\r\n this.realtime_.sendRequest(msg);\r\n if (onResponse) {\r\n this.requestCBHash_[curReqNum] = onResponse;\r\n }\r\n }\r\n get(query) {\r\n this.initConnection_();\r\n const deferred = new Deferred();\r\n const request = {\r\n p: query._path.toString(),\r\n q: query._queryObject\r\n };\r\n const outstandingGet = {\r\n action: 'g',\r\n request,\r\n onComplete: (message) => {\r\n const payload = message['d'];\r\n if (message['s'] === 'ok') {\r\n deferred.resolve(payload);\r\n }\r\n else {\r\n deferred.reject(payload);\r\n }\r\n }\r\n };\r\n this.outstandingGets_.push(outstandingGet);\r\n this.outstandingGetCount_++;\r\n const index = this.outstandingGets_.length - 1;\r\n if (this.connected_) {\r\n this.sendGet_(index);\r\n }\r\n return deferred.promise;\r\n }\r\n listen(query, currentHashFn, tag, onComplete) {\r\n this.initConnection_();\r\n const queryId = query._queryIdentifier;\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + queryId);\r\n if (!this.listens.has(pathString)) {\r\n this.listens.set(pathString, new Map());\r\n }\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');\r\n assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);\r\n const listenSpec = {\r\n onComplete,\r\n hashFn: currentHashFn,\r\n query,\r\n tag\r\n };\r\n this.listens.get(pathString).set(queryId, listenSpec);\r\n if (this.connected_) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n sendGet_(index) {\r\n const get = this.outstandingGets_[index];\r\n this.sendRequest('g', get.request, (message) => {\r\n delete this.outstandingGets_[index];\r\n this.outstandingGetCount_--;\r\n if (this.outstandingGetCount_ === 0) {\r\n this.outstandingGets_ = [];\r\n }\r\n if (get.onComplete) {\r\n get.onComplete(message);\r\n }\r\n });\r\n }\r\n sendListen_(listenSpec) {\r\n const query = listenSpec.query;\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Listen on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'q';\r\n // Only bother to send query if it's non-default.\r\n if (listenSpec.tag) {\r\n req['q'] = query._queryObject;\r\n req['t'] = listenSpec.tag;\r\n }\r\n req[ /*hash*/'h'] = listenSpec.hashFn();\r\n this.sendRequest(action, req, (message) => {\r\n const payload = message[ /*data*/'d'];\r\n const status = message[ /*status*/'s'];\r\n // print warnings in any case...\r\n PersistentConnection.warnOnListenWarnings_(payload, query);\r\n const currentListenSpec = this.listens.get(pathString) &&\r\n this.listens.get(pathString).get(queryId);\r\n // only trigger actions if the listen hasn't been removed and readded\r\n if (currentListenSpec === listenSpec) {\r\n this.log_('listen response', message);\r\n if (status !== 'ok') {\r\n this.removeListen_(pathString, queryId);\r\n }\r\n if (listenSpec.onComplete) {\r\n listenSpec.onComplete(status, payload);\r\n }\r\n }\r\n });\r\n }\r\n static warnOnListenWarnings_(payload, query) {\r\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const warnings = safeGet(payload, 'w');\r\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\r\n const indexSpec = '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\r\n const indexPath = query._path.toString();\r\n warn(`Using an unspecified index. Your data will be downloaded and ` +\r\n `filtered on the client. Consider adding ${indexSpec} at ` +\r\n `${indexPath} to your security rules for better performance.`);\r\n }\r\n }\r\n }\r\n refreshAuthToken(token) {\r\n this.authToken_ = token;\r\n this.log_('Auth token refreshed');\r\n if (this.authToken_) {\r\n this.tryAuth();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\r\n //the credential so we dont become authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unauth', {}, () => { });\r\n }\r\n }\r\n this.reduceReconnectDelayIfAdminCredential_(token);\r\n }\r\n reduceReconnectDelayIfAdminCredential_(credential) {\r\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\r\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\r\n const isFirebaseSecret = credential && credential.length === 40;\r\n if (isFirebaseSecret || isAdmin(credential)) {\r\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n }\r\n }\r\n refreshAppCheckToken(token) {\r\n this.appCheckToken_ = token;\r\n this.log_('App check token refreshed');\r\n if (this.appCheckToken_) {\r\n this.tryAppCheck();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us.\r\n //If we're not connected, simply delete the credential so we dont become\r\n // authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unappeck', {}, () => { });\r\n }\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\r\n * a auth revoked (the connection is closed).\r\n */\r\n tryAuth() {\r\n if (this.connected_ && this.authToken_) {\r\n const token = this.authToken_;\r\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\r\n const requestData = { cred: token };\r\n if (this.authOverride_ === null) {\r\n requestData['noauth'] = true;\r\n }\r\n else if (typeof this.authOverride_ === 'object') {\r\n requestData['authvar'] = this.authOverride_;\r\n }\r\n this.sendRequest(authMethod, requestData, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (this.authToken_ === token) {\r\n if (status === 'ok') {\r\n this.invalidAuthTokenCount_ = 0;\r\n }\r\n else {\r\n // Triggers reconnect and force refresh for auth token\r\n this.onAuthRevoked_(status, data);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given token. If the authentication\r\n * attempt fails, it's triggered like the token was revoked (the connection is\r\n * closed).\r\n */\r\n tryAppCheck() {\r\n if (this.connected_ && this.appCheckToken_) {\r\n this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (status === 'ok') {\r\n this.invalidAppCheckTokenCount_ = 0;\r\n }\r\n else {\r\n this.onAppCheckRevoked_(status, data);\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n unlisten(query, tag) {\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && this.connected_) {\r\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\r\n }\r\n }\r\n sendUnlisten_(pathString, queryId, queryObj, tag) {\r\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'n';\r\n // Only bother sending queryId if it's non-default.\r\n if (tag) {\r\n req['q'] = queryObj;\r\n req['t'] = tag;\r\n }\r\n this.sendRequest(action, req);\r\n }\r\n onDisconnectPut(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('o', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'o',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectMerge(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('om', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'om',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectCancel(pathString, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'oc',\r\n data: null,\r\n onComplete\r\n });\r\n }\r\n }\r\n sendOnDisconnect_(action, pathString, data, onComplete) {\r\n const request = { /*path*/ p: pathString, /*data*/ d: data };\r\n this.log_('onDisconnect ' + action, request);\r\n this.sendRequest(action, request, (response) => {\r\n if (onComplete) {\r\n setTimeout(() => {\r\n onComplete(response[ /*status*/'s'], response[ /* data */'d']);\r\n }, Math.floor(0));\r\n }\r\n });\r\n }\r\n put(pathString, data, onComplete, hash) {\r\n this.putInternal('p', pathString, data, onComplete, hash);\r\n }\r\n merge(pathString, data, onComplete, hash) {\r\n this.putInternal('m', pathString, data, onComplete, hash);\r\n }\r\n putInternal(action, pathString, data, onComplete, hash) {\r\n this.initConnection_();\r\n const request = {\r\n /*path*/ p: pathString,\r\n /*data*/ d: data\r\n };\r\n if (hash !== undefined) {\r\n request[ /*hash*/'h'] = hash;\r\n }\r\n // TODO: Only keep track of the most recent put for a given path?\r\n this.outstandingPuts_.push({\r\n action,\r\n request,\r\n onComplete\r\n });\r\n this.outstandingPutCount_++;\r\n const index = this.outstandingPuts_.length - 1;\r\n if (this.connected_) {\r\n this.sendPut_(index);\r\n }\r\n else {\r\n this.log_('Buffering put: ' + pathString);\r\n }\r\n }\r\n sendPut_(index) {\r\n const action = this.outstandingPuts_[index].action;\r\n const request = this.outstandingPuts_[index].request;\r\n const onComplete = this.outstandingPuts_[index].onComplete;\r\n this.outstandingPuts_[index].queued = this.connected_;\r\n this.sendRequest(action, request, (message) => {\r\n this.log_(action + ' response', message);\r\n delete this.outstandingPuts_[index];\r\n this.outstandingPutCount_--;\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n if (onComplete) {\r\n onComplete(message[ /*status*/'s'], message[ /* data */'d']);\r\n }\r\n });\r\n }\r\n reportStats(stats) {\r\n // If we're not connected, we just drop the stats.\r\n if (this.connected_) {\r\n const request = { /*counters*/ c: stats };\r\n this.log_('reportStats', request);\r\n this.sendRequest(/*stats*/ 's', request, result => {\r\n const status = result[ /*status*/'s'];\r\n if (status !== 'ok') {\r\n const errorReason = result[ /* data */'d'];\r\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\r\n }\r\n });\r\n }\r\n }\r\n onDataMessage_(message) {\r\n if ('r' in message) {\r\n // this is a response\r\n this.log_('from server: ' + stringify(message));\r\n const reqNum = message['r'];\r\n const onResponse = this.requestCBHash_[reqNum];\r\n if (onResponse) {\r\n delete this.requestCBHash_[reqNum];\r\n onResponse(message[ /*body*/'b']);\r\n }\r\n }\r\n else if ('error' in message) {\r\n throw 'A server-side error has occurred: ' + message['error'];\r\n }\r\n else if ('a' in message) {\r\n // a and b are action and body, respectively\r\n this.onDataPush_(message['a'], message['b']);\r\n }\r\n }\r\n onDataPush_(action, body) {\r\n this.log_('handleServerMessage', action, body);\r\n if (action === 'd') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge*/ false, body['t']);\r\n }\r\n else if (action === 'm') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge=*/ true, body['t']);\r\n }\r\n else if (action === 'c') {\r\n this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);\r\n }\r\n else if (action === 'ac') {\r\n this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'apc') {\r\n this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'sd') {\r\n this.onSecurityDebugPacket_(body);\r\n }\r\n else {\r\n error('Unrecognized action received from server: ' +\r\n stringify(action) +\r\n '\\nAre you using the latest client?');\r\n }\r\n }\r\n onReady_(timestamp, sessionId) {\r\n this.log_('connection ready');\r\n this.connected_ = true;\r\n this.lastConnectionEstablishedTime_ = new Date().getTime();\r\n this.handleTimestamp_(timestamp);\r\n this.lastSessionId = sessionId;\r\n if (this.firstConnection_) {\r\n this.sendConnectStats_();\r\n }\r\n this.restoreState_();\r\n this.firstConnection_ = false;\r\n this.onConnectStatus_(true);\r\n }\r\n scheduleConnect_(timeout) {\r\n assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n }\r\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\r\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\r\n this.establishConnectionTimer_ = setTimeout(() => {\r\n this.establishConnectionTimer_ = null;\r\n this.establishConnection_();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(timeout));\r\n }\r\n initConnection_() {\r\n if (!this.realtime_ && this.firstConnection_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n onVisible_(visible) {\r\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\r\n if (visible &&\r\n !this.visible_ &&\r\n this.reconnectDelay_ === this.maxReconnectDelay_) {\r\n this.log_('Window became visible. Reducing delay.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n this.visible_ = visible;\r\n }\r\n onOnline_(online) {\r\n if (online) {\r\n this.log_('Browser went online.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n else {\r\n this.log_('Browser went offline. Killing connection.');\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n }\r\n }\r\n onRealtimeDisconnect_() {\r\n this.log_('data client disconnected');\r\n this.connected_ = false;\r\n this.realtime_ = null;\r\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\r\n this.cancelSentTransactions_();\r\n // Clear out the pending requests.\r\n this.requestCBHash_ = {};\r\n if (this.shouldReconnect_()) {\r\n if (!this.visible_) {\r\n this.log_(\"Window isn't visible. Delaying reconnect.\");\r\n this.reconnectDelay_ = this.maxReconnectDelay_;\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n }\r\n else if (this.lastConnectionEstablishedTime_) {\r\n // If we've been connected long enough, reset reconnect delay to minimum.\r\n const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\r\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n }\r\n this.lastConnectionEstablishedTime_ = null;\r\n }\r\n const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\r\n let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\r\n reconnectDelay = Math.random() * reconnectDelay;\r\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\r\n this.scheduleConnect_(reconnectDelay);\r\n // Adjust reconnect delay for next time.\r\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\r\n }\r\n this.onConnectStatus_(false);\r\n }\r\n async establishConnection_() {\r\n if (this.shouldReconnect_()) {\r\n this.log_('Making a connection attempt');\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n this.lastConnectionEstablishedTime_ = null;\r\n const onDataMessage = this.onDataMessage_.bind(this);\r\n const onReady = this.onReady_.bind(this);\r\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\r\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\r\n const lastSessionId = this.lastSessionId;\r\n let canceled = false;\r\n let connection = null;\r\n const closeFn = function () {\r\n if (connection) {\r\n connection.close();\r\n }\r\n else {\r\n canceled = true;\r\n onDisconnect();\r\n }\r\n };\r\n const sendRequestFn = function (msg) {\r\n assert(connection, \"sendRequest call when we're not connected not allowed.\");\r\n connection.sendRequest(msg);\r\n };\r\n this.realtime_ = {\r\n close: closeFn,\r\n sendRequest: sendRequestFn\r\n };\r\n const forceRefresh = this.forceTokenRefresh_;\r\n this.forceTokenRefresh_ = false;\r\n try {\r\n // First fetch auth and app check token, and establish connection after\r\n // fetching the token was successful\r\n const [authToken, appCheckToken] = await Promise.all([\r\n this.authTokenProvider_.getToken(forceRefresh),\r\n this.appCheckTokenProvider_.getToken(forceRefresh)\r\n ]);\r\n if (!canceled) {\r\n log('getToken() completed. Creating connection.');\r\n this.authToken_ = authToken && authToken.accessToken;\r\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\r\n connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, \r\n /* onKill= */ reason => {\r\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\r\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\r\n }, lastSessionId);\r\n }\r\n else {\r\n log('getToken() completed but was canceled');\r\n }\r\n }\r\n catch (error) {\r\n this.log_('Failed to get token: ' + error);\r\n if (!canceled) {\r\n if (this.repoInfo_.nodeAdmin) {\r\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\r\n // But getToken() may also just have temporarily failed, so we still want to\r\n // continue retrying.\r\n warn(error);\r\n }\r\n closeFn();\r\n }\r\n }\r\n }\r\n }\r\n interrupt(reason) {\r\n log('Interrupting connection for reason: ' + reason);\r\n this.interruptReasons_[reason] = true;\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n else {\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n this.establishConnectionTimer_ = null;\r\n }\r\n if (this.connected_) {\r\n this.onRealtimeDisconnect_();\r\n }\r\n }\r\n }\r\n resume(reason) {\r\n log('Resuming connection for reason: ' + reason);\r\n delete this.interruptReasons_[reason];\r\n if (isEmpty(this.interruptReasons_)) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n }\r\n handleTimestamp_(timestamp) {\r\n const delta = timestamp - new Date().getTime();\r\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\r\n }\r\n cancelSentTransactions_() {\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n const put = this.outstandingPuts_[i];\r\n if (put && /*hash*/ 'h' in put.request && put.queued) {\r\n if (put.onComplete) {\r\n put.onComplete('disconnect');\r\n }\r\n delete this.outstandingPuts_[i];\r\n this.outstandingPutCount_--;\r\n }\r\n }\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n }\r\n onListenRevoked_(pathString, query) {\r\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\r\n let queryId;\r\n if (!query) {\r\n queryId = 'default';\r\n }\r\n else {\r\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\r\n }\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && listen.onComplete) {\r\n listen.onComplete('permission_denied');\r\n }\r\n }\r\n removeListen_(pathString, queryId) {\r\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\r\n let listen;\r\n if (this.listens.has(normalizedPathString)) {\r\n const map = this.listens.get(normalizedPathString);\r\n listen = map.get(queryId);\r\n map.delete(queryId);\r\n if (map.size === 0) {\r\n this.listens.delete(normalizedPathString);\r\n }\r\n }\r\n else {\r\n // all listens for this path has already been removed\r\n listen = undefined;\r\n }\r\n return listen;\r\n }\r\n onAuthRevoked_(statusCode, explanation) {\r\n log('Auth token revoked: ' + statusCode + '/' + explanation);\r\n this.authToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n this.realtime_.close();\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAuthTokenCount_++;\r\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n // Set a long reconnect delay because recovery is unlikely\r\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n // Notify the auth token provider that the token is invalid, which will log\r\n // a warning\r\n this.authTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onAppCheckRevoked_(statusCode, explanation) {\r\n log('App check token revoked: ' + statusCode + '/' + explanation);\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n // Note: We don't close the connection as the developer may not have\r\n // enforcement enabled. The backend closes connections with enforcements.\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAppCheckTokenCount_++;\r\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n this.appCheckTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onSecurityDebugPacket_(body) {\r\n if (this.securityDebugCallback_) {\r\n this.securityDebugCallback_(body);\r\n }\r\n else {\r\n if ('msg' in body) {\r\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\r\n }\r\n }\r\n }\r\n restoreState_() {\r\n //Re-authenticate ourselves if we have a credential stored.\r\n this.tryAuth();\r\n this.tryAppCheck();\r\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\r\n // make sure to send listens before puts.\r\n for (const queries of this.listens.values()) {\r\n for (const listenSpec of queries.values()) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n if (this.outstandingPuts_[i]) {\r\n this.sendPut_(i);\r\n }\r\n }\r\n while (this.onDisconnectRequestQueue_.length) {\r\n const request = this.onDisconnectRequestQueue_.shift();\r\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\r\n }\r\n for (let i = 0; i < this.outstandingGets_.length; i++) {\r\n if (this.outstandingGets_[i]) {\r\n this.sendGet_(i);\r\n }\r\n }\r\n }\r\n /**\r\n * Sends client stats for first connection\r\n */\r\n sendConnectStats_() {\r\n const stats = {};\r\n let clientName = 'js';\r\n if (isNodeSdk()) {\r\n if (this.repoInfo_.nodeAdmin) {\r\n clientName = 'admin_node';\r\n }\r\n else {\r\n clientName = 'node';\r\n }\r\n }\r\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\r\n if (isMobileCordova()) {\r\n stats['framework.cordova'] = 1;\r\n }\r\n else if (isReactNative()) {\r\n stats['framework.reactnative'] = 1;\r\n }\r\n this.reportStats(stats);\r\n }\r\n shouldReconnect_() {\r\n const online = OnlineMonitor.getInstance().currentlyOnline();\r\n return isEmpty(this.interruptReasons_) && online;\r\n }\r\n}\r\nPersistentConnection.nextPersistentConnectionId_ = 0;\r\n/**\r\n * Counter for number of connections created. Mainly used for tagging in the logs\r\n */\r\nPersistentConnection.nextConnectionId_ = 0;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass NamedNode {\r\n constructor(name, node) {\r\n this.name = name;\r\n this.node = node;\r\n }\r\n static Wrap(name, node) {\r\n return new NamedNode(name, node);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Index {\r\n /**\r\n * @returns A standalone comparison function for\r\n * this index\r\n */\r\n getCompare() {\r\n return this.compare.bind(this);\r\n }\r\n /**\r\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\r\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\r\n *\r\n *\r\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\r\n */\r\n indexedValueChanged(oldNode, newNode) {\r\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\r\n const newWrapped = new NamedNode(MIN_NAME, newNode);\r\n return this.compare(oldWrapped, newWrapped) !== 0;\r\n }\r\n /**\r\n * @returns a node wrapper that will sort equal to or less than\r\n * any other node wrapper, using this index\r\n */\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet __EMPTY_NODE;\r\nclass KeyIndex extends Index {\r\n static get __EMPTY_NODE() {\r\n return __EMPTY_NODE;\r\n }\r\n static set __EMPTY_NODE(val) {\r\n __EMPTY_NODE = val;\r\n }\r\n compare(a, b) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n isDefinedOn(node) {\r\n // We could probably return true here (since every node has a key), but it's never called\r\n // so just leaving unimplemented for now.\r\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return false; // The key for a node never changes.\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // TODO: This should really be created once and cached in a static property, but\r\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\r\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\r\n }\r\n makePost(indexValue, name) {\r\n assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\r\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\r\n return new NamedNode(indexValue, __EMPTY_NODE);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.key';\r\n }\r\n}\r\nconst KEY_INDEX = new KeyIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An iterator over an LLRBNode.\r\n */\r\nclass SortedMapIterator {\r\n /**\r\n * @param node - Node to iterate.\r\n * @param isReverse_ - Whether or not to iterate in reverse\r\n */\r\n constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {\r\n this.isReverse_ = isReverse_;\r\n this.resultGenerator_ = resultGenerator_;\r\n this.nodeStack_ = [];\r\n let cmp = 1;\r\n while (!node.isEmpty()) {\r\n node = node;\r\n cmp = startKey ? comparator(node.key, startKey) : 1;\r\n // flip the comparison if we're going in reverse\r\n if (isReverse_) {\r\n cmp *= -1;\r\n }\r\n if (cmp < 0) {\r\n // This node is less than our start key. ignore it\r\n if (this.isReverse_) {\r\n node = node.left;\r\n }\r\n else {\r\n node = node.right;\r\n }\r\n }\r\n else if (cmp === 0) {\r\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\r\n this.nodeStack_.push(node);\r\n break;\r\n }\r\n else {\r\n // This node is greater than our start key, add it to the stack and move to the next one\r\n this.nodeStack_.push(node);\r\n if (this.isReverse_) {\r\n node = node.right;\r\n }\r\n else {\r\n node = node.left;\r\n }\r\n }\r\n }\r\n }\r\n getNext() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n let node = this.nodeStack_.pop();\r\n let result;\r\n if (this.resultGenerator_) {\r\n result = this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n result = { key: node.key, value: node.value };\r\n }\r\n if (this.isReverse_) {\r\n node = node.left;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.right;\r\n }\r\n }\r\n else {\r\n node = node.right;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.left;\r\n }\r\n }\r\n return result;\r\n }\r\n hasNext() {\r\n return this.nodeStack_.length > 0;\r\n }\r\n peek() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n const node = this.nodeStack_[this.nodeStack_.length - 1];\r\n if (this.resultGenerator_) {\r\n return this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n return { key: node.key, value: node.value };\r\n }\r\n }\r\n}\r\n/**\r\n * Represents a node in a Left-leaning Red-Black tree.\r\n */\r\nclass LLRBNode {\r\n /**\r\n * @param key - Key associated with this node.\r\n * @param value - Value associated with this node.\r\n * @param color - Whether this node is red.\r\n * @param left - Left child.\r\n * @param right - Right child.\r\n */\r\n constructor(key, value, color, left, right) {\r\n this.key = key;\r\n this.value = value;\r\n this.color = color != null ? color : LLRBNode.RED;\r\n this.left =\r\n left != null ? left : SortedMap.EMPTY_NODE;\r\n this.right =\r\n right != null ? right : SortedMap.EMPTY_NODE;\r\n }\r\n /**\r\n * Returns a copy of the current node, optionally replacing pieces of it.\r\n *\r\n * @param key - New key for the node, or null.\r\n * @param value - New value for the node, or null.\r\n * @param color - New color for the node, or null.\r\n * @param left - New left child for the node, or null.\r\n * @param right - New right child for the node, or null.\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return this.left.count() + 1 + this.right.count();\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return (this.left.inorderTraversal(action) ||\r\n !!action(this.key, this.value) ||\r\n this.right.inorderTraversal(action));\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return (this.right.reverseTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.left.reverseTraversal(action));\r\n }\r\n /**\r\n * @returns The minimum node in the tree.\r\n */\r\n min_() {\r\n if (this.left.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n return this.left.min_();\r\n }\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n minKey() {\r\n return this.min_().key;\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n maxKey() {\r\n if (this.right.isEmpty()) {\r\n return this.key;\r\n }\r\n else {\r\n return this.right.maxKey();\r\n }\r\n }\r\n /**\r\n * @param key - Key to insert.\r\n * @param value - Value to insert.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the key/value added.\r\n */\r\n insert(key, value, comparator) {\r\n let n = this;\r\n const cmp = comparator(key, n.key);\r\n if (cmp < 0) {\r\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\r\n }\r\n else if (cmp === 0) {\r\n n = n.copy(null, value, null, null, null);\r\n }\r\n else {\r\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns New tree, with the minimum key removed.\r\n */\r\n removeMin_() {\r\n if (this.left.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n let n = this;\r\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.removeMin_(), null);\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @param key - The key of the item to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the specified item removed.\r\n */\r\n remove(key, comparator) {\r\n let n, smallest;\r\n n = this;\r\n if (comparator(key, n.key) < 0) {\r\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\r\n }\r\n else {\r\n if (n.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\r\n n = n.moveRedRight_();\r\n }\r\n if (comparator(key, n.key) === 0) {\r\n if (n.right.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n else {\r\n smallest = n.right.min_();\r\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\r\n }\r\n }\r\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns Whether this is a RED node.\r\n */\r\n isRed_() {\r\n return this.color;\r\n }\r\n /**\r\n * @returns New tree after performing any needed rotations.\r\n */\r\n fixUp_() {\r\n let n = this;\r\n if (n.right.isRed_() && !n.left.isRed_()) {\r\n n = n.rotateLeft_();\r\n }\r\n if (n.left.isRed_() && n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (n.left.isRed_() && n.right.isRed_()) {\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedLeft.\r\n */\r\n moveRedLeft_() {\r\n let n = this.colorFlip_();\r\n if (n.right.left.isRed_()) {\r\n n = n.copy(null, null, null, null, n.right.rotateRight_());\r\n n = n.rotateLeft_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedRight.\r\n */\r\n moveRedRight_() {\r\n let n = this.colorFlip_();\r\n if (n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after rotateLeft.\r\n */\r\n rotateLeft_() {\r\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\r\n return this.right.copy(null, null, this.color, nl, null);\r\n }\r\n /**\r\n * @returns New tree, after rotateRight.\r\n */\r\n rotateRight_() {\r\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\r\n return this.left.copy(null, null, this.color, null, nr);\r\n }\r\n /**\r\n * @returns Newt ree, after colorFlip.\r\n */\r\n colorFlip_() {\r\n const left = this.left.copy(null, null, !this.left.color, null, null);\r\n const right = this.right.copy(null, null, !this.right.color, null, null);\r\n return this.copy(null, null, !this.color, left, right);\r\n }\r\n /**\r\n * For testing.\r\n *\r\n * @returns True if all is well.\r\n */\r\n checkMaxDepth_() {\r\n const blackDepth = this.check_();\r\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\r\n }\r\n check_() {\r\n if (this.isRed_() && this.left.isRed_()) {\r\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\r\n }\r\n if (this.right.isRed_()) {\r\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\r\n }\r\n const blackDepth = this.left.check_();\r\n if (blackDepth !== this.right.check_()) {\r\n throw new Error('Black depths differ');\r\n }\r\n else {\r\n return blackDepth + (this.isRed_() ? 0 : 1);\r\n }\r\n }\r\n}\r\nLLRBNode.RED = true;\r\nLLRBNode.BLACK = false;\r\n/**\r\n * Represents an empty node (a leaf node in the Red-Black Tree).\r\n */\r\nclass LLRBEmptyNode {\r\n /**\r\n * Returns a copy of the current node.\r\n *\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return this;\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key/value added.\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item added.\r\n */\r\n insert(key, value, comparator) {\r\n return new LLRBNode(key, value, null);\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item removed.\r\n */\r\n remove(key, comparator) {\r\n return this;\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return 0;\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return true;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n inorderTraversal(action) {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return false;\r\n }\r\n minKey() {\r\n return null;\r\n }\r\n maxKey() {\r\n return null;\r\n }\r\n check_() {\r\n return 0;\r\n }\r\n /**\r\n * @returns Whether this node is red.\r\n */\r\n isRed_() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\r\n * tree.\r\n */\r\nclass SortedMap {\r\n /**\r\n * @param comparator_ - Key comparator.\r\n * @param root_ - Optional root node for the map.\r\n */\r\n constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {\r\n this.comparator_ = comparator_;\r\n this.root_ = root_;\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key/value added or replaced.\r\n * (TODO: We should perhaps rename this method to 'put')\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @returns New map, with item added.\r\n */\r\n insert(key, value) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .insert(key, value, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @returns New map, with item removed.\r\n */\r\n remove(key) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .remove(key, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns the value of the node with the given key, or null.\r\n *\r\n * @param key - The key to look up.\r\n * @returns The value of the node with the given key, or null if the\r\n * key doesn't exist.\r\n */\r\n get(key) {\r\n let cmp;\r\n let node = this.root_;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n return node.value;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n node = node.right;\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n * Returns the key of the item *before* the specified key, or null if key is the first item.\r\n * @param key - The key to find the predecessor of\r\n * @returns The predecessor key.\r\n */\r\n getPredecessorKey(key) {\r\n let cmp, node = this.root_, rightParent = null;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n if (!node.left.isEmpty()) {\r\n node = node.left;\r\n while (!node.right.isEmpty()) {\r\n node = node.right;\r\n }\r\n return node.key;\r\n }\r\n else if (rightParent) {\r\n return rightParent.key;\r\n }\r\n else {\r\n return null; // first item.\r\n }\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n rightParent = node;\r\n node = node.right;\r\n }\r\n }\r\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\r\n }\r\n /**\r\n * @returns True if the map is empty.\r\n */\r\n isEmpty() {\r\n return this.root_.isEmpty();\r\n }\r\n /**\r\n * @returns The total number of nodes in the map.\r\n */\r\n count() {\r\n return this.root_.count();\r\n }\r\n /**\r\n * @returns The minimum key in the map.\r\n */\r\n minKey() {\r\n return this.root_.minKey();\r\n }\r\n /**\r\n * @returns The maximum key in the map.\r\n */\r\n maxKey() {\r\n return this.root_.maxKey();\r\n }\r\n /**\r\n * Traverses the map in key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return this.root_.inorderTraversal(action);\r\n }\r\n /**\r\n * Traverses the map in reverse key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns True if the traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return this.root_.reverseTraversal(action);\r\n }\r\n /**\r\n * Returns an iterator over the SortedMap.\r\n * @returns The iterator.\r\n */\r\n getIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\r\n }\r\n getIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\r\n }\r\n getReverseIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\r\n }\r\n getReverseIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\r\n }\r\n}\r\n/**\r\n * Always use the same empty node, to reduce memory.\r\n */\r\nSortedMap.EMPTY_NODE = new LLRBEmptyNode();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction NAME_ONLY_COMPARATOR(left, right) {\r\n return nameCompare(left.name, right.name);\r\n}\r\nfunction NAME_COMPARATOR(left, right) {\r\n return nameCompare(left, right);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet MAX_NODE$2;\r\nfunction setMaxNode$1(val) {\r\n MAX_NODE$2 = val;\r\n}\r\nconst priorityHashText = function (priority) {\r\n if (typeof priority === 'number') {\r\n return 'number:' + doubleToIEEE754String(priority);\r\n }\r\n else {\r\n return 'string:' + priority;\r\n }\r\n};\r\n/**\r\n * Validates that a priority snapshot Node is valid.\r\n */\r\nconst validatePriorityNode = function (priorityNode) {\r\n if (priorityNode.isLeafNode()) {\r\n const val = priorityNode.val();\r\n assert(typeof val === 'string' ||\r\n typeof val === 'number' ||\r\n (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');\r\n }\r\n else {\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');\r\n }\r\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet __childrenNodeConstructor;\r\n/**\r\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\r\n * implements Node and stores the value of the node (a string,\r\n * number, or boolean) accessible via getValue().\r\n */\r\nclass LeafNode {\r\n /**\r\n * @param value_ - The value to store in this leaf node. The object type is\r\n * possible in the event of a deferred value\r\n * @param priorityNode_ - The priority of this node.\r\n */\r\n constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n this.value_ = value_;\r\n this.priorityNode_ = priorityNode_;\r\n this.lazyHash_ = null;\r\n assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n static set __childrenNodeConstructor(val) {\r\n __childrenNodeConstructor = val;\r\n }\r\n static get __childrenNodeConstructor() {\r\n return __childrenNodeConstructor;\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return true;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n return new LeafNode(this.value_, newPriorityNode);\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n if (pathIsEmpty(path)) {\r\n return this;\r\n }\r\n else if (pathGetFront(path) === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n hasChild() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode) {\r\n return null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else if (newChildNode.isEmpty() && childName !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else if (newChildNode.isEmpty() && front !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return 0;\r\n }\r\n /** @inheritDoc */\r\n forEachChild(index, action) {\r\n return false;\r\n }\r\n val(exportFormat) {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n return {\r\n '.value': this.getValue(),\r\n '.priority': this.getPriority().val()\r\n };\r\n }\r\n else {\r\n return this.getValue();\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.priorityNode_.isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.priorityNode_.val()) +\r\n ':';\r\n }\r\n const type = typeof this.value_;\r\n toHash += type + ':';\r\n if (type === 'number') {\r\n toHash += doubleToIEEE754String(this.value_);\r\n }\r\n else {\r\n toHash += this.value_;\r\n }\r\n this.lazyHash_ = sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /**\r\n * Returns the value of the leaf node.\r\n * @returns The value of the node.\r\n */\r\n getValue() {\r\n return this.value_;\r\n }\r\n compareTo(other) {\r\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n return 1;\r\n }\r\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\r\n return -1;\r\n }\r\n else {\r\n assert(other.isLeafNode(), 'Unknown node type');\r\n return this.compareToLeafNode_(other);\r\n }\r\n }\r\n /**\r\n * Comparison specifically for two leaf nodes\r\n */\r\n compareToLeafNode_(otherLeaf) {\r\n const otherLeafType = typeof otherLeaf.value_;\r\n const thisLeafType = typeof this.value_;\r\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\r\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\r\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\r\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\r\n if (otherIndex === thisIndex) {\r\n // Same type, compare values\r\n if (thisLeafType === 'object') {\r\n // Deferred value nodes are all equal, but we should also never get to this point...\r\n return 0;\r\n }\r\n else {\r\n // Note that this works because true > false, all others are number or string comparisons\r\n if (this.value_ < otherLeaf.value_) {\r\n return -1;\r\n }\r\n else if (this.value_ === otherLeaf.value_) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n }\r\n else {\r\n return thisIndex - otherIndex;\r\n }\r\n }\r\n withIndex() {\r\n return this;\r\n }\r\n isIndexed() {\r\n return true;\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n const otherLeaf = other;\r\n return (this.value_ === otherLeaf.value_ &&\r\n this.priorityNode_.equals(otherLeaf.priorityNode_));\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n}\r\n/**\r\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\r\n * the same type, the comparison falls back to their value\r\n */\r\nLeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet nodeFromJSON$1;\r\nlet MAX_NODE$1;\r\nfunction setNodeFromJSON(val) {\r\n nodeFromJSON$1 = val;\r\n}\r\nfunction setMaxNode(val) {\r\n MAX_NODE$1 = val;\r\n}\r\nclass PriorityIndex extends Index {\r\n compare(a, b) {\r\n const aPriority = a.node.getPriority();\r\n const bPriority = b.node.getPriority();\r\n const indexCmp = aPriority.compareTo(bPriority);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return !node.getPriority().isEmpty();\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.getPriority().equals(newNode.getPriority());\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));\r\n }\r\n makePost(indexValue, name) {\r\n const priorityNode = nodeFromJSON$1(indexValue);\r\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.priority';\r\n }\r\n}\r\nconst PRIORITY_INDEX = new PriorityIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst LOG_2 = Math.log(2);\r\nclass Base12Num {\r\n constructor(length) {\r\n const logBase2 = (num) => \r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n parseInt((Math.log(num) / LOG_2), 10);\r\n const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);\r\n this.count = logBase2(length + 1);\r\n this.current_ = this.count - 1;\r\n const mask = bitMask(this.count);\r\n this.bits_ = (length + 1) & mask;\r\n }\r\n nextBitIsOne() {\r\n //noinspection JSBitwiseOperatorUsage\r\n const result = !(this.bits_ & (0x1 << this.current_));\r\n this.current_--;\r\n return result;\r\n }\r\n}\r\n/**\r\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\r\n * function\r\n *\r\n * Uses the algorithm described in the paper linked here:\r\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\r\n *\r\n * @param childList - Unsorted list of children\r\n * @param cmp - The comparison method to be used\r\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\r\n * type is not NamedNode\r\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\r\n */\r\nconst buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\r\n childList.sort(cmp);\r\n const buildBalancedTree = function (low, high) {\r\n const length = high - low;\r\n let namedNode;\r\n let key;\r\n if (length === 0) {\r\n return null;\r\n }\r\n else if (length === 1) {\r\n namedNode = childList[low];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);\r\n }\r\n else {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const middle = parseInt((length / 2), 10) + low;\r\n const left = buildBalancedTree(low, middle);\r\n const right = buildBalancedTree(middle + 1, high);\r\n namedNode = childList[middle];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);\r\n }\r\n };\r\n const buildFrom12Array = function (base12) {\r\n let node = null;\r\n let root = null;\r\n let index = childList.length;\r\n const buildPennant = function (chunkSize, color) {\r\n const low = index - chunkSize;\r\n const high = index;\r\n index -= chunkSize;\r\n const childTree = buildBalancedTree(low + 1, high);\r\n const namedNode = childList[low];\r\n const key = keyFn ? keyFn(namedNode) : namedNode;\r\n attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));\r\n };\r\n const attachPennant = function (pennant) {\r\n if (node) {\r\n node.left = pennant;\r\n node = pennant;\r\n }\r\n else {\r\n root = pennant;\r\n node = pennant;\r\n }\r\n };\r\n for (let i = 0; i < base12.count; ++i) {\r\n const isOne = base12.nextBitIsOne();\r\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\r\n const chunkSize = Math.pow(2, base12.count - (i + 1));\r\n if (isOne) {\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n }\r\n else {\r\n // current == 2\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n buildPennant(chunkSize, LLRBNode.RED);\r\n }\r\n }\r\n return root;\r\n };\r\n const base12 = new Base12Num(childList.length);\r\n const root = buildFrom12Array(base12);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return new SortedMap(mapSortFn || cmp, root);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet _defaultIndexMap;\r\nconst fallbackObject = {};\r\nclass IndexMap {\r\n constructor(indexes_, indexSet_) {\r\n this.indexes_ = indexes_;\r\n this.indexSet_ = indexSet_;\r\n }\r\n /**\r\n * The default IndexMap for nodes without a priority\r\n */\r\n static get Default() {\r\n assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\r\n _defaultIndexMap =\r\n _defaultIndexMap ||\r\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });\r\n return _defaultIndexMap;\r\n }\r\n get(indexKey) {\r\n const sortedMap = safeGet(this.indexes_, indexKey);\r\n if (!sortedMap) {\r\n throw new Error('No index defined for ' + indexKey);\r\n }\r\n if (sortedMap instanceof SortedMap) {\r\n return sortedMap;\r\n }\r\n else {\r\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\r\n // regular child map\r\n return null;\r\n }\r\n }\r\n hasIndex(indexDefinition) {\r\n return contains(this.indexSet_, indexDefinition.toString());\r\n }\r\n addIndex(indexDefinition, existingChildren) {\r\n assert(indexDefinition !== KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\r\n const childList = [];\r\n let sawIndexedValue = false;\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n sawIndexedValue =\r\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\r\n childList.push(next);\r\n next = iter.getNext();\r\n }\r\n let newIndex;\r\n if (sawIndexedValue) {\r\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\r\n }\r\n else {\r\n newIndex = fallbackObject;\r\n }\r\n const indexName = indexDefinition.toString();\r\n const newIndexSet = Object.assign({}, this.indexSet_);\r\n newIndexSet[indexName] = indexDefinition;\r\n const newIndexes = Object.assign({}, this.indexes_);\r\n newIndexes[indexName] = newIndex;\r\n return new IndexMap(newIndexes, newIndexSet);\r\n }\r\n /**\r\n * Ensure that this node is properly tracked in any indexes that we're maintaining\r\n */\r\n addToIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {\r\n const index = safeGet(this.indexSet_, indexName);\r\n assert(index, 'Missing index implementation for ' + indexName);\r\n if (indexedChildren === fallbackObject) {\r\n // Check to see if we need to index everything\r\n if (index.isDefinedOn(namedNode.node)) {\r\n // We need to build this index\r\n const childList = [];\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n if (next.name !== namedNode.name) {\r\n childList.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n childList.push(namedNode);\r\n return buildChildSet(childList, index.getCompare());\r\n }\r\n else {\r\n // No change, this remains a fallback\r\n return fallbackObject;\r\n }\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n let newChildren = indexedChildren;\r\n if (existingSnap) {\r\n newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n return newChildren.insert(namedNode, namedNode.node);\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n }\r\n /**\r\n * Create a new IndexMap instance with the given value removed\r\n */\r\n removeFromIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren) => {\r\n if (indexedChildren === fallbackObject) {\r\n // This is the fallback. Just return it, nothing to do in this case\r\n return indexedChildren;\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n if (existingSnap) {\r\n return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n else {\r\n // No record of this child\r\n return indexedChildren;\r\n }\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\r\nlet EMPTY_NODE;\r\n/**\r\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\r\n * (i.e. nodes with children). It implements Node and stores the\r\n * list of children in the children property, sorted by child name.\r\n */\r\nclass ChildrenNode {\r\n /**\r\n * @param children_ - List of children of this node..\r\n * @param priorityNode_ - The priority of this node (as a snapshot node).\r\n */\r\n constructor(children_, priorityNode_, indexMap_) {\r\n this.children_ = children_;\r\n this.priorityNode_ = priorityNode_;\r\n this.indexMap_ = indexMap_;\r\n this.lazyHash_ = null;\r\n /**\r\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\r\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\r\n * class instead of an empty ChildrenNode.\r\n */\r\n if (this.priorityNode_) {\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n if (this.children_.isEmpty()) {\r\n assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\r\n }\r\n }\r\n static get EMPTY_NODE() {\r\n return (EMPTY_NODE ||\r\n (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_ || EMPTY_NODE;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n if (this.children_.isEmpty()) {\r\n // Don't allow priorities on empty nodes\r\n return this;\r\n }\r\n else {\r\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.getPriority();\r\n }\r\n else {\r\n const child = this.children_.get(childName);\r\n return child === null ? EMPTY_NODE : child;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return this;\r\n }\r\n return this.getImmediateChild(front).getChild(pathPopFront(path));\r\n }\r\n /** @inheritDoc */\r\n hasChild(childName) {\r\n return this.children_.get(childName) !== null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n assert(newChildNode, 'We should always be passing snapshot nodes');\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else {\r\n const namedNode = new NamedNode(childName, newChildNode);\r\n let newChildren, newIndexMap;\r\n if (newChildNode.isEmpty()) {\r\n newChildren = this.children_.remove(childName);\r\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\r\n }\r\n else {\r\n newChildren = this.children_.insert(childName, newChildNode);\r\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\r\n }\r\n const newPriority = newChildren.isEmpty()\r\n ? EMPTY_NODE\r\n : this.priorityNode_;\r\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else {\r\n assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);\r\n return this.updateImmediateChild(front, newImmediateChild);\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return this.children_.isEmpty();\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return this.children_.count();\r\n }\r\n /** @inheritDoc */\r\n val(exportFormat) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const obj = {};\r\n let numKeys = 0, maxKey = 0, allIntegerKeys = true;\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n obj[key] = childNode.val(exportFormat);\r\n numKeys++;\r\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\r\n maxKey = Math.max(maxKey, Number(key));\r\n }\r\n else {\r\n allIntegerKeys = false;\r\n }\r\n });\r\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\r\n // convert to array.\r\n const array = [];\r\n // eslint-disable-next-line guard-for-in\r\n for (const key in obj) {\r\n array[key] = obj[key];\r\n }\r\n return array;\r\n }\r\n else {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n obj['.priority'] = this.getPriority().val();\r\n }\r\n return obj;\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.getPriority().isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.getPriority().val()) +\r\n ':';\r\n }\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n const childHash = childNode.hash();\r\n if (childHash !== '') {\r\n toHash += ':' + key + ':' + childHash;\r\n }\r\n });\r\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode, index) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));\r\n return predecessor ? predecessor.name : null;\r\n }\r\n else {\r\n return this.children_.getPredecessorKey(childName);\r\n }\r\n }\r\n getFirstChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const minKey = idx.minKey();\r\n return minKey && minKey.name;\r\n }\r\n else {\r\n return this.children_.minKey();\r\n }\r\n }\r\n getFirstChild(indexDefinition) {\r\n const minKey = this.getFirstChildName(indexDefinition);\r\n if (minKey) {\r\n return new NamedNode(minKey, this.children_.get(minKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n /**\r\n * Given an index, return the key name of the largest value we have, according to that index\r\n */\r\n getLastChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const maxKey = idx.maxKey();\r\n return maxKey && maxKey.name;\r\n }\r\n else {\r\n return this.children_.maxKey();\r\n }\r\n }\r\n getLastChild(indexDefinition) {\r\n const maxKey = this.getLastChildName(indexDefinition);\r\n if (maxKey) {\r\n return new NamedNode(maxKey, this.children_.get(maxKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n forEachChild(index, action) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n return idx.inorderTraversal(wrappedNode => {\r\n return action(wrappedNode.name, wrappedNode.node);\r\n });\r\n }\r\n else {\r\n return this.children_.inorderTraversal(action);\r\n }\r\n }\r\n getIterator(indexDefinition) {\r\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\r\n }\r\n getIteratorFrom(startPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getIteratorFrom(startPost, key => key);\r\n }\r\n else {\r\n const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n getReverseIterator(indexDefinition) {\r\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\r\n }\r\n getReverseIteratorFrom(endPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getReverseIteratorFrom(endPost, key => {\r\n return key;\r\n });\r\n }\r\n else {\r\n const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n compareTo(other) {\r\n if (this.isEmpty()) {\r\n if (other.isEmpty()) {\r\n return 0;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (other.isLeafNode() || other.isEmpty()) {\r\n return 1;\r\n }\r\n else if (other === MAX_NODE) {\r\n return -1;\r\n }\r\n else {\r\n // Must be another node with children.\r\n return 0;\r\n }\r\n }\r\n withIndex(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX ||\r\n this.indexMap_.hasIndex(indexDefinition)) {\r\n return this;\r\n }\r\n else {\r\n const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\r\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\r\n }\r\n }\r\n isIndexed(index) {\r\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n const otherChildrenNode = other;\r\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\r\n return false;\r\n }\r\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\r\n const thisIter = this.getIterator(PRIORITY_INDEX);\r\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\r\n let thisCurrent = thisIter.getNext();\r\n let otherCurrent = otherIter.getNext();\r\n while (thisCurrent && otherCurrent) {\r\n if (thisCurrent.name !== otherCurrent.name ||\r\n !thisCurrent.node.equals(otherCurrent.node)) {\r\n return false;\r\n }\r\n thisCurrent = thisIter.getNext();\r\n otherCurrent = otherIter.getNext();\r\n }\r\n return thisCurrent === null && otherCurrent === null;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n }\r\n /**\r\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\r\n * instead.\r\n *\r\n */\r\n resolveIndex_(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX) {\r\n return null;\r\n }\r\n else {\r\n return this.indexMap_.get(indexDefinition.toString());\r\n }\r\n }\r\n}\r\nChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\r\nclass MaxNode extends ChildrenNode {\r\n constructor() {\r\n super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);\r\n }\r\n compareTo(other) {\r\n if (other === this) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n equals(other) {\r\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\r\n return other === this;\r\n }\r\n getPriority() {\r\n return this;\r\n }\r\n getImmediateChild(childName) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n isEmpty() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Marker that will sort higher than any other snapshot.\r\n */\r\nconst MAX_NODE = new MaxNode();\r\nObject.defineProperties(NamedNode, {\r\n MIN: {\r\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\r\n },\r\n MAX: {\r\n value: new NamedNode(MAX_NAME, MAX_NODE)\r\n }\r\n});\r\n/**\r\n * Reference Extensions\r\n */\r\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\r\nLeafNode.__childrenNodeConstructor = ChildrenNode;\r\nsetMaxNode$1(MAX_NODE);\r\nsetMaxNode(MAX_NODE);\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst USE_HINZE = true;\r\n/**\r\n * Constructs a snapshot node representing the passed JSON and returns it.\r\n * @param json - JSON to create a node for.\r\n * @param priority - Optional priority to use. This will be ignored if the\r\n * passed JSON contains a .priority property.\r\n */\r\nfunction nodeFromJSON(json, priority = null) {\r\n if (json === null) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n if (typeof json === 'object' && '.priority' in json) {\r\n priority = json['.priority'];\r\n }\r\n assert(priority === null ||\r\n typeof priority === 'string' ||\r\n typeof priority === 'number' ||\r\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\r\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\r\n json = json['.value'];\r\n }\r\n // Valid leaf nodes include non-objects or server-value wrapper objects\r\n if (typeof json !== 'object' || '.sv' in json) {\r\n const jsonLeaf = json;\r\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\r\n }\r\n if (!(json instanceof Array) && USE_HINZE) {\r\n const children = [];\r\n let childrenHavePriority = false;\r\n const hinzeJsonObj = json;\r\n each(hinzeJsonObj, (key, child) => {\r\n if (key.substring(0, 1) !== '.') {\r\n // Ignore metadata nodes\r\n const childNode = nodeFromJSON(child);\r\n if (!childNode.isEmpty()) {\r\n childrenHavePriority =\r\n childrenHavePriority || !childNode.getPriority().isEmpty();\r\n children.push(new NamedNode(key, childNode));\r\n }\r\n }\r\n });\r\n if (children.length === 0) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);\r\n if (childrenHavePriority) {\r\n const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));\r\n }\r\n else {\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);\r\n }\r\n }\r\n else {\r\n let node = ChildrenNode.EMPTY_NODE;\r\n each(json, (key, childData) => {\r\n if (contains(json, key)) {\r\n if (key.substring(0, 1) !== '.') {\r\n // ignore metadata nodes.\r\n const childNode = nodeFromJSON(childData);\r\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\r\n node = node.updateImmediateChild(key, childNode);\r\n }\r\n }\r\n }\r\n });\r\n return node.updatePriority(nodeFromJSON(priority));\r\n }\r\n}\r\nsetNodeFromJSON(nodeFromJSON);\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PathIndex extends Index {\r\n constructor(indexPath_) {\r\n super();\r\n this.indexPath_ = indexPath_;\r\n assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\r\n }\r\n extractChild(snap) {\r\n return snap.getChild(this.indexPath_);\r\n }\r\n isDefinedOn(node) {\r\n return !node.getChild(this.indexPath_).isEmpty();\r\n }\r\n compare(a, b) {\r\n const aChild = this.extractChild(a.node);\r\n const bChild = this.extractChild(b.node);\r\n const indexCmp = aChild.compareTo(bChild);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\r\n return new NamedNode(name, node);\r\n }\r\n maxPost() {\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\r\n return new NamedNode(MAX_NAME, node);\r\n }\r\n toString() {\r\n return pathSlice(this.indexPath_, 0).join('/');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ValueIndex extends Index {\r\n compare(a, b) {\r\n const indexCmp = a.node.compareTo(b.node);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return true;\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.equals(newNode);\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MAX;\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n return new NamedNode(name, valueNode);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.value';\r\n }\r\n}\r\nconst VALUE_INDEX = new ValueIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction changeValue(snapshotNode) {\r\n return { type: \"value\" /* ChangeType.VALUE */, snapshotNode };\r\n}\r\nfunction changeChildAdded(childName, snapshotNode) {\r\n return { type: \"child_added\" /* ChangeType.CHILD_ADDED */, snapshotNode, childName };\r\n}\r\nfunction changeChildRemoved(childName, snapshotNode) {\r\n return { type: \"child_removed\" /* ChangeType.CHILD_REMOVED */, snapshotNode, childName };\r\n}\r\nfunction changeChildChanged(childName, snapshotNode, oldSnap) {\r\n return {\r\n type: \"child_changed\" /* ChangeType.CHILD_CHANGED */,\r\n snapshotNode,\r\n childName,\r\n oldSnap\r\n };\r\n}\r\nfunction changeChildMoved(childName, snapshotNode) {\r\n return { type: \"child_moved\" /* ChangeType.CHILD_MOVED */, snapshotNode, childName };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\r\n */\r\nclass IndexedFilter {\r\n constructor(index_) {\r\n this.index_ = index_;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\r\n const oldChild = snap.getImmediateChild(key);\r\n // Check if anything actually changed.\r\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\r\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\r\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\r\n // to avoid treating these cases as \"nothing changed.\"\r\n if (oldChild.isEmpty() === newChild.isEmpty()) {\r\n // Nothing changed.\r\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\r\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\r\n return snap;\r\n }\r\n }\r\n if (optChangeAccumulator != null) {\r\n if (newChild.isEmpty()) {\r\n if (snap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));\r\n }\r\n else {\r\n assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\r\n }\r\n }\r\n else if (oldChild.isEmpty()) {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));\r\n }\r\n }\r\n if (snap.isLeafNode() && newChild.isEmpty()) {\r\n return snap;\r\n }\r\n else {\r\n // Make sure the node is indexed\r\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (optChangeAccumulator != null) {\r\n if (!oldSnap.isLeafNode()) {\r\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!newSnap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));\r\n }\r\n });\r\n }\r\n if (!newSnap.isLeafNode()) {\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (oldSnap.hasChild(key)) {\r\n const oldChild = oldSnap.getImmediateChild(key);\r\n if (!oldChild.equals(childNode)) {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));\r\n }\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));\r\n }\r\n });\r\n }\r\n }\r\n return newSnap.withIndex(this.index_);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n if (oldSnap.isEmpty()) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n else {\r\n return oldSnap.updatePriority(newPriority);\r\n }\r\n }\r\n filtersNodes() {\r\n return false;\r\n }\r\n getIndexedFilter() {\r\n return this;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\r\n */\r\nclass RangedFilter {\r\n constructor(params) {\r\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\r\n this.index_ = params.getIndex();\r\n this.startPost_ = RangedFilter.getStartPost_(params);\r\n this.endPost_ = RangedFilter.getEndPost_(params);\r\n this.startIsInclusive_ = !params.startAfterSet_;\r\n this.endIsInclusive_ = !params.endBeforeSet_;\r\n }\r\n getStartPost() {\r\n return this.startPost_;\r\n }\r\n getEndPost() {\r\n return this.endPost_;\r\n }\r\n matches(node) {\r\n const isWithinStart = this.startIsInclusive_\r\n ? this.index_.compare(this.getStartPost(), node) <= 0\r\n : this.index_.compare(this.getStartPost(), node) < 0;\r\n const isWithinEnd = this.endIsInclusive_\r\n ? this.index_.compare(node, this.getEndPost()) <= 0\r\n : this.index_.compare(node, this.getEndPost()) < 0;\r\n return isWithinStart && isWithinEnd;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (newSnap.isLeafNode()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n newSnap = ChildrenNode.EMPTY_NODE;\r\n }\r\n let filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n const self = this;\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!self.matches(new NamedNode(key, childNode))) {\r\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\r\n }\r\n });\r\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.indexedFilter_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n static getStartPost_(params) {\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\r\n }\r\n else {\r\n return params.getIndex().minPost();\r\n }\r\n }\r\n static getEndPost_(params) {\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\r\n }\r\n else {\r\n return params.getIndex().maxPost();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\r\n */\r\nclass LimitedFilter {\r\n constructor(params) {\r\n this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);\r\n this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);\r\n this.withinStartPost = (node) => {\r\n const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);\r\n return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;\r\n };\r\n this.withinEndPost = (node) => {\r\n const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());\r\n return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;\r\n };\r\n this.rangedFilter_ = new RangedFilter(params);\r\n this.index_ = params.getIndex();\r\n this.limit_ = params.getLimit();\r\n this.reverse_ = !params.isViewFromLeft();\r\n this.startIsInclusive_ = !params.startAfterSet_;\r\n this.endIsInclusive_ = !params.endBeforeSet_;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n if (snap.getImmediateChild(key).equals(newChild)) {\r\n // No change\r\n return snap;\r\n }\r\n else if (snap.numChildren() < this.limit_) {\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n else {\r\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n let filtered;\r\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n }\r\n else {\r\n if (this.limit_ * 2 < newSnap.numChildren() &&\r\n newSnap.isIndexed(this.index_)) {\r\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n // anchor to the startPost, endPost, or last element as appropriate\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\r\n }\r\n else {\r\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\r\n }\r\n let count = 0;\r\n while (iterator.hasNext() && count < this.limit_) {\r\n const next = iterator.getNext();\r\n if (!this.withinDirectionalStart(next)) {\r\n // if we have not reached the start, skip to the next element\r\n continue;\r\n }\r\n else if (!this.withinDirectionalEnd(next)) {\r\n // if we have reached the end, stop adding elements\r\n break;\r\n }\r\n else {\r\n filtered = filtered.updateImmediateChild(next.name, next.node);\r\n count++;\r\n }\r\n }\r\n }\r\n else {\r\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\r\n filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = filtered.getReverseIterator(this.index_);\r\n }\r\n else {\r\n iterator = filtered.getIterator(this.index_);\r\n }\r\n let count = 0;\r\n while (iterator.hasNext()) {\r\n const next = iterator.getNext();\r\n const inRange = count < this.limit_ &&\r\n this.withinDirectionalStart(next) &&\r\n this.withinDirectionalEnd(next);\r\n if (inRange) {\r\n count++;\r\n }\r\n else {\r\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n }\r\n }\r\n }\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.rangedFilter_.getIndexedFilter();\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {\r\n // TODO: rename all cache stuff etc to general snap terminology\r\n let cmp;\r\n if (this.reverse_) {\r\n const indexCmp = this.index_.getCompare();\r\n cmp = (a, b) => indexCmp(b, a);\r\n }\r\n else {\r\n cmp = this.index_.getCompare();\r\n }\r\n const oldEventCache = snap;\r\n assert(oldEventCache.numChildren() === this.limit_, '');\r\n const newChildNamedNode = new NamedNode(childKey, childSnap);\r\n const windowBoundary = this.reverse_\r\n ? oldEventCache.getFirstChild(this.index_)\r\n : oldEventCache.getLastChild(this.index_);\r\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\r\n if (oldEventCache.hasChild(childKey)) {\r\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\r\n let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\r\n while (nextChild != null &&\r\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {\r\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\r\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\r\n // the limited filter...\r\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\r\n }\r\n const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\r\n const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\r\n if (remainsInWindow) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));\r\n }\r\n return oldEventCache.updateImmediateChild(childKey, childSnap);\r\n }\r\n else {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));\r\n }\r\n const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);\r\n const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\r\n if (nextChildInRange) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));\r\n }\r\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\r\n }\r\n else {\r\n return newEventCache;\r\n }\r\n }\r\n }\r\n else if (childSnap.isEmpty()) {\r\n // we're deleting a node, but it was not in the window, so ignore it\r\n return snap;\r\n }\r\n else if (inRange) {\r\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));\r\n changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));\r\n }\r\n return oldEventCache\r\n .updateImmediateChild(childKey, childSnap)\r\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\r\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\r\n * user-facing API level, so it is not done here.\r\n *\r\n * @internal\r\n */\r\nclass QueryParams {\r\n constructor() {\r\n this.limitSet_ = false;\r\n this.startSet_ = false;\r\n this.startNameSet_ = false;\r\n this.startAfterSet_ = false; // can only be true if startSet_ is true\r\n this.endSet_ = false;\r\n this.endNameSet_ = false;\r\n this.endBeforeSet_ = false; // can only be true if endSet_ is true\r\n this.limit_ = 0;\r\n this.viewFrom_ = '';\r\n this.indexStartValue_ = null;\r\n this.indexStartName_ = '';\r\n this.indexEndValue_ = null;\r\n this.indexEndName_ = '';\r\n this.index_ = PRIORITY_INDEX;\r\n }\r\n hasStart() {\r\n return this.startSet_;\r\n }\r\n /**\r\n * @returns True if it would return from left.\r\n */\r\n isViewFromLeft() {\r\n if (this.viewFrom_ === '') {\r\n // limit(), rather than limitToFirst or limitToLast was called.\r\n // This means that only one of startSet_ and endSet_ is true. Use them\r\n // to calculate which side of the view to anchor to. If neither is set,\r\n // anchor to the end.\r\n return this.startSet_;\r\n }\r\n else {\r\n return this.viewFrom_ === \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\r\n }\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true\r\n */\r\n getIndexStartValue() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n return this.indexStartValue_;\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true.\r\n * Returns the starting key name for the range defined by these query parameters\r\n */\r\n getIndexStartName() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n if (this.startNameSet_) {\r\n return this.indexStartName_;\r\n }\r\n else {\r\n return MIN_NAME;\r\n }\r\n }\r\n hasEnd() {\r\n return this.endSet_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n */\r\n getIndexEndValue() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n return this.indexEndValue_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n * Returns the end key name for the range defined by these query parameters\r\n */\r\n getIndexEndName() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n if (this.endNameSet_) {\r\n return this.indexEndName_;\r\n }\r\n else {\r\n return MAX_NAME;\r\n }\r\n }\r\n hasLimit() {\r\n return this.limitSet_;\r\n }\r\n /**\r\n * @returns True if a limit has been set and it has been explicitly anchored\r\n */\r\n hasAnchoredLimit() {\r\n return this.limitSet_ && this.viewFrom_ !== '';\r\n }\r\n /**\r\n * Only valid to call if hasLimit() returns true\r\n */\r\n getLimit() {\r\n assert(this.limitSet_, 'Only valid if limit has been set');\r\n return this.limit_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n loadsAllData() {\r\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\r\n }\r\n isDefault() {\r\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\r\n }\r\n copy() {\r\n const copy = new QueryParams();\r\n copy.limitSet_ = this.limitSet_;\r\n copy.limit_ = this.limit_;\r\n copy.startSet_ = this.startSet_;\r\n copy.startAfterSet_ = this.startAfterSet_;\r\n copy.indexStartValue_ = this.indexStartValue_;\r\n copy.startNameSet_ = this.startNameSet_;\r\n copy.indexStartName_ = this.indexStartName_;\r\n copy.endSet_ = this.endSet_;\r\n copy.endBeforeSet_ = this.endBeforeSet_;\r\n copy.indexEndValue_ = this.indexEndValue_;\r\n copy.endNameSet_ = this.endNameSet_;\r\n copy.indexEndName_ = this.indexEndName_;\r\n copy.index_ = this.index_;\r\n copy.viewFrom_ = this.viewFrom_;\r\n return copy;\r\n }\r\n}\r\nfunction queryParamsGetNodeFilter(queryParams) {\r\n if (queryParams.loadsAllData()) {\r\n return new IndexedFilter(queryParams.getIndex());\r\n }\r\n else if (queryParams.hasLimit()) {\r\n return new LimitedFilter(queryParams);\r\n }\r\n else {\r\n return new RangedFilter(queryParams);\r\n }\r\n}\r\nfunction queryParamsLimitToFirst(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\r\n return newParams;\r\n}\r\nfunction queryParamsLimitToLast(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\r\n return newParams;\r\n}\r\nfunction queryParamsStartAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.startSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexStartValue_ = indexValue;\r\n if (key != null) {\r\n newParams.startNameSet_ = true;\r\n newParams.indexStartName_ = key;\r\n }\r\n else {\r\n newParams.startNameSet_ = false;\r\n newParams.indexStartName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsStartAfter(queryParams, indexValue, key) {\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX || !!key) {\r\n params = queryParamsStartAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n params = queryParamsStartAt(queryParams, indexValue, MAX_NAME);\r\n }\r\n params.startAfterSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsEndAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.endSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexEndValue_ = indexValue;\r\n if (key !== undefined) {\r\n newParams.endNameSet_ = true;\r\n newParams.indexEndName_ = key;\r\n }\r\n else {\r\n newParams.endNameSet_ = false;\r\n newParams.indexEndName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsEndBefore(queryParams, indexValue, key) {\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX || !!key) {\r\n params = queryParamsEndAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n params = queryParamsEndAt(queryParams, indexValue, MIN_NAME);\r\n }\r\n params.endBeforeSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsOrderBy(queryParams, index) {\r\n const newParams = queryParams.copy();\r\n newParams.index_ = index;\r\n return newParams;\r\n}\r\n/**\r\n * Returns a set of REST query string parameters representing this query.\r\n *\r\n * @returns query string parameters\r\n */\r\nfunction queryParamsToRestQueryStringParameters(queryParams) {\r\n const qs = {};\r\n if (queryParams.isDefault()) {\r\n return qs;\r\n }\r\n let orderBy;\r\n if (queryParams.index_ === PRIORITY_INDEX) {\r\n orderBy = \"$priority\" /* REST_QUERY_CONSTANTS.PRIORITY_INDEX */;\r\n }\r\n else if (queryParams.index_ === VALUE_INDEX) {\r\n orderBy = \"$value\" /* REST_QUERY_CONSTANTS.VALUE_INDEX */;\r\n }\r\n else if (queryParams.index_ === KEY_INDEX) {\r\n orderBy = \"$key\" /* REST_QUERY_CONSTANTS.KEY_INDEX */;\r\n }\r\n else {\r\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\r\n orderBy = queryParams.index_.toString();\r\n }\r\n qs[\"orderBy\" /* REST_QUERY_CONSTANTS.ORDER_BY */] = stringify(orderBy);\r\n if (queryParams.startSet_) {\r\n const startParam = queryParams.startAfterSet_\r\n ? \"startAfter\" /* REST_QUERY_CONSTANTS.START_AFTER */\r\n : \"startAt\" /* REST_QUERY_CONSTANTS.START_AT */;\r\n qs[startParam] = stringify(queryParams.indexStartValue_);\r\n if (queryParams.startNameSet_) {\r\n qs[startParam] += ',' + stringify(queryParams.indexStartName_);\r\n }\r\n }\r\n if (queryParams.endSet_) {\r\n const endParam = queryParams.endBeforeSet_\r\n ? \"endBefore\" /* REST_QUERY_CONSTANTS.END_BEFORE */\r\n : \"endAt\" /* REST_QUERY_CONSTANTS.END_AT */;\r\n qs[endParam] = stringify(queryParams.indexEndValue_);\r\n if (queryParams.endNameSet_) {\r\n qs[endParam] += ',' + stringify(queryParams.indexEndName_);\r\n }\r\n }\r\n if (queryParams.limitSet_) {\r\n if (queryParams.isViewFromLeft()) {\r\n qs[\"limitToFirst\" /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */] = queryParams.limit_;\r\n }\r\n else {\r\n qs[\"limitToLast\" /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */] = queryParams.limit_;\r\n }\r\n }\r\n return qs;\r\n}\r\nfunction queryParamsGetQueryObject(queryParams) {\r\n const obj = {};\r\n if (queryParams.startSet_) {\r\n obj[\"sp\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */] =\r\n queryParams.indexStartValue_;\r\n if (queryParams.startNameSet_) {\r\n obj[\"sn\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */] =\r\n queryParams.indexStartName_;\r\n }\r\n obj[\"sin\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */] =\r\n !queryParams.startAfterSet_;\r\n }\r\n if (queryParams.endSet_) {\r\n obj[\"ep\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */] = queryParams.indexEndValue_;\r\n if (queryParams.endNameSet_) {\r\n obj[\"en\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */] = queryParams.indexEndName_;\r\n }\r\n obj[\"ein\" /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */] =\r\n !queryParams.endBeforeSet_;\r\n }\r\n if (queryParams.limitSet_) {\r\n obj[\"l\" /* WIRE_PROTOCOL_CONSTANTS.LIMIT */] = queryParams.limit_;\r\n let viewFrom = queryParams.viewFrom_;\r\n if (viewFrom === '') {\r\n if (queryParams.isViewFromLeft()) {\r\n viewFrom = \"l\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT */;\r\n }\r\n else {\r\n viewFrom = \"r\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT */;\r\n }\r\n }\r\n obj[\"vf\" /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */] = viewFrom;\r\n }\r\n // For now, priority index is the default, so we only specify if it's some other index\r\n if (queryParams.index_ !== PRIORITY_INDEX) {\r\n obj[\"i\" /* WIRE_PROTOCOL_CONSTANTS.INDEX */] = queryParams.index_.toString();\r\n }\r\n return obj;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of ServerActions that communicates with the server via REST requests.\r\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\r\n * persistent connection (using WebSockets or long-polling)\r\n */\r\nclass ReadonlyRestClient extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n /** @private {function(...[*])} */\r\n this.log_ = logWrapper('p:rest:');\r\n /**\r\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\r\n * that's been removed. :-/\r\n */\r\n this.listens_ = {};\r\n }\r\n reportStats(stats) {\r\n throw new Error('Method not implemented.');\r\n }\r\n static getListenId_(query, tag) {\r\n if (tag !== undefined) {\r\n return 'tag$' + tag;\r\n }\r\n else {\r\n assert(query._queryParams.isDefault(), \"should have a tag if it's not a default query.\");\r\n return query._path.toString();\r\n }\r\n }\r\n /** @inheritDoc */\r\n listen(query, currentHashFn, tag, onComplete) {\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\r\n // Mark this listener so we can tell if it's removed.\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n const thisListen = {};\r\n this.listens_[listenId] = thisListen;\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\r\n }\r\n if (safeGet(this.listens_, listenId) === thisListen) {\r\n let status;\r\n if (!error) {\r\n status = 'ok';\r\n }\r\n else if (error === 401) {\r\n status = 'permission_denied';\r\n }\r\n else {\r\n status = 'rest_error:' + error;\r\n }\r\n onComplete(status, null);\r\n }\r\n });\r\n }\r\n /** @inheritDoc */\r\n unlisten(query, tag) {\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n delete this.listens_[listenId];\r\n }\r\n get(query) {\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n const pathString = query._path.toString();\r\n const deferred = new Deferred();\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, \r\n /*isMerge=*/ false, \r\n /*tag=*/ null);\r\n deferred.resolve(data);\r\n }\r\n else {\r\n deferred.reject(new Error(data));\r\n }\r\n });\r\n return deferred.promise;\r\n }\r\n /** @inheritDoc */\r\n refreshAuthToken(token) {\r\n // no-op since we just always call getToken.\r\n }\r\n /**\r\n * Performs a REST request to the given path, with the provided query string parameters,\r\n * and any auth credentials we have.\r\n */\r\n restRequest_(pathString, queryStringParameters = {}, callback) {\r\n queryStringParameters['format'] = 'export';\r\n return Promise.all([\r\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\r\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\r\n ]).then(([authToken, appCheckToken]) => {\r\n if (authToken && authToken.accessToken) {\r\n queryStringParameters['auth'] = authToken.accessToken;\r\n }\r\n if (appCheckToken && appCheckToken.token) {\r\n queryStringParameters['ac'] = appCheckToken.token;\r\n }\r\n const url = (this.repoInfo_.secure ? 'https://' : 'http://') +\r\n this.repoInfo_.host +\r\n pathString +\r\n '?' +\r\n 'ns=' +\r\n this.repoInfo_.namespace +\r\n querystring(queryStringParameters);\r\n this.log_('Sending REST request for ' + url);\r\n const xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange = () => {\r\n if (callback && xhr.readyState === 4) {\r\n this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\r\n let res = null;\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n try {\r\n res = jsonEval(xhr.responseText);\r\n }\r\n catch (e) {\r\n warn('Failed to parse JSON response for ' +\r\n url +\r\n ': ' +\r\n xhr.responseText);\r\n }\r\n callback(null, res);\r\n }\r\n else {\r\n // 401 and 404 are expected.\r\n if (xhr.status !== 401 && xhr.status !== 404) {\r\n warn('Got unsuccessful REST response for ' +\r\n url +\r\n ' Status: ' +\r\n xhr.status);\r\n }\r\n callback(xhr.status);\r\n }\r\n callback = null;\r\n }\r\n };\r\n xhr.open('GET', url, /*asynchronous=*/ true);\r\n xhr.send();\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\r\n */\r\nclass SnapshotHolder {\r\n constructor() {\r\n this.rootNode_ = ChildrenNode.EMPTY_NODE;\r\n }\r\n getNode(path) {\r\n return this.rootNode_.getChild(path);\r\n }\r\n updateSnapshot(path, newSnapshotNode) {\r\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newSparseSnapshotTree() {\r\n return {\r\n value: null,\r\n children: new Map()\r\n };\r\n}\r\n/**\r\n * Stores the given node at the specified path. If there is already a node\r\n * at a shallower path, it merges the new data into that snapshot node.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @param data - The new data, or null.\r\n */\r\nfunction sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = data;\r\n sparseSnapshotTree.children.clear();\r\n }\r\n else if (sparseSnapshotTree.value !== null) {\r\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n if (!sparseSnapshotTree.children.has(childKey)) {\r\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\r\n }\r\n const child = sparseSnapshotTree.children.get(childKey);\r\n path = pathPopFront(path);\r\n sparseSnapshotTreeRemember(child, path, data);\r\n }\r\n}\r\n/**\r\n * Purge the data at path from the cache.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @returns True if this node should now be removed.\r\n */\r\nfunction sparseSnapshotTreeForget(sparseSnapshotTree, path) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = null;\r\n sparseSnapshotTree.children.clear();\r\n return true;\r\n }\r\n else {\r\n if (sparseSnapshotTree.value !== null) {\r\n if (sparseSnapshotTree.value.isLeafNode()) {\r\n // We're trying to forget a node that doesn't exist\r\n return false;\r\n }\r\n else {\r\n const value = sparseSnapshotTree.value;\r\n sparseSnapshotTree.value = null;\r\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\r\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\r\n });\r\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\r\n }\r\n }\r\n else if (sparseSnapshotTree.children.size > 0) {\r\n const childKey = pathGetFront(path);\r\n path = pathPopFront(path);\r\n if (sparseSnapshotTree.children.has(childKey)) {\r\n const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);\r\n if (safeToRemove) {\r\n sparseSnapshotTree.children.delete(childKey);\r\n }\r\n }\r\n return sparseSnapshotTree.children.size === 0;\r\n }\r\n else {\r\n return true;\r\n }\r\n }\r\n}\r\n/**\r\n * Recursively iterates through all of the stored tree and calls the\r\n * callback on each one.\r\n *\r\n * @param prefixPath - Path to look up node for.\r\n * @param func - The function to invoke for each tree.\r\n */\r\nfunction sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {\r\n if (sparseSnapshotTree.value !== null) {\r\n func(prefixPath, sparseSnapshotTree.value);\r\n }\r\n else {\r\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\r\n const path = new Path(prefixPath.toString() + '/' + key);\r\n sparseSnapshotTreeForEachTree(tree, path, func);\r\n });\r\n }\r\n}\r\n/**\r\n * Iterates through each immediate child and triggers the callback.\r\n * Only seems to be used in tests.\r\n *\r\n * @param func - The function to invoke for each child.\r\n */\r\nfunction sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {\r\n sparseSnapshotTree.children.forEach((tree, key) => {\r\n func(key, tree);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns the delta from the previous call to get stats.\r\n *\r\n * @param collection_ - The collection to \"listen\" to.\r\n */\r\nclass StatsListener {\r\n constructor(collection_) {\r\n this.collection_ = collection_;\r\n this.last_ = null;\r\n }\r\n get() {\r\n const newStats = this.collection_.get();\r\n const delta = Object.assign({}, newStats);\r\n if (this.last_) {\r\n each(this.last_, (stat, value) => {\r\n delta[stat] = delta[stat] - value;\r\n });\r\n }\r\n this.last_ = newStats;\r\n return delta;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\r\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\r\n// seconds to try to ensure the Firebase connection is established / settled.\r\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\r\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\r\n// We'll continue to report stats on average every 5 minutes.\r\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\r\nclass StatsReporter {\r\n constructor(collection, server_) {\r\n this.server_ = server_;\r\n this.statsToReport_ = {};\r\n this.statsListener_ = new StatsListener(collection);\r\n const timeout = FIRST_STATS_MIN_TIME +\r\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\r\n }\r\n reportStats_() {\r\n const stats = this.statsListener_.get();\r\n const reportedStats = {};\r\n let haveStatsToReport = false;\r\n each(stats, (stat, value) => {\r\n if (value > 0 && contains(this.statsToReport_, stat)) {\r\n reportedStats[stat] = value;\r\n haveStatsToReport = true;\r\n }\r\n });\r\n if (haveStatsToReport) {\r\n this.server_.reportStats(reportedStats);\r\n }\r\n // queue our next run.\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n *\r\n * @enum\r\n */\r\nvar OperationType;\r\n(function (OperationType) {\r\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\r\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\r\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\r\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\r\n})(OperationType || (OperationType = {}));\r\nfunction newOperationSourceUser() {\r\n return {\r\n fromUser: true,\r\n fromServer: false,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServer() {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServerTaggedQuery(queryId) {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId,\r\n tagged: true\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AckUserWrite {\r\n /**\r\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\r\n */\r\n constructor(\r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ affectedTree, \r\n /** @inheritDoc */ revert) {\r\n this.path = path;\r\n this.affectedTree = affectedTree;\r\n this.revert = revert;\r\n /** @inheritDoc */\r\n this.type = OperationType.ACK_USER_WRITE;\r\n /** @inheritDoc */\r\n this.source = newOperationSourceUser();\r\n }\r\n operationForChild(childName) {\r\n if (!pathIsEmpty(this.path)) {\r\n assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');\r\n return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);\r\n }\r\n else if (this.affectedTree.value != null) {\r\n assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\r\n // All child locations are affected as well; just return same operation.\r\n return this;\r\n }\r\n else {\r\n const childTree = this.affectedTree.subtree(new Path(childName));\r\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ListenComplete {\r\n constructor(source, path) {\r\n this.source = source;\r\n this.path = path;\r\n /** @inheritDoc */\r\n this.type = OperationType.LISTEN_COMPLETE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new ListenComplete(this.source, newEmptyPath());\r\n }\r\n else {\r\n return new ListenComplete(this.source, pathPopFront(this.path));\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Overwrite {\r\n constructor(source, path, snap) {\r\n this.source = source;\r\n this.path = path;\r\n this.snap = snap;\r\n /** @inheritDoc */\r\n this.type = OperationType.OVERWRITE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));\r\n }\r\n else {\r\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Merge {\r\n constructor(\r\n /** @inheritDoc */ source, \r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ children) {\r\n this.source = source;\r\n this.path = path;\r\n this.children = children;\r\n /** @inheritDoc */\r\n this.type = OperationType.MERGE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n const childTree = this.children.subtree(new Path(childName));\r\n if (childTree.isEmpty()) {\r\n // This child is unaffected\r\n return null;\r\n }\r\n else if (childTree.value) {\r\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\r\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\r\n }\r\n else {\r\n // This is a merge at a deeper level\r\n return new Merge(this.source, newEmptyPath(), childTree);\r\n }\r\n }\r\n else {\r\n assert(pathGetFront(this.path) === childName, \"Can't get a merge for a child not on the path of the operation\");\r\n return new Merge(this.source, pathPopFront(this.path), this.children);\r\n }\r\n }\r\n toString() {\r\n return ('Operation(' +\r\n this.path +\r\n ': ' +\r\n this.source.toString() +\r\n ' merge: ' +\r\n this.children.toString() +\r\n ')');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\r\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\r\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\r\n * whether a node potentially had children removed due to a filter.\r\n */\r\nclass CacheNode {\r\n constructor(node_, fullyInitialized_, filtered_) {\r\n this.node_ = node_;\r\n this.fullyInitialized_ = fullyInitialized_;\r\n this.filtered_ = filtered_;\r\n }\r\n /**\r\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\r\n */\r\n isFullyInitialized() {\r\n return this.fullyInitialized_;\r\n }\r\n /**\r\n * Returns whether this node is potentially missing children due to a filter applied to the node\r\n */\r\n isFiltered() {\r\n return this.filtered_;\r\n }\r\n isCompleteForPath(path) {\r\n if (pathIsEmpty(path)) {\r\n return this.isFullyInitialized() && !this.filtered_;\r\n }\r\n const childKey = pathGetFront(path);\r\n return this.isCompleteForChild(childKey);\r\n }\r\n isCompleteForChild(key) {\r\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\r\n }\r\n getNode() {\r\n return this.node_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\r\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\r\n * for details.\r\n *\r\n */\r\nclass EventGenerator {\r\n constructor(query_) {\r\n this.query_ = query_;\r\n this.index_ = this.query_._queryParams.getIndex();\r\n }\r\n}\r\n/**\r\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\r\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\r\n *\r\n * Notes:\r\n * - child_moved events will be synthesized at this time for any child_changed events that affect\r\n * our index.\r\n * - prevName will be calculated based on the index ordering.\r\n */\r\nfunction eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {\r\n const events = [];\r\n const moves = [];\r\n changes.forEach(change => {\r\n if (change.type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\r\n eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\r\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\r\n }\r\n });\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_removed\" /* ChangeType.CHILD_REMOVED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_added\" /* ChangeType.CHILD_ADDED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_moved\" /* ChangeType.CHILD_MOVED */, moves, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_changed\" /* ChangeType.CHILD_CHANGED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"value\" /* ChangeType.VALUE */, changes, eventRegistrations, eventCache);\r\n return events;\r\n}\r\n/**\r\n * Given changes of a single change type, generate the corresponding events.\r\n */\r\nfunction eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {\r\n const filteredChanges = changes.filter(change => change.type === eventType);\r\n filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));\r\n filteredChanges.forEach(change => {\r\n const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);\r\n registrations.forEach(registration => {\r\n if (registration.respondsTo(change.type)) {\r\n events.push(registration.createEvent(materializedChange, eventGenerator.query_));\r\n }\r\n });\r\n });\r\n}\r\nfunction eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {\r\n if (change.type === 'value' || change.type === 'child_removed') {\r\n return change;\r\n }\r\n else {\r\n change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);\r\n return change;\r\n }\r\n}\r\nfunction eventGeneratorCompareChanges(eventGenerator, a, b) {\r\n if (a.childName == null || b.childName == null) {\r\n throw assertionError('Should only compare child_ events.');\r\n }\r\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\r\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\r\n return eventGenerator.index_.compare(aWrapped, bWrapped);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newViewCache(eventCache, serverCache) {\r\n return { eventCache, serverCache };\r\n}\r\nfunction viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {\r\n return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);\r\n}\r\nfunction viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {\r\n return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));\r\n}\r\nfunction viewCacheGetCompleteEventSnap(viewCache) {\r\n return viewCache.eventCache.isFullyInitialized()\r\n ? viewCache.eventCache.getNode()\r\n : null;\r\n}\r\nfunction viewCacheGetCompleteServerSnap(viewCache) {\r\n return viewCache.serverCache.isFullyInitialized()\r\n ? viewCache.serverCache.getNode()\r\n : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet emptyChildrenSingleton;\r\n/**\r\n * Singleton empty children collection.\r\n *\r\n */\r\nconst EmptyChildren = () => {\r\n if (!emptyChildrenSingleton) {\r\n emptyChildrenSingleton = new SortedMap(stringCompare);\r\n }\r\n return emptyChildrenSingleton;\r\n};\r\n/**\r\n * A tree with immutable elements.\r\n */\r\nclass ImmutableTree {\r\n constructor(value, children = EmptyChildren()) {\r\n this.value = value;\r\n this.children = children;\r\n }\r\n static fromObject(obj) {\r\n let tree = new ImmutableTree(null);\r\n each(obj, (childPath, childSnap) => {\r\n tree = tree.set(new Path(childPath), childSnap);\r\n });\r\n return tree;\r\n }\r\n /**\r\n * True if the value is empty and there are no children\r\n */\r\n isEmpty() {\r\n return this.value === null && this.children.isEmpty();\r\n }\r\n /**\r\n * Given a path and predicate, return the first node and the path to that node\r\n * where the predicate returns true.\r\n *\r\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\r\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\r\n *\r\n * @param relativePath - The remainder of the path\r\n * @param predicate - The predicate to satisfy to return a node\r\n */\r\n findRootMostMatchingPathAndValue(relativePath, predicate) {\r\n if (this.value != null && predicate(this.value)) {\r\n return { path: newEmptyPath(), value: this.value };\r\n }\r\n else {\r\n if (pathIsEmpty(relativePath)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child !== null) {\r\n const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);\r\n if (childExistingPathAndValue != null) {\r\n const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);\r\n return { path: fullPath, value: childExistingPathAndValue.value };\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n /**\r\n * Find, if it exists, the shortest subpath of the given path that points a defined\r\n * value in the tree\r\n */\r\n findRootMostValueAndPath(relativePath) {\r\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\r\n }\r\n /**\r\n * @returns The subtree at the given path\r\n */\r\n subtree(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const childTree = this.children.get(front);\r\n if (childTree !== null) {\r\n return childTree.subtree(pathPopFront(relativePath));\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Sets a value at the specified path.\r\n *\r\n * @param relativePath - Path to set value at.\r\n * @param toSet - Value to set.\r\n * @returns Resulting tree.\r\n */\r\n set(relativePath, toSet) {\r\n if (pathIsEmpty(relativePath)) {\r\n return new ImmutableTree(toSet, this.children);\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.set(pathPopFront(relativePath), toSet);\r\n const newChildren = this.children.insert(front, newChild);\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Removes the value at the specified path.\r\n *\r\n * @param relativePath - Path to value to remove.\r\n * @returns Resulting tree.\r\n */\r\n remove(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n if (this.children.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(null, this.children);\r\n }\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n const newChild = child.remove(pathPopFront(relativePath));\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n if (this.value === null && newChildren.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n else {\r\n return this;\r\n }\r\n }\r\n }\r\n /**\r\n * Gets a value from the tree.\r\n *\r\n * @param relativePath - Path to get value for.\r\n * @returns Value at path, or null.\r\n */\r\n get(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this.value;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n return child.get(pathPopFront(relativePath));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n /**\r\n * Replace the subtree at the specified path with the given new tree.\r\n *\r\n * @param relativePath - Path to replace subtree for.\r\n * @param newTree - New tree.\r\n * @returns Resulting tree.\r\n */\r\n setTree(relativePath, newTree) {\r\n if (pathIsEmpty(relativePath)) {\r\n return newTree;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Performs a depth first fold on this tree. Transforms a tree into a single\r\n * value, given a function that operates on the path to a node, an optional\r\n * current value, and a map of child names to folded subtrees\r\n */\r\n fold(fn) {\r\n return this.fold_(newEmptyPath(), fn);\r\n }\r\n /**\r\n * Recursive helper for public-facing fold() method\r\n */\r\n fold_(pathSoFar, fn) {\r\n const accum = {};\r\n this.children.inorderTraversal((childKey, childTree) => {\r\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\r\n });\r\n return fn(pathSoFar, this.value, accum);\r\n }\r\n /**\r\n * Find the first matching value on the given path. Return the result of applying f to it.\r\n */\r\n findOnPath(path, f) {\r\n return this.findOnPath_(path, newEmptyPath(), f);\r\n }\r\n findOnPath_(pathToFollow, pathSoFar, f) {\r\n const result = this.value ? f(pathSoFar, this.value) : false;\r\n if (result) {\r\n return result;\r\n }\r\n else {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n foreachOnPath(path, f) {\r\n return this.foreachOnPath_(path, newEmptyPath(), f);\r\n }\r\n foreachOnPath_(pathToFollow, currentRelativePath, f) {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return this;\r\n }\r\n else {\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Calls the given function for each node in the tree that has a value.\r\n *\r\n * @param f - A function to be called with the path from the root of the tree to\r\n * a node, and the value at that node. Called in depth-first order.\r\n */\r\n foreach(f) {\r\n this.foreach_(newEmptyPath(), f);\r\n }\r\n foreach_(currentRelativePath, f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\r\n });\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n }\r\n foreachChild(f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value) {\r\n f(childName, childTree.value);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\r\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\r\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\r\n * to reflect the write added.\r\n */\r\nclass CompoundWrite {\r\n constructor(writeTree_) {\r\n this.writeTree_ = writeTree_;\r\n }\r\n static empty() {\r\n return new CompoundWrite(new ImmutableTree(null));\r\n }\r\n}\r\nfunction compoundWriteAddWrite(compoundWrite, path, node) {\r\n if (pathIsEmpty(path)) {\r\n return new CompoundWrite(new ImmutableTree(node));\r\n }\r\n else {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n const rootMostPath = rootmost.path;\r\n let value = rootmost.value;\r\n const relativePath = newRelativePath(rootMostPath, path);\r\n value = value.updateChild(relativePath, node);\r\n return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));\r\n }\r\n else {\r\n const subtree = new ImmutableTree(node);\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n }\r\n}\r\nfunction compoundWriteAddWrites(compoundWrite, path, updates) {\r\n let newWrite = compoundWrite;\r\n each(updates, (childKey, node) => {\r\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\r\n });\r\n return newWrite;\r\n}\r\n/**\r\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\r\n * location, which must be removed by calling this method with that path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to remove.\r\n * @param path - The path at which a write and all deeper writes should be removed\r\n * @returns The new CompoundWrite with the removed path\r\n */\r\nfunction compoundWriteRemoveWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return CompoundWrite.empty();\r\n }\r\n else {\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n}\r\n/**\r\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\r\n * considered \"complete\".\r\n *\r\n * @param compoundWrite - The CompoundWrite to check.\r\n * @param path - The path to check for\r\n * @returns Whether there is a complete write at that path\r\n */\r\nfunction compoundWriteHasCompleteWrite(compoundWrite, path) {\r\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\r\n}\r\n/**\r\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\r\n * writes from deeper paths, but will return child nodes from a more shallow path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get the node from.\r\n * @param path - The path to get a complete write\r\n * @returns The node if complete at that path, or null otherwise.\r\n */\r\nfunction compoundWriteGetCompleteNode(compoundWrite, path) {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n return compoundWrite.writeTree_\r\n .get(rootmost.path)\r\n .getChild(newRelativePath(rootmost.path, path));\r\n }\r\n else {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Returns all children that are guaranteed to be a complete overwrite.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get children from.\r\n * @returns A list of all complete children.\r\n */\r\nfunction compoundWriteGetCompleteChildren(compoundWrite) {\r\n const children = [];\r\n const node = compoundWrite.writeTree_.value;\r\n if (node != null) {\r\n // If it's a leaf node, it has no children; so nothing to do.\r\n if (!node.isLeafNode()) {\r\n node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n children.push(new NamedNode(childName, childNode));\r\n });\r\n }\r\n }\r\n else {\r\n compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value != null) {\r\n children.push(new NamedNode(childName, childTree.value));\r\n }\r\n });\r\n }\r\n return children;\r\n}\r\nfunction compoundWriteChildCompoundWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return compoundWrite;\r\n }\r\n else {\r\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\r\n if (shadowingNode != null) {\r\n return new CompoundWrite(new ImmutableTree(shadowingNode));\r\n }\r\n else {\r\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\r\n * @returns Whether this CompoundWrite is empty\r\n */\r\nfunction compoundWriteIsEmpty(compoundWrite) {\r\n return compoundWrite.writeTree_.isEmpty();\r\n}\r\n/**\r\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\r\n * node\r\n * @param node - The node to apply this CompoundWrite to\r\n * @returns The node with all writes applied\r\n */\r\nfunction compoundWriteApply(compoundWrite, node) {\r\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\r\n}\r\nfunction applySubtreeWrite(relativePath, writeTree, node) {\r\n if (writeTree.value != null) {\r\n // Since there a write is always a leaf, we're done here\r\n return node.updateChild(relativePath, writeTree.value);\r\n }\r\n else {\r\n let priorityWrite = null;\r\n writeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (childKey === '.priority') {\r\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\r\n // to apply priorities to empty nodes that are later filled\r\n assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\r\n priorityWrite = childTree.value;\r\n }\r\n else {\r\n node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);\r\n }\r\n });\r\n // If there was a priority write, we only apply it if the node is not empty\r\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\r\n node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);\r\n }\r\n return node;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\r\n *\r\n */\r\nfunction writeTreeChildWrites(writeTree, path) {\r\n return newWriteTreeRef(path, writeTree);\r\n}\r\n/**\r\n * Record a new overwrite from user code.\r\n *\r\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\r\n */\r\nfunction writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');\r\n if (visible === undefined) {\r\n visible = true;\r\n }\r\n writeTree.allWrites.push({\r\n path,\r\n snap,\r\n writeId,\r\n visible\r\n });\r\n if (visible) {\r\n writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);\r\n }\r\n writeTree.lastWriteId = writeId;\r\n}\r\n/**\r\n * Record a new merge from user code.\r\n */\r\nfunction writeTreeAddMerge(writeTree, path, changedChildren, writeId) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');\r\n writeTree.allWrites.push({\r\n path,\r\n children: changedChildren,\r\n writeId,\r\n visible: true\r\n });\r\n writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);\r\n writeTree.lastWriteId = writeId;\r\n}\r\nfunction writeTreeGetWrite(writeTree, writeId) {\r\n for (let i = 0; i < writeTree.allWrites.length; i++) {\r\n const record = writeTree.allWrites[i];\r\n if (record.writeId === writeId) {\r\n return record;\r\n }\r\n }\r\n return null;\r\n}\r\n/**\r\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\r\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\r\n *\r\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\r\n * events as a result).\r\n */\r\nfunction writeTreeRemoveWrite(writeTree, writeId) {\r\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\r\n // out of order.\r\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\r\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\r\n const idx = writeTree.allWrites.findIndex(s => {\r\n return s.writeId === writeId;\r\n });\r\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\r\n const writeToRemove = writeTree.allWrites[idx];\r\n writeTree.allWrites.splice(idx, 1);\r\n let removedWriteWasVisible = writeToRemove.visible;\r\n let removedWriteOverlapsWithOtherWrites = false;\r\n let i = writeTree.allWrites.length - 1;\r\n while (removedWriteWasVisible && i >= 0) {\r\n const currentWrite = writeTree.allWrites[i];\r\n if (currentWrite.visible) {\r\n if (i >= idx &&\r\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {\r\n // The removed write was completely shadowed by a subsequent write.\r\n removedWriteWasVisible = false;\r\n }\r\n else if (pathContains(writeToRemove.path, currentWrite.path)) {\r\n // Either we're covering some writes or they're covering part of us (depending on which came first).\r\n removedWriteOverlapsWithOtherWrites = true;\r\n }\r\n }\r\n i--;\r\n }\r\n if (!removedWriteWasVisible) {\r\n return false;\r\n }\r\n else if (removedWriteOverlapsWithOtherWrites) {\r\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\r\n writeTreeResetTree_(writeTree);\r\n return true;\r\n }\r\n else {\r\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\r\n if (writeToRemove.snap) {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);\r\n }\r\n else {\r\n const children = writeToRemove.children;\r\n each(children, (childName) => {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));\r\n });\r\n }\r\n return true;\r\n }\r\n}\r\nfunction writeTreeRecordContainsPath_(writeRecord, path) {\r\n if (writeRecord.snap) {\r\n return pathContains(writeRecord.path, path);\r\n }\r\n else {\r\n for (const childName in writeRecord.children) {\r\n if (writeRecord.children.hasOwnProperty(childName) &&\r\n pathContains(pathChild(writeRecord.path, childName), path)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n}\r\n/**\r\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\r\n */\r\nfunction writeTreeResetTree_(writeTree) {\r\n writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());\r\n if (writeTree.allWrites.length > 0) {\r\n writeTree.lastWriteId =\r\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\r\n }\r\n else {\r\n writeTree.lastWriteId = -1;\r\n }\r\n}\r\n/**\r\n * The default filter used when constructing the tree. Keep everything that's visible.\r\n */\r\nfunction writeTreeDefaultFilter_(write) {\r\n return write.visible;\r\n}\r\n/**\r\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\r\n * event data at that path.\r\n */\r\nfunction writeTreeLayerTree_(writes, filter, treeRoot) {\r\n let compoundWrite = CompoundWrite.empty();\r\n for (let i = 0; i < writes.length; ++i) {\r\n const write = writes[i];\r\n // Theory, a later set will either:\r\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\r\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\r\n if (filter(write)) {\r\n const writePath = write.path;\r\n let relativePath;\r\n if (write.snap) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));\r\n }\r\n else ;\r\n }\r\n else if (write.children) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n if (pathIsEmpty(relativePath)) {\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);\r\n }\r\n else {\r\n const child = safeGet(write.children, pathGetFront(relativePath));\r\n if (child) {\r\n // There exists a child in this node that matches the root path\r\n const deepNode = child.getChild(pathPopFront(relativePath));\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);\r\n }\r\n }\r\n }\r\n else ;\r\n }\r\n else {\r\n throw assertionError('WriteRecord should have .snap or .children');\r\n }\r\n }\r\n }\r\n return compoundWrite;\r\n}\r\n/**\r\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\r\n * writes), attempt to calculate a complete snapshot for the given path\r\n *\r\n * @param writeIdsToExclude - An optional set to be excluded\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n if (!writeIdsToExclude && !includeHiddenWrites) {\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (compoundWriteIsEmpty(subMerge)) {\r\n return completeServerCache;\r\n }\r\n else if (completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {\r\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\r\n return null;\r\n }\r\n else {\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(subMerge, layeredCache);\r\n }\r\n }\r\n }\r\n else {\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\r\n return completeServerCache;\r\n }\r\n else {\r\n // If the server cache is null, and we don't have a complete cache, we need to return null\r\n if (!includeHiddenWrites &&\r\n completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {\r\n return null;\r\n }\r\n else {\r\n const filter = function (write) {\r\n return ((write.visible || includeHiddenWrites) &&\r\n (!writeIdsToExclude ||\r\n !~writeIdsToExclude.indexOf(write.writeId)) &&\r\n (pathContains(write.path, treePath) ||\r\n pathContains(treePath, write.path)));\r\n };\r\n const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(mergeAtPath, layeredCache);\r\n }\r\n }\r\n }\r\n}\r\n/**\r\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\r\n * Used when creating new views, to pre-fill their complete event children snapshot.\r\n */\r\nfunction writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {\r\n let completeChildren = ChildrenNode.EMPTY_NODE;\r\n const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (topLevelSet) {\r\n if (!topLevelSet.isLeafNode()) {\r\n // we're shadowing everything. Return the children.\r\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\r\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\r\n });\r\n }\r\n return completeChildren;\r\n }\r\n else if (completeServerChildren) {\r\n // Layer any children we have on top of this\r\n // We know we don't have a top-level set, so just enumerate existing children\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);\r\n completeChildren = completeChildren.updateImmediateChild(childName, node);\r\n });\r\n // Add any complete children we have from the set\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n else {\r\n // We don't have anything to layer on top of. Layer on any children we have\r\n // Note that we can return an empty snap if we have a defined delete\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n}\r\n/**\r\n * Given that the underlying server data has updated, determine what, if anything, needs to be\r\n * applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist\r\n */\r\nfunction writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {\r\n assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\r\n const path = pathChild(treePath, childPath);\r\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\r\n // At this point we can probably guarantee that we're in case 2, meaning no events\r\n // May need to check visibility while doing the findRootMostValueAndPath call\r\n return null;\r\n }\r\n else {\r\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n if (compoundWriteIsEmpty(childMerge)) {\r\n // We're not shadowing at all. Case 1\r\n return existingServerSnap.getChild(childPath);\r\n }\r\n else {\r\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\r\n // However this is tricky to find out, since user updates don't necessary change the server\r\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\r\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\r\n // only check if the updates change the serverNode.\r\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\r\n return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {\r\n const path = pathChild(treePath, childKey);\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n if (existingServerSnap.isCompleteForChild(childKey)) {\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n */\r\nfunction writeTreeShadowingWrite(writeTree, path) {\r\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window.\r\n */\r\nfunction writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {\r\n let toIterate;\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\r\n if (shadowingNode != null) {\r\n toIterate = shadowingNode;\r\n }\r\n else if (completeServerData != null) {\r\n toIterate = compoundWriteApply(merge, completeServerData);\r\n }\r\n else {\r\n // no children to iterate on\r\n return [];\r\n }\r\n toIterate = toIterate.withIndex(index);\r\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\r\n const nodes = [];\r\n const cmp = index.getCompare();\r\n const iter = reverse\r\n ? toIterate.getReverseIteratorFrom(startPost, index)\r\n : toIterate.getIteratorFrom(startPost, index);\r\n let next = iter.getNext();\r\n while (next && nodes.length < count) {\r\n if (cmp(next, startPost) !== 0) {\r\n nodes.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n return nodes;\r\n }\r\n else {\r\n return [];\r\n }\r\n}\r\nfunction newWriteTree() {\r\n return {\r\n visibleWrites: CompoundWrite.empty(),\r\n allWrites: [],\r\n lastWriteId: -1\r\n };\r\n}\r\n/**\r\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\r\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\r\n * can lead to a more expensive calculation.\r\n *\r\n * @param writeIdsToExclude - Optional writes to exclude.\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);\r\n}\r\n/**\r\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\r\n * mix of the given server data and write data.\r\n *\r\n */\r\nfunction writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {\r\n return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);\r\n}\r\n/**\r\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\r\n * if anything, needs to be applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events should be raised\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\r\n *\r\n *\r\n */\r\nfunction writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {\r\n return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n *\r\n */\r\nfunction writeTreeRefShadowingWrite(writeTreeRef, path) {\r\n return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window\r\n */\r\nfunction writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {\r\n return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {\r\n return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);\r\n}\r\n/**\r\n * Return a WriteTreeRef for a child.\r\n */\r\nfunction writeTreeRefChild(writeTreeRef, childName) {\r\n return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);\r\n}\r\nfunction newWriteTreeRef(path, writeTree) {\r\n return {\r\n treePath: path,\r\n writeTree\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ChildChangeAccumulator {\r\n constructor() {\r\n this.changeMap = new Map();\r\n }\r\n trackChildChange(change) {\r\n const type = change.type;\r\n const childKey = change.childName;\r\n assert(type === \"child_added\" /* ChangeType.CHILD_ADDED */ ||\r\n type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ ||\r\n type === \"child_removed\" /* ChangeType.CHILD_REMOVED */, 'Only child changes supported for tracking');\r\n assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\r\n const oldChange = this.changeMap.get(childKey);\r\n if (oldChange) {\r\n const oldType = oldChange.type;\r\n if (type === \"child_added\" /* ChangeType.CHILD_ADDED */ &&\r\n oldType === \"child_removed\" /* ChangeType.CHILD_REMOVED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));\r\n }\r\n else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\r\n oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\r\n this.changeMap.delete(childKey);\r\n }\r\n else if (type === \"child_removed\" /* ChangeType.CHILD_REMOVED */ &&\r\n oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));\r\n }\r\n else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\r\n oldType === \"child_added\" /* ChangeType.CHILD_ADDED */) {\r\n this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));\r\n }\r\n else if (type === \"child_changed\" /* ChangeType.CHILD_CHANGED */ &&\r\n oldType === \"child_changed\" /* ChangeType.CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));\r\n }\r\n else {\r\n throw assertionError('Illegal combination of changes: ' +\r\n change +\r\n ' occurred after ' +\r\n oldChange);\r\n }\r\n }\r\n else {\r\n this.changeMap.set(childKey, change);\r\n }\r\n }\r\n getChanges() {\r\n return Array.from(this.changeMap.values());\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of CompleteChildSource that never returns any additional children\r\n */\r\n// eslint-disable-next-line @typescript-eslint/naming-convention\r\nclass NoCompleteChildSource_ {\r\n getCompleteChild(childKey) {\r\n return null;\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Singleton instance.\r\n */\r\nconst NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\r\n/**\r\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\r\n * old event caches available to calculate complete children.\r\n */\r\nclass WriteTreeCompleteChildSource {\r\n constructor(writes_, viewCache_, optCompleteServerCache_ = null) {\r\n this.writes_ = writes_;\r\n this.viewCache_ = viewCache_;\r\n this.optCompleteServerCache_ = optCompleteServerCache_;\r\n }\r\n getCompleteChild(childKey) {\r\n const node = this.viewCache_.eventCache;\r\n if (node.isCompleteForChild(childKey)) {\r\n return node.getNode().getImmediateChild(childKey);\r\n }\r\n else {\r\n const serverNode = this.optCompleteServerCache_ != null\r\n ? new CacheNode(this.optCompleteServerCache_, true, false)\r\n : this.viewCache_.serverCache;\r\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\r\n }\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n const completeServerData = this.optCompleteServerCache_ != null\r\n ? this.optCompleteServerCache_\r\n : viewCacheGetCompleteServerSnap(this.viewCache_);\r\n const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);\r\n if (nodes.length === 0) {\r\n return null;\r\n }\r\n else {\r\n return nodes[0];\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newViewProcessor(filter) {\r\n return { filter };\r\n}\r\nfunction viewProcessorAssertIndexed(viewProcessor, viewCache) {\r\n assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');\r\n assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');\r\n}\r\nfunction viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {\r\n const accumulator = new ChildChangeAccumulator();\r\n let newViewCache, filterServerNode;\r\n if (operation.type === OperationType.OVERWRITE) {\r\n const overwrite = operation;\r\n if (overwrite.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(overwrite.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered and the\r\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\r\n // again\r\n filterServerNode =\r\n overwrite.source.tagged ||\r\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\r\n newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.MERGE) {\r\n const merge = operation;\r\n if (merge.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(merge.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered\r\n filterServerNode =\r\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\r\n newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.ACK_USER_WRITE) {\r\n const ackUserWrite = operation;\r\n if (!ackUserWrite.revert) {\r\n newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.LISTEN_COMPLETE) {\r\n newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);\r\n }\r\n else {\r\n throw assertionError('Unknown operation type: ' + operation.type);\r\n }\r\n const changes = accumulator.getChanges();\r\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\r\n return { viewCache: newViewCache, changes };\r\n}\r\nfunction viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {\r\n const eventSnap = newViewCache.eventCache;\r\n if (eventSnap.isFullyInitialized()) {\r\n const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\r\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\r\n if (accumulator.length > 0 ||\r\n !oldViewCache.eventCache.isFullyInitialized() ||\r\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\r\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {\r\n accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));\r\n }\r\n }\r\n}\r\nfunction viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {\r\n const oldEventSnap = viewCache.eventCache;\r\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\r\n // we have a shadowing write, ignore changes\r\n return viewCache;\r\n }\r\n else {\r\n let newEventCache, serverNode;\r\n if (pathIsEmpty(changePath)) {\r\n // TODO: figure out how this plays with \"sliding ack windows\"\r\n assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');\r\n if (viewCache.serverCache.isFiltered()) {\r\n // We need to special case this, because we need to only apply writes to complete children, or\r\n // we might end up raising events for incomplete children. If the server data is filtered deep\r\n // writes cannot be guaranteed to be complete\r\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\r\n const completeChildren = serverCache instanceof ChildrenNode\r\n ? serverCache\r\n : ChildrenNode.EMPTY_NODE;\r\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);\r\n }\r\n else {\r\n const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);\r\n }\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n assert(pathGetLength(changePath) === 1, \"Can't have a priority with additional path components\");\r\n const oldEventNode = oldEventSnap.getNode();\r\n serverNode = viewCache.serverCache.getNode();\r\n // we might have overwrites for this priority\r\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);\r\n if (updatedPriority != null) {\r\n newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);\r\n }\r\n else {\r\n // priority didn't change, keep old node\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n // update child\r\n let newEventChild;\r\n if (oldEventSnap.isCompleteForChild(childKey)) {\r\n serverNode = viewCache.serverCache.getNode();\r\n const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);\r\n if (eventChildUpdate != null) {\r\n newEventChild = oldEventSnap\r\n .getNode()\r\n .getImmediateChild(childKey)\r\n .updateChild(childChangePath, eventChildUpdate);\r\n }\r\n else {\r\n // Nothing changed, just keep the old child\r\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n }\r\n }\r\n else {\r\n newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n }\r\n if (newEventChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\r\n }\r\n else {\r\n // no complete child available or no change\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n }\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());\r\n }\r\n}\r\nfunction viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\r\n const oldServerSnap = oldViewCache.serverCache;\r\n let newServerCache;\r\n const serverFilter = filterServerNode\r\n ? viewProcessor.filter\r\n : viewProcessor.filter.getIndexedFilter();\r\n if (pathIsEmpty(changePath)) {\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\r\n }\r\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\r\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\r\n const newServerNode = oldServerSnap\r\n .getNode()\r\n .updateChild(changePath, changedSnap);\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (!oldServerSnap.isCompleteForPath(changePath) &&\r\n pathGetLength(changePath) > 1) {\r\n // We don't update incomplete nodes with updates intended for other listeners\r\n return oldViewCache;\r\n }\r\n const childChangePath = pathPopFront(changePath);\r\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\r\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\r\n if (childKey === '.priority') {\r\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\r\n }\r\n else {\r\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);\r\n }\r\n }\r\n const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());\r\n const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);\r\n}\r\nfunction viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\r\n const oldEventSnap = oldViewCache.eventCache;\r\n let newViewCache, newEventCache;\r\n const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\r\n if (pathIsEmpty(changePath)) {\r\n newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n let newChild;\r\n if (pathIsEmpty(childChangePath)) {\r\n // Child overwrite, we can replace the child\r\n newChild = changedSnap;\r\n }\r\n else {\r\n const childNode = source.getCompleteChild(childKey);\r\n if (childNode != null) {\r\n if (pathGetBack(childChangePath) === '.priority' &&\r\n childNode.getChild(pathParent(childChangePath)).isEmpty()) {\r\n // This is a priority update on an empty node. If this node exists on the server, the\r\n // server will send down the priority in the update, so ignore for now\r\n newChild = childNode;\r\n }\r\n else {\r\n newChild = childNode.updateChild(childChangePath, changedSnap);\r\n }\r\n }\r\n else {\r\n // There is no complete child node available\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n }\r\n if (!oldChild.equals(newChild)) {\r\n const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n newViewCache = oldViewCache;\r\n }\r\n }\r\n }\r\n return newViewCache;\r\n}\r\nfunction viewProcessorCacheHasChild(viewCache, childKey) {\r\n return viewCache.eventCache.isCompleteForChild(childKey);\r\n}\r\nfunction viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorApplyMerge(viewProcessor, node, merge) {\r\n merge.foreach((relativePath, childNode) => {\r\n node = node.updateChild(relativePath, childNode);\r\n });\r\n return node;\r\n}\r\nfunction viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\r\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\r\n // wait for the complete data update coming soon.\r\n if (viewCache.serverCache.getNode().isEmpty() &&\r\n !viewCache.serverCache.isFullyInitialized()) {\r\n return viewCache;\r\n }\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n let viewMergeTree;\r\n if (pathIsEmpty(path)) {\r\n viewMergeTree = changedChildren;\r\n }\r\n else {\r\n viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);\r\n }\r\n const serverNode = viewCache.serverCache.getNode();\r\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (serverNode.hasChild(childKey)) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\r\n const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&\r\n childMergeTree.value === null;\r\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\r\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\r\n return viewCache;\r\n }\r\n // Only filter server node if it is currently filtered\r\n const filterServerNode = viewCache.serverCache.isFiltered();\r\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\r\n // now that it won't be shadowed.\r\n const serverCache = viewCache.serverCache;\r\n if (affectedTree.value != null) {\r\n // This is an overwrite.\r\n if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\r\n serverCache.isCompleteForPath(ackPath)) {\r\n return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else if (pathIsEmpty(ackPath)) {\r\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\r\n // should just re-apply whatever we have in our cache as a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\r\n changedChildren = changedChildren.set(new Path(name), node);\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else {\r\n return viewCache;\r\n }\r\n }\r\n else {\r\n // This is a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n affectedTree.foreach((mergePath, value) => {\r\n const serverCachePath = pathChild(ackPath, mergePath);\r\n if (serverCache.isCompleteForPath(serverCachePath)) {\r\n changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));\r\n }\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n}\r\nfunction viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {\r\n const oldServerNode = viewCache.serverCache;\r\n const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);\r\n}\r\nfunction viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {\r\n let complete;\r\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\r\n return viewCache;\r\n }\r\n else {\r\n const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\r\n const oldEventCache = viewCache.eventCache.getNode();\r\n let newEventCache;\r\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\r\n let newNode;\r\n if (viewCache.serverCache.isFullyInitialized()) {\r\n newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n }\r\n else {\r\n const serverChildren = viewCache.serverCache.getNode();\r\n assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');\r\n newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);\r\n }\r\n newNode = newNode;\r\n newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n if (newChild == null &&\r\n viewCache.serverCache.isCompleteForChild(childKey)) {\r\n newChild = oldEventCache.getImmediateChild(childKey);\r\n }\r\n if (newChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);\r\n }\r\n else if (viewCache.eventCache.getNode().hasChild(childKey)) {\r\n // No complete child available, delete the existing one, if any\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);\r\n }\r\n else {\r\n newEventCache = oldEventCache;\r\n }\r\n if (newEventCache.isEmpty() &&\r\n viewCache.serverCache.isFullyInitialized()) {\r\n // We might have reverted all child writes. Maybe the old event was a leaf node\r\n complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n if (complete.isLeafNode()) {\r\n newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);\r\n }\r\n }\r\n }\r\n complete =\r\n viewCache.serverCache.isFullyInitialized() ||\r\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A view represents a specific location and query that has 1 or more event registrations.\r\n *\r\n * It does several things:\r\n * - Maintains the list of event registrations for this location/query.\r\n * - Maintains a cache of the data visible for this location/query.\r\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\r\n * registrations returns the set of events to be raised.\r\n */\r\nclass View {\r\n constructor(query_, initialViewCache) {\r\n this.query_ = query_;\r\n this.eventRegistrations_ = [];\r\n const params = this.query_._queryParams;\r\n const indexFilter = new IndexedFilter(params.getIndex());\r\n const filter = queryParamsGetNodeFilter(params);\r\n this.processor_ = newViewProcessor(filter);\r\n const initialServerCache = initialViewCache.serverCache;\r\n const initialEventCache = initialViewCache.eventCache;\r\n // Don't filter server node with other filter than index, wait for tagged listen\r\n const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\r\n const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\r\n const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\r\n const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\r\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\r\n this.eventGenerator_ = new EventGenerator(this.query_);\r\n }\r\n get query() {\r\n return this.query_;\r\n }\r\n}\r\nfunction viewGetServerCache(view) {\r\n return view.viewCache_.serverCache.getNode();\r\n}\r\nfunction viewGetCompleteNode(view) {\r\n return viewCacheGetCompleteEventSnap(view.viewCache_);\r\n}\r\nfunction viewGetCompleteServerCache(view, path) {\r\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\r\n if (cache) {\r\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\r\n // we need to see if it contains the child we're interested in.\r\n if (view.query._queryParams.loadsAllData() ||\r\n (!pathIsEmpty(path) &&\r\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {\r\n return cache.getChild(path);\r\n }\r\n }\r\n return null;\r\n}\r\nfunction viewIsEmpty(view) {\r\n return view.eventRegistrations_.length === 0;\r\n}\r\nfunction viewAddEventRegistration(view, eventRegistration) {\r\n view.eventRegistrations_.push(eventRegistration);\r\n}\r\n/**\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction viewRemoveEventRegistration(view, eventRegistration, cancelError) {\r\n const cancelEvents = [];\r\n if (cancelError) {\r\n assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\r\n const path = view.query._path;\r\n view.eventRegistrations_.forEach(registration => {\r\n const maybeEvent = registration.createCancelEvent(cancelError, path);\r\n if (maybeEvent) {\r\n cancelEvents.push(maybeEvent);\r\n }\r\n });\r\n }\r\n if (eventRegistration) {\r\n let remaining = [];\r\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\r\n const existing = view.eventRegistrations_[i];\r\n if (!existing.matches(eventRegistration)) {\r\n remaining.push(existing);\r\n }\r\n else if (eventRegistration.hasAnyCallback()) {\r\n // We're removing just this one\r\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\r\n break;\r\n }\r\n }\r\n view.eventRegistrations_ = remaining;\r\n }\r\n else {\r\n view.eventRegistrations_ = [];\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Applies the given Operation, updates our cache, and returns the appropriate events.\r\n */\r\nfunction viewApplyOperation(view, operation, writesCache, completeServerCache) {\r\n if (operation.type === OperationType.MERGE &&\r\n operation.source.queryId !== null) {\r\n assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');\r\n assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');\r\n }\r\n const oldViewCache = view.viewCache_;\r\n const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);\r\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\r\n assert(result.viewCache.serverCache.isFullyInitialized() ||\r\n !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');\r\n view.viewCache_ = result.viewCache;\r\n return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);\r\n}\r\nfunction viewGetInitialEvents(view, registration) {\r\n const eventSnap = view.viewCache_.eventCache;\r\n const initialChanges = [];\r\n if (!eventSnap.getNode().isLeafNode()) {\r\n const eventNode = eventSnap.getNode();\r\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n initialChanges.push(changeChildAdded(key, childNode));\r\n });\r\n }\r\n if (eventSnap.isFullyInitialized()) {\r\n initialChanges.push(changeValue(eventSnap.getNode()));\r\n }\r\n return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);\r\n}\r\nfunction viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {\r\n const registrations = eventRegistration\r\n ? [eventRegistration]\r\n : view.eventRegistrations_;\r\n return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet referenceConstructor$1;\r\n/**\r\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\r\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\r\n * and user writes (set, transaction, update).\r\n *\r\n * It's responsible for:\r\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\r\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\r\n * applyUserOverwrite, etc.)\r\n */\r\nclass SyncPoint {\r\n constructor() {\r\n /**\r\n * The Views being tracked at this location in the tree, stored as a map where the key is a\r\n * queryId and the value is the View for that query.\r\n *\r\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\r\n */\r\n this.views = new Map();\r\n }\r\n}\r\nfunction syncPointSetReferenceConstructor(val) {\r\n assert(!referenceConstructor$1, '__referenceConstructor has already been defined');\r\n referenceConstructor$1 = val;\r\n}\r\nfunction syncPointGetReferenceConstructor() {\r\n assert(referenceConstructor$1, 'Reference.ts has not been loaded');\r\n return referenceConstructor$1;\r\n}\r\nfunction syncPointIsEmpty(syncPoint) {\r\n return syncPoint.views.size === 0;\r\n}\r\nfunction syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {\r\n const queryId = operation.source.queryId;\r\n if (queryId !== null) {\r\n const view = syncPoint.views.get(queryId);\r\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\r\n return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);\r\n }\r\n else {\r\n let events = [];\r\n for (const view of syncPoint.views.values()) {\r\n events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Get a view for the specified query.\r\n *\r\n * @param query - The query to return a view for\r\n * @param writesCache\r\n * @param serverCache\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {\r\n const queryId = query._queryIdentifier;\r\n const view = syncPoint.views.get(queryId);\r\n if (!view) {\r\n // TODO: make writesCache take flag for complete server node\r\n let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);\r\n let eventCacheComplete = false;\r\n if (eventCache) {\r\n eventCacheComplete = true;\r\n }\r\n else if (serverCache instanceof ChildrenNode) {\r\n eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);\r\n eventCacheComplete = false;\r\n }\r\n else {\r\n eventCache = ChildrenNode.EMPTY_NODE;\r\n eventCacheComplete = false;\r\n }\r\n const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));\r\n return new View(query, viewCache);\r\n }\r\n return view;\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @param query\r\n * @param eventRegistration\r\n * @param writesCache\r\n * @param serverCache - Complete server cache, if we have it.\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);\r\n if (!syncPoint.views.has(query._queryIdentifier)) {\r\n syncPoint.views.set(query._queryIdentifier, view);\r\n }\r\n // This is guaranteed to exist now, we just created anything that was missing\r\n viewAddEventRegistration(view, eventRegistration);\r\n return viewGetInitialEvents(view, eventRegistration);\r\n}\r\n/**\r\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\r\n *\r\n * If query is the default query, we'll check all views for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\r\n *\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns removed queries and any cancel events\r\n */\r\nfunction syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {\r\n const queryId = query._queryIdentifier;\r\n const removed = [];\r\n let cancelEvents = [];\r\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\r\n if (queryId === 'default') {\r\n // When you do ref.off(...), we search all views for the registration to remove.\r\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(viewQueryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // remove the callback from the specific view.\r\n const view = syncPoint.views.get(queryId);\r\n if (view) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(queryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\r\n // We removed our last complete view.\r\n removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));\r\n }\r\n return { removed, events: cancelEvents };\r\n}\r\nfunction syncPointGetQueryViews(syncPoint) {\r\n const result = [];\r\n for (const view of syncPoint.views.values()) {\r\n if (!view.query._queryParams.loadsAllData()) {\r\n result.push(view);\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * @param path - The path to the desired complete snapshot\r\n * @returns A complete cache, if it exists\r\n */\r\nfunction syncPointGetCompleteServerCache(syncPoint, path) {\r\n let serverCache = null;\r\n for (const view of syncPoint.views.values()) {\r\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\r\n }\r\n return serverCache;\r\n}\r\nfunction syncPointViewForQuery(syncPoint, query) {\r\n const params = query._queryParams;\r\n if (params.loadsAllData()) {\r\n return syncPointGetCompleteView(syncPoint);\r\n }\r\n else {\r\n const queryId = query._queryIdentifier;\r\n return syncPoint.views.get(queryId);\r\n }\r\n}\r\nfunction syncPointViewExistsForQuery(syncPoint, query) {\r\n return syncPointViewForQuery(syncPoint, query) != null;\r\n}\r\nfunction syncPointHasCompleteView(syncPoint) {\r\n return syncPointGetCompleteView(syncPoint) != null;\r\n}\r\nfunction syncPointGetCompleteView(syncPoint) {\r\n for (const view of syncPoint.views.values()) {\r\n if (view.query._queryParams.loadsAllData()) {\r\n return view;\r\n }\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet referenceConstructor;\r\nfunction syncTreeSetReferenceConstructor(val) {\r\n assert(!referenceConstructor, '__referenceConstructor has already been defined');\r\n referenceConstructor = val;\r\n}\r\nfunction syncTreeGetReferenceConstructor() {\r\n assert(referenceConstructor, 'Reference.ts has not been loaded');\r\n return referenceConstructor;\r\n}\r\n/**\r\n * Static tracker for next query tag.\r\n */\r\nlet syncTreeNextQueryTag_ = 1;\r\n/**\r\n * SyncTree is the central class for managing event callback registration, data caching, views\r\n * (query processing), and event generation. There are typically two SyncTree instances for\r\n * each Repo, one for the normal Firebase data, and one for the .info data.\r\n *\r\n * It has a number of responsibilities, including:\r\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\r\n * - Applying and caching data changes for user set(), transaction(), and update() calls\r\n * (applyUserOverwrite(), applyUserMerge()).\r\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\r\n * applyServerMerge()).\r\n * - Generating user-facing events for server and user changes (all of the apply* methods\r\n * return the set of events that need to be raised as a result).\r\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\r\n * to the correct set of paths and queries to satisfy the current set of user event\r\n * callbacks (listens are started/stopped using the provided listenProvider).\r\n *\r\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\r\n * events are returned to the caller rather than raised synchronously.\r\n *\r\n */\r\nclass SyncTree {\r\n /**\r\n * @param listenProvider_ - Used by SyncTree to start / stop listening\r\n * to server data.\r\n */\r\n constructor(listenProvider_) {\r\n this.listenProvider_ = listenProvider_;\r\n /**\r\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\r\n */\r\n this.syncPointTree_ = new ImmutableTree(null);\r\n /**\r\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\r\n */\r\n this.pendingWriteTree_ = newWriteTree();\r\n this.tagToQueryMap = new Map();\r\n this.queryToTagMap = new Map();\r\n }\r\n}\r\n/**\r\n * Apply the data changes for a user-generated set() or transaction() call.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {\r\n // Record pending write.\r\n writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);\r\n if (!visible) {\r\n return [];\r\n }\r\n else {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));\r\n }\r\n}\r\n/**\r\n * Apply the data from a user-generated update() call\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {\r\n // Record pending merge.\r\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));\r\n}\r\n/**\r\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\r\n *\r\n * @param revert - True if the given write failed and needs to be reverted\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAckUserWrite(syncTree, writeId, revert = false) {\r\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\r\n const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);\r\n if (!needToReevaluate) {\r\n return [];\r\n }\r\n else {\r\n let affectedTree = new ImmutableTree(null);\r\n if (write.snap != null) {\r\n // overwrite\r\n affectedTree = affectedTree.set(newEmptyPath(), true);\r\n }\r\n else {\r\n each(write.children, (pathString) => {\r\n affectedTree = affectedTree.set(new Path(pathString), true);\r\n });\r\n }\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));\r\n }\r\n}\r\n/**\r\n * Apply new server data for the specified path..\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerOverwrite(syncTree, path, newData) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));\r\n}\r\n/**\r\n * Apply new server data to be merged in at the specified path.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerMerge(syncTree, path, changedChildren) {\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));\r\n}\r\n/**\r\n * Apply a listen complete for a query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyListenComplete(syncTree, path) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));\r\n}\r\n/**\r\n * Apply a listen complete for a tagged query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedListenComplete(syncTree, path, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Remove event callback(s).\r\n *\r\n * If query is the default query, we'll check all queries for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\r\n *\r\n * @param eventRegistration - If null, all callbacks are removed.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @param skipListenerDedup - When performing a `get()`, we don't add any new listeners, so no\r\n * deduping needs to take place. This flag allows toggling of that behavior\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {\r\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\r\n const path = query._path;\r\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\r\n let cancelEvents = [];\r\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\r\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\r\n // not loadsAllData().\r\n if (maybeSyncPoint &&\r\n (query._queryIdentifier === 'default' ||\r\n syncPointViewExistsForQuery(maybeSyncPoint, query))) {\r\n const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);\r\n if (syncPointIsEmpty(maybeSyncPoint)) {\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\r\n }\r\n const removed = removedAndEvents.removed;\r\n cancelEvents = removedAndEvents.events;\r\n if (!skipListenerDedup) {\r\n /**\r\n * We may have just removed one of many listeners and can short-circuit this whole process\r\n * We may also not have removed a default listener, in which case all of the descendant listeners should already be\r\n * properly set up.\r\n */\r\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\r\n // queryId === 'default'\r\n const removingDefault = -1 !==\r\n removed.findIndex(query => {\r\n return query._queryParams.loadsAllData();\r\n });\r\n const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));\r\n if (removingDefault && !covered) {\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\r\n // removal\r\n if (!subtree.isEmpty()) {\r\n // We need to fold over our subtree and collect the listeners to send\r\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\r\n // Ok, we've collected all the listens we need. Set them up.\r\n for (let i = 0; i < newViews.length; ++i) {\r\n const view = newViews[i], newQuery = view.query;\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);\r\n }\r\n }\r\n // Otherwise there's nothing below us, so nothing we need to start listening on\r\n }\r\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\r\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\r\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\r\n if (!covered && removed.length > 0 && !cancelError) {\r\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\r\n // default. Otherwise, we need to iterate through and cancel each individual query\r\n if (removingDefault) {\r\n // We don't tag default listeners\r\n const defaultTag = null;\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);\r\n }\r\n else {\r\n removed.forEach((queryToRemove) => {\r\n const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);\r\n });\r\n }\r\n }\r\n }\r\n // Now, clear all of the tags we're tracking for the removed listens\r\n syncTreeRemoveTags_(syncTree, removed);\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Apply new server data for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey != null) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // Query must have been removed already\r\n return [];\r\n }\r\n}\r\n/**\r\n * Apply server data to be merged in for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {\r\n const path = query._path;\r\n let serverCache = null;\r\n let foundAncestorDefaultView = false;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let serverCacheComplete;\r\n if (serverCache != null) {\r\n serverCacheComplete = true;\r\n }\r\n else {\r\n serverCacheComplete = false;\r\n serverCache = ChildrenNode.EMPTY_NODE;\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n subtree.foreachChild((childName, childSyncPoint) => {\r\n const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());\r\n if (completeCache) {\r\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\r\n }\r\n });\r\n }\r\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\r\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\r\n // We need to track a tag for this query\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');\r\n const tag = syncTreeGetNextQueryTag_();\r\n syncTree.queryToTagMap.set(queryKey, tag);\r\n syncTree.tagToQueryMap.set(tag, queryKey);\r\n }\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\r\n let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);\r\n if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {\r\n const view = syncPointViewForQuery(syncPoint, query);\r\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\r\n }\r\n return events;\r\n}\r\n/**\r\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\r\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\r\n * have a listener above, and atomic operations would correctly show a jitter of ->\r\n * as the write is applied locally and then acknowledged at the server.\r\n *\r\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\r\n *\r\n * @param path - The path to the data we want\r\n * @param writeIdsToExclude - A specific set to be excluded\r\n */\r\nfunction syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {\r\n const includeHiddenSets = true;\r\n const writeTree = syncTree.pendingWriteTree_;\r\n const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {\r\n const relativePath = newRelativePath(pathSoFar, path);\r\n const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);\r\n if (serverCache) {\r\n return serverCache;\r\n }\r\n });\r\n return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);\r\n}\r\nfunction syncTreeGetServerValue(syncTree, query) {\r\n const path = query._path;\r\n let serverCache = null;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n const serverCacheComplete = serverCache != null;\r\n const serverCacheNode = serverCacheComplete\r\n ? new CacheNode(serverCache, true, false)\r\n : null;\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);\r\n return viewGetCompleteNode(view);\r\n}\r\n/**\r\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\r\n *\r\n * NOTES:\r\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\r\n *\r\n * - We call applyOperation() on each SyncPoint passing three things:\r\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\r\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\r\n * 3. A snapshot Node with cached server data, if we have it.\r\n *\r\n * - We concatenate all of the events returned by each SyncPoint and return the result.\r\n */\r\nfunction syncTreeApplyOperationToSyncPoints_(syncTree, operation) {\r\n return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, \r\n /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n if (pathIsEmpty(operation.path)) {\r\n return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\r\n }\r\n else {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n const childName = pathGetFront(operation.path);\r\n const childOperation = operation.operationForChild(childName);\r\n const childTree = syncPointTree.children.get(childName);\r\n if (childTree && childOperation) {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n syncPointTree.children.inorderTraversal((childName, childTree) => {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n const childOperation = operation.operationForChild(childName);\r\n if (childOperation) {\r\n events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n });\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n}\r\nfunction syncTreeCreateListenerForView_(syncTree, view) {\r\n const query = view.query;\r\n const tag = syncTreeTagForQuery(syncTree, query);\r\n return {\r\n hashFn: () => {\r\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\r\n return cache.hash();\r\n },\r\n onComplete: (status) => {\r\n if (status === 'ok') {\r\n if (tag) {\r\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\r\n }\r\n else {\r\n return syncTreeApplyListenComplete(syncTree, query._path);\r\n }\r\n }\r\n else {\r\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\r\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\r\n const error = errorForServerCode(status, query);\r\n return syncTreeRemoveEventRegistration(syncTree, query, \r\n /*eventRegistration*/ null, error);\r\n }\r\n }\r\n };\r\n}\r\n/**\r\n * Return the tag associated with the given query.\r\n */\r\nfunction syncTreeTagForQuery(syncTree, query) {\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n return syncTree.queryToTagMap.get(queryKey);\r\n}\r\n/**\r\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\r\n */\r\nfunction syncTreeMakeQueryKey_(query) {\r\n return query._path.toString() + '$' + query._queryIdentifier;\r\n}\r\n/**\r\n * Return the query associated with the given tag, if we have one\r\n */\r\nfunction syncTreeQueryKeyForTag_(syncTree, tag) {\r\n return syncTree.tagToQueryMap.get(tag);\r\n}\r\n/**\r\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\r\n */\r\nfunction syncTreeParseQueryKey_(queryKey) {\r\n const splitIndex = queryKey.indexOf('$');\r\n assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\r\n return {\r\n queryId: queryKey.substr(splitIndex + 1),\r\n path: new Path(queryKey.substr(0, splitIndex))\r\n };\r\n}\r\n/**\r\n * A helper method to apply tagged operations\r\n */\r\nfunction syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {\r\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\r\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);\r\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\r\n}\r\n/**\r\n * This collapses multiple unfiltered views into a single view, since we only need a single\r\n * listener for them.\r\n */\r\nfunction syncTreeCollectDistinctViewsForSubTree_(subtree) {\r\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\r\n return [completeView];\r\n }\r\n else {\r\n // No complete view here, flatten any deeper listens into an array\r\n let views = [];\r\n if (maybeChildSyncPoint) {\r\n views = syncPointGetQueryViews(maybeChildSyncPoint);\r\n }\r\n each(childMap, (_key, childViews) => {\r\n views = views.concat(childViews);\r\n });\r\n return views;\r\n }\r\n });\r\n}\r\n/**\r\n * Normalizes a query to a query we send the server for listening\r\n *\r\n * @returns The normalized query\r\n */\r\nfunction syncTreeQueryForListening_(query) {\r\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\r\n // We treat queries that load all data as default queries\r\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\r\n // from Query\r\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\r\n }\r\n else {\r\n return query;\r\n }\r\n}\r\nfunction syncTreeRemoveTags_(syncTree, queries) {\r\n for (let j = 0; j < queries.length; ++j) {\r\n const removedQuery = queries[j];\r\n if (!removedQuery._queryParams.loadsAllData()) {\r\n // We should have a tag for this\r\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\r\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\r\n syncTree.queryToTagMap.delete(removedQueryKey);\r\n syncTree.tagToQueryMap.delete(removedQueryTag);\r\n }\r\n }\r\n}\r\n/**\r\n * Static accessor for query tags.\r\n */\r\nfunction syncTreeGetNextQueryTag_() {\r\n return syncTreeNextQueryTag_++;\r\n}\r\n/**\r\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\r\n *\r\n * @returns This method can return events to support synchronous data sources\r\n */\r\nfunction syncTreeSetupListener_(syncTree, query, view) {\r\n const path = query._path;\r\n const tag = syncTreeTagForQuery(syncTree, query);\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\r\n // may need to shadow other listens as well.\r\n if (tag) {\r\n assert(!syncPointHasCompleteView(subtree.value), \"If we're adding a query, it shouldn't be shadowed\");\r\n }\r\n else {\r\n // Shadow everything at or below this location, this is a default listener.\r\n const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (!pathIsEmpty(relativePath) &&\r\n maybeChildSyncPoint &&\r\n syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\r\n }\r\n else {\r\n // No default listener here, flatten any deeper queries into an array\r\n let queries = [];\r\n if (maybeChildSyncPoint) {\r\n queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));\r\n }\r\n each(childMap, (_key, childQueries) => {\r\n queries = queries.concat(childQueries);\r\n });\r\n return queries;\r\n }\r\n });\r\n for (let i = 0; i < queriesToStop.length; ++i) {\r\n const queryToStop = queriesToStop[i];\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));\r\n }\r\n }\r\n return events;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ExistingValueProvider {\r\n constructor(node_) {\r\n this.node_ = node_;\r\n }\r\n getImmediateChild(childName) {\r\n const child = this.node_.getImmediateChild(childName);\r\n return new ExistingValueProvider(child);\r\n }\r\n node() {\r\n return this.node_;\r\n }\r\n}\r\nclass DeferredValueProvider {\r\n constructor(syncTree, path) {\r\n this.syncTree_ = syncTree;\r\n this.path_ = path;\r\n }\r\n getImmediateChild(childName) {\r\n const childPath = pathChild(this.path_, childName);\r\n return new DeferredValueProvider(this.syncTree_, childPath);\r\n }\r\n node() {\r\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\r\n }\r\n}\r\n/**\r\n * Generate placeholders for deferred values.\r\n */\r\nconst generateWithValues = function (values) {\r\n values = values || {};\r\n values['timestamp'] = values['timestamp'] || new Date().getTime();\r\n return values;\r\n};\r\n/**\r\n * Value to use when firing local events. When writing server values, fire\r\n * local events with an approximate value, otherwise return value as-is.\r\n */\r\nconst resolveDeferredLeafValue = function (value, existingVal, serverValues) {\r\n if (!value || typeof value !== 'object') {\r\n return value;\r\n }\r\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\r\n if (typeof value['.sv'] === 'string') {\r\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\r\n }\r\n else if (typeof value['.sv'] === 'object') {\r\n return resolveComplexDeferredValue(value['.sv'], existingVal);\r\n }\r\n else {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\r\n }\r\n};\r\nconst resolveScalarDeferredValue = function (op, existing, serverValues) {\r\n switch (op) {\r\n case 'timestamp':\r\n return serverValues['timestamp'];\r\n default:\r\n assert(false, 'Unexpected server value: ' + op);\r\n }\r\n};\r\nconst resolveComplexDeferredValue = function (op, existing, unused) {\r\n if (!op.hasOwnProperty('increment')) {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\r\n }\r\n const delta = op['increment'];\r\n if (typeof delta !== 'number') {\r\n assert(false, 'Unexpected increment value: ' + delta);\r\n }\r\n const existingNode = existing.node();\r\n assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');\r\n // Incrementing a non-number sets the value to the incremented amount\r\n if (!existingNode.isLeafNode()) {\r\n return delta;\r\n }\r\n const leaf = existingNode;\r\n const existingVal = leaf.getValue();\r\n if (typeof existingVal !== 'number') {\r\n return delta;\r\n }\r\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\r\n return existingVal + delta;\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the tree with the\r\n * specified generated replacement values.\r\n * @param path - path to which write is relative\r\n * @param node - new data written at path\r\n * @param syncTree - current data\r\n */\r\nconst resolveDeferredValueTree = function (path, node, syncTree, serverValues) {\r\n return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the node with the\r\n * specified generated replacement values. If there are no server values in the node,\r\n * it'll be returned as-is.\r\n */\r\nconst resolveDeferredValueSnapshot = function (node, existing, serverValues) {\r\n return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);\r\n};\r\nfunction resolveDeferredValue(node, existingVal, serverValues) {\r\n const rawPri = node.getPriority().val();\r\n const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);\r\n let newNode;\r\n if (node.isLeafNode()) {\r\n const leafNode = node;\r\n const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);\r\n if (value !== leafNode.getValue() ||\r\n priority !== leafNode.getPriority().val()) {\r\n return new LeafNode(value, nodeFromJSON(priority));\r\n }\r\n else {\r\n return node;\r\n }\r\n }\r\n else {\r\n const childrenNode = node;\r\n newNode = childrenNode;\r\n if (priority !== childrenNode.getPriority().val()) {\r\n newNode = newNode.updatePriority(new LeafNode(priority));\r\n }\r\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);\r\n if (newChildNode !== childNode) {\r\n newNode = newNode.updateImmediateChild(childName, newChildNode);\r\n }\r\n });\r\n return newNode;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A light-weight tree, traversable by path. Nodes can have both values and children.\r\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\r\n * children.\r\n */\r\nclass Tree {\r\n /**\r\n * @param name - Optional name of the node.\r\n * @param parent - Optional parent node.\r\n * @param node - Optional node to wrap.\r\n */\r\n constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {\r\n this.name = name;\r\n this.parent = parent;\r\n this.node = node;\r\n }\r\n}\r\n/**\r\n * Returns a sub-Tree for the given path.\r\n *\r\n * @param pathObj - Path to look up.\r\n * @returns Tree for path.\r\n */\r\nfunction treeSubTree(tree, pathObj) {\r\n // TODO: Require pathObj to be Path?\r\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\r\n let child = tree, next = pathGetFront(path);\r\n while (next !== null) {\r\n const childNode = safeGet(child.node.children, next) || {\r\n children: {},\r\n childCount: 0\r\n };\r\n child = new Tree(next, child, childNode);\r\n path = pathPopFront(path);\r\n next = pathGetFront(path);\r\n }\r\n return child;\r\n}\r\n/**\r\n * Returns the data associated with this tree node.\r\n *\r\n * @returns The data or null if no data exists.\r\n */\r\nfunction treeGetValue(tree) {\r\n return tree.node.value;\r\n}\r\n/**\r\n * Sets data to this tree node.\r\n *\r\n * @param value - Value to set.\r\n */\r\nfunction treeSetValue(tree, value) {\r\n tree.node.value = value;\r\n treeUpdateParents(tree);\r\n}\r\n/**\r\n * @returns Whether the tree has any children.\r\n */\r\nfunction treeHasChildren(tree) {\r\n return tree.node.childCount > 0;\r\n}\r\n/**\r\n * @returns Whethe rthe tree is empty (no value or children).\r\n */\r\nfunction treeIsEmpty(tree) {\r\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\r\n}\r\n/**\r\n * Calls action for each child of this tree node.\r\n *\r\n * @param action - Action to be called for each child.\r\n */\r\nfunction treeForEachChild(tree, action) {\r\n each(tree.node.children, (child, childTree) => {\r\n action(new Tree(child, tree, childTree));\r\n });\r\n}\r\n/**\r\n * Does a depth-first traversal of this node's descendants, calling action for each one.\r\n *\r\n * @param action - Action to be called for each child.\r\n * @param includeSelf - Whether to call action on this node as well. Defaults to\r\n * false.\r\n * @param childrenFirst - Whether to call action on children before calling it on\r\n * parent.\r\n */\r\nfunction treeForEachDescendant(tree, action, includeSelf, childrenFirst) {\r\n if (includeSelf && !childrenFirst) {\r\n action(tree);\r\n }\r\n treeForEachChild(tree, child => {\r\n treeForEachDescendant(child, action, true, childrenFirst);\r\n });\r\n if (includeSelf && childrenFirst) {\r\n action(tree);\r\n }\r\n}\r\n/**\r\n * Calls action on each ancestor node.\r\n *\r\n * @param action - Action to be called on each parent; return\r\n * true to abort.\r\n * @param includeSelf - Whether to call action on this node as well.\r\n * @returns true if the action callback returned true.\r\n */\r\nfunction treeForEachAncestor(tree, action, includeSelf) {\r\n let node = includeSelf ? tree : tree.parent;\r\n while (node !== null) {\r\n if (action(node)) {\r\n return true;\r\n }\r\n node = node.parent;\r\n }\r\n return false;\r\n}\r\n/**\r\n * @returns The path of this tree node, as a Path.\r\n */\r\nfunction treeGetPath(tree) {\r\n return new Path(tree.parent === null\r\n ? tree.name\r\n : treeGetPath(tree.parent) + '/' + tree.name);\r\n}\r\n/**\r\n * Adds or removes this child from its parent based on whether it's empty or not.\r\n */\r\nfunction treeUpdateParents(tree) {\r\n if (tree.parent !== null) {\r\n treeUpdateChild(tree.parent, tree.name, tree);\r\n }\r\n}\r\n/**\r\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\r\n *\r\n * @param childName - The name of the child to update.\r\n * @param child - The child to update.\r\n */\r\nfunction treeUpdateChild(tree, childName, child) {\r\n const childEmpty = treeIsEmpty(child);\r\n const childExists = contains(tree.node.children, childName);\r\n if (childEmpty && childExists) {\r\n delete tree.node.children[childName];\r\n tree.node.childCount--;\r\n treeUpdateParents(tree);\r\n }\r\n else if (!childEmpty && !childExists) {\r\n tree.node.children[childName] = child.node;\r\n tree.node.childCount++;\r\n treeUpdateParents(tree);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * True for invalid Firebase keys\r\n */\r\nconst INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * True for invalid Firebase paths.\r\n * Allows '/' in paths.\r\n */\r\nconst INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * Maximum number of characters to allow in leaf value\r\n */\r\nconst MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\r\nconst isValidKey = function (key) {\r\n return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));\r\n};\r\nconst isValidPathString = function (pathString) {\r\n return (typeof pathString === 'string' &&\r\n pathString.length !== 0 &&\r\n !INVALID_PATH_REGEX_.test(pathString));\r\n};\r\nconst isValidRootPathString = function (pathString) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n return isValidPathString(pathString);\r\n};\r\nconst isValidPriority = function (priority) {\r\n return (priority === null ||\r\n typeof priority === 'string' ||\r\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\r\n (priority &&\r\n typeof priority === 'object' &&\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n contains(priority, '.sv')));\r\n};\r\n/**\r\n * Pre-validate a datum passed as an argument to Firebase function.\r\n */\r\nconst validateFirebaseDataArg = function (fnName, value, path, optional) {\r\n if (optional && value === undefined) {\r\n return;\r\n }\r\n validateFirebaseData(errorPrefix(fnName, 'value'), value, path);\r\n};\r\n/**\r\n * Validate a data object client-side before sending to server.\r\n */\r\nconst validateFirebaseData = function (errorPrefix, data, path_) {\r\n const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\r\n if (data === undefined) {\r\n throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));\r\n }\r\n if (typeof data === 'function') {\r\n throw new Error(errorPrefix +\r\n 'contains a function ' +\r\n validationPathToErrorString(path) +\r\n ' with contents = ' +\r\n data.toString());\r\n }\r\n if (isInvalidJSONNumber(data)) {\r\n throw new Error(errorPrefix +\r\n 'contains ' +\r\n data.toString() +\r\n ' ' +\r\n validationPathToErrorString(path));\r\n }\r\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\r\n if (typeof data === 'string' &&\r\n data.length > MAX_LEAF_SIZE_ / 3 &&\r\n stringLength(data) > MAX_LEAF_SIZE_) {\r\n throw new Error(errorPrefix +\r\n 'contains a string greater than ' +\r\n MAX_LEAF_SIZE_ +\r\n ' utf8 bytes ' +\r\n validationPathToErrorString(path) +\r\n \" ('\" +\r\n data.substring(0, 50) +\r\n \"...')\");\r\n }\r\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\r\n // to save extra walking of large objects.\r\n if (data && typeof data === 'object') {\r\n let hasDotValue = false;\r\n let hasActualChild = false;\r\n each(data, (key, value) => {\r\n if (key === '.value') {\r\n hasDotValue = true;\r\n }\r\n else if (key !== '.priority' && key !== '.sv') {\r\n hasActualChild = true;\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix +\r\n ' contains an invalid key (' +\r\n key +\r\n ') ' +\r\n validationPathToErrorString(path) +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n validationPathPush(path, key);\r\n validateFirebaseData(errorPrefix, value, path);\r\n validationPathPop(path);\r\n });\r\n if (hasDotValue && hasActualChild) {\r\n throw new Error(errorPrefix +\r\n ' contains \".value\" child ' +\r\n validationPathToErrorString(path) +\r\n ' in addition to actual children.');\r\n }\r\n }\r\n};\r\n/**\r\n * Pre-validate paths passed in the firebase function.\r\n */\r\nconst validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\r\n let i, curPath;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n const keys = pathSlice(curPath);\r\n for (let j = 0; j < keys.length; j++) {\r\n if (keys[j] === '.priority' && j === keys.length - 1) ;\r\n else if (!isValidKey(keys[j])) {\r\n throw new Error(errorPrefix +\r\n 'contains an invalid key (' +\r\n keys[j] +\r\n ') in path ' +\r\n curPath.toString() +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n }\r\n // Check that update keys are not descendants of each other.\r\n // We rely on the property that sorting guarantees that ancestors come\r\n // right before descendants.\r\n mergePaths.sort(pathCompare);\r\n let prevPath = null;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n if (prevPath !== null && pathContains(prevPath, curPath)) {\r\n throw new Error(errorPrefix +\r\n 'contains a path ' +\r\n prevPath.toString() +\r\n ' that is ancestor of another path ' +\r\n curPath.toString());\r\n }\r\n prevPath = curPath;\r\n }\r\n};\r\n/**\r\n * pre-validate an object passed as an argument to firebase function (\r\n * must be an object - e.g. for firebase.update()).\r\n */\r\nconst validateFirebaseMergeDataArg = function (fnName, data, path, optional) {\r\n if (optional && data === undefined) {\r\n return;\r\n }\r\n const errorPrefix$1 = errorPrefix(fnName, 'values');\r\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\r\n throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');\r\n }\r\n const mergePaths = [];\r\n each(data, (key, value) => {\r\n const curPath = new Path(key);\r\n validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));\r\n if (pathGetBack(curPath) === '.priority') {\r\n if (!isValidPriority(value)) {\r\n throw new Error(errorPrefix$1 +\r\n \"contains an invalid value for '\" +\r\n curPath.toString() +\r\n \"', which must be a valid \" +\r\n 'Firebase priority (a string, finite number, server value, or null).');\r\n }\r\n }\r\n mergePaths.push(curPath);\r\n });\r\n validateFirebaseMergePaths(errorPrefix$1, mergePaths);\r\n};\r\nconst validatePriority = function (fnName, priority, optional) {\r\n if (optional && priority === undefined) {\r\n return;\r\n }\r\n if (isInvalidJSONNumber(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'is ' +\r\n priority.toString() +\r\n ', but must be a valid Firebase priority (a string, finite number, ' +\r\n 'server value, or null).');\r\n }\r\n // Special case to allow importing data with a .sv.\r\n if (!isValidPriority(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'must be a valid Firebase priority ' +\r\n '(a string, finite number, server value, or null).');\r\n }\r\n};\r\nconst validateKey = function (fnName, argumentName, key, optional) {\r\n if (optional && key === undefined) {\r\n return;\r\n }\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid key = \"' +\r\n key +\r\n '\". Firebase keys must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\r\n }\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validatePathString = function (fnName, argumentName, pathString, optional) {\r\n if (optional && pathString === undefined) {\r\n return;\r\n }\r\n if (!isValidPathString(pathString)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid path = \"' +\r\n pathString +\r\n '\". Paths must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\r\n }\r\n};\r\nconst validateRootPathString = function (fnName, argumentName, pathString, optional) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n validatePathString(fnName, argumentName, pathString, optional);\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validateWritablePath = function (fnName, path) {\r\n if (pathGetFront(path) === '.info') {\r\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\r\n }\r\n};\r\nconst validateUrl = function (fnName, parsedUrl) {\r\n // TODO = Validate server better.\r\n const pathString = parsedUrl.path.toString();\r\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\r\n parsedUrl.repoInfo.host.length === 0 ||\r\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\r\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\r\n (pathString.length !== 0 && !isValidRootPathString(pathString))) {\r\n throw new Error(errorPrefix(fnName, 'url') +\r\n 'must be a valid firebase URL and ' +\r\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\r\n }\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The event queue serves a few purposes:\r\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\r\n * events being queued.\r\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\r\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\r\n * left off, ensuring that the events are still raised synchronously and in order.\r\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\r\n * events are raised synchronously.\r\n *\r\n * NOTE: This can all go away if/when we move to async events.\r\n *\r\n */\r\nclass EventQueue {\r\n constructor() {\r\n this.eventLists_ = [];\r\n /**\r\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\r\n */\r\n this.recursionDepth_ = 0;\r\n }\r\n}\r\n/**\r\n * @param eventDataList - The new events to queue.\r\n */\r\nfunction eventQueueQueueEvents(eventQueue, eventDataList) {\r\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\r\n let currList = null;\r\n for (let i = 0; i < eventDataList.length; i++) {\r\n const data = eventDataList[i];\r\n const path = data.getPath();\r\n if (currList !== null && !pathEquals(path, currList.path)) {\r\n eventQueue.eventLists_.push(currList);\r\n currList = null;\r\n }\r\n if (currList === null) {\r\n currList = { events: [], path };\r\n }\r\n currList.events.push(data);\r\n }\r\n if (currList) {\r\n eventQueue.eventLists_.push(currList);\r\n }\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones)\r\n * for the specified path.\r\n *\r\n * It is assumed that the new events are all for the specified path.\r\n *\r\n * @param path - The path to raise events for.\r\n * @param eventDataList - The new events to raise.\r\n */\r\nfunction eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\r\n * locations related to the specified change path (i.e. all ancestors and descendants).\r\n *\r\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\r\n *\r\n * @param changedPath - The path to raise events for.\r\n * @param eventDataList - The events to raise\r\n */\r\nfunction eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||\r\n pathContains(changedPath, eventPath));\r\n}\r\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {\r\n eventQueue.recursionDepth_++;\r\n let sentAll = true;\r\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\r\n const eventList = eventQueue.eventLists_[i];\r\n if (eventList) {\r\n const eventPath = eventList.path;\r\n if (predicate(eventPath)) {\r\n eventListRaise(eventQueue.eventLists_[i]);\r\n eventQueue.eventLists_[i] = null;\r\n }\r\n else {\r\n sentAll = false;\r\n }\r\n }\r\n }\r\n if (sentAll) {\r\n eventQueue.eventLists_ = [];\r\n }\r\n eventQueue.recursionDepth_--;\r\n}\r\n/**\r\n * Iterates through the list and raises each event\r\n */\r\nfunction eventListRaise(eventList) {\r\n for (let i = 0; i < eventList.events.length; i++) {\r\n const eventData = eventList.events[i];\r\n if (eventData !== null) {\r\n eventList.events[i] = null;\r\n const eventFn = eventData.getEventRunner();\r\n if (logger) {\r\n log('event: ' + eventData.toString());\r\n }\r\n exceptionGuard(eventFn);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INTERRUPT_REASON = 'repo_interrupt';\r\n/**\r\n * If a transaction does not succeed after 25 retries, we abort it. Among other\r\n * things this ensure that if there's ever a bug causing a mismatch between\r\n * client / server hashes for some data, we won't retry indefinitely.\r\n */\r\nconst MAX_TRANSACTION_RETRIES = 25;\r\n/**\r\n * A connection to a single data repository.\r\n */\r\nclass Repo {\r\n constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {\r\n this.repoInfo_ = repoInfo_;\r\n this.forceRestClient_ = forceRestClient_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckProvider_ = appCheckProvider_;\r\n this.dataUpdateCount = 0;\r\n this.statsListener_ = null;\r\n this.eventQueue_ = new EventQueue();\r\n this.nextWriteId_ = 1;\r\n this.interceptServerDataCallback_ = null;\r\n /** A list of data pieces and paths to be set when this client disconnects. */\r\n this.onDisconnect_ = newSparseSnapshotTree();\r\n /** Stores queues of outstanding transactions for Firebase locations. */\r\n this.transactionQueueTree_ = new Tree();\r\n // TODO: This should be @private but it's used by test_access.js and internal.js\r\n this.persistentConnection_ = null;\r\n // This key is intentionally not updated if RepoInfo is later changed or replaced\r\n this.key = this.repoInfo_.toURLString();\r\n }\r\n /**\r\n * @returns The URL corresponding to the root of this Firebase.\r\n */\r\n toString() {\r\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\r\n }\r\n}\r\nfunction repoStart(repo, appId, authOverride) {\r\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\r\n if (repo.forceRestClient_ || beingCrawled()) {\r\n repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_);\r\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\r\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\r\n }\r\n else {\r\n // Validate authOverride\r\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\r\n if (typeof authOverride !== 'object') {\r\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\r\n }\r\n try {\r\n stringify(authOverride);\r\n }\r\n catch (e) {\r\n throw new Error('Invalid authOverride provided: ' + e);\r\n }\r\n }\r\n repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, (connectStatus) => {\r\n repoOnConnectStatus(repo, connectStatus);\r\n }, (updates) => {\r\n repoOnServerInfoUpdate(repo, updates);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);\r\n repo.server_ = repo.persistentConnection_;\r\n }\r\n repo.authTokenProvider_.addTokenChangeListener(token => {\r\n repo.server_.refreshAuthToken(token);\r\n });\r\n repo.appCheckProvider_.addTokenChangeListener(result => {\r\n repo.server_.refreshAppCheckToken(result.token);\r\n });\r\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\r\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\r\n repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));\r\n // Used for .info.\r\n repo.infoData_ = new SnapshotHolder();\r\n repo.infoSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n let infoEvents = [];\r\n const node = repo.infoData_.getNode(query._path);\r\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\r\n // on initial data...\r\n if (!node.isEmpty()) {\r\n infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);\r\n setTimeout(() => {\r\n onComplete('ok');\r\n }, 0);\r\n }\r\n return infoEvents;\r\n },\r\n stopListening: () => { }\r\n });\r\n repoUpdateInfo(repo, 'connected', false);\r\n repo.serverSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\r\n const events = onComplete(status, data);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\r\n });\r\n // No synchronous events for network-backed sync trees\r\n return [];\r\n },\r\n stopListening: (query, tag) => {\r\n repo.server_.unlisten(query, tag);\r\n }\r\n });\r\n}\r\n/**\r\n * @returns The time in milliseconds, taking the server offset into account if we have one.\r\n */\r\nfunction repoServerTime(repo) {\r\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\r\n const offset = offsetNode.val() || 0;\r\n return new Date().getTime() + offset;\r\n}\r\n/**\r\n * Generate ServerValues using some variables from the repo object.\r\n */\r\nfunction repoGenerateServerValues(repo) {\r\n return generateWithValues({\r\n timestamp: repoServerTime(repo)\r\n });\r\n}\r\n/**\r\n * Called by realtime when we get new messages from the server.\r\n */\r\nfunction repoOnDataUpdate(repo, pathString, data, isMerge, tag) {\r\n // For testing.\r\n repo.dataUpdateCount++;\r\n const path = new Path(pathString);\r\n data = repo.interceptServerDataCallback_\r\n ? repo.interceptServerDataCallback_(pathString, data)\r\n : data;\r\n let events = [];\r\n if (tag) {\r\n if (isMerge) {\r\n const taggedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);\r\n }\r\n else {\r\n const taggedSnap = nodeFromJSON(data);\r\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);\r\n }\r\n }\r\n else if (isMerge) {\r\n const changedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);\r\n }\r\n else {\r\n const snap = nodeFromJSON(data);\r\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\r\n }\r\n let affectedPath = path;\r\n if (events.length > 0) {\r\n // Since we have a listener outstanding for each transaction, receiving any events\r\n // is a proxy for some change having occurred.\r\n affectedPath = repoRerunTransactions(repo, path);\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\r\n}\r\nfunction repoOnConnectStatus(repo, connectStatus) {\r\n repoUpdateInfo(repo, 'connected', connectStatus);\r\n if (connectStatus === false) {\r\n repoRunOnDisconnectEvents(repo);\r\n }\r\n}\r\nfunction repoOnServerInfoUpdate(repo, updates) {\r\n each(updates, (key, value) => {\r\n repoUpdateInfo(repo, key, value);\r\n });\r\n}\r\nfunction repoUpdateInfo(repo, pathString, value) {\r\n const path = new Path('/.info/' + pathString);\r\n const newNode = nodeFromJSON(value);\r\n repo.infoData_.updateSnapshot(path, newNode);\r\n const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n}\r\nfunction repoGetNextWriteId(repo) {\r\n return repo.nextWriteId_++;\r\n}\r\n/**\r\n * The purpose of `getValue` is to return the latest known value\r\n * satisfying `query`.\r\n *\r\n * This method will first check for in-memory cached values\r\n * belonging to active listeners. If they are found, such values\r\n * are considered to be the most up-to-date.\r\n *\r\n * If the client is not connected, this method will wait until the\r\n * repo has established a connection and then request the value for `query`.\r\n * If the client is not able to retrieve the query result for another reason,\r\n * it reports an error.\r\n *\r\n * @param query - The query to surface a value for.\r\n */\r\nfunction repoGetValue(repo, query, eventRegistration) {\r\n // Only active queries are cached. There is no persisted cache.\r\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\r\n if (cached != null) {\r\n return Promise.resolve(cached);\r\n }\r\n return repo.server_.get(query).then(payload => {\r\n const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());\r\n /**\r\n * Below we simulate the actions of an `onlyOnce` `onValue()` event where:\r\n * Add an event registration,\r\n * Update data at the path,\r\n * Raise any events,\r\n * Cleanup the SyncTree\r\n */\r\n syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);\r\n let events;\r\n if (query._queryParams.loadsAllData()) {\r\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);\r\n }\r\n else {\r\n const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);\r\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);\r\n }\r\n /*\r\n * We need to raise events in the scenario where `get()` is called at a parent path, and\r\n * while the `get()` is pending, `onValue` is called at a child location. While get() is waiting\r\n * for the data, `onValue` will register a new event. Then, get() will come back, and update the syncTree\r\n * and its corresponding serverCache, including the child location where `onValue` is called. Then,\r\n * `onValue` will receive the event from the server, but look at the syncTree and see that the data received\r\n * from the server is already at the SyncPoint, and so the `onValue` callback will never get fired.\r\n * Calling `eventQueueRaiseEventsForChangedPath()` is the correct way to propagate the events and\r\n * ensure the corresponding child events will get fired.\r\n */\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\r\n syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);\r\n return node;\r\n }, err => {\r\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\r\n return Promise.reject(new Error(err));\r\n });\r\n}\r\nfunction repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {\r\n repoLog(repo, 'set', {\r\n path: path.toString(),\r\n value: newVal,\r\n priority: newPriority\r\n });\r\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\r\n // (b) store unresolved paths on JSON parse\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\r\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('set at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\r\n}\r\nfunction repoUpdate(repo, path, childrenToMerge, onComplete) {\r\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\r\n // Start with our existing data and merge each child into it.\r\n let empty = true;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const changedChildren = {};\r\n each(childrenToMerge, (changedKey, changedValue) => {\r\n empty = false;\r\n changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);\r\n });\r\n if (!empty) {\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('update at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n each(childrenToMerge, (changedPath) => {\r\n const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\r\n }\r\n else {\r\n log(\"update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n }\r\n}\r\n/**\r\n * Applies all of the changes stored up in the onDisconnect_ tree.\r\n */\r\nfunction repoRunOnDisconnectEvents(repo) {\r\n repoLog(repo, 'onDisconnectEvents');\r\n const serverValues = repoGenerateServerValues(repo);\r\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\r\n sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {\r\n const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);\r\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\r\n });\r\n let events = [];\r\n sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {\r\n events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n repo.onDisconnect_ = newSparseSnapshotTree();\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\r\n}\r\nfunction repoOnDisconnectCancel(repo, path, onComplete) {\r\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSet(repo, path, value, onComplete) {\r\n const newNode = nodeFromJSON(value);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {\r\n const newNode = nodeFromJSON(value, priority);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {\r\n if (isEmpty(childrenToMerge)) {\r\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n return;\r\n }\r\n repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n if (status === 'ok') {\r\n each(childrenToMerge, (childName, childNode) => {\r\n const newChildNode = nodeFromJSON(childNode);\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);\r\n });\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoAddEventCallbackForQuery(repo, query, eventRegistration) {\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {\r\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\r\n // a little bit by handling the return values anyways.\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoInterrupt(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoResume(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.resume(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoLog(repo, ...varArgs) {\r\n let prefix = '';\r\n if (repo.persistentConnection_) {\r\n prefix = repo.persistentConnection_.id + ':';\r\n }\r\n log(prefix, ...varArgs);\r\n}\r\nfunction repoCallOnCompleteCallback(repo, callback, status, errorReason) {\r\n if (callback) {\r\n exceptionGuard(() => {\r\n if (status === 'ok') {\r\n callback(null);\r\n }\r\n else {\r\n const code = (status || 'error').toUpperCase();\r\n let message = code;\r\n if (errorReason) {\r\n message += ': ' + errorReason;\r\n }\r\n const error = new Error(message);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n error.code = code;\r\n callback(error);\r\n }\r\n });\r\n }\r\n}\r\n/**\r\n * Creates a new transaction, adds it to the transactions we're tracking, and\r\n * sends it to the server if possible.\r\n *\r\n * @param path - Path at which to do transaction.\r\n * @param transactionUpdate - Update callback.\r\n * @param onComplete - Completion callback.\r\n * @param unwatcher - Function that will be called when the transaction no longer\r\n * need data updates for `path`.\r\n * @param applyLocally - Whether or not to make intermediate results visible\r\n */\r\nfunction repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {\r\n repoLog(repo, 'transaction on ' + path);\r\n // Initialize transaction.\r\n const transaction = {\r\n path,\r\n update: transactionUpdate,\r\n onComplete,\r\n // One of TransactionStatus enums.\r\n status: null,\r\n // Used when combining transactions at different locations to figure out\r\n // which one goes first.\r\n order: LUIDGenerator(),\r\n // Whether to raise local events for this transaction.\r\n applyLocally,\r\n // Count of how many times we've retried the transaction.\r\n retryCount: 0,\r\n // Function to call to clean up our .on() listener.\r\n unwatcher,\r\n // Stores why a transaction was aborted.\r\n abortReason: null,\r\n currentWriteId: null,\r\n currentInputSnapshot: null,\r\n currentOutputSnapshotRaw: null,\r\n currentOutputSnapshotResolved: null\r\n };\r\n // Run transaction initially.\r\n const currentState = repoGetLatestState(repo, path, undefined);\r\n transaction.currentInputSnapshot = currentState;\r\n const newVal = transaction.update(currentState.val());\r\n if (newVal === undefined) {\r\n // Abort transaction.\r\n transaction.unwatcher();\r\n transaction.currentOutputSnapshotRaw = null;\r\n transaction.currentOutputSnapshotResolved = null;\r\n if (transaction.onComplete) {\r\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\r\n }\r\n }\r\n else {\r\n validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\r\n // Mark as run and add to our queue.\r\n transaction.status = 0 /* TransactionStatus.RUN */;\r\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\r\n const nodeQueue = treeGetValue(queueNode) || [];\r\n nodeQueue.push(transaction);\r\n treeSetValue(queueNode, nodeQueue);\r\n // Update visibleData and raise events\r\n // Note: We intentionally raise events after updating all of our\r\n // transaction state, since the user could start new transactions from the\r\n // event callbacks.\r\n let priorityForNode;\r\n if (typeof newVal === 'object' &&\r\n newVal !== null &&\r\n contains(newVal, '.priority')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n priorityForNode = safeGet(newVal, '.priority');\r\n assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\r\n 'Priority must be a valid string, finite number, server value, or null.');\r\n }\r\n else {\r\n const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\r\n ChildrenNode.EMPTY_NODE;\r\n priorityForNode = currentNode.getPriority().val();\r\n }\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);\r\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\r\n transaction.currentOutputSnapshotResolved = newNode;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n }\r\n}\r\n/**\r\n * @param excludeSets - A specific set to exclude\r\n */\r\nfunction repoGetLatestState(repo, path, excludeSets) {\r\n return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\r\n ChildrenNode.EMPTY_NODE);\r\n}\r\n/**\r\n * Sends any already-run transactions that aren't waiting for outstanding\r\n * transactions to complete.\r\n *\r\n * Externally it's called with no arguments, but it calls itself recursively\r\n * with a particular transactionQueueTree node to recurse through the tree.\r\n *\r\n * @param node - transactionQueueTree node to start at.\r\n */\r\nfunction repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {\r\n // Before recursing, make sure any completed transactions are removed.\r\n if (!node) {\r\n repoPruneCompletedTransactionsBelowNode(repo, node);\r\n }\r\n if (treeGetValue(node)) {\r\n const queue = repoBuildTransactionQueue(repo, node);\r\n assert(queue.length > 0, 'Sending zero length transaction queue');\r\n const allRun = queue.every((transaction) => transaction.status === 0 /* TransactionStatus.RUN */);\r\n // If they're all run (and not sent), we can send them. Else, we must wait.\r\n if (allRun) {\r\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\r\n }\r\n }\r\n else if (treeHasChildren(node)) {\r\n treeForEachChild(node, childNode => {\r\n repoSendReadyTransactions(repo, childNode);\r\n });\r\n }\r\n}\r\n/**\r\n * Given a list of run transactions, send them to the server and then handle\r\n * the result (success or failure).\r\n *\r\n * @param path - The location of the queue.\r\n * @param queue - Queue of transactions under the specified location.\r\n */\r\nfunction repoSendTransactionQueue(repo, path, queue) {\r\n // Mark transactions as sent and increment retry count!\r\n const setsToIgnore = queue.map(txn => {\r\n return txn.currentWriteId;\r\n });\r\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\r\n let snapToSend = latestState;\r\n const latestHash = latestState.hash();\r\n for (let i = 0; i < queue.length; i++) {\r\n const txn = queue[i];\r\n assert(txn.status === 0 /* TransactionStatus.RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');\r\n txn.status = 1 /* TransactionStatus.SENT */;\r\n txn.retryCount++;\r\n const relativePath = newRelativePath(path, txn.path);\r\n // If we've gotten to this point, the output snapshot must be defined.\r\n snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);\r\n }\r\n const dataToSend = snapToSend.val(true);\r\n const pathToSend = path;\r\n // Send the put.\r\n repo.server_.put(pathToSend.toString(), dataToSend, (status) => {\r\n repoLog(repo, 'transaction put response', {\r\n path: pathToSend.toString(),\r\n status\r\n });\r\n let events = [];\r\n if (status === 'ok') {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more\r\n // transactions or sets.\r\n const callbacks = [];\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 2 /* TransactionStatus.COMPLETED */;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));\r\n if (queue[i].onComplete) {\r\n // We never unset the output snapshot, and given that this\r\n // transaction is complete, it should be set\r\n callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));\r\n }\r\n queue[i].unwatcher();\r\n }\r\n // Now remove the completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));\r\n // There may be pending transactions that we can now send.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n // Finally, trigger onComplete callbacks.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n else {\r\n // transactions are no longer sent. Update their status appropriately.\r\n if (status === 'datastale') {\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) {\r\n queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\r\n }\r\n else {\r\n queue[i].status = 0 /* TransactionStatus.RUN */;\r\n }\r\n }\r\n }\r\n else {\r\n warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 4 /* TransactionStatus.NEEDS_ABORT */;\r\n queue[i].abortReason = status;\r\n }\r\n }\r\n repoRerunTransactions(repo, path);\r\n }\r\n }, latestHash);\r\n}\r\n/**\r\n * Finds all transactions dependent on the data at changedPath and reruns them.\r\n *\r\n * Should be called any time cached data changes.\r\n *\r\n * Return the highest path that was affected by rerunning transactions. This\r\n * is the path at which events need to be raised for.\r\n *\r\n * @param changedPath - The path in mergedData that changed.\r\n * @returns The rootmost path that was affected by rerunning transactions.\r\n */\r\nfunction repoRerunTransactions(repo, changedPath) {\r\n const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);\r\n const path = treeGetPath(rootMostTransactionNode);\r\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\r\n repoRerunTransactionQueue(repo, queue, path);\r\n return path;\r\n}\r\n/**\r\n * Does all the work of rerunning transactions (as well as cleans up aborted\r\n * transactions and whatnot).\r\n *\r\n * @param queue - The queue of transactions to run.\r\n * @param path - The path the queue is for.\r\n */\r\nfunction repoRerunTransactionQueue(repo, queue, path) {\r\n if (queue.length === 0) {\r\n return; // Nothing to do!\r\n }\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions or\r\n // sets.\r\n const callbacks = [];\r\n let events = [];\r\n // Ignore all of the sets we're going to re-run.\r\n const txnsToRerun = queue.filter(q => {\r\n return q.status === 0 /* TransactionStatus.RUN */;\r\n });\r\n const setsToIgnore = txnsToRerun.map(q => {\r\n return q.currentWriteId;\r\n });\r\n for (let i = 0; i < queue.length; i++) {\r\n const transaction = queue[i];\r\n const relativePath = newRelativePath(path, transaction.path);\r\n let abortTransaction = false, abortReason;\r\n assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\r\n if (transaction.status === 4 /* TransactionStatus.NEEDS_ABORT */) {\r\n abortTransaction = true;\r\n abortReason = transaction.abortReason;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else if (transaction.status === 0 /* TransactionStatus.RUN */) {\r\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\r\n abortTransaction = true;\r\n abortReason = 'maxretry';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else {\r\n // This code reruns a transaction\r\n const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);\r\n transaction.currentInputSnapshot = currentNode;\r\n const newData = queue[i].update(currentNode.val());\r\n if (newData !== undefined) {\r\n validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\r\n let newDataNode = nodeFromJSON(newData);\r\n const hasExplicitPriority = typeof newData === 'object' &&\r\n newData != null &&\r\n contains(newData, '.priority');\r\n if (!hasExplicitPriority) {\r\n // Keep the old priority if there wasn't a priority explicitly specified.\r\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\r\n }\r\n const oldWriteId = transaction.currentWriteId;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);\r\n transaction.currentOutputSnapshotRaw = newDataNode;\r\n transaction.currentOutputSnapshotResolved = newNodeResolved;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n // Mutates setsToIgnore in place\r\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\r\n events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));\r\n }\r\n else {\r\n abortTransaction = true;\r\n abortReason = 'nodata';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n }\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n events = [];\r\n if (abortTransaction) {\r\n // Abort.\r\n queue[i].status = 2 /* TransactionStatus.COMPLETED */;\r\n // Removing a listener can trigger pruning which can muck with\r\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\r\n // until we're done.\r\n (function (unwatcher) {\r\n setTimeout(unwatcher, Math.floor(0));\r\n })(queue[i].unwatcher);\r\n if (queue[i].onComplete) {\r\n if (abortReason === 'nodata') {\r\n callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));\r\n }\r\n else {\r\n callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));\r\n }\r\n }\r\n }\r\n }\r\n // Clean up completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\r\n // Now fire callbacks, now that we're in a good, known state.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n // Try to send the transaction result to the server.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n}\r\n/**\r\n * Returns the rootmost ancestor node of the specified path that has a pending\r\n * transaction on it, or just returns the node for the given path if there are\r\n * no pending transactions on any ancestor.\r\n *\r\n * @param path - The location to start at.\r\n * @returns The rootmost node with a transaction.\r\n */\r\nfunction repoGetAncestorTransactionNode(repo, path) {\r\n let front;\r\n // Start at the root and walk deeper into the tree towards path until we\r\n // find a node with pending transactions.\r\n let transactionNode = repo.transactionQueueTree_;\r\n front = pathGetFront(path);\r\n while (front !== null && treeGetValue(transactionNode) === undefined) {\r\n transactionNode = treeSubTree(transactionNode, front);\r\n path = pathPopFront(path);\r\n front = pathGetFront(path);\r\n }\r\n return transactionNode;\r\n}\r\n/**\r\n * Builds the queue of all transactions at or below the specified\r\n * transactionNode.\r\n *\r\n * @param transactionNode\r\n * @returns The generated queue.\r\n */\r\nfunction repoBuildTransactionQueue(repo, transactionNode) {\r\n // Walk any child transaction queues and aggregate them into a single queue.\r\n const transactionQueue = [];\r\n repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);\r\n // Sort them by the order the transactions were created.\r\n transactionQueue.sort((a, b) => a.order - b.order);\r\n return transactionQueue;\r\n}\r\nfunction repoAggregateTransactionQueuesForNode(repo, node, queue) {\r\n const nodeQueue = treeGetValue(node);\r\n if (nodeQueue) {\r\n for (let i = 0; i < nodeQueue.length; i++) {\r\n queue.push(nodeQueue[i]);\r\n }\r\n }\r\n treeForEachChild(node, child => {\r\n repoAggregateTransactionQueuesForNode(repo, child, queue);\r\n });\r\n}\r\n/**\r\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\r\n */\r\nfunction repoPruneCompletedTransactionsBelowNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n let to = 0;\r\n for (let from = 0; from < queue.length; from++) {\r\n if (queue[from].status !== 2 /* TransactionStatus.COMPLETED */) {\r\n queue[to] = queue[from];\r\n to++;\r\n }\r\n }\r\n queue.length = to;\r\n treeSetValue(node, queue.length > 0 ? queue : undefined);\r\n }\r\n treeForEachChild(node, childNode => {\r\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\r\n });\r\n}\r\n/**\r\n * Aborts all transactions on ancestors or descendants of the specified path.\r\n * Called when doing a set() or update() since we consider them incompatible\r\n * with transactions.\r\n *\r\n * @param path - Path for which we want to abort related transactions.\r\n */\r\nfunction repoAbortTransactions(repo, path) {\r\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\r\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\r\n treeForEachAncestor(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n repoAbortTransactionsOnNode(repo, transactionNode);\r\n treeForEachDescendant(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n return affectedPath;\r\n}\r\n/**\r\n * Abort transactions stored in this transaction queue node.\r\n *\r\n * @param node - Node to abort transactions for.\r\n */\r\nfunction repoAbortTransactionsOnNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions\r\n // or sets.\r\n const callbacks = [];\r\n // Go through queue. Any already-sent transactions must be marked for\r\n // abort, while the unsent ones can be immediately aborted and removed.\r\n let events = [];\r\n let lastSent = -1;\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* TransactionStatus.SENT_NEEDS_ABORT */) ;\r\n else if (queue[i].status === 1 /* TransactionStatus.SENT */) {\r\n assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\r\n lastSent = i;\r\n // Mark transaction for abort when it comes back.\r\n queue[i].status = 3 /* TransactionStatus.SENT_NEEDS_ABORT */;\r\n queue[i].abortReason = 'set';\r\n }\r\n else {\r\n assert(queue[i].status === 0 /* TransactionStatus.RUN */, 'Unexpected transaction status in abort');\r\n // We can abort it immediately.\r\n queue[i].unwatcher();\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));\r\n if (queue[i].onComplete) {\r\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));\r\n }\r\n }\r\n }\r\n if (lastSent === -1) {\r\n // We're not waiting for any sent transactions. We can clear the queue.\r\n treeSetValue(node, undefined);\r\n }\r\n else {\r\n // Remove the transactions we aborted.\r\n queue.length = lastSent + 1;\r\n }\r\n // Now fire the callbacks.\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction decodePath(pathString) {\r\n let pathStringDecoded = '';\r\n const pieces = pathString.split('/');\r\n for (let i = 0; i < pieces.length; i++) {\r\n if (pieces[i].length > 0) {\r\n let piece = pieces[i];\r\n try {\r\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\r\n }\r\n catch (e) { }\r\n pathStringDecoded += '/' + piece;\r\n }\r\n }\r\n return pathStringDecoded;\r\n}\r\n/**\r\n * @returns key value hash\r\n */\r\nfunction decodeQuery(queryString) {\r\n const results = {};\r\n if (queryString.charAt(0) === '?') {\r\n queryString = queryString.substring(1);\r\n }\r\n for (const segment of queryString.split('&')) {\r\n if (segment.length === 0) {\r\n continue;\r\n }\r\n const kv = segment.split('=');\r\n if (kv.length === 2) {\r\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\r\n }\r\n else {\r\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\r\n }\r\n }\r\n return results;\r\n}\r\nconst parseRepoInfo = function (dataURL, nodeAdmin) {\r\n const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;\r\n if (parsedUrl.domain === 'firebase.com') {\r\n fatal(parsedUrl.host +\r\n ' is no longer supported. ' +\r\n 'Please use .firebaseio.com instead');\r\n }\r\n // Catch common error of uninitialized namespace value.\r\n if ((!namespace || namespace === 'undefined') &&\r\n parsedUrl.domain !== 'localhost') {\r\n fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\r\n }\r\n if (!parsedUrl.secure) {\r\n warnIfPageIsSecure();\r\n }\r\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\r\n return {\r\n repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, \r\n /*persistenceKey=*/ '', \r\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),\r\n path: new Path(parsedUrl.pathString)\r\n };\r\n};\r\nconst parseDatabaseURL = function (dataURL) {\r\n // Default to empty strings in the event of a malformed string.\r\n let host = '', domain = '', subdomain = '', pathString = '', namespace = '';\r\n // Always default to SSL, unless otherwise specified.\r\n let secure = true, scheme = 'https', port = 443;\r\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\r\n if (typeof dataURL === 'string') {\r\n // Parse scheme.\r\n let colonInd = dataURL.indexOf('//');\r\n if (colonInd >= 0) {\r\n scheme = dataURL.substring(0, colonInd - 1);\r\n dataURL = dataURL.substring(colonInd + 2);\r\n }\r\n // Parse host, path, and query string.\r\n let slashInd = dataURL.indexOf('/');\r\n if (slashInd === -1) {\r\n slashInd = dataURL.length;\r\n }\r\n let questionMarkInd = dataURL.indexOf('?');\r\n if (questionMarkInd === -1) {\r\n questionMarkInd = dataURL.length;\r\n }\r\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\r\n if (slashInd < questionMarkInd) {\r\n // For pathString, questionMarkInd will always come after slashInd\r\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\r\n }\r\n const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\r\n // If we have a port, use scheme for determining if it's secure.\r\n colonInd = host.indexOf(':');\r\n if (colonInd >= 0) {\r\n secure = scheme === 'https' || scheme === 'wss';\r\n port = parseInt(host.substring(colonInd + 1), 10);\r\n }\r\n else {\r\n colonInd = host.length;\r\n }\r\n const hostWithoutPort = host.slice(0, colonInd);\r\n if (hostWithoutPort.toLowerCase() === 'localhost') {\r\n domain = 'localhost';\r\n }\r\n else if (hostWithoutPort.split('.').length <= 2) {\r\n domain = hostWithoutPort;\r\n }\r\n else {\r\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\r\n const dotInd = host.indexOf('.');\r\n subdomain = host.substring(0, dotInd).toLowerCase();\r\n domain = host.substring(dotInd + 1);\r\n // Normalize namespaces to lowercase to share storage / connection.\r\n namespace = subdomain;\r\n }\r\n // Always treat the value of the `ns` as the namespace name if it is present.\r\n if ('ns' in queryParams) {\r\n namespace = queryParams['ns'];\r\n }\r\n }\r\n return {\r\n host,\r\n port,\r\n domain,\r\n subdomain,\r\n secure,\r\n scheme,\r\n pathString,\r\n namespace\r\n };\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Modeled after base64 web-safe chars, but ordered by ASCII.\r\nconst PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\r\n/**\r\n * Fancy ID generator that creates 20-character string identifiers with the\r\n * following properties:\r\n *\r\n * 1. They're based on timestamp so that they sort *after* any existing ids.\r\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\r\n * collide with other clients' IDs.\r\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\r\n * that will sort properly).\r\n * 4. They're monotonically increasing. Even if you generate more than one in\r\n * the same timestamp, the latter ones will sort after the former ones. We do\r\n * this by using the previous random bits but \"incrementing\" them by 1 (only\r\n * in the case of a timestamp collision).\r\n */\r\nconst nextPushId = (function () {\r\n // Timestamp of last push, used to prevent local collisions if you push twice\r\n // in one ms.\r\n let lastPushTime = 0;\r\n // We generate 72-bits of randomness which get turned into 12 characters and\r\n // appended to the timestamp to prevent collisions with other clients. We\r\n // store the last characters we generated because in the event of a collision,\r\n // we'll use those same characters except \"incremented\" by one.\r\n const lastRandChars = [];\r\n return function (now) {\r\n const duplicateTime = now === lastPushTime;\r\n lastPushTime = now;\r\n let i;\r\n const timeStampChars = new Array(8);\r\n for (i = 7; i >= 0; i--) {\r\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\r\n // NOTE: Can't use << here because javascript will convert to int and lose\r\n // the upper bits.\r\n now = Math.floor(now / 64);\r\n }\r\n assert(now === 0, 'Cannot push at time == 0');\r\n let id = timeStampChars.join('');\r\n if (!duplicateTime) {\r\n for (i = 0; i < 12; i++) {\r\n lastRandChars[i] = Math.floor(Math.random() * 64);\r\n }\r\n }\r\n else {\r\n // If the timestamp hasn't changed since last push, use the same random\r\n // number, except incremented by 1.\r\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\r\n lastRandChars[i] = 0;\r\n }\r\n lastRandChars[i]++;\r\n }\r\n for (i = 0; i < 12; i++) {\r\n id += PUSH_CHARS.charAt(lastRandChars[i]);\r\n }\r\n assert(id.length === 20, 'nextPushId: Length should be 20.');\r\n return id;\r\n };\r\n})();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Encapsulates the data needed to raise an event\r\n */\r\nclass DataEvent {\r\n /**\r\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\r\n * @param eventRegistration - The function to call to with the event data. User provided\r\n * @param snapshot - The data backing the event\r\n * @param prevName - Optional, the name of the previous child for child_* events.\r\n */\r\n constructor(eventType, eventRegistration, snapshot, prevName) {\r\n this.eventType = eventType;\r\n this.eventRegistration = eventRegistration;\r\n this.snapshot = snapshot;\r\n this.prevName = prevName;\r\n }\r\n getPath() {\r\n const ref = this.snapshot.ref;\r\n if (this.eventType === 'value') {\r\n return ref._path;\r\n }\r\n else {\r\n return ref.parent._path;\r\n }\r\n }\r\n getEventType() {\r\n return this.eventType;\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return (this.getPath().toString() +\r\n ':' +\r\n this.eventType +\r\n ':' +\r\n stringify(this.snapshot.exportVal()));\r\n }\r\n}\r\nclass CancelEvent {\r\n constructor(eventRegistration, error, path) {\r\n this.eventRegistration = eventRegistration;\r\n this.error = error;\r\n this.path = path;\r\n }\r\n getPath() {\r\n return this.path;\r\n }\r\n getEventType() {\r\n return 'cancel';\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return this.path.toString() + ':cancel';\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A wrapper class that converts events from the database@exp SDK to the legacy\r\n * Database SDK. Events are not converted directly as event registration relies\r\n * on reference comparison of the original user callback (see `matches()`) and\r\n * relies on equality of the legacy SDK's `context` object.\r\n */\r\nclass CallbackContext {\r\n constructor(snapshotCallback, cancelCallback) {\r\n this.snapshotCallback = snapshotCallback;\r\n this.cancelCallback = cancelCallback;\r\n }\r\n onValue(expDataSnapshot, previousChildName) {\r\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\r\n }\r\n onCancel(error) {\r\n assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');\r\n return this.cancelCallback.call(null, error);\r\n }\r\n get hasCancelCallback() {\r\n return !!this.cancelCallback;\r\n }\r\n matches(other) {\r\n return (this.snapshotCallback === other.snapshotCallback ||\r\n (this.snapshotCallback.userCallback !== undefined &&\r\n this.snapshotCallback.userCallback ===\r\n other.snapshotCallback.userCallback &&\r\n this.snapshotCallback.context === other.snapshotCallback.context));\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The `onDisconnect` class allows you to write or clear data when your client\r\n * disconnects from the Database server. These updates occur whether your\r\n * client disconnects cleanly or not, so you can rely on them to clean up data\r\n * even if a connection is dropped or a client crashes.\r\n *\r\n * The `onDisconnect` class is most commonly used to manage presence in\r\n * applications where it is useful to detect how many clients are connected and\r\n * when other clients disconnect. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * To avoid problems when a connection is dropped before the requests can be\r\n * transferred to the Database server, these functions should be called before\r\n * writing any data.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time you reconnect.\r\n */\r\nclass OnDisconnect {\r\n /** @hideconstructor */\r\n constructor(_repo, _path) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n }\r\n /**\r\n * Cancels all previously queued `onDisconnect()` set or update events for this\r\n * location and all children.\r\n *\r\n * If a write has been queued for this location via a `set()` or `update()` at a\r\n * parent location, the write at this location will be canceled, though writes\r\n * to sibling locations will still occur.\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n cancel() {\r\n const deferred = new Deferred();\r\n repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is deleted when the client is disconnected\r\n * (due to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n remove() {\r\n validateWritablePath('OnDisconnect.remove', this._path);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value when the\r\n * client is disconnected (due to closing the browser, navigating to a new page,\r\n * or network issues).\r\n *\r\n * `set()` is especially useful for implementing \"presence\" systems, where a\r\n * value should be changed or cleared when a user disconnects so that they\r\n * appear \"offline\" to other users. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time.\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n set(value) {\r\n validateWritablePath('OnDisconnect.set', this._path);\r\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value and priority\r\n * when the client is disconnected (due to closing the browser, navigating to a\r\n * new page, or network issues).\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n setWithPriority(value, priority) {\r\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\r\n validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);\r\n validatePriority('OnDisconnect.setWithPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Writes multiple values at this location when the client is disconnected (due\r\n * to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\r\n * from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n update(values) {\r\n validateWritablePath('OnDisconnect.update', this._path);\r\n validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nclass QueryImpl {\r\n /**\r\n * @hideconstructor\r\n */\r\n constructor(_repo, _path, _queryParams, _orderByCalled) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n this._queryParams = _queryParams;\r\n this._orderByCalled = _orderByCalled;\r\n }\r\n get key() {\r\n if (pathIsEmpty(this._path)) {\r\n return null;\r\n }\r\n else {\r\n return pathGetBack(this._path);\r\n }\r\n }\r\n get ref() {\r\n return new ReferenceImpl(this._repo, this._path);\r\n }\r\n get _queryIdentifier() {\r\n const obj = queryParamsGetQueryObject(this._queryParams);\r\n const id = ObjectToUniqueKey(obj);\r\n return id === '{}' ? 'default' : id;\r\n }\r\n /**\r\n * An object representation of the query parameters used by this Query.\r\n */\r\n get _queryObject() {\r\n return queryParamsGetQueryObject(this._queryParams);\r\n }\r\n isEqual(other) {\r\n other = getModularInstance(other);\r\n if (!(other instanceof QueryImpl)) {\r\n return false;\r\n }\r\n const sameRepo = this._repo === other._repo;\r\n const samePath = pathEquals(this._path, other._path);\r\n const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;\r\n return sameRepo && samePath && sameQueryIdentifier;\r\n }\r\n toJSON() {\r\n return this.toString();\r\n }\r\n toString() {\r\n return this._repo.toString() + pathToUrlEncodedString(this._path);\r\n }\r\n}\r\n/**\r\n * Validates that no other order by call has been made\r\n */\r\nfunction validateNoPreviousOrderByCall(query, fnName) {\r\n if (query._orderByCalled === true) {\r\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\r\n }\r\n}\r\n/**\r\n * Validates start/end values for queries.\r\n */\r\nfunction validateQueryEndpoints(params) {\r\n let startNode = null;\r\n let endNode = null;\r\n if (params.hasStart()) {\r\n startNode = params.getIndexStartValue();\r\n }\r\n if (params.hasEnd()) {\r\n endNode = params.getIndexEndValue();\r\n }\r\n if (params.getIndex() === KEY_INDEX) {\r\n const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\r\n 'startAt(), endAt(), or equalTo().';\r\n const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\r\n 'endAt(), endBefore(), or equalTo() must be a string.';\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n if (startName !== MIN_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof startNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n if (endName !== MAX_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof endNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n }\r\n else if (params.getIndex() === PRIORITY_INDEX) {\r\n if ((startNode != null && !isValidPriority(startNode)) ||\r\n (endNode != null && !isValidPriority(endNode))) {\r\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\r\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\r\n '(null, a number, or a string).');\r\n }\r\n }\r\n else {\r\n assert(params.getIndex() instanceof PathIndex ||\r\n params.getIndex() === VALUE_INDEX, 'unknown index type.');\r\n if ((startNode != null && typeof startNode === 'object') ||\r\n (endNode != null && typeof endNode === 'object')) {\r\n throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\r\n 'equalTo() cannot be an object.');\r\n }\r\n }\r\n}\r\n/**\r\n * Validates that limit* has been called with the correct combination of parameters\r\n */\r\nfunction validateLimit(params) {\r\n if (params.hasStart() &&\r\n params.hasEnd() &&\r\n params.hasLimit() &&\r\n !params.hasAnchoredLimit()) {\r\n throw new Error(\"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\r\n 'limitToFirst() or limitToLast() instead.');\r\n }\r\n}\r\n/**\r\n * @internal\r\n */\r\nclass ReferenceImpl extends QueryImpl {\r\n /** @hideconstructor */\r\n constructor(repo, path) {\r\n super(repo, path, new QueryParams(), false);\r\n }\r\n get parent() {\r\n const parentPath = pathParent(this._path);\r\n return parentPath === null\r\n ? null\r\n : new ReferenceImpl(this._repo, parentPath);\r\n }\r\n get root() {\r\n let ref = this;\r\n while (ref.parent !== null) {\r\n ref = ref.parent;\r\n }\r\n return ref;\r\n }\r\n}\r\n/**\r\n * A `DataSnapshot` contains data from a Database location.\r\n *\r\n * Any time you read data from the Database, you receive the data as a\r\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\r\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\r\n * JavaScript object by calling the `val()` method. Alternatively, you can\r\n * traverse into the snapshot by calling `child()` to return child snapshots\r\n * (which you could then call `val()` on).\r\n *\r\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\r\n * a Database location. It cannot be modified and will never change (to modify\r\n * data, you always call the `set()` method on a `Reference` directly).\r\n */\r\nclass DataSnapshot {\r\n /**\r\n * @param _node - A SnapshotNode to wrap.\r\n * @param ref - The location this snapshot came from.\r\n * @param _index - The iteration order for this snapshot\r\n * @hideconstructor\r\n */\r\n constructor(_node, \r\n /**\r\n * The location of this DataSnapshot.\r\n */\r\n ref, _index) {\r\n this._node = _node;\r\n this.ref = ref;\r\n this._index = _index;\r\n }\r\n /**\r\n * Gets the priority value of the data in this `DataSnapshot`.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\r\n * ).\r\n */\r\n get priority() {\r\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\r\n return this._node.getPriority().val();\r\n }\r\n /**\r\n * The key (last part of the path) of the location of this `DataSnapshot`.\r\n *\r\n * The last token in a Database location is considered its key. For example,\r\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\r\n * `DataSnapshot` will return the key for the location that generated it.\r\n * However, accessing the key on the root URL of a Database will return\r\n * `null`.\r\n */\r\n get key() {\r\n return this.ref.key;\r\n }\r\n /** Returns the number of child properties of this `DataSnapshot`. */\r\n get size() {\r\n return this._node.numChildren();\r\n }\r\n /**\r\n * Gets another `DataSnapshot` for the location at the specified relative path.\r\n *\r\n * Passing a relative path to the `child()` method of a DataSnapshot returns\r\n * another `DataSnapshot` for the location at the specified relative path. The\r\n * relative path can either be a simple child name (for example, \"ada\") or a\r\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\r\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\r\n * whose value is `null`) is returned.\r\n *\r\n * @param path - A relative path to the location of child data.\r\n */\r\n child(path) {\r\n const childPath = new Path(path);\r\n const childRef = child(this.ref, path);\r\n return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);\r\n }\r\n /**\r\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\r\n * efficient than using `snapshot.val() !== null`.\r\n */\r\n exists() {\r\n return !this._node.isEmpty();\r\n }\r\n /**\r\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\r\n *\r\n * The `exportVal()` method is similar to `val()`, except priority information\r\n * is included (if available), making it suitable for backing up your data.\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n exportVal() {\r\n return this._node.val(true);\r\n }\r\n /**\r\n * Enumerates the top-level children in the `IteratedDataSnapshot`.\r\n *\r\n * Because of the way JavaScript objects work, the ordering of data in the\r\n * JavaScript object returned by `val()` is not guaranteed to match the\r\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\r\n * where `forEach()` comes in handy. It guarantees the children of a\r\n * `DataSnapshot` will be iterated in their query order.\r\n *\r\n * If no explicit `orderBy*()` method is used, results are returned\r\n * ordered by key (unless priorities are used, in which case, results are\r\n * returned by priority).\r\n *\r\n * @param action - A function that will be called for each child DataSnapshot.\r\n * The callback can return true to cancel further enumeration.\r\n * @returns true if enumeration was canceled due to your callback returning\r\n * true.\r\n */\r\n forEach(action) {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n const childrenNode = this._node;\r\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\r\n return !!childrenNode.forEachChild(this._index, (key, node) => {\r\n return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));\r\n });\r\n }\r\n /**\r\n * Returns true if the specified child path has (non-null) data.\r\n *\r\n * @param path - A relative path to the location of a potential child.\r\n * @returns `true` if data exists at the specified child path; else\r\n * `false`.\r\n */\r\n hasChild(path) {\r\n const childPath = new Path(path);\r\n return !this._node.getChild(childPath).isEmpty();\r\n }\r\n /**\r\n * Returns whether or not the `DataSnapshot` has any non-`null` child\r\n * properties.\r\n *\r\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\r\n * children. If it does, you can enumerate them using `forEach()`. If it\r\n * doesn't, then either this snapshot contains a primitive value (which can be\r\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\r\n * `null`).\r\n *\r\n * @returns true if this snapshot has any children; else false.\r\n */\r\n hasChildren() {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n return !this._node.isEmpty();\r\n }\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return this.exportVal();\r\n }\r\n /**\r\n * Extracts a JavaScript value from a `DataSnapshot`.\r\n *\r\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\r\n * scalar type (string, number, or boolean), an array, or an object. It may\r\n * also return null, indicating that the `DataSnapshot` is empty (contains no\r\n * data).\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n val() {\r\n return this._node.val();\r\n }\r\n}\r\n/**\r\n *\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided path. If no path is provided, the `Reference`\r\n * will point to the root of the Database.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param path - Optional path representing the location the returned\r\n * `Reference` will point. If not provided, the returned `Reference` will\r\n * point to the root of the Database.\r\n * @returns If a path is provided, a `Reference`\r\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\r\n * root of the Database.\r\n */\r\nfunction ref(db, path) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('ref');\r\n return path !== undefined ? child(db._root, path) : db._root;\r\n}\r\n/**\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided Firebase URL.\r\n *\r\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\r\n * has a different domain than the current `Database` instance.\r\n *\r\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\r\n * and are not applied to the returned `Reference`.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param url - The Firebase URL at which the returned `Reference` will\r\n * point.\r\n * @returns A `Reference` pointing to the provided\r\n * Firebase URL.\r\n */\r\nfunction refFromURL(db, url) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('refFromURL');\r\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\r\n validateUrl('refFromURL', parsedURL);\r\n const repoInfo = parsedURL.repoInfo;\r\n if (!db._repo.repoInfo_.isCustomHost() &&\r\n repoInfo.host !== db._repo.repoInfo_.host) {\r\n fatal('refFromURL' +\r\n ': Host name does not match the current database: ' +\r\n '(found ' +\r\n repoInfo.host +\r\n ' but expected ' +\r\n db._repo.repoInfo_.host +\r\n ')');\r\n }\r\n return ref(db, parsedURL.path.toString());\r\n}\r\n/**\r\n * Gets a `Reference` for the location at the specified relative path.\r\n *\r\n * The relative path can either be a simple child name (for example, \"ada\") or\r\n * a deeper slash-separated path (for example, \"ada/name/first\").\r\n *\r\n * @param parent - The parent location.\r\n * @param path - A relative path from this location to the desired child\r\n * location.\r\n * @returns The specified child location.\r\n */\r\nfunction child(parent, path) {\r\n parent = getModularInstance(parent);\r\n if (pathGetFront(parent._path) === null) {\r\n validateRootPathString('child', 'path', path, false);\r\n }\r\n else {\r\n validatePathString('child', 'path', path, false);\r\n }\r\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\r\n}\r\n/**\r\n * Returns an `OnDisconnect` object - see\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information on how to use it.\r\n *\r\n * @param ref - The reference to add OnDisconnect triggers for.\r\n */\r\nfunction onDisconnect(ref) {\r\n ref = getModularInstance(ref);\r\n return new OnDisconnect(ref._repo, ref._path);\r\n}\r\n/**\r\n * Generates a new child location using a unique key and returns its\r\n * `Reference`.\r\n *\r\n * This is the most common pattern for adding data to a collection of items.\r\n *\r\n * If you provide a value to `push()`, the value is written to the\r\n * generated location. If you don't pass a value, nothing is written to the\r\n * database and the child remains empty (but you can use the `Reference`\r\n * elsewhere).\r\n *\r\n * The unique keys generated by `push()` are ordered by the current time, so the\r\n * resulting list of items is chronologically sorted. The keys are also\r\n * designed to be unguessable (they contain 72 random bits of entropy).\r\n *\r\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}.\r\n * See {@link https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}.\r\n *\r\n * @param parent - The parent location.\r\n * @param value - Optional value to be written at the generated location.\r\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\r\n * but can be used immediately as the `Reference` to the child location.\r\n */\r\nfunction push(parent, value) {\r\n parent = getModularInstance(parent);\r\n validateWritablePath('push', parent._path);\r\n validateFirebaseDataArg('push', value, parent._path, true);\r\n const now = repoServerTime(parent._repo);\r\n const name = nextPushId(now);\r\n // push() returns a ThennableReference whose promise is fulfilled with a\r\n // regular Reference. We use child() to create handles to two different\r\n // references. The first is turned into a ThennableReference below by adding\r\n // then() and catch() methods and is used as the return value of push(). The\r\n // second remains a regular Reference and is used as the fulfilled value of\r\n // the first ThennableReference.\r\n const thennablePushRef = child(parent, name);\r\n const pushRef = child(parent, name);\r\n let promise;\r\n if (value != null) {\r\n promise = set(pushRef, value).then(() => pushRef);\r\n }\r\n else {\r\n promise = Promise.resolve(pushRef);\r\n }\r\n thennablePushRef.then = promise.then.bind(promise);\r\n thennablePushRef.catch = promise.then.bind(promise, undefined);\r\n return thennablePushRef;\r\n}\r\n/**\r\n * Removes the data at this Database location.\r\n *\r\n * Any data at child locations will also be deleted.\r\n *\r\n * The effect of the remove will be visible immediately and the corresponding\r\n * event 'value' will be triggered. Synchronization of the remove to the\r\n * Firebase servers will also be started, and the returned Promise will resolve\r\n * when complete. If provided, the onComplete callback will be called\r\n * asynchronously after synchronization has finished.\r\n *\r\n * @param ref - The location to remove.\r\n * @returns Resolves when remove on server is complete.\r\n */\r\nfunction remove(ref) {\r\n validateWritablePath('remove', ref._path);\r\n return set(ref, null);\r\n}\r\n/**\r\n * Writes data to this Database location.\r\n *\r\n * This will overwrite any data at this location and all child locations.\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\r\n * all data at this location and all child locations will be deleted.\r\n *\r\n * `set()` will remove any priority stored at this location, so if priority is\r\n * meant to be preserved, you need to use `setWithPriority()` instead.\r\n *\r\n * Note that modifying data with `set()` will cancel any pending transactions\r\n * at that location, so extreme care should be taken if mixing `set()` and\r\n * `transaction()` to modify the same data.\r\n *\r\n * A single `set()` will generate a single \"value\" event at the location where\r\n * the `set()` was performed.\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction set(ref, value) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('set', ref._path);\r\n validateFirebaseDataArg('set', value, ref._path, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, \r\n /*priority=*/ null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Sets a priority for the data at this Database location.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setPriority(ref, priority) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('setPriority', ref._path);\r\n validatePriority('setPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes data the Database location. Like `set()` but also specifies the\r\n * priority for that data.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setWithPriority(ref, value, priority) {\r\n validateWritablePath('setWithPriority', ref._path);\r\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\r\n validatePriority('setWithPriority', priority, false);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\r\n }\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes multiple values to the Database at once.\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example,\r\n * \"name/first\") from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * A single `update()` will generate a single \"value\" event at the location\r\n * where the `update()` was performed, regardless of how many children were\r\n * modified.\r\n *\r\n * Note that modifying data with `update()` will cancel any pending\r\n * transactions at that location, so extreme care should be taken if mixing\r\n * `update()` and `transaction()` to modify the same data.\r\n *\r\n * Passing `null` to `update()` will remove the data at this location.\r\n *\r\n * See\r\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\r\n *\r\n * @param ref - The location to write to.\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when update on server is complete.\r\n */\r\nfunction update(ref, values) {\r\n validateFirebaseMergeDataArg('update', values, ref._path, false);\r\n const deferred = new Deferred();\r\n repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Gets the most up-to-date result for this query.\r\n *\r\n * @param query - The query to run.\r\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\r\n * available, or rejects if the client is unable to return a value (e.g., if the\r\n * server is unreachable and there is nothing cached).\r\n */\r\nfunction get(query) {\r\n query = getModularInstance(query);\r\n const callbackContext = new CallbackContext(() => { });\r\n const container = new ValueEventRegistration(callbackContext);\r\n return repoGetValue(query._repo, query, container).then(node => {\r\n return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());\r\n });\r\n}\r\n/**\r\n * Represents registration for 'value' events.\r\n */\r\nclass ValueEventRegistration {\r\n constructor(callbackContext) {\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n return eventType === 'value';\r\n }\r\n createEvent(change, query) {\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, null);\r\n }\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n matches(other) {\r\n if (!(other instanceof ValueEventRegistration)) {\r\n return false;\r\n }\r\n else if (!other.callbackContext || !this.callbackContext) {\r\n // If no callback specified, we consider it to match any callback.\r\n return true;\r\n }\r\n else {\r\n return other.callbackContext.matches(this.callbackContext);\r\n }\r\n }\r\n hasAnyCallback() {\r\n return this.callbackContext !== null;\r\n }\r\n}\r\n/**\r\n * Represents the registration of a child_x event.\r\n */\r\nclass ChildEventRegistration {\r\n constructor(eventType, callbackContext) {\r\n this.eventType = eventType;\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\r\n eventToCheck =\r\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\r\n return this.eventType === eventToCheck;\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n createEvent(change, query) {\r\n assert(change.childName != null, 'Child events should have a childName.');\r\n const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);\r\n }\r\n }\r\n matches(other) {\r\n if (other instanceof ChildEventRegistration) {\r\n return (this.eventType === other.eventType &&\r\n (!this.callbackContext ||\r\n !other.callbackContext ||\r\n this.callbackContext.matches(other.callbackContext)));\r\n }\r\n return false;\r\n }\r\n hasAnyCallback() {\r\n return !!this.callbackContext;\r\n }\r\n}\r\nfunction addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {\r\n let cancelCallback;\r\n if (typeof cancelCallbackOrListenOptions === 'object') {\r\n cancelCallback = undefined;\r\n options = cancelCallbackOrListenOptions;\r\n }\r\n if (typeof cancelCallbackOrListenOptions === 'function') {\r\n cancelCallback = cancelCallbackOrListenOptions;\r\n }\r\n if (options && options.onlyOnce) {\r\n const userCallback = callback;\r\n const onceCallback = (dataSnapshot, previousChildName) => {\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n userCallback(dataSnapshot, previousChildName);\r\n };\r\n onceCallback.userCallback = callback.userCallback;\r\n onceCallback.context = callback.context;\r\n callback = onceCallback;\r\n }\r\n const callbackContext = new CallbackContext(callback, cancelCallback || undefined);\r\n const container = eventType === 'value'\r\n ? new ValueEventRegistration(callbackContext)\r\n : new ChildEventRegistration(eventType, callbackContext);\r\n repoAddEventCallbackForQuery(query._repo, query, container);\r\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\nfunction onValue(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\n/**\r\n * Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.\r\n * Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from\r\n * the respective `on*` callbacks.\r\n *\r\n * Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener\r\n * will not automatically remove listeners registered on child nodes, `off()`\r\n * must also be called on any child listeners to remove the callback.\r\n *\r\n * If a callback is not specified, all callbacks for the specified eventType\r\n * will be removed. Similarly, if no eventType is specified, all callbacks\r\n * for the `Reference` will be removed.\r\n *\r\n * Individual listeners can also be removed by invoking their unsubscribe\r\n * callbacks.\r\n *\r\n * @param query - The query that the listener was registered with.\r\n * @param eventType - One of the following strings: \"value\", \"child_added\",\r\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\r\n * for the `Reference` will be removed.\r\n * @param callback - The callback function that was passed to `on()` or\r\n * `undefined` to remove all callbacks.\r\n */\r\nfunction off(query, eventType, callback) {\r\n let container = null;\r\n const expCallback = callback ? new CallbackContext(callback) : null;\r\n if (eventType === 'value') {\r\n container = new ValueEventRegistration(expCallback);\r\n }\r\n else if (eventType) {\r\n container = new ChildEventRegistration(eventType, expCallback);\r\n }\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\n/**\r\n * A `QueryConstraint` is used to narrow the set of documents returned by a\r\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\r\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\r\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\r\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\r\n * {@link orderByValue} or {@link equalTo} and\r\n * can then be passed to {@link query} to create a new query instance that\r\n * also contains this `QueryConstraint`.\r\n */\r\nclass QueryConstraint {\r\n}\r\nclass QueryEndAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'endAt';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endAt', this._value, query._path, true);\r\n const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endAt: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name less than or equal\r\n * to the specified key.\r\n *\r\n * You can read more about `endAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to end at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end at, among the children with the previously\r\n * specified priority. This argument is only allowed if ordering by child,\r\n * value, or priority.\r\n */\r\nfunction endAt(value, key) {\r\n validateKey('endAt', 'key', key, true);\r\n return new QueryEndAtConstraint(value, key);\r\n}\r\nclass QueryEndBeforeConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'endBefore';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\r\n const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is exclusive. If only a value is provided, children\r\n * with a value less than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value less than or equal\r\n * to the specified value and a key name less than the specified key.\r\n *\r\n * @param value - The value to end before. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end before, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction endBefore(value, key) {\r\n validateKey('endBefore', 'key', key, true);\r\n return new QueryEndBeforeConstraint(value, key);\r\n}\r\nclass QueryStartAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'startAt';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAt', this._value, query._path, true);\r\n const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAt: Starting point was already set (by another call to startAt, ' +\r\n 'startBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name greater than or\r\n * equal to the specified key.\r\n *\r\n * You can read more about `startAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to start at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAt(value = null, key) {\r\n validateKey('startAt', 'key', key, true);\r\n return new QueryStartAtConstraint(value, key);\r\n}\r\nclass QueryStartAfterConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'startAfter';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\r\n const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +\r\n 'startAfter, or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is exclusive. If only a value is provided, children\r\n * with a value greater than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value greater than or equal\r\n * to the specified value and a a key name greater than the specified key.\r\n *\r\n * @param value - The value to start after. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start after. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAfter(value, key) {\r\n validateKey('startAfter', 'key', key, true);\r\n return new QueryStartAfterConstraint(value, key);\r\n}\r\nclass QueryLimitToFirstConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n this.type = 'limitToFirst';\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that if limited to the first specific number\r\n * of children.\r\n *\r\n * The `limitToFirst()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the first 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToFirst()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToFirst(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToFirst: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToFirstConstraint(limit);\r\n}\r\nclass QueryLimitToLastConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n this.type = 'limitToLast';\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that is limited to return only the last\r\n * specified number of children.\r\n *\r\n * The `limitToLast()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the last 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToLast()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToLast(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToLast: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToLastConstraint(limit);\r\n}\r\nclass QueryOrderByChildConstraint extends QueryConstraint {\r\n constructor(_path) {\r\n super();\r\n this._path = _path;\r\n this.type = 'orderByChild';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByChild');\r\n const parsedPath = new Path(this._path);\r\n if (pathIsEmpty(parsedPath)) {\r\n throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');\r\n }\r\n const index = new PathIndex(parsedPath);\r\n const newParams = queryParamsOrderBy(query._queryParams, index);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the specified child key.\r\n *\r\n * Queries can only order by one key at a time. Calling `orderByChild()`\r\n * multiple times on the same query is an error.\r\n *\r\n * Firebase queries allow you to order your data by any child key on the fly.\r\n * However, if you know in advance what your indexes will be, you can define\r\n * them via the .indexOn rule in your Security Rules for better performance. See\r\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\r\n * rule for more information.\r\n *\r\n * You can read more about `orderByChild()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n *\r\n * @param path - The path to order by.\r\n */\r\nfunction orderByChild(path) {\r\n if (path === '$key') {\r\n throw new Error('orderByChild: \"$key\" is invalid. Use orderByKey() instead.');\r\n }\r\n else if (path === '$priority') {\r\n throw new Error('orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.');\r\n }\r\n else if (path === '$value') {\r\n throw new Error('orderByChild: \"$value\" is invalid. Use orderByValue() instead.');\r\n }\r\n validatePathString('orderByChild', 'path', path, false);\r\n return new QueryOrderByChildConstraint(path);\r\n}\r\nclass QueryOrderByKeyConstraint extends QueryConstraint {\r\n constructor() {\r\n super(...arguments);\r\n this.type = 'orderByKey';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByKey');\r\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the key.\r\n *\r\n * Sorts the results of a query by their (ascending) key values.\r\n *\r\n * You can read more about `orderByKey()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByKey() {\r\n return new QueryOrderByKeyConstraint();\r\n}\r\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\r\n constructor() {\r\n super(...arguments);\r\n this.type = 'orderByPriority';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByPriority');\r\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by priority.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\r\n * for alternatives to priority.\r\n */\r\nfunction orderByPriority() {\r\n return new QueryOrderByPriorityConstraint();\r\n}\r\nclass QueryOrderByValueConstraint extends QueryConstraint {\r\n constructor() {\r\n super(...arguments);\r\n this.type = 'orderByValue';\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByValue');\r\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by value.\r\n *\r\n * If the children of a query are all scalar values (string, number, or\r\n * boolean), you can order the results by their (ascending) values.\r\n *\r\n * You can read more about `orderByValue()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByValue() {\r\n return new QueryOrderByValueConstraint();\r\n}\r\nclass QueryEqualToValueConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n this.type = 'equalTo';\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\r\n 'equalTo).');\r\n }\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\r\n 'equalTo).');\r\n }\r\n return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` that includes children that match the specified\r\n * value.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The optional key argument can be used to further limit the range of the\r\n * query. If it is specified, then children that have exactly the specified\r\n * value must also have exactly the specified key as their key name. This can be\r\n * used to filter result sets with many matches for the same value.\r\n *\r\n * You can read more about `equalTo()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to match for. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction equalTo(value, key) {\r\n validateKey('equalTo', 'key', key, true);\r\n return new QueryEqualToValueConstraint(value, key);\r\n}\r\n/**\r\n * Creates a new immutable instance of `Query` that is extended to also include\r\n * additional query constraints.\r\n *\r\n * @param query - The Query instance to use as a base for the new constraints.\r\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\r\n * @throws if any of the provided query constraints cannot be combined with the\r\n * existing or new constraints.\r\n */\r\nfunction query(query, ...queryConstraints) {\r\n let queryImpl = getModularInstance(query);\r\n for (const constraint of queryConstraints) {\r\n queryImpl = constraint._apply(queryImpl);\r\n }\r\n return queryImpl;\r\n}\r\n/**\r\n * Define reference constructor in various modules\r\n *\r\n * We are doing this here to avoid several circular\r\n * dependency issues\r\n */\r\nsyncPointSetReferenceConstructor(ReferenceImpl);\r\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This variable is also defined in the firebase Node.js Admin SDK. Before\r\n * modifying this definition, consult the definition in:\r\n *\r\n * https://github.com/firebase/firebase-admin-node\r\n *\r\n * and make sure the two are consistent.\r\n */\r\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\r\n/**\r\n * Creates and caches `Repo` instances.\r\n */\r\nconst repos = {};\r\n/**\r\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\r\n */\r\nlet useRestClient = false;\r\n/**\r\n * Update an existing `Repo` in place to point to a new host/port.\r\n */\r\nfunction repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {\r\n repo.repoInfo_ = new RepoInfo(`${host}:${port}`, \r\n /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams, \r\n /*isUsingEmulator=*/ true);\r\n if (tokenProvider) {\r\n repo.authTokenProvider_ = tokenProvider;\r\n }\r\n}\r\n/**\r\n * This function should only ever be called to CREATE a new database instance.\r\n * @internal\r\n */\r\nfunction repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {\r\n let dbUrl = url || app.options.databaseURL;\r\n if (dbUrl === undefined) {\r\n if (!app.options.projectId) {\r\n fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\r\n ' a Project ID when calling firebase.initializeApp().');\r\n }\r\n log('Using default host for project ', app.options.projectId);\r\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\r\n }\r\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n let repoInfo = parsedUrl.repoInfo;\r\n let isEmulator;\r\n let dbEmulatorHost = undefined;\r\n if (typeof process !== 'undefined' && process.env) {\r\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\r\n }\r\n if (dbEmulatorHost) {\r\n isEmulator = true;\r\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\r\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n repoInfo = parsedUrl.repoInfo;\r\n }\r\n else {\r\n isEmulator = !parsedUrl.repoInfo.secure;\r\n }\r\n const authTokenProvider = nodeAdmin && isEmulator\r\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\r\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\r\n validateUrl('Invalid Firebase Database URL', parsedUrl);\r\n if (!pathIsEmpty(parsedUrl.path)) {\r\n fatal('Database URL must point to the root of a Firebase Database ' +\r\n '(not including a child path).');\r\n }\r\n const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));\r\n return new Database(repo, app);\r\n}\r\n/**\r\n * Remove the repo and make sure it is disconnected.\r\n *\r\n */\r\nfunction repoManagerDeleteRepo(repo, appName) {\r\n const appRepos = repos[appName];\r\n // This should never happen...\r\n if (!appRepos || appRepos[repo.key] !== repo) {\r\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\r\n }\r\n repoInterrupt(repo);\r\n delete appRepos[repo.key];\r\n}\r\n/**\r\n * Ensures a repo doesn't already exist and then creates one using the\r\n * provided app.\r\n *\r\n * @param repoInfo - The metadata about the Repo\r\n * @returns The Repo object for the specified server / repoName.\r\n */\r\nfunction repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {\r\n let appRepos = repos[app.name];\r\n if (!appRepos) {\r\n appRepos = {};\r\n repos[app.name] = appRepos;\r\n }\r\n let repo = appRepos[repoInfo.toURLString()];\r\n if (repo) {\r\n fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\r\n }\r\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\r\n appRepos[repoInfo.toURLString()] = repo;\r\n return repo;\r\n}\r\n/**\r\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\r\n */\r\nfunction repoManagerForceRestClient(forceRestClient) {\r\n useRestClient = forceRestClient;\r\n}\r\n/**\r\n * Class representing a Firebase Realtime Database.\r\n */\r\nclass Database {\r\n /** @hideconstructor */\r\n constructor(_repoInternal, \r\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\r\n app) {\r\n this._repoInternal = _repoInternal;\r\n this.app = app;\r\n /** Represents a `Database` instance. */\r\n this['type'] = 'database';\r\n /** Track if the instance has been used (root or repo accessed) */\r\n this._instanceStarted = false;\r\n }\r\n get _repo() {\r\n if (!this._instanceStarted) {\r\n repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);\r\n this._instanceStarted = true;\r\n }\r\n return this._repoInternal;\r\n }\r\n get _root() {\r\n if (!this._rootInternal) {\r\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\r\n }\r\n return this._rootInternal;\r\n }\r\n _delete() {\r\n if (this._rootInternal !== null) {\r\n repoManagerDeleteRepo(this._repo, this.app.name);\r\n this._repoInternal = null;\r\n this._rootInternal = null;\r\n }\r\n return Promise.resolve();\r\n }\r\n _checkNotDeleted(apiName) {\r\n if (this._rootInternal === null) {\r\n fatal('Cannot call ' + apiName + ' on a deleted database.');\r\n }\r\n }\r\n}\r\nfunction checkTransportInit() {\r\n if (TransportManager.IS_TRANSPORT_INITIALIZED) {\r\n warn('Transport has already been initialized. Please call this function before calling ref or setting up a listener');\r\n }\r\n}\r\n/**\r\n * Force the use of websockets instead of longPolling.\r\n */\r\nfunction forceWebSockets() {\r\n checkTransportInit();\r\n BrowserPollConnection.forceDisallow();\r\n}\r\n/**\r\n * Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.\r\n */\r\nfunction forceLongPolling() {\r\n checkTransportInit();\r\n WebSocketConnection.forceDisallow();\r\n BrowserPollConnection.forceAllow();\r\n}\r\n/**\r\n * Returns the instance of the Realtime Database SDK that is associated\r\n * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with\r\n * with default settings if no instance exists or if the existing instance uses\r\n * a custom database URL.\r\n *\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\r\n * Database instance is associated with.\r\n * @param url - The URL of the Realtime Database instance to connect to. If not\r\n * provided, the SDK connects to the default instance of the Firebase App.\r\n * @returns The `Database` instance of the provided app.\r\n */\r\nfunction getDatabase(app = getApp(), url) {\r\n const db = _getProvider(app, 'database').getImmediate({\r\n identifier: url\r\n });\r\n if (!db._instanceStarted) {\r\n const emulator = getDefaultEmulatorHostnameAndPort('database');\r\n if (emulator) {\r\n connectDatabaseEmulator(db, ...emulator);\r\n }\r\n }\r\n return db;\r\n}\r\n/**\r\n * Modify the provided instance to communicate with the Realtime Database\r\n * emulator.\r\n *\r\n *

Note: This method must be called before performing any other operation.\r\n *\r\n * @param db - The instance to modify.\r\n * @param host - The emulator host (ex: localhost)\r\n * @param port - The emulator port (ex: 8080)\r\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\r\n */\r\nfunction connectDatabaseEmulator(db, host, port, options = {}) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('useEmulator');\r\n if (db._instanceStarted) {\r\n fatal('Cannot call useEmulator() after instance has already been initialized.');\r\n }\r\n const repo = db._repoInternal;\r\n let tokenProvider = undefined;\r\n if (repo.repoInfo_.nodeAdmin) {\r\n if (options.mockUserToken) {\r\n fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".');\r\n }\r\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\r\n }\r\n else if (options.mockUserToken) {\r\n const token = typeof options.mockUserToken === 'string'\r\n ? options.mockUserToken\r\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\r\n tokenProvider = new EmulatorTokenProvider(token);\r\n }\r\n // Modify the repo to apply emulator settings\r\n repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);\r\n}\r\n/**\r\n * Disconnects from the server (all Database operations will be completed\r\n * offline).\r\n *\r\n * The client automatically maintains a persistent connection to the Database\r\n * server, which will remain active indefinitely and reconnect when\r\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\r\n * to control the client connection in cases where a persistent connection is\r\n * undesirable.\r\n *\r\n * While offline, the client will no longer receive data updates from the\r\n * Database. However, all Database operations performed locally will continue to\r\n * immediately fire events, allowing your application to continue behaving\r\n * normally. Additionally, each operation performed locally will automatically\r\n * be queued and retried upon reconnection to the Database server.\r\n *\r\n * To reconnect to the Database and begin receiving remote events, see\r\n * `goOnline()`.\r\n *\r\n * @param db - The instance to disconnect.\r\n */\r\nfunction goOffline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOffline');\r\n repoInterrupt(db._repo);\r\n}\r\n/**\r\n * Reconnects to the server and synchronizes the offline Database state\r\n * with the server state.\r\n *\r\n * This method should be used after disabling the active connection with\r\n * `goOffline()`. Once reconnected, the client will transmit the proper data\r\n * and fire the appropriate events so that your client \"catches up\"\r\n * automatically.\r\n *\r\n * @param db - The instance to reconnect.\r\n */\r\nfunction goOnline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOnline');\r\n repoResume(db._repo);\r\n}\r\nfunction enableLogging(logger, persistent) {\r\n enableLogging$1(logger, persistent);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerDatabase(variant) {\r\n setSDKVersion(SDK_VERSION$1);\r\n _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const authProvider = container.getProvider('auth-internal');\r\n const appCheckProvider = container.getProvider('app-check-internal');\r\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);\r\n }, \"PUBLIC\" /* ComponentType.PUBLIC */).setMultipleInstances(true));\r\n registerVersion(name, version, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SERVER_TIMESTAMP = {\r\n '.sv': 'timestamp'\r\n};\r\n/**\r\n * Returns a placeholder value for auto-populating the current timestamp (time\r\n * since the Unix epoch, in milliseconds) as determined by the Firebase\r\n * servers.\r\n */\r\nfunction serverTimestamp() {\r\n return SERVER_TIMESTAMP;\r\n}\r\n/**\r\n * Returns a placeholder value that can be used to atomically increment the\r\n * current database value by the provided delta.\r\n *\r\n * @param delta - the amount to modify the current value atomically.\r\n * @returns A placeholder value for modifying data atomically server-side.\r\n */\r\nfunction increment(delta) {\r\n return {\r\n '.sv': {\r\n 'increment': delta\r\n }\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A type for the resolve value of {@link runTransaction}.\r\n */\r\nclass TransactionResult {\r\n /** @hideconstructor */\r\n constructor(\r\n /** Whether the transaction was successfully committed. */\r\n committed, \r\n /** The resulting data snapshot. */\r\n snapshot) {\r\n this.committed = committed;\r\n this.snapshot = snapshot;\r\n }\r\n /** Returns a JSON-serializable representation of this object. */\r\n toJSON() {\r\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\r\n }\r\n}\r\n/**\r\n * Atomically modifies the data at this location.\r\n *\r\n * Atomically modify the data at this location. Unlike a normal `set()`, which\r\n * just overwrites the data regardless of its previous value, `runTransaction()` is\r\n * used to modify the existing value to a new value, ensuring there are no\r\n * conflicts with other clients writing to the same location at the same time.\r\n *\r\n * To accomplish this, you pass `runTransaction()` an update function which is\r\n * used to transform the current value into a new value. If another client\r\n * writes to the location before your new value is successfully written, your\r\n * update function will be called again with the new current value, and the\r\n * write will be retried. This will happen repeatedly until your write succeeds\r\n * without conflict or you abort the transaction by not returning a value from\r\n * your update function.\r\n *\r\n * Note: Modifying data with `set()` will cancel any pending transactions at\r\n * that location, so extreme care should be taken if mixing `set()` and\r\n * `runTransaction()` to update the same data.\r\n *\r\n * Note: When using transactions with Security and Firebase Rules in place, be\r\n * aware that a client needs `.read` access in addition to `.write` access in\r\n * order to perform a transaction. This is because the client-side nature of\r\n * transactions requires the client to read the data in order to transactionally\r\n * update it.\r\n *\r\n * @param ref - The location to atomically modify.\r\n * @param transactionUpdate - A developer-supplied function which will be passed\r\n * the current data stored at this location (as a JavaScript object). The\r\n * function should return the new value it would like written (as a JavaScript\r\n * object). If `undefined` is returned (i.e. you return with no arguments) the\r\n * transaction will be aborted and the data at this location will not be\r\n * modified.\r\n * @param options - An options object to configure transactions.\r\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\r\n * callback to handle success and failure.\r\n */\r\nfunction runTransaction(ref, \r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\ntransactionUpdate, options) {\r\n var _a;\r\n ref = getModularInstance(ref);\r\n validateWritablePath('Reference.transaction', ref._path);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');\r\n }\r\n const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;\r\n const deferred = new Deferred();\r\n const promiseComplete = (error, committed, node) => {\r\n let dataSnapshot = null;\r\n if (error) {\r\n deferred.reject(error);\r\n }\r\n else {\r\n dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);\r\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\r\n }\r\n };\r\n // Add a watch to make sure we get server updates.\r\n const unwatcher = onValue(ref, () => { });\r\n repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);\r\n return deferred.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nPersistentConnection;\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\r\n this.sendRequest('q', { p: pathString }, onComplete);\r\n};\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.echo = function (data, onEcho) {\r\n this.sendRequest('echo', { d: data }, onEcho);\r\n};\r\n// RealTimeConnection properties that we use in tests.\r\nConnection;\r\n/**\r\n * @internal\r\n */\r\nconst hijackHash = function (newHash) {\r\n const oldPut = PersistentConnection.prototype.put;\r\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\r\n if (hash !== undefined) {\r\n hash = newHash();\r\n }\r\n oldPut.call(this, pathString, data, onComplete, hash);\r\n };\r\n return function () {\r\n PersistentConnection.prototype.put = oldPut;\r\n };\r\n};\r\nRepoInfo;\r\n/**\r\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\r\n * @internal\r\n */\r\nconst forceRestClient = function (forceRestClient) {\r\n repoManagerForceRestClient(forceRestClient);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2023 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Used by console to create a database based on the app,\r\n * passed database URL and a custom auth implementation.\r\n * @internal\r\n * @param app - A valid FirebaseApp-like object\r\n * @param url - A valid Firebase databaseURL\r\n * @param version - custom version e.g. firebase-admin version\r\n * @param customAppCheckImpl - custom app check implementation\r\n * @param customAuthImpl - custom auth implementation\r\n */\r\nfunction _initStandalone({ app, url, version, customAuthImpl, customAppCheckImpl, nodeAdmin = false }) {\r\n setSDKVersion(version);\r\n /**\r\n * ComponentContainer('database-standalone') is just a placeholder that doesn't perform\r\n * any actual function.\r\n */\r\n const componentContainer = new ComponentContainer('database-standalone');\r\n const authProvider = new Provider('auth-internal', componentContainer);\r\n let appCheckProvider;\r\n if (customAppCheckImpl) {\r\n appCheckProvider = new Provider('app-check-internal', componentContainer);\r\n appCheckProvider.setComponent(new Component('app-check-internal', () => customAppCheckImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n }\r\n authProvider.setComponent(new Component('auth-internal', () => customAuthImpl, \"PRIVATE\" /* ComponentType.PRIVATE */));\r\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin);\r\n}\n\n/**\r\n * Firebase Realtime Database\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterDatabase();\n\nexport { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, _initStandalone, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, forceLongPolling, forceWebSockets, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };\n//# sourceMappingURL=index.esm2017.js.map\n","/* eslint-disable import/prefer-default-export */\n/* eslint-disable import/no-extraneous-dependencies */\nimport { initializeApp } from 'firebase/app';\nimport {\n\tgetAuth,\n\tsignInWithEmailAndPassword,\n\tonAuthStateChanged,\n\tsignOut,\n\tsendPasswordResetEmail,\n\tconfirmPasswordReset,\n\tverifyPasswordResetCode,\n} from 'firebase/auth';\nimport { getDatabase } from 'firebase/database';\n\nfunction loadFirebaseConfig() {\n\tconst el = document.getElementById('wp-script-module-data-@prc/firebase');\n\ttry {\n\t\tconst config = JSON.parse(el.textContent);\n\t\treturn config;\n\t} catch (err) {\n\t\tconsole.error(err);\n\t\treturn {};\n\t}\n}\n\nconst _app = initializeApp(loadFirebaseConfig());\nconst _auth = getAuth();\nconst _signInWithEmailAndPassword = signInWithEmailAndPassword;\nconst _onAuthStateChanged = onAuthStateChanged;\nconst _signOut = signOut;\nconst _sendPasswordResetEmail = sendPasswordResetEmail;\nconst _confirmPasswordReset = confirmPasswordReset;\nconst _verifyPasswordResetCode = verifyPasswordResetCode;\nconst _db = getDatabase();\n\nexport {\n\t_app as app,\n\t_auth as auth,\n\t_signInWithEmailAndPassword as signInWithEmailAndPassword,\n\t_onAuthStateChanged as onAuthStateChanged,\n\t_signOut as signOut,\n\t_sendPasswordResetEmail as sendPasswordResetEmail,\n\t_confirmPasswordReset as confirmPasswordReset,\n\t_verifyPasswordResetCode as verifyPasswordResetCode,\n\t_db as getDatabase,\n};\n"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","g","globalThis","this","Function","e","window","obj","prop","prototype","hasOwnProperty","call","assertion","message","assertionError","Error","stringToByteArray$1","str","out","p","i","length","c","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","push","join","encodeString","btoa","decodeString","bytes","pos","c1","String","fromCharCode","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","DecodeBase64StringError","constructor","super","arguments","name","base64Encode","utf8Bytes","base64urlEncodeWithoutPadding","replace","base64Decode","console","error","deepCopy","value","deepExtend","undefined","target","source","Date","getTime","getDefaults","self","getGlobal","__FIREBASE_DEFAULTS__","process","env","defaultsJsonString","JSON","parse","getDefaultsFromEnvVariable","document","match","cookie","decoded","getDefaultsFromCookie","info","getDefaultEmulatorHost","productName","_a","_b","emulatorHosts","getDefaultAppConfig","config","getExperimentalSetting","reject","resolve","promise","Promise","wrapCallback","callback","catch","navigator","isMobileCordova","test","isReactNative","FirebaseError","code","customData","setPrototypeOf","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","PATTERN","_","replaceTemplate","fullMessage","jsonEval","stringify","decode","token","header","claims","signature","parts","split","map","fn","contextObj","res","deepEqual","a","b","aKeys","keys","bKeys","k","includes","aProp","bProp","isObject","thing","querystringParams","params","entries","forEach","arrayVal","encodeURIComponent","querystringDecode","querystring","decodeURIComponent","extractQuerystring","url","queryStart","indexOf","fragmentStart","substring","Sha1","chain_","buf_","W_","pad_","inbuf_","total_","blockSize","reset","compress_","buf","offset","W","t","f","d","update","lengthMinusBlock","n","inbuf","digest","totalBits","j","ObserverProxy","executor","onNoObservers","observers","unsubscribes","observerCount","task","finalized","then","next","forEachObserver","observer","close","complete","subscribe","nextOrObserver","methods","method","implementsAnyMethods","noop","unsub","unsubscribeOne","bind","finalError","sendOne","err","stringLength","_delegate","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","DEFAULT_ENTRY_NAME","container","component","instances","Map","instancesDeferred","instancesOptions","onInitCallbacks","identifier","normalizedIdentifier","normalizeInstanceIdentifier","has","deferred","set","isInitialized","shouldAutoInitialize","instance","getOrInitializeService","instanceIdentifier","getImmediate","options","optional","getComponent","setComponent","isComponentEager","instanceDeferred","clearInstance","delete","services","from","values","all","filter","INTERNAL","_delete","isComponentSet","getOptions","initialize","opts","onInit","existingCallbacks","Set","add","existingInstance","invokeOnInitCallbacks","callbacks","providers","addComponent","provider","getProvider","addOrOverwriteComponent","getProviders","LogLevel","levelStringToEnum","DEBUG","VERBOSE","INFO","WARN","ERROR","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","logType","args","logLevel","now","toISOString","Logger","_logLevel","_logHandler","_userLogHandler","val","TypeError","setLogLevel","logHandler","userLogHandler","debug","log","warn","instanceOfAny","object","constructors","some","idbProxyableTypes","cursorAdvanceMethods","cursorRequestMap","WeakMap","transactionDoneMap","transactionStoreNamesMap","transformCache","reverseTransformCache","idbProxyTraps","receiver","IDBTransaction","objectStoreNames","objectStore","transformCachableValue","func","IDBDatabase","transaction","IDBCursor","advance","continue","continuePrimaryKey","apply","unwrap","storeNames","tx","sort","done","unlisten","removeEventListener","DOMException","addEventListener","cacheDonePromiseForTransaction","IDBObjectStore","IDBIndex","Proxy","IDBRequest","request","success","result","promisifyRequest","newValue","readMethods","writeMethods","cachedMethods","getMethod","targetFuncName","useIndex","isWrite","async","storeName","store","index","shift","oldTraps","PlatformLoggerServiceImpl","getPlatformInfoString","isVersionServiceProvider","library","version","logString","name$p","version$1","logger","name$o","name$n","name$m","name$l","name$k","name$j","name$i","name$h","name$g","name$f","name$e","name$d","name$c","name$b","name$a","name$9","name$8","name$7","name$6","name$5","name$4","name$3","name$2","name$1","PLATFORM_LOG_STRING","_apps","_serverApps","_components","_addComponent","app","_registerComponent","componentName","serverApp","_getProvider","heartbeatController","triggerHeartbeat","settings","ERROR_FACTORY","FirebaseAppImpl","_isDeleted","_options","assign","_config","_name","_automaticDataCollectionEnabled","automaticDataCollectionEnabled","_container","checkDestroyed","isDeleted","appName","SDK_VERSION","initializeApp","rawConfig","existingApp","newApp","getApp","registerVersion","libraryKeyOrName","variant","libraryMismatch","versionMismatch","warning","DB_NAME","DB_VERSION","STORE_NAME","dbPromise","getDbPromise","blocked","upgrade","blocking","terminated","indexedDB","open","openPromise","event","oldVersion","newVersion","db","openDB","createObjectStore","originalErrorMessage","writeHeartbeatsToIndexedDB","heartbeatObject","put","computeKey","idbGetError","appId","HeartbeatServiceImpl","_heartbeatsCache","_storage","HeartbeatStorageImpl","_heartbeatsCachePromise","read","agent","date","getUTCDateString","heartbeats","lastSentHeartbeatDate","singleDateHeartbeat","hbTimestamp","valueOf","overwrite","getHeartbeatsHeader","heartbeatsToSend","unsentEntries","heartbeatsCache","maxSize","slice","heartbeatEntry","find","hb","dates","countBytes","pop","extractHeartbeatsForHeader","headerString","_canUseIndexedDBPromise","runIndexedDBEnvironmentCheck","isIndexedDBAvailable","preExist","DB_CHECK_NAME","onsuccess","deleteDatabase","onupgradeneeded","onerror","idbHeartbeatObject","readHeartbeatsFromIndexedDB","heartbeatsObject","existingHeartbeatsObject","__rest","s","getOwnPropertySymbols","propertyIsEnumerable","SuppressedError","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logError","msg","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","auth","errorMap","_serverAppCurrentUserOperationNotSupportedError","fullParams","_errorFactory","_assert","debugFail","failure","debugAssert","_getCurrentUrl","location","href","_getCurrentScheme","protocol","_isOnline","onLine","runtime","chrome","browser","id","isBrowserExtension","Delay","shortDelay","longDelay","isMobile","Math","min","_emulatorUrl","path","emulator","startsWith","FetchProvider","fetchImpl","headersImpl","responseImpl","fetch","headers","Headers","response","Response","SERVER_ERROR_MAP","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","tenantId","_performApiRequest","customErrorMap","_performFetchWithErrorHandling","body","query","apiKey","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","race","clearNetworkTimeout","json","_makeTaggedError","ok","errorMessage","serverErrorCode","serverErrorMessage","authError","toLowerCase","_performSignInRequest","serverResponse","_serverResponse","host","base","apiScheme","_parseEnforcementState","enforcementStateStr","timer","setTimeout","clearTimeout","errorParams","email","phoneNumber","_tokenResponse","isEnterprise","grecaptcha","enterprise","RecaptchaConfig","siteKey","recaptchaEnforcementState","recaptchaKey","getProviderEnforcementState","providerStr","enforcementState","isProviderEnabled","getAccountInfo","utcTimestampToDateString","utcTimestamp","Number","isNaN","toUTCString","secondsStringToMilliseconds","seconds","_parseToken","algorithm","payload","toString","_tokenExpiresIn","parsedToken","exp","iat","_logoutIfInvalidated","user","bypassAuthState","isUserInvalidated","currentUser","signOut","ProactiveRefresh","isRunning","timerId","errorBackoff","_start","schedule","_stop","getInterval","wasError","interval","stsTokenManager","expirationTime","max","iteration","getIdToken","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","creationTime","_copy","metadata","toJSON","_reloadWithoutSaving","idToken","users","coreAccount","_notifyReloadListener","newProviderData","providerUserInfo","extractProviderData","providerData","original","newData","providerId","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","updates","uid","localId","displayName","photoURL","photoUrl","emailVerified","rawId","StsTokenManager","refreshToken","accessToken","isExpired","updateFromServerResponse","expiresIn","updateTokensAndExpiration","updateFromIdToken","getToken","forceRefresh","refresh","clearRefreshToken","oldToken","tokenApiHost","access_token","expires_in","refresh_token","requestStsToken","expiresInSec","fromJSON","manager","_assign","_clone","_performRefresh","assertStringOrUndefined","UserImpl","opt","proactiveRefresh","reloadUserInfo","reloadListener","_persistUserIfCurrent","_notifyListenersIfCurrent","getIdTokenResult","userInternal","auth_time","firebase","signInProvider","authTime","issuedAtTime","signInSecondFactor","reload","userInfo","newUser","_onReload","_startProactiveRefresh","_stopProactiveRefresh","_updateTokensIfNecessary","tokensRefreshed","deleteAccount","_redirectEventId","_fromJSON","_c","_d","_e","_f","_g","_h","plainObjectTokenManager","_fromIdTokenResponse","idTokenResponse","_fromGetAccountInfoResponse","instanceCache","_getInstance","cls","InMemoryPersistence","storage","_isAvailable","_set","_get","_remove","_addListener","_key","_listener","_removeListener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","persistence","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","setCurrentUser","getCurrentUser","blob","removeCurrentUser","savePersistenceForRedirect","setPersistence","newPersistence","persistenceHierarchy","availablePersistences","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","userAgent","ua","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","re","matches","_isIOS","_isMobileBrowser","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","AuthMiddlewareQueue","queue","pushCallback","onAbort","wrappedCallback","runMiddleware","nextUser","onAbortStack","beforeStateCallback","reverse","originalMessage","PasswordPolicyImpl","responseOptions","customStrengthOptions","minPasswordLength","maxPasswordLength","containsLowercaseCharacter","containsLowercaseLetter","containsUppercaseCharacter","containsUppercaseLetter","containsNumericCharacter","containsNonAlphanumericCharacter","allowedNonAlphanumericCharacters","forceUpgradeOnSignin","schemaVersion","validatePassword","password","status","isValid","passwordPolicy","validatePasswordLengthOptions","validatePasswordCharacterOptions","meetsMinPasswordLength","meetsMaxPasswordLength","passwordChar","updatePasswordCharacterOptionsStatuses","AuthImpl","heartbeatServiceProvider","appCheckServiceProvider","emulatorConfig","operations","authStateSubscription","Subscription","idTokenSubscription","beforeStateQueue","redirectUser","isProactiveRefreshEnabled","EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","_agentRecaptchaConfig","_tenantRecaptchaConfigs","_projectPasswordPolicy","_tenantPasswordPolicies","lastNotifiedUid","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","_initializeWithPersistence","popupRedirectResolver","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","initializeCurrentUserFromIdToken","directlySetCurrentUser","authIdToken","previouslyStoredUser","futureCurrentUser","needsTocheckMiddleware","authDomain","getOrInitRedirectPersistenceManager","redirectUserEventId","storedUserEventId","tryRedirectSignIn","_overrideRedirectResult","reloadAndSetCurrentUserOrClear","redirectResolver","_completeRedirectFn","_setRedirectUser","useDeviceLanguage","navigatorLanguage","languages","language","_getUserLanguage","updateCurrentUser","userExtern","skipBeforeStateCallbacks","notifyAuthListeners","redirectPersistenceManager","_getRecaptchaConfig","_getPasswordPolicyInternal","_updatePasswordPolicy","_getPasswordPolicy","_getPersistence","_updateErrorMap","onAuthStateChanged","completed","registerStateListener","beforeAuthStateChanged","onIdTokenChanged","authStateReady","unsubscribe","revokeAccessToken","tokenType","revokeToken","redirectManager","resolver","_redirectPersistence","_redirectUserForId","currentUid","subscription","cb","isUnsubscribed","addObserver","action","_logFramework","framework","_getFrameworks","heartbeatsHeader","appCheckToken","_getAppCheckToken","appCheckTokenResult","_logWarn","_castAuth","proxy","createSubscribe","externalJSProvider","loadJS","recaptchaV2Script","recaptchaEnterpriseScript","gapiScript","_loadJS","_generateCallbackName","prefix","floor","random","RecaptchaEnterpriseVerifier","authExtern","verify","retrieveRecaptchaToken","ready","execute","getRecaptchaConfig","clientType","retrieveSiteKey","injectRecaptchaFields","captchaResp","verifier","captchaResponse","newRequest","handleRecaptchaFlow","authInstance","actionName","actionMethod","requestWithRecaptcha","extractProtocol","protocolEnd","substr","parsePort","portStr","port","AuthCredential","signInMethod","_getIdTokenResponse","_auth","_linkToIdToken","_idToken","_getReauthenticationResolver","resetPassword","linkEmailPassword","signInWithPassword","sendPasswordResetEmail$1","sendOobCode","EmailAuthCredential","_email","_password","_tenantId","_fromEmailAndPassword","_fromEmailAndCode","oobCode","returnSecureToken","signInWithEmailLink$1","signInWithEmailLinkForLinking","signInWithIdp","OAuthCredential","pendingToken","_fromParams","cred","nonce","oauthToken","oauthTokenSecret","secret","buildRequest","autoCreate","requestUri","postBody","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","PhoneAuthCredential","_fromVerification","verificationId","verificationCode","_fromTokenResponse","temporaryProof","signInWithPhoneNumber$1","_makeVerificationRequest","linkWithPhoneNumber$1","operation","verifyPhoneNumberForExisting","sessionInfo","ActionCodeURL","actionLink","searchParams","parseMode","continueUrl","parseLink","link","doubleDeepLink","iOSDeepLink","parseDeepLink","EmailAuthProvider","PROVIDER_ID","credential","credentialWithLink","emailLink","actionCodeUrl","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_LINK_SIGN_IN_METHOD","FederatedAuthProvider","defaultLanguageCode","customParameters","setDefaultLanguage","setCustomParameters","customOAuthParameters","getCustomParameters","BaseOAuthProvider","scopes","addScope","scope","getScopes","FacebookAuthProvider","FACEBOOK_SIGN_IN_METHOD","credentialFromResult","userCredential","credentialFromTaggedObject","credentialFromError","tokenResponse","oauthAccessToken","GoogleAuthProvider","GOOGLE_SIGN_IN_METHOD","oauthIdToken","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","UserCredentialImpl","operationType","providerIdForResponse","_forOperation","MultiFactorError","_fromErrorAndOperation","_processCredentialSavingMfaContextIfNecessary","_signInWithCredential","MultiFactorInfoImpl","factorId","mfaEnrollmentId","enrollmentTime","enrolledAt","_fromServerResponse","enrollment","PhoneMultiFactorInfoImpl","TotpMultiFactorInfoImpl","phoneInfo","recachePasswordPolicy","authInternal","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","setItem","removeItem","getItem","BrowserLocalPersistence","localStorage","poll","onStorageEvent","listeners","localCache","pollTimer","safariLocalStorageNotSynced","_iframeCannotSyncWebStorage","top","_isIframe","fallbackToPolling","forAllChangedKeys","oldValue","_oldValue","notifyListeners","detachListener","stopPolling","storedValue","triggerListeners","isIE","documentMode","listener","startPolling","setInterval","StorageEvent","clearInterval","attachListener","size","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","Receiver","eventTarget","handlersMap","handleEvent","receivers","isListeningto","newInstance","messageEvent","eventId","eventType","handlers","ports","postMessage","promises","handler","origin","fulfilled","reason","_allSettled","_subscribe","eventHandler","_unsubscribe","_generateEventId","digits","Sender","removeMessageHandler","messageChannel","port1","onMessage","_send","timeout","MessageChannel","completionTimer","start","ackTimer","port2","finally","_window","_isWorker","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","toPromise","getObjectStore","isReadWrite","_openDatabase","keyPath","contains","_deleteDatabase","_putObject","_deleteObject","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","_openDb","_withRetries","op","numAttempts","initializeReceiver","initializeSender","_origin","keyProcessed","_poll","_data","serviceWorker","active","_getActiveServiceWorker","results","notifyServiceWorker","controller","_withPendingWrite","write","getObject","getAllRequest","getAll","keysInResult","fbase_key","localKey","indexedDBLocalPersistence","PhoneAuthProvider","verifyPhoneNumber","phoneOptions","applicationVerifier","recaptchaToken","phoneInfoOptions","session","startEnrollPhoneMfa","phoneEnrollmentInfo","phoneSessionInfo","multiFactorHint","multiFactorUid","startSignInPhoneMfa","mfaPendingCredential","phoneSignInInfo","phoneResponseInfo","sendPhoneVerificationCode","_reset","_verifyPhoneNumber","PHONE_SIGN_IN_METHOD","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_reauth","parsed","sub","_reauthenticate","_link","_link$1","AbstractPopupRedirectOperation","pendingPromise","eventManager","onExecution","registerConsumer","onAuthEvent","urlResponse","getIdpTask","onError","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","PopupOperation","authWindow","pollId","currentPopupAction","cancel","executeNotNull","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","isSupported","pollUserCancellation","closed","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","pendingRedirectKey","resolverPersistence","hasPendingRedirect","_getAndClearPendingRedirectStatus","_getRedirectResult","resolverExtern","resolverOverride","_withDefaultResolver","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","onEvent","hasEventBeenHandled","handled","consumer","isNullRedirectEvent","isRedirectEvent","eventIdMatches","clear","eventUid","v","IP_ADDRESS_REGEX","HTTP_REGEX","matchDomain","expected","currentUrl","hostname","URL","ceUrl","escapedDomainPattern","RegExp","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","H","hint","r","L","CP","loadGapi","loadGapiIframe","gapi","load","iframes","getContext","ontimeout","Iframe","cbName","cachedGApiLoader","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","style","position","width","height","tabindex","EID_FROM_APIHOST","getIframeUrl","eid","fw","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","AuthPopup","FIREBASE_APP_CHECK_FRAGMENT_ID","_getRedirectUrl","authType","redirectUrl","additionalParams","tid","paramsDict","appCheckTokenFragment","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","browserPopupRedirectResolver","eventManagers","originValidationPromises","screen","availHeight","left","availWidth","scrollbars","optionsString","reduce","accum","standalone","_isIOSStandalone","el","createElement","click","createEvent","initMouseEvent","dispatchEvent","openAsNewWindowIOS","newWin","focus","_open","_openRedirect","initAndGetManager","iframe","context","_loadGapi","where","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","attributes","dontclear","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","_openIframe","register","iframeEvent","authEvent","send","authorizedDomains","_getProjectConfig","domain","_validateOrigin","AuthInterop","internalListeners","getUid","assertAuthConfigured","addAuthTokenListener","updateProactiveRefresh","removeAuthTokenListener","authIdTokenMaxAge","lastPostedIdToken","setAttribute","onload","charset","getElementsByTagName","appendChild","deps","hierarchy","_initializeAuthInstance","_instanceIdentifier","_instance","getVersionForPlatform","DOMStorageWrapper","domStorage_","prefix_","prefixedName_","storedVal","remove","MemoryStorage","cache_","isInMemoryStorage","createStoragefor","domStorageName","domStorage","PersistentStorage","SessionStorage","LUIDGenerator","sha1","high","stringToByteArray","sha1Bytes","buildLogMessage_","varArgs","arg","firstLog_","logger_","persistent","logWrapper","fatal","isInvalidJSONNumber","POSITIVE_INFINITY","NEGATIVE_INFINITY","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","ObjectToUniqueKey","splitStringBySize","segsize","len","dataSegs","each","doubleToIEEE754String","ln","abs","pow","LN2","round","bits","hexByteString","hexByte","parseInt","INTEGER_REGEXP_","intVal","exceptionGuard","stack","setTimeoutNonBlocking","time","Deno","unrefTimer","AppCheckTokenProvider","appName_","appCheckProvider","appCheck","addTokenChangeListener","addTokenListener","notifyForInvalidToken","FirebaseAuthTokenProvider","firebaseOptions_","authProvider_","auth_","removeTokenChangeListener","EmulatorTokenProvider","OWNER","PROTOCOL_VERSION","FORGE_DOMAIN_RE","APP_CHECK_TOKEN_PARAM","WEBSOCKET","LONG_POLLING","RepoInfo","secure","namespace","webSocketOnly","nodeAdmin","persistenceKey","includeNamespaceInQueryParams","isUsingEmulator","_host","_domain","internalHost","isCacheableHost","isCustomHost","newHost","toURLString","repoInfoConnectionURL","repoInfo","connURL","repoInfoNeedsQueryParam","pairs","StatsCollection","counters_","incrementCounter","amount","collections","reporters","statsManagerGetCollection","hashString","PacketReceiver","onMessage_","pendingResponses","currentResponseNum","closeAfterResponse","onClose","closeAfter","responseNum","handleResponse","requestNum","toProcess","FIREBASE_LONGPOLL_START_PARAM","BrowserPollConnection","connId","applicationId","authToken","transportSessionId","lastSessionId","bytesSent","bytesReceived","everConnected_","log_","stats_","urlFn","onDisconnect","curSegmentNum","onDisconnect_","myPacketOrderer","isClosed_","connectTimeoutTimer_","onClosed_","readyState","called","wrappedFn","attachEvent","executeWhenDOMReady","scriptTagHolder","FirebaseIFrameScriptHolder","command","arg1","arg2","arg3","arg4","incrementIncomingBytes_","sendNewPolls","pN","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","isAvailable","Windows","UI","markConnectionHealthy","shutdown_","myDisconnFrame","removeChild","dataStr","base64data","MAX_URL_DATA_SIZE","enqueueSegment","pw","src","display","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","script","iframeContents","doc","contentWindow","contentDocument","alive","textContent","myID","myPW","newRequest_","theURL","curDataString","theSeg","seg","ts","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","loadCB","newScript","onreadystatechange","rstate","parentNode","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","CONSTANTS","mySock","onopen","onclose","onmessage","m","handleIncomingFrame","isOldAndroid","oldAndroidRegex","oldAndroidMatch","parseFloat","previouslyFailed","appendFrame_","fullMess","jsonMess","handleNewFrameCount_","frameCount","extractFrameCount_","mess","resetKeepAlive","remainingData","sendString_","responsesRequiredToBeHealthy","healthyTimeout","TransportManager","initTransports_","ALL_TRANSPORTS","IS_TRANSPORT_INITIALIZED","globalTransportInitialized_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports","transport","initialTransport","upgradeTransport","Connection","repoInfo_","applicationId_","appCheckToken_","authToken_","onReady_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","start_","conn","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeoutMS","healthyTimeout_","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","sendRequest","dataMsg","sendData_","tryCleanupConnection","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","onControl_","onDataMessage_","onPrimaryResponse_","handshakePayload","h","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","timestamp","onConnectionEstablished_","tryStartUpgrade_","startUpgrade_","closeConnections_","ServerActions","pathString","onComplete","hash","merge","refreshAuthToken","refreshAppCheckToken","onDisconnectPut","onDisconnectMerge","onDisconnectCancel","reportStats","stats","EventEmitter","allowedEvents_","listeners_","trigger","on","validateEventType_","eventData","getInitialEvent","off","splice","et","OnlineMonitor","online_","getInstance","currentlyOnline","Path","pathOrString","pieceNum","pieces_","copyTo","pieceNum_","newEmptyPath","pathGetFront","pathGetLength","pathPopFront","pathGetBack","pathSlice","begin","pathParent","pieces","pathChild","childPathObj","childPieces","pathIsEmpty","newRelativePath","outerPath","innerPath","outer","inner","pathEquals","other","pathContains","ValidationPath","errorPrefix_","parts_","byteLength_","validationPathCheckValid","validationPath","validationPathToErrorString","VisibilityMonitor","hidden","visibilityChange","visible_","visible","RECONNECT_MIN_DELAY","PersistentConnection","onDataUpdate_","onConnectStatus_","onServerInfoUpdate_","authTokenProvider_","appCheckTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens","outstandingPuts_","outstandingGets_","outstandingPutCount_","outstandingGetCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","establishConnectionTimer_","requestCBHash_","requestNumber_","realtime_","forceTokenRefresh_","invalidAuthTokenCount_","invalidAppCheckTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","onVisible_","onOnline_","onResponse","curReqNum","initConnection_","outstandingGet","_path","q","_queryObject","sendGet_","listen","currentHashFn","tag","queryId","_queryIdentifier","_queryParams","isDefault","loadsAllData","listenSpec","hashFn","sendListen_","req","warnOnListenWarnings_","removeListen_","warnings","indexSpec","getIndex","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","isAdmin","tryAppCheck","authMethod","isValidFormat","requestData","onAuthRevoked_","onAppCheckRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","putInternal","sendPut_","queued","errorReason","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","handleTimestamp_","sendConnectStats_","restoreState_","scheduleConnect_","establishConnection_","online","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage","onReady","nextConnectionId_","canceled","connection","closeFn","sendRequestFn","interrupt","resume","delta","serverTimeOffset","normalizedPathString","statusCode","explanation","queries","clientName","NamedNode","node","Wrap","Index","getCompare","compare","indexedValueChanged","oldNode","newNode","oldWrapped","newWrapped","minPost","MIN","__EMPTY_NODE","KeyIndex","isDefinedOn","maxPost","makePost","indexValue","KEY_INDEX","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","cmp","isEmpty","right","getNext","hasNext","peek","LLRBNode","color","RED","SortedMap","EMPTY_NODE","copy","count","inorderTraversal","reverseTraversal","min_","minKey","maxKey","insert","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","nr","checkMaxDepth_","blackDepth","check_","BLACK","comparator_","root_","getPredecessorKey","rightParent","getIterator","resultGenerator","getIteratorFrom","getReverseIteratorFrom","getReverseIterator","NAME_ONLY_COMPARATOR","NAME_COMPARATOR","MAX_NODE$2","priorityHashText","priority","validatePriorityNode","priorityNode","isLeafNode","getPriority","__childrenNodeConstructor","nodeFromJSON$1","MAX_NODE$1","LeafNode","value_","priorityNode_","lazyHash_","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","hasChild","getPredecessorChildName","childNode","updateImmediateChild","newChildNode","updateChild","front","numChildren","forEachChild","exportFormat","getValue","toHash","compareTo","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","withIndex","isIndexed","equals","PRIORITY_INDEX","aPriority","bPriority","indexCmp","LOG_2","Base12Num","num","current_","mask","bits_","nextBitIsOne","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","low","namedNode","middle","root","base12","buildPennant","chunkSize","childTree","attachPennant","pennant","isOne","buildFrom12Array","_defaultIndexMap","fallbackObject","IndexMap","indexes_","indexSet_","Default","indexKey","sortedMap","hasIndex","indexDefinition","addIndex","existingChildren","sawIndexedValue","iter","newIndex","indexName","newIndexSet","newIndexes","addToIndexes","indexedChildren","existingSnap","newChildren","removeFromIndexes","ChildrenNode","children_","indexMap_","child","newIndexMap","newPriority","newImmediateChild","numKeys","allIntegerKeys","array","childHash","idx","resolveIndex_","predecessor","getFirstChildName","getFirstChild","getLastChildName","getLastChild","wrappedNode","startPost","iterator","endPost","MAX_NODE","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","defineProperties","MAX","USE_HINZE","nodeFromJSON","childData","children","childrenHavePriority","childSet","sortedChildSet","PathIndex","indexPath_","extractChild","snap","aChild","bChild","valueNode","VALUE_INDEX","changeChildChanged","snapshotNode","oldSnap","QueryParams","limitSet_","startSet_","startNameSet_","startAfterSet_","endSet_","endNameSet_","endBeforeSet_","limit_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","index_","hasStart","isViewFromLeft","getIndexStartValue","getIndexStartName","hasEnd","getIndexEndValue","getIndexEndName","hasLimit","hasAnchoredLimit","getLimit","queryParamsToRestQueryStringParameters","queryParams","qs","orderBy","startParam","endParam","queryParamsGetQueryObject","viewFrom","ReadonlyRestClient","listens_","getListenId_","listenId","thisListen","queryStringParameters","restRequest_","xhr","XMLHttpRequest","responseText","SnapshotHolder","rootNode_","getNode","updateSnapshot","newSnapshotNode","newSparseSnapshotTree","sparseSnapshotTreeRemember","sparseSnapshotTree","childKey","sparseSnapshotTreeForEachTree","prefixPath","tree","sparseSnapshotTreeForEachChild","StatsListener","collection_","last_","newStats","stat","StatsReporter","collection","server_","statsToReport_","statsListener_","reportStats_","reportedStats","haveStatsToReport","OperationType","newOperationSourceServerTaggedQuery","fromUser","fromServer","tagged","AckUserWrite","affectedTree","revert","ACK_USER_WRITE","operationForChild","subtree","Overwrite","OVERWRITE","Merge","MERGE","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","eventGeneratorGenerateEventsForType","eventGenerator","events","changes","registrations","eventCache","filteredChanges","change","aWrapped","bWrapped","eventGeneratorCompareChanges","materializedChange","prevName","eventGeneratorMaterializeSingleChange","registration","respondsTo","query_","newViewCache","serverCache","viewCacheUpdateEventSnap","viewCache","eventSnap","filtered","viewCacheUpdateServerSnap","serverSnap","viewCacheGetCompleteEventSnap","viewCacheGetCompleteServerSnap","emptyChildrenSingleton","ImmutableTree","EmptyChildren","fromObject","childPath","childSnap","findRootMostMatchingPathAndValue","relativePath","predicate","childExistingPathAndValue","findRootMostValueAndPath","toSet","newChild","setTree","newTree","fold","fold_","pathSoFar","findOnPath","findOnPath_","pathToFollow","nextChild","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","CompoundWrite","writeTree_","empty","compoundWriteAddWrite","compoundWrite","rootmost","rootMostPath","newWriteTree","compoundWriteAddWrites","newWrite","compoundWriteRemoveWrite","compoundWriteHasCompleteWrite","compoundWriteGetCompleteNode","compoundWriteGetCompleteChildren","compoundWriteChildCompoundWrite","shadowingNode","compoundWriteIsEmpty","compoundWriteApply","applySubtreeWrite","writeTree","priorityWrite","writeTreeChildWrites","newWriteTreeRef","writeTreeRecordContainsPath_","writeRecord","writeTreeDefaultFilter_","writeTreeLayerTree_","writes","treeRoot","writePath","deepNode","writeTreeCalcCompleteEventCache","treePath","completeServerCache","writeIdsToExclude","includeHiddenWrites","visibleWrites","writeId","allWrites","subMerge","writeTreeRefCalcCompleteEventCache","writeTreeRef","writeTreeRefCalcCompleteEventChildren","completeServerChildren","completeChildren","topLevelSet","writeTreeCalcCompleteEventChildren","writeTreeRefCalcEventCacheAfterServerOverwrite","existingEventSnap","existingServerSnap","childMerge","writeTreeCalcEventCacheAfterServerOverwrite","writeTreeRefShadowingWrite","writeTreeShadowingWrite","writeTreeRefCalcCompleteChild","existingServerCache","writeTreeCalcCompleteChild","writeTreeRefChild","ChildChangeAccumulator","changeMap","trackChildChange","oldChange","oldType","changeChildAdded","getChanges","NO_COMPLETE_CHILD_SOURCE","getCompleteChild","getChildAfterChild","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","completeServerData","nodes","toIterate","writeTreeCalcIndexedSlice","writeTreeRefCalcIndexedSlice","viewProcessorGenerateEventCacheAfterServerEvent","viewProcessor","changePath","writesCache","accumulator","oldEventSnap","newEventCache","completeEventChildren","updateFullNode","completeNode","oldEventNode","updatedPriority","childChangePath","newEventChild","eventChildUpdate","filtersNodes","viewProcessorApplyServerOverwrite","oldViewCache","changedSnap","completeCache","filterServerNode","oldServerSnap","newServerCache","serverFilter","getIndexedFilter","newServerNode","viewProcessorApplyUserOverwrite","oldChild","viewProcessorCacheHasChild","viewProcessorApplyMerge","viewProcessorApplyServerMerge","changedChildren","viewMergeTree","curViewCache","childMergeTree","isUnknownDeepMerge","viewGetCompleteServerCache","view","cache","viewApplyOperation","viewProcessorApplyUserMerge","ackUserWrite","oldEventCache","serverChildren","viewProcessorRevertUserWrite","ackPath","mergePath","serverCachePath","viewProcessorAckUserWrite","LISTEN_COMPLETE","oldServerNode","viewProcessorListenComplete","isLeafOrEmpty","oldCompleteSnap","viewProcessorMaybeAddValueEvent","viewProcessorApplyOperation","processor_","eventRegistration","eventRegistrations_","eventRegistrations","moves","eventGeneratorGenerateEventsForChanges","eventGenerator_","viewGenerateEventsForChanges_","referenceConstructor$1","referenceConstructor","syncPointApplyOperation","syncPoint","optCompleteServerCache","views","concat","syncPointGetCompleteServerCache","SyncTree","listenProvider_","syncPointTree_","pendingWriteTree_","lastWriteId","tagToQueryMap","queryToTagMap","syncTreeApplyUserOverwrite","syncTree","writeTreeAddOverwrite","syncTreeApplyOperationToSyncPoints_","syncTreeAckUserWrite","record","writeTreeGetWrite","findIndex","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","writeTreeResetTree_","writeTreeRemoveWrite","syncTreeApplyServerOverwrite","syncTreeCalcCompleteEventCache","syncTreeApplyOperationHelper_","syncPointTree","syncTreeApplyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","syncTreeQueryKeyForTag_","syncTreeParseQueryKey_","queryKey","splitIndex","syncTreeApplyTaggedOperation_","queryPath","ExistingValueProvider","DeferredValueProvider","syncTree_","path_","generateWithValues","resolveDeferredLeafValue","existingVal","serverValues","resolveScalarDeferredValue","resolveComplexDeferredValue","existing","unused","existingNode","resolveDeferredValueTree","resolveDeferredValue","resolveDeferredValueSnapshot","rawPri","leafNode","childrenNode","Tree","parent","childCount","treeSubTree","pathObj","treeGetValue","treeSetValue","treeUpdateParents","treeHasChildren","treeForEachChild","treeForEachDescendant","includeSelf","childrenFirst","treeGetPath","childEmpty","treeIsEmpty","childExists","treeUpdateChild","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","validateFirebaseData","errorPrefix","hasDotValue","hasActualChild","last","validationPathPop","validateUrl","fnName","parsedUrl","isValidPathString","isValidRootPathString","argName","EventQueue","eventLists_","recursionDepth_","eventQueueRaiseEventsForChangedPath","eventQueue","changedPath","eventDataList","currList","getPath","eventQueueQueueEvents","sentAll","eventList","eventListRaise","eventQueueRaiseQueuedEventsMatchingPredicate","eventPath","eventFn","getEventRunner","MAX_TRANSACTION_RETRIES","Repo","forceRestClient_","appCheckProvider_","dataUpdateCount","eventQueue_","nextWriteId_","interceptServerDataCallback_","transactionQueueTree_","persistentConnection_","repoStart","repo","authOverride","search","isMerge","repoOnDataUpdate","repoOnConnectStatus","connectStatus","repoUpdateInfo","repoOnServerInfoUpdate","statsReporter_","creatorFunction","statsManagerGetOrCreateReporter","infoData_","infoSyncTree_","startListening","infoEvents","stopListening","serverSyncTree_","repoServerTime","repoGenerateServerValues","taggedChildren","raw","changeTree","syncTreeApplyTaggedQueryMerge","taggedSnap","syncTreeApplyTaggedQueryOverwrite","syncTreeApplyServerMerge","affectedPath","repoRerunTransactions","repoLog","resolvedOnDisconnectTree","resolved","repoGetAncestorTransactionNode","transactionNode","treeForEachAncestor","repoAbortTransactionsOnNode","repoAbortTransactions","repoRunOnDisconnectEvents","repoGetNextWriteId","repoGetLatestState","excludeSets","repoSendReadyTransactions","repoPruneCompletedTransactionsBelowNode","repoBuildTransactionQueue","every","setsToIgnore","txn","currentWriteId","latestState","snapToSend","latestHash","retryCount","currentOutputSnapshotRaw","dataToSend","pathToSend","currentOutputSnapshotResolved","unwatcher","abortReason","repoSendTransactionQueue","rootMostTransactionNode","abortTransaction","currentNode","currentInputSnapshot","newDataNode","oldWriteId","newNodeResolved","applyLocally","repoRerunTransactionQueue","transactionQueue","repoAggregateTransactionQueuesForNode","order","nodeQueue","to","lastSent","parseRepoInfo","dataURL","parseDatabaseURL","scheme","subdomain","colonInd","slashInd","questionMarkInd","pathStringDecoded","piece","decodePath","queryString","segment","kv","decodeQuery","hostWithoutPort","dotInd","QueryImpl","_repo","_orderByCalled","ref","ReferenceImpl","isEqual","sameRepo","samePath","sameQueryIdentifier","pathToUrlEncodedString","parentPath","syncTreeSetReferenceConstructor","repos","Database","_repoInternal","_instanceStarted","_root","_rootInternal","appRepos","repoInterrupt","repoManagerDeleteRepo","_checkNotDeleted","apiName","simpleListen","echo","onEcho","authProvider","dbUrl","databaseURL","projectId","isEmulator","dbEmulatorHost","authTokenProvider","repoManagerCreateRepo","repoManagerDatabaseFromApp","registerDatabase","_app","getElementById","loadFirebaseConfig","initializeAuth","authTokenSyncPath","isSecureContext","authTokenSyncUrl","mintCookie","idTokenResult","idTokenAge","authEmulatorHost","disableWarnings","authority","exec","hostAndPort","bracketedIPv6","extractHostAndPort","freeze","attachBanner","sty","innerText","backgroundColor","border","bottom","margin","zIndex","textAlign","classList","emitEmulatorWarning","connectAuthEmulator","getAuth","_signInWithEmailAndPassword","signInWithCredential","_onAuthStateChanged","_signOut","_sendPasswordResetEmail","actionCodeSettings","requestType","dynamicLinkDomain","canHandleCodeInApp","handleCodeInApp","iOS","bundleId","iOSBundleId","android","packageName","androidInstallApp","installApp","androidMinimumVersionCode","minimumVersion","androidPackageName","_setActionCodeSettingsOnRequest","_confirmPasswordReset","newPassword","_verifyPasswordResetCode","authModular","newEmail","mfaInfo","multiFactorInfo","previousEmail","checkActionCode","_db","separatorIndex","lastIndexOf","getDefaultEmulatorHostnameAndPort","tokenProvider","mockUserToken","project","user_id","iss","aud","sign_in_provider","identities","alg","createMockUserToken","repoManagerApplyEmulatorSettings","connectDatabaseEmulator","getDatabase"],"sourceRoot":""} \ No newline at end of file diff --git a/includes/firebase/package-lock.json b/includes/firebase/package-lock.json index a9dab4cc..a096ce94 100644 --- a/includes/firebase/package-lock.json +++ b/includes/firebase/package-lock.json @@ -7,18 +7,18 @@ "name": "@pewresearch/prc-platform-firebase", "license": "GPL-2.0-or-later", "dependencies": { - "firebase": "^10.12.3" + "firebase": "^10.12.4" }, "devDependencies": { - "@wordpress/dependency-extraction-webpack-plugin": "^6.2.0", - "@wordpress/readable-js-assets-webpack-plugin": "^3.2.0", - "@wordpress/scripts": "^28.2.0", + "@wordpress/dependency-extraction-webpack-plugin": "^6.3.0", + "@wordpress/readable-js-assets-webpack-plugin": "^3.3.0", + "@wordpress/scripts": "^28.3.0", "copy-webpack-plugin": "^12.0.2", "cssnano": "^7.0.4", "es-module-shims": "^1.10.0", "postcss": "^8.4.39", "terser-webpack-plugin": "^5.3.10", - "webpack": "^5.92.1", + "webpack": "^5.93.0", "webpack-bundle-analyzer": "^4.10.2" } }, @@ -88,9 +88,9 @@ } }, "node_modules/@babel/eslint-parser": { - "version": "7.24.7", - "resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.24.7.tgz", - "integrity": "sha512-SO5E3bVxDuxyNxM5agFv480YA2HO6ohZbGxbazZdIk3KQOPOGVNw6q78I9/lbviIf95eq6tPozeYnJLbjnC8IA==", + "version": "7.24.8", + "resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.24.8.tgz", + "integrity": "sha512-nYAikI4XTGokU2QX7Jx+v4rxZKhKivaQaREZjuW3mrJrbdWJ5yUfohnoUULge+zEEaKjPYNxhoRgUKktjXtbwA==", "dev": true, "dependencies": { "@nicolo-ribaudo/eslint-scope-5-internals": "5.1.1-v1", @@ -2191,14 +2191,15 @@ } }, "node_modules/@firebase/analytics": { - "version": "0.10.5", - "resolved": "https://registry.npmjs.org/@firebase/analytics/-/analytics-0.10.5.tgz", - "integrity": "sha512-d0X2ksTOKHMf5zFAMKFZWXa8hSbgohsG507xFsGhF4Uet2b8uEUL/YLrEth67jXEbGEi1UQZX4AaGBxKNiDzjw==", + "version": "0.10.6", + "resolved": "https://registry.npmjs.org/@firebase/analytics/-/analytics-0.10.6.tgz", + "integrity": "sha512-sB59EwcAvLt0fINGfMWmcRKcdUiYhE4AJNdDXSCSDo4D/ZXFRmb6qwX9YesKHXFB59XTLT03mAjqQcDrdym9qA==", "dependencies": { "@firebase/component": "0.6.8", "@firebase/installations": "0.6.8", "@firebase/logger": "0.4.2", "@firebase/util": "1.9.7", + "safevalues": "0.6.0", "tslib": "^2.1.0" }, "peerDependencies": { @@ -2206,11 +2207,11 @@ } }, "node_modules/@firebase/analytics-compat": { - "version": "0.2.11", - "resolved": "https://registry.npmjs.org/@firebase/analytics-compat/-/analytics-compat-0.2.11.tgz", - "integrity": "sha512-wmXxJ49pEY7H549Pa4CDPOTzkPJnfG2Yolptg72ntTgSrbKVq+Eg9cAQY6Z5Kn9ATSQRX5oGXKlNfEk5DJBvvA==", + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@firebase/analytics-compat/-/analytics-compat-0.2.12.tgz", + "integrity": "sha512-rXWnOAdEHbvBPLNjFLu3U0yDZVIAi+C0DL+RkUEOirfSqAeQaKzBCATeBw6+K7FVpEnknhm4tZrvVUVtJjShMw==", "dependencies": { - "@firebase/analytics": "0.10.5", + "@firebase/analytics": "0.10.6", "@firebase/analytics-types": "0.8.2", "@firebase/component": "0.6.8", "@firebase/util": "1.9.7", @@ -2226,9 +2227,9 @@ "integrity": "sha512-EnzNNLh+9/sJsimsA/FGqzakmrAUKLeJvjRHlg8df1f97NLUlFidk9600y0ZgWOp3CAxn6Hjtk+08tixlUOWyw==" }, "node_modules/@firebase/app": { - "version": "0.10.6", - "resolved": "https://registry.npmjs.org/@firebase/app/-/app-0.10.6.tgz", - "integrity": "sha512-/r8Ikp7TOrIIdp7v2adD2kg9SqIXMGOoJXJB1HsX7LjpjWdsoy1fMkP0HlI7GQqqRxDueHNhETx5Zn5E8HyVAQ==", + "version": "0.10.7", + "resolved": "https://registry.npmjs.org/@firebase/app/-/app-0.10.7.tgz", + "integrity": "sha512-7OCd53B+wnk/onbMLn/vM10pDjw97zzWUD8m3swtLYKJIrL+gDZ7HZ4xcbBLw7OB8ikzu8k1ORNjRe2itgAy4g==", "dependencies": { "@firebase/component": "0.6.8", "@firebase/logger": "0.4.2", @@ -2238,13 +2239,14 @@ } }, "node_modules/@firebase/app-check": { - "version": "0.8.5", - "resolved": "https://registry.npmjs.org/@firebase/app-check/-/app-check-0.8.5.tgz", - "integrity": "sha512-WyIckkVYAfnzsPIw6EAt/qBUANkUAVl6irF0xuJ1R9ISNyUT1h7dPAwvs/g3rsx0fpBWaHRAH0IFiN6zO6yLqQ==", + "version": "0.8.6", + "resolved": "https://registry.npmjs.org/@firebase/app-check/-/app-check-0.8.6.tgz", + "integrity": "sha512-uSzl0/SDw54hwuORWHDtldb9kK/QEVZOcoPn2mlIjMrJOLDug/6kcqnIN3IHzwmPyf23Epg0AGBktvG2FugW4w==", "dependencies": { "@firebase/component": "0.6.8", "@firebase/logger": "0.4.2", "@firebase/util": "1.9.7", + "safevalues": "0.6.0", "tslib": "^2.1.0" }, "peerDependencies": { @@ -2252,11 +2254,11 @@ } }, "node_modules/@firebase/app-check-compat": { - "version": "0.3.12", - "resolved": "https://registry.npmjs.org/@firebase/app-check-compat/-/app-check-compat-0.3.12.tgz", - "integrity": "sha512-p/5w3pMih3JVT6u7g04KXgSZr6HDsQXyeWZkIe0+r71dPOlcKyUooe9/feTc8BWpjha3rUOkqQ7+JXZObwvYoQ==", + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@firebase/app-check-compat/-/app-check-compat-0.3.13.tgz", + "integrity": "sha512-1sbS5Apq7dLys1KYdNQsmZLFIjJoFP9Mv4bzIcdXuTkWQjr3X2qAvwiTslC6prVAUMiTV0eM9eicdQIXVsiSRw==", "dependencies": { - "@firebase/app-check": "0.8.5", + "@firebase/app-check": "0.8.6", "@firebase/app-check-types": "0.5.2", "@firebase/component": "0.6.8", "@firebase/logger": "0.4.2", @@ -2278,11 +2280,11 @@ "integrity": "sha512-FSOEzTzL5bLUbD2co3Zut46iyPWML6xc4x+78TeaXMSuJap5QObfb+rVvZJtla3asN4RwU7elaQaduP+HFizDA==" }, "node_modules/@firebase/app-compat": { - "version": "0.2.36", - "resolved": "https://registry.npmjs.org/@firebase/app-compat/-/app-compat-0.2.36.tgz", - "integrity": "sha512-qsf+pllpgy1IGe2f5vfenOHSX8Cs58sVR5L6h/zBlNy9Yo54B2jy61KxLpSOgyRZb18IlnLLGjo7VtGU1CHvHA==", + "version": "0.2.37", + "resolved": "https://registry.npmjs.org/@firebase/app-compat/-/app-compat-0.2.37.tgz", + "integrity": "sha512-yiQLYT9LYQHuJGu/msuBLFtdWWTJ3Pz04E9gSeWykSB+8s0XXJJqfqQlghH7CcQ3KnJZR+Wuc3zSMcY3a+dn6Q==", "dependencies": { - "@firebase/app": "0.10.6", + "@firebase/app": "0.10.7", "@firebase/component": "0.6.8", "@firebase/logger": "0.4.2", "@firebase/util": "1.9.7", @@ -3025,9 +3027,9 @@ } }, "node_modules/@jest/reporters/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -3256,13 +3258,13 @@ } }, "node_modules/@playwright/test": { - "version": "1.45.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.45.1.tgz", - "integrity": "sha512-Wo1bWTzQvGA7LyKGIZc8nFSTFf2TkthGIFBR+QVNilvwouGzFd4PYukZe3rvf5PSqjHi1+1NyKSDZKcQWETzaA==", + "version": "1.45.2", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.45.2.tgz", + "integrity": "sha512-JxG9eq92ET75EbVi3s+4sYbcG7q72ECeZNbdBlaMkGcNbiDQ4cAi8U2QP5oKkOx+1gpaiL1LDStmzCaEM1Z6fQ==", "dev": true, "peer": true, "dependencies": { - "playwright": "1.45.1" + "playwright": "1.45.2" }, "bin": { "playwright": "cli.js" @@ -4384,9 +4386,9 @@ } }, "node_modules/@typescript-eslint/eslint-plugin/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -4509,9 +4511,9 @@ } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -4546,9 +4548,9 @@ } }, "node_modules/@typescript-eslint/utils/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -4783,9 +4785,9 @@ } }, "node_modules/@wordpress/babel-preset-default": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/babel-preset-default/-/babel-preset-default-8.2.0.tgz", - "integrity": "sha512-bOvP+8b0zk7wjIbpaAnJSc0kkKZA6oeyJ4/GRtp+mmcrIXJWL+LNCGYQM+aUDSGO7j1QazLpTR7p5br8ygl5/g==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/babel-preset-default/-/babel-preset-default-8.3.0.tgz", + "integrity": "sha512-lLPZuKdJF6CLS/YUv7c2OkGhplEpKZBQ4YiCQUdbhg8joFZH12QICUxtT2kvoUxLQ22zwLtNMPYTzISClE8zSw==", "dev": true, "dependencies": { "@babel/core": "^7.16.0", @@ -4794,8 +4796,8 @@ "@babel/preset-env": "^7.16.0", "@babel/preset-typescript": "^7.16.0", "@babel/runtime": "^7.16.0", - "@wordpress/browserslist-config": "^6.2.0", - "@wordpress/warning": "^3.2.0", + "@wordpress/browserslist-config": "^6.3.0", + "@wordpress/warning": "^3.3.0", "browserslist": "^4.21.10", "core-js": "^3.31.0", "react": "^18.3.0" @@ -4806,9 +4808,9 @@ } }, "node_modules/@wordpress/base-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/base-styles/-/base-styles-5.2.0.tgz", - "integrity": "sha512-yBMVbn4gvNQimVfLAZ+/F7F/Tpl+femF9ojgv90c0A0o6IDEtdC+6vUvtAxvXVoruwmxsq8ncouoorZbYDb3yg==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/base-styles/-/base-styles-5.3.0.tgz", + "integrity": "sha512-2Azr6XLCejtEzxhTv71x1VS30D5k0xL91CGRL1PTlnBRe/3Ki09hvz45kr52BI6YWnKtDUvCBw1USiGB9UJhgw==", "dev": true, "engines": { "node": ">=18.12.0", @@ -4816,9 +4818,9 @@ } }, "node_modules/@wordpress/browserslist-config": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/browserslist-config/-/browserslist-config-6.2.0.tgz", - "integrity": "sha512-+/qiAQmWd+d7/yvVRxXevLKurlHjknO4EcFRlBfKM3moS6GNVSkCb3n6HwFXGawaQH7aaO3pPRdzmG5SIIxrEA==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/browserslist-config/-/browserslist-config-6.3.0.tgz", + "integrity": "sha512-DDz/Iiax7RQR7cuTdv1ZlAfPgCDijiszg9xE9c2lO/2Hvv7voP/sLKQhdr/mSUzNW9ZXK7/NVIYAXxFd3Eee2A==", "dev": true, "engines": { "node": ">=18.12.0", @@ -4826,9 +4828,9 @@ } }, "node_modules/@wordpress/dependency-extraction-webpack-plugin": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/dependency-extraction-webpack-plugin/-/dependency-extraction-webpack-plugin-6.2.0.tgz", - "integrity": "sha512-zHVfv9hPuWxBoGi7ZMmNPaDX0cn3RMQyu0t2pp/WaNIPLDUjHf4H/gLDeA0G8CiiQCDuiOvtPctqIC8UvmF7vw==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/dependency-extraction-webpack-plugin/-/dependency-extraction-webpack-plugin-6.3.0.tgz", + "integrity": "sha512-m7ELFLFVVR8BSEwRaxeKzvldLttIKjbdgRC9lLmCOrbcrpruKr9x6SF1FPCravb3DUfdVVg/RhuGqTMLXSv4Vw==", "dev": true, "dependencies": { "json2php": "^0.0.7" @@ -4842,9 +4844,9 @@ } }, "node_modules/@wordpress/e2e-test-utils-playwright": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/e2e-test-utils-playwright/-/e2e-test-utils-playwright-1.2.0.tgz", - "integrity": "sha512-AxoEVI1KvSSAjBu9gq7AYgS0fhtGqkzdItHn0ivowQSctQHqcXJF0mIFReuvYwUKR6q9jtbyzUVkszYG4dOdJQ==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/e2e-test-utils-playwright/-/e2e-test-utils-playwright-1.3.0.tgz", + "integrity": "sha512-QiOLaqxstekAgfC/s0m9yl9ZNw5UXatqGOAY6i6PqJjuwfk1Xkvb5arGyJ6B0dd8puhNweuCv102l3WduWaFYw==", "dev": true, "dependencies": { "change-case": "^4.1.2", @@ -4852,7 +4854,7 @@ "get-port": "^5.1.1", "lighthouse": "^10.4.0", "mime": "^3.0.0", - "web-vitals": "^3.5.0" + "web-vitals": "^4.2.1" }, "engines": { "node": ">=18.12.0", @@ -4863,16 +4865,16 @@ } }, "node_modules/@wordpress/eslint-plugin": { - "version": "19.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/eslint-plugin/-/eslint-plugin-19.2.0.tgz", - "integrity": "sha512-2mRC7WRV9qwdcMsm+VSTjcYQbLcBag5UTUXrClsQPqDZ9aeoL8QloStFCKOqXuYRYN4tYytIgnM/blvEz7OlAw==", + "version": "20.0.0", + "resolved": "https://registry.npmjs.org/@wordpress/eslint-plugin/-/eslint-plugin-20.0.0.tgz", + "integrity": "sha512-rOzkWHX6xjTt7Gmhe/nwlcgQJe4O6bCXkCJKcL+iyBhYABVjCnzneDiVh4bM1cNmL8zUx6/f1ADjmb3Xz9vG0g==", "dev": true, "dependencies": { "@babel/eslint-parser": "^7.16.0", "@typescript-eslint/eslint-plugin": "^6.4.1", "@typescript-eslint/parser": "^6.4.1", - "@wordpress/babel-preset-default": "^8.2.0", - "@wordpress/prettier-config": "^4.2.0", + "@wordpress/babel-preset-default": "^8.3.0", + "@wordpress/prettier-config": "^4.3.0", "cosmiconfig": "^7.0.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-import": "^2.25.2", @@ -4949,9 +4951,9 @@ } }, "node_modules/@wordpress/jest-console": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/jest-console/-/jest-console-8.2.0.tgz", - "integrity": "sha512-FPTF0b4E+AhpvaWMzSPZhaboqiHXvAkY/F9Oah5yIXt3ktRBP+AStDRKv8cbzSDtDqtFOSbdXMzZ4upjCR+TJg==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/jest-console/-/jest-console-8.3.0.tgz", + "integrity": "sha512-aPVdS1V5YLlqhc00458qmc1TujhDbi6WDoT9m63aOuRGcmb223DNuKEkI77p0RV3F7QB39dBqa466mOUbKaX2w==", "dev": true, "dependencies": { "@babel/runtime": "^7.16.0", @@ -4966,12 +4968,12 @@ } }, "node_modules/@wordpress/jest-preset-default": { - "version": "12.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/jest-preset-default/-/jest-preset-default-12.2.0.tgz", - "integrity": "sha512-iRuqnSP4VlOYiVCry96srqS7tyM5eaCO67s3fi/LA/YIu0mSp1Sq4f5JnxtVhZuS8Sk2GOWCuw3DMPs/mDGUlA==", + "version": "12.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/jest-preset-default/-/jest-preset-default-12.3.0.tgz", + "integrity": "sha512-xYXndYJFr9QDsO3fTl5JUXJs80Xq/fxLiOa4zlrrXmWy3L/7+uPik9Jgy0KZOu4FqiYp5wJFX6Arp9dzqH3Xug==", "dev": true, "dependencies": { - "@wordpress/jest-console": "^8.2.0", + "@wordpress/jest-console": "^8.3.0", "babel-jest": "^29.6.2" }, "engines": { @@ -4984,9 +4986,9 @@ } }, "node_modules/@wordpress/npm-package-json-lint-config": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/npm-package-json-lint-config/-/npm-package-json-lint-config-5.2.0.tgz", - "integrity": "sha512-J2Mo2VteIEKQ7C5FHI3qdwemOPwHshUBu8k6d/2yg8iA1soaq3e1GYtjCz28ILMjwbzn4ntwd5Nz/rCnSIqm3Q==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/npm-package-json-lint-config/-/npm-package-json-lint-config-5.3.0.tgz", + "integrity": "sha512-a/y7Y5qutUtmVX89/VuZcO33deIFj96dZWFT43kdzuYPns1O2jIV1jt3dts8VNcykZG6KyQATQGa6M7Sbj1UAQ==", "dev": true, "engines": { "node": ">=18.12.0", @@ -4997,12 +4999,12 @@ } }, "node_modules/@wordpress/postcss-plugins-preset": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/postcss-plugins-preset/-/postcss-plugins-preset-5.2.0.tgz", - "integrity": "sha512-02TJmmVvsn8YFYXwgShX0VaPFLFUIlgtjD/6dguqNDaE/HhPpGwdgOOKS4KdbTFGMY0L14iA8rS3zbZO2fTFlg==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/postcss-plugins-preset/-/postcss-plugins-preset-5.3.0.tgz", + "integrity": "sha512-LzTcAlnjNJKncu9e1BwlnUrW04+WIl+KH1bqJK+FF5WTsVrCAvhvhoYS1WX06oHrpofBPyGovw5hwB2ZqSHv+Q==", "dev": true, "dependencies": { - "@wordpress/base-styles": "^5.2.0", + "@wordpress/base-styles": "^5.3.0", "autoprefixer": "^10.2.5" }, "engines": { @@ -5014,9 +5016,9 @@ } }, "node_modules/@wordpress/prettier-config": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/prettier-config/-/prettier-config-4.2.0.tgz", - "integrity": "sha512-OvIUKpaphNdS26mQ9C9/bGzRZJnoyEzbJdtCmWr45fHAcfmkYbyNdyBERGjcne0F9BbMWP3yIqfB7eHZjQ1hnw==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/prettier-config/-/prettier-config-4.3.0.tgz", + "integrity": "sha512-2OWp2g/e0y2iKh1LZvc+f0pxesI5NYBQSgnJkaXHt6ktc7QaBX3nwYcZQ030TBMxl2hnNclLAPUR85UMSRx0dw==", "dev": true, "engines": { "node": ">=18.12.0", @@ -5027,9 +5029,9 @@ } }, "node_modules/@wordpress/readable-js-assets-webpack-plugin": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/readable-js-assets-webpack-plugin/-/readable-js-assets-webpack-plugin-3.2.0.tgz", - "integrity": "sha512-j2Gp4eWOYoLiNUxQSXiXJErXLvTRbjeM56wzbJTflG4TgMFvwUodrcxjVWunAA6400fim7R0NDZdKW4tdppvnw==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/readable-js-assets-webpack-plugin/-/readable-js-assets-webpack-plugin-3.3.0.tgz", + "integrity": "sha512-5J0bFzO0bwgiEuwNHI6juqODzF8xtWNIeRQ8ciWUXvlSEY7gYlyBVESQ1ibhmVJEnTt0Mr0tUoeL7dNMPTBWNw==", "dev": true, "engines": { "node": ">=18.12.0", @@ -5040,24 +5042,24 @@ } }, "node_modules/@wordpress/scripts": { - "version": "28.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/scripts/-/scripts-28.2.0.tgz", - "integrity": "sha512-4C9zsVCu4M1Rc/aiPBkT3z25CwOwiWdegvleEPY6nR/mrduFpoNt+BRBq56AuY53lcQkv1N/d4iSHjv+Njodfw==", + "version": "28.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/scripts/-/scripts-28.3.0.tgz", + "integrity": "sha512-NoxWYammghicxaU+7glao64KxS6SRdU2fa01dKqhy1UEkNH2TH6spgK4TA14Dpsbudaf5N362dO2n7UZBe/Euw==", "dev": true, "dependencies": { "@babel/core": "^7.16.0", "@pmmmwh/react-refresh-webpack-plugin": "^0.5.11", "@svgr/webpack": "^8.0.1", - "@wordpress/babel-preset-default": "^8.2.0", - "@wordpress/browserslist-config": "^6.2.0", - "@wordpress/dependency-extraction-webpack-plugin": "^6.2.0", - "@wordpress/e2e-test-utils-playwright": "^1.2.0", - "@wordpress/eslint-plugin": "^19.2.0", - "@wordpress/jest-preset-default": "^12.2.0", - "@wordpress/npm-package-json-lint-config": "^5.2.0", - "@wordpress/postcss-plugins-preset": "^5.2.0", - "@wordpress/prettier-config": "^4.2.0", - "@wordpress/stylelint-config": "^22.2.0", + "@wordpress/babel-preset-default": "^8.3.0", + "@wordpress/browserslist-config": "^6.3.0", + "@wordpress/dependency-extraction-webpack-plugin": "^6.3.0", + "@wordpress/e2e-test-utils-playwright": "^1.3.0", + "@wordpress/eslint-plugin": "^20.0.0", + "@wordpress/jest-preset-default": "^12.3.0", + "@wordpress/npm-package-json-lint-config": "^5.3.0", + "@wordpress/postcss-plugins-preset": "^5.3.0", + "@wordpress/prettier-config": "^4.3.0", + "@wordpress/stylelint-config": "^22.3.0", "adm-zip": "^0.5.9", "babel-jest": "^29.6.2", "babel-loader": "^8.2.3", @@ -5685,9 +5687,9 @@ } }, "node_modules/@wordpress/stylelint-config": { - "version": "22.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/stylelint-config/-/stylelint-config-22.2.0.tgz", - "integrity": "sha512-Afc1ce0zpUkMlDG3lvJr59q6LC+sb1igIawyF8Vl8eRLBeQP7bNN8d6NVFmirUzYCD98UZqt2DRCLi72/K1Oig==", + "version": "22.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/stylelint-config/-/stylelint-config-22.3.0.tgz", + "integrity": "sha512-bVx0sf+SFJKBmOMCPdnGyjNKBBMhqfbDIysqjx7V34mglGdO2+8LJdoyrG6WzJgjjtEceORswEdirX7GBb9pUA==", "dev": true, "dependencies": { "stylelint-config-recommended": "^6.0.0", @@ -5702,9 +5704,9 @@ } }, "node_modules/@wordpress/warning": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/@wordpress/warning/-/warning-3.2.0.tgz", - "integrity": "sha512-i+EYX506tE45+lhOW4qAwXm/5/PmkAdvKhNt+dTxJDif+ATUqp4QaFFRl9yFIt/v+ksAapQ0bnPkKNSDsECGtA==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/@wordpress/warning/-/warning-3.3.0.tgz", + "integrity": "sha512-n82aKCxuGRNwAtSLaycErJuhKgfOc+KtiljyQITPperMh9i8bH6I+JxtYiu+aLMaY5vrVLVb+/kCzKuWVQIKPA==", "dev": true, "engines": { "node": ">=18.12.0", @@ -6144,18 +6146,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/array.prototype.toreversed": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/array.prototype.toreversed/-/array.prototype.toreversed-1.1.2.tgz", - "integrity": "sha512-wwDCoT4Ck4Cz7sLtgUmzR5UV3YF5mFHUlbChCzZBQZ+0m2cl/DH3tKgvphv1nKgFsJ48oCSg6p91q2Vm0I/ZMA==", - "dev": true, - "dependencies": { - "call-bind": "^1.0.2", - "define-properties": "^1.2.0", - "es-abstract": "^1.22.1", - "es-shim-unscopables": "^1.0.0" - } - }, "node_modules/array.prototype.tosorted": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz", @@ -9068,9 +9058,9 @@ } }, "node_modules/eslint-plugin-jest/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -9103,9 +9093,9 @@ } }, "node_modules/eslint-plugin-jsdoc/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -9182,13 +9172,13 @@ } }, "node_modules/eslint-plugin-prettier": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.1.3.tgz", - "integrity": "sha512-C9GCVAs4Eq7ZC/XFQHITLiHJxQngdtraXaM+LoUFoFp/lHNl2Zn8f3WQbe9HvTBBQ9YnKFB0/2Ajdqwo5D1EAw==", + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-5.2.1.tgz", + "integrity": "sha512-gH3iR3g4JfF+yYPaJYkN7jEl9QbweL/YfkoRlNnuIEHEz1vHVlCmWOS+eGGiRuzHQXdJFCOTxRgvju9b8VUmrw==", "dev": true, "dependencies": { "prettier-linter-helpers": "^1.0.0", - "synckit": "^0.8.6" + "synckit": "^0.9.1" }, "engines": { "node": "^14.18.0 || >=16.0.0" @@ -9212,35 +9202,35 @@ } }, "node_modules/eslint-plugin-react": { - "version": "7.34.3", - "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.34.3.tgz", - "integrity": "sha512-aoW4MV891jkUulwDApQbPYTVZmeuSyFrudpbTAQuj5Fv8VL+o6df2xIGpw8B0hPjAaih1/Fb0om9grCdyFYemA==", + "version": "7.35.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.35.0.tgz", + "integrity": "sha512-v501SSMOWv8gerHkk+IIQBkcGRGrO2nfybfj5pLxuJNFTPxxA3PSryhXTK+9pNbtkggheDdsC0E9Q8CuPk6JKA==", "dev": true, "dependencies": { "array-includes": "^3.1.8", "array.prototype.findlast": "^1.2.5", "array.prototype.flatmap": "^1.3.2", - "array.prototype.toreversed": "^1.1.2", "array.prototype.tosorted": "^1.1.4", "doctrine": "^2.1.0", "es-iterator-helpers": "^1.0.19", "estraverse": "^5.3.0", + "hasown": "^2.0.2", "jsx-ast-utils": "^2.4.1 || ^3.0.0", "minimatch": "^3.1.2", "object.entries": "^1.1.8", "object.fromentries": "^2.0.8", - "object.hasown": "^1.1.4", "object.values": "^1.2.0", "prop-types": "^15.8.1", "resolve": "^2.0.0-next.5", "semver": "^6.3.1", - "string.prototype.matchall": "^4.0.11" + "string.prototype.matchall": "^4.0.11", + "string.prototype.repeat": "^1.0.0" }, "engines": { "node": ">=4" }, "peerDependencies": { - "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8" + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" } }, "node_modules/eslint-plugin-react-hooks": { @@ -9571,9 +9561,9 @@ } }, "node_modules/esquery": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.5.0.tgz", - "integrity": "sha512-YQLXUplAwJgCydQ78IMJywZCceoqk1oH01OERdSAJc/7U2AylwjhSCLDEtqwg811idIS/9fIU5GjG73IgjKMVg==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", "dev": true, "dependencies": { "estraverse": "^5.1.0" @@ -9911,6 +9901,12 @@ "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", "dev": true }, + "node_modules/fast-uri": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.0.1.tgz", + "integrity": "sha512-MWipKbbYiYI0UC7cl8m/i/IWTqfC8YXsqjzybjddLsFjStroQzsHXkc73JutMvBiXmOvapk+axIl79ig5t55Bw==", + "dev": true + }, "node_modules/fastest-levenshtein": { "version": "1.0.16", "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", @@ -10117,16 +10113,16 @@ } }, "node_modules/firebase": { - "version": "10.12.3", - "resolved": "https://registry.npmjs.org/firebase/-/firebase-10.12.3.tgz", - "integrity": "sha512-dO2cQ8eP6RnM2wcGzbxnoljjjMBf1suUrHYFftjSpbPn/8bEx959cwTRDHqBx3MwSzNsg6zZV/wiWydJPhUKgw==", - "dependencies": { - "@firebase/analytics": "0.10.5", - "@firebase/analytics-compat": "0.2.11", - "@firebase/app": "0.10.6", - "@firebase/app-check": "0.8.5", - "@firebase/app-check-compat": "0.3.12", - "@firebase/app-compat": "0.2.36", + "version": "10.12.4", + "resolved": "https://registry.npmjs.org/firebase/-/firebase-10.12.4.tgz", + "integrity": "sha512-SQz49NMpwG4MLTPZ9C8jBp7IyS2haTvsIvjclgu+v/jvzNtjZoxIcoF6A13EIfBHmJ5eiuVlvttxElOf7LnJew==", + "dependencies": { + "@firebase/analytics": "0.10.6", + "@firebase/analytics-compat": "0.2.12", + "@firebase/app": "0.10.7", + "@firebase/app-check": "0.8.6", + "@firebase/app-check-compat": "0.3.13", + "@firebase/app-compat": "0.2.37", "@firebase/app-types": "0.9.2", "@firebase/auth": "1.7.5", "@firebase/auth-compat": "0.5.10", @@ -11973,9 +11969,9 @@ } }, "node_modules/istanbul-lib-report/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -12539,9 +12535,9 @@ } }, "node_modules/jest-snapshot/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -14015,9 +14011,9 @@ } }, "node_modules/normalize-package-data/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -14098,9 +14094,9 @@ "dev": true }, "node_modules/npm-package-json-lint/node_modules/semver": { - "version": "7.6.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", - "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", + "version": "7.6.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz", + "integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==", "dev": true, "bin": { "semver": "bin/semver.js" @@ -14285,23 +14281,6 @@ "node": ">= 0.4" } }, - "node_modules/object.hasown": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/object.hasown/-/object.hasown-1.1.4.tgz", - "integrity": "sha512-FZ9LZt9/RHzGySlBARE3VF+gE26TxR38SdmqOqliuTnl9wrKulaQs+4dee1V+Io8VfxqzAfHu6YuRgUy8OHoTg==", - "dev": true, - "dependencies": { - "define-properties": "^1.2.1", - "es-abstract": "^1.23.2", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/object.values": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.0.tgz", @@ -14791,13 +14770,13 @@ } }, "node_modules/playwright": { - "version": "1.45.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.45.1.tgz", - "integrity": "sha512-Hjrgae4kpSQBr98nhCj3IScxVeVUixqj+5oyif8TdIn2opTCPEzqAqNMeK42i3cWDCVu9MI+ZsGWw+gVR4ISBg==", + "version": "1.45.2", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.45.2.tgz", + "integrity": "sha512-ReywF2t/0teRvNBpfIgh5e4wnrI/8Su8ssdo5XsQKpjxJj+jspm00jSoz9BTg91TT0c9HRjXO7LBNVrgYj9X0g==", "dev": true, "peer": true, "dependencies": { - "playwright-core": "1.45.1" + "playwright-core": "1.45.2" }, "bin": { "playwright": "cli.js" @@ -14810,9 +14789,9 @@ } }, "node_modules/playwright-core": { - "version": "1.45.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.45.1.tgz", - "integrity": "sha512-LF4CUUtrUu2TCpDw4mcrAIuYrEjVDfT1cHbJMfwnE2+1b8PZcFzPNgvZCvq2JfQ4aTjRCCHw5EJ2tmr2NSzdPg==", + "version": "1.45.2", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.45.2.tgz", + "integrity": "sha512-ha175tAWb0dTK0X4orvBIqi3jGEt701SMxMhyujxNrgd8K0Uy5wMSwwcQHtyB4om7INUkfndx02XnQ2p6dvLDw==", "dev": true, "peer": true, "bin": { @@ -16567,6 +16546,11 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true }, + "node_modules/safevalues": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/safevalues/-/safevalues-0.6.0.tgz", + "integrity": "sha512-MZ7DcTOcIoPXN36/UONVE9BT0pmwlCr9WcS7Pj/q4FxOwr33FkWC0CUWj/THQXYWxf/F7urbhaHaOeFPSqGqHA==" + }, "node_modules/sass": { "version": "1.77.6", "resolved": "https://registry.npmjs.org/sass/-/sass-1.77.6.tgz", @@ -17453,6 +17437,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/string.prototype.repeat": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz", + "integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==", + "dev": true, + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, "node_modules/string.prototype.trim": { "version": "1.2.9", "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz", @@ -17848,9 +17842,9 @@ "dev": true }, "node_modules/synckit": { - "version": "0.8.8", - "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.8.8.tgz", - "integrity": "sha512-HwOKAP7Wc5aRGYdKH+dw0PRRpbO841v2DENBtjnR5HFWoiNByAl7vrx3p0G/rCyYXQsrxqtX48TImFtPcIHSpQ==", + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.9.1.tgz", + "integrity": "sha512-7gr8p9TQP6RAHusBOSLs46F4564ZrjV8xFmw5zCmgmhGUcw2hxsShhJ6CEiHQMgPDwAQ1fWHPM0ypc4RMAig4A==", "dev": true, "dependencies": { "@pkgr/core": "^0.1.0", @@ -17880,15 +17874,15 @@ } }, "node_modules/table/node_modules/ajv": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.16.0.tgz", - "integrity": "sha512-F0twR8U1ZU67JIEtekUcLkXkoO5mMMmgGD8sK/xUFzJ805jxHQl92hImFAqqXMyMYjSPOyUPAwHYhB72g5sTXw==", + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", "dev": true, "dependencies": { "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", - "uri-js": "^4.4.1" + "require-from-string": "^2.0.2" }, "funding": { "type": "github", @@ -18099,9 +18093,9 @@ } }, "node_modules/text-decoder": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.1.0.tgz", - "integrity": "sha512-TmLJNj6UgX8xcUZo4UDStGQtDiTzF7BzWlzn9g7UWrjkpHr5uJTK1ld16wZ3LXb2vb6jH8qU89dW5whuMdXYdw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.1.1.tgz", + "integrity": "sha512-8zll7REEv4GDD3x4/0pW+ppIxSNs7H1J10IKFZsuOMscumCdM2a+toDGLPA3T+1+fLBql4zbt5z83GEQGGV5VA==", "dev": true, "dependencies": { "b4a": "^1.6.4" @@ -18841,9 +18835,9 @@ } }, "node_modules/web-vitals": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-3.5.2.tgz", - "integrity": "sha512-c0rhqNcHXRkY/ogGDJQxZ9Im9D19hDihbzSQJrsioex+KnFgmMzBiy57Z1EjkhX/+OjyBpclDCzz2ITtjokFmg==", + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-4.2.2.tgz", + "integrity": "sha512-nYfoOqb4EmElljyXU2qdeE76KsvoHdftQKY4DzA9Aw8DervCg2bG634pHLrJ/d6+B4mE3nWTSJv8Mo7B2mbZkw==", "dev": true }, "node_modules/webidl-conversions": { @@ -18856,9 +18850,9 @@ } }, "node_modules/webpack": { - "version": "5.92.1", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.92.1.tgz", - "integrity": "sha512-JECQ7IwJb+7fgUFBlrJzbyu3GEuNBcdqr1LD7IbSzwkSmIevTm8PF+wej3Oxuz/JFBUZ6O1o43zsPkwm1C4TmA==", + "version": "5.93.0", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.93.0.tgz", + "integrity": "sha512-Y0m5oEY1LRuwly578VqluorkXbvXKh7U3rLoQCEO04M97ScRr44afGVkI0FQFsXzysk5OgFAxjZAb9rsGQVihA==", "dev": true, "dependencies": { "@types/eslint-scope": "^3.7.3", diff --git a/includes/firebase/package.json b/includes/firebase/package.json index 716e4ed0..834eba0b 100644 --- a/includes/firebase/package.json +++ b/includes/firebase/package.json @@ -3,19 +3,19 @@ "description": "Google Firebase functionality for PRC Platform", "license": "GPL-2.0-or-later", "devDependencies": { - "@wordpress/scripts": "^28.2.0", - "@wordpress/dependency-extraction-webpack-plugin": "^6.2.0", - "@wordpress/readable-js-assets-webpack-plugin": "^3.2.0", + "@wordpress/scripts": "^28.3.0", + "@wordpress/dependency-extraction-webpack-plugin": "^6.3.0", + "@wordpress/readable-js-assets-webpack-plugin": "^3.3.0", "copy-webpack-plugin": "^12.0.2", "cssnano": "^7.0.4", "es-module-shims": "^1.10.0", "postcss": "^8.4.39", "terser-webpack-plugin": "^5.3.10", - "webpack": "^5.92.1", + "webpack": "^5.93.0", "webpack-bundle-analyzer": "^4.10.2" }, "dependencies": { - "firebase": "^10.12.3" + "firebase": "^10.12.4" }, "module": "build/index.js", "scripts": { diff --git a/includes/firebase/src/index.js b/includes/firebase/src/index.js index a9a3f00a..f6ac43e5 100644 --- a/includes/firebase/src/index.js +++ b/includes/firebase/src/index.js @@ -6,6 +6,9 @@ import { signInWithEmailAndPassword, onAuthStateChanged, signOut, + sendPasswordResetEmail, + confirmPasswordReset, + verifyPasswordResetCode, } from 'firebase/auth'; import { getDatabase } from 'firebase/database'; @@ -25,6 +28,9 @@ const _auth = getAuth(); const _signInWithEmailAndPassword = signInWithEmailAndPassword; const _onAuthStateChanged = onAuthStateChanged; const _signOut = signOut; +const _sendPasswordResetEmail = sendPasswordResetEmail; +const _confirmPasswordReset = confirmPasswordReset; +const _verifyPasswordResetCode = verifyPasswordResetCode; const _db = getDatabase(); export { @@ -33,5 +39,8 @@ export { _signInWithEmailAndPassword as signInWithEmailAndPassword, _onAuthStateChanged as onAuthStateChanged, _signOut as signOut, + _sendPasswordResetEmail as sendPasswordResetEmail, + _confirmPasswordReset as confirmPasswordReset, + _verifyPasswordResetCode as verifyPasswordResetCode, _db as getDatabase, }; diff --git a/includes/firebase/webpack.config.js b/includes/firebase/webpack.config.js index 83a855f3..c4bffd66 100644 --- a/includes/firebase/webpack.config.js +++ b/includes/firebase/webpack.config.js @@ -9,8 +9,6 @@ const CopyWebpackPlugin = require('copy-webpack-plugin'); */ const DependencyExtractionWebpackPlugin = require('@wordpress/dependency-extraction-webpack-plugin'); - - const webpack = require('webpack'); /** @@ -77,7 +75,6 @@ module.exports = { react: 'preact/compat', 'react-dom': 'preact/compat', }), - // TODO: Move it to a different Webpack file. new CopyWebpackPlugin({ patterns: [ { diff --git a/includes/media/class-media.php b/includes/media/class-media.php index 2f8e101b..492589c4 100644 --- a/includes/media/class-media.php +++ b/includes/media/class-media.php @@ -71,6 +71,17 @@ public function init($loader = null) { } } + /** + * Modifies the default image link to use the raw ?attachment_id url. + * @hook attachment_link + * @param string $link + * @param int $post_id + * @return string + */ + public function default_image_link(string $link, int $post_id) { + return \wp_get_attachment_url( $post_id ); + } + /** * @hook wp_get_attachment_image_src */ diff --git a/includes/newrelic/class-newrelic.php b/includes/newrelic/class-newrelic.php index 9fa50038..4e07e7c4 100644 --- a/includes/newrelic/class-newrelic.php +++ b/includes/newrelic/class-newrelic.php @@ -16,7 +16,14 @@ public function log_error() { // WIP: move the central error logging utility into here but keep a simple php utility exposed. } + /** + * This is the Newrelic browser performance monitoring script. We output directly into the head so that Newrelic can monitor the page load. + * @TODO container environment variablify the id's and keys so that they can be set in the container environment. + */ public function script() { + if ( 'production' !== wp_get_environment_type() ) { + return; + } ob_start(); ?>