(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[888],{4444:function(e,i,s){"use strict";s.d(i,{BH:function(){return Deferred},G6:function(){return isSafari},L:function(){return base64urlEncodeWithoutPadding},LL:function(){return ErrorFactory},L_:function(){return isCloudflareWorker},P0:function(){return getDefaultEmulatorHostnameAndPort},Pz:function(){return getExperimentalSetting},Sg:function(){return createMockUserToken},ZR:function(){return FirebaseError},aH:function(){return getDefaultAppConfig},b$:function(){return isReactNative},eu:function(){return validateIndexedDBOpenable},hl:function(){return isIndexedDBAvailable},m9:function(){return getModularInstance},ne:function(){return createSubscribe},pd:function(){return extractQuerystring},q4:function(){return getDefaultEmulatorHost},ru:function(){return isBrowserExtension},tV:function(){return base64Decode},uI:function(){return isMobileCordova},vZ:function(){return function deepEqual(e,i){if(e===i)return!0;let s=Object.keys(e),o=Object.keys(i);for(let l of s){if(!o.includes(l))return!1;let s=e[l],h=i[l];if(isObject(s)&&isObject(h)){if(!deepEqual(s,h))return!1}else if(s!==h)return!1}for(let e of o)if(!s.includes(e))return!1;return!0}},w1:function(){return isIE},xO:function(){return querystring},xb:function(){return isEmpty},z$:function(){return getUA},zd:function(){return querystringDecode}});var o=s(3454);/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let stringToByteArray$1=function(e){let i=[],s=0;for(let o=0;o<e.length;o++){let l=e.charCodeAt(o);l<128?i[s++]=l:(l<2048?i[s++]=l>>6|192:((64512&l)==55296&&o+1<e.length&&(64512&e.charCodeAt(o+1))==56320?(l=65536+((1023&l)<<10)+(1023&e.charCodeAt(++o)),i[s++]=l>>18|240,i[s++]=l>>12&63|128):i[s++]=l>>12|224,i[s++]=l>>6&63|128),i[s++]=63&l|128)}return i},byteArrayToString=function(e){let i=[],s=0,o=0;for(;s<e.length;){let l=e[s++];if(l<128)i[o++]=String.fromCharCode(l);else if(l>191&&l<224){let h=e[s++];i[o++]=String.fromCharCode((31&l)<<6|63&h)}else if(l>239&&l<365){let h=e[s++],d=e[s++],f=e[s++],_=((7&l)<<18|(63&h)<<12|(63&d)<<6|63&f)-65536;i[o++]=String.fromCharCode(55296+(_>>10)),i[o++]=String.fromCharCode(56320+(1023&_))}else{let h=e[s++],d=e[s++];i[o++]=String.fromCharCode((15&l)<<12|(63&h)<<6|63&d)}}return i.join("")},l={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,i){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();let s=i?this.byteToCharMapWebSafe_:this.byteToCharMap_,o=[];for(let i=0;i<e.length;i+=3){let l=e[i],h=i+1<e.length,d=h?e[i+1]:0,f=i+2<e.length,_=f?e[i+2]:0,g=l>>2,b=(3&l)<<4|d>>4,w=(15&d)<<2|_>>6,k=63&_;f||(k=64,h||(w=64)),o.push(s[g],s[b],s[w],s[k])}return o.join("")},encodeString(e,i){return this.HAS_NATIVE_SUPPORT&&!i?btoa(e):this.encodeByteArray(stringToByteArray$1(e),i)},decodeString(e,i){return this.HAS_NATIVE_SUPPORT&&!i?atob(e):byteArrayToString(this.decodeStringToByteArray(e,i))},decodeStringToByteArray(e,i){this.init_();let s=i?this.charToByteMapWebSafe_:this.charToByteMap_,o=[];for(let i=0;i<e.length;){let l=s[e.charAt(i++)],h=i<e.length,d=h?s[e.charAt(i)]:0;++i;let f=i<e.length,_=f?s[e.charAt(i)]:64;++i;let g=i<e.length,b=g?s[e.charAt(i)]:64;if(++i,null==l||null==d||null==_||null==b)throw new DecodeBase64StringError;let w=l<<2|d>>4;if(o.push(w),64!==_){let e=d<<4&240|_>>2;if(o.push(e),64!==b){let e=_<<6&192|b;o.push(e)}}}return o},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};let DecodeBase64StringError=class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}};let base64Encode=function(e){let i=stringToByteArray$1(e);return l.encodeByteArray(i,!0)},base64urlEncodeWithoutPadding=function(e){return base64Encode(e).replace(/\./g,"")},base64Decode=function(e){try{return l.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null},getDefaultsFromGlobal=()=>/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==s.g)return s.g;throw Error("Unable to locate global object.")})().__FIREBASE_DEFAULTS__,getDefaultsFromEnvVariable=()=>{if(void 0===o||void 0===o.env)return;let e=o.env.__FIREBASE_DEFAULTS__;if(e)return JSON.parse(e)},getDefaultsFromCookie=()=>{let e;if("undefined"==typeof document)return;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}let i=e&&base64Decode(e[1]);return i&&JSON.parse(i)},getDefaults=()=>{try{return getDefaultsFromGlobal()||getDefaultsFromEnvVariable()||getDefaultsFromCookie()}catch(e){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);return}},getDefaultEmulatorHost=e=>{var i,s;return null===(s=null===(i=getDefaults())||void 0===i?void 0:i.emulatorHosts)||void 0===s?void 0:s[e]},getDefaultEmulatorHostnameAndPort=e=>{let i=getDefaultEmulatorHost(e);if(!i)return;let s=i.lastIndexOf(":");if(s<=0||s+1===i.length)throw Error(`Invalid host ${i} with no separate hostname and port!`);let o=parseInt(i.substring(s+1),10);return"["===i[0]?[i.substring(1,s-1),o]:[i.substring(0,s),o]},getDefaultAppConfig=()=>{var e;return null===(e=getDefaults())||void 0===e?void 0:e.config},getExperimentalSetting=e=>{var i;return null===(i=getDefaults())||void 0===i?void 0:i[`_${e}`]};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Deferred=class Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,i)=>{this.resolve=e,this.reject=i})}wrapCallback(e){return(i,s)=>{i?this.reject(i):this.resolve(s),"function"==typeof e&&(this.promise.catch(()=>{}),1===e.length?e(i):e(i,s))}}};/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function createMockUserToken(e,i){if(e.uid)throw Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');let s=i||"demo-project",o=e.iat||0,l=e.sub||e.user_id;if(!l)throw Error("mockUserToken must contain 'sub' or 'user_id' field!");let h=Object.assign({iss:`https://securetoken.google.com/${s}`,aud:s,iat:o,exp:o+3600,auth_time:o,sub:l,user_id:l,firebase:{sign_in_provider:"custom",identities:{}}},e);return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(h)),""].join(".")}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function getUA(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function isMobileCordova(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())}function isCloudflareWorker(){return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent}function isBrowserExtension(){let e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function isReactNative(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function isIE(){let e=getUA();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}function isSafari(){return!function(){var e;let i=null===(e=getDefaults())||void 0===e?void 0:e.forceEnvironment;if("node"===i)return!0;if("browser"===i)return!1;try{return"[object process]"===Object.prototype.toString.call(s.g.process)}catch(e){return!1}}()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}function validateIndexedDBOpenable(){return new Promise((e,i)=>{try{let s=!0,o="validate-browser-context-for-indexeddb-analytics-module",l=self.indexedDB.open(o);l.onsuccess=()=>{l.result.close(),s||self.indexedDB.deleteDatabase(o),e(!0)},l.onupgradeneeded=()=>{s=!1},l.onerror=()=>{var e;i((null===(e=l.error)||void 0===e?void 0:e.message)||"")}}catch(e){i(e)}})}let FirebaseError=class FirebaseError extends Error{constructor(e,i,s){super(i),this.code=e,this.customData=s,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}};let ErrorFactory=class ErrorFactory{constructor(e,i,s){this.service=e,this.serviceName=i,this.errors=s}create(e,...i){let s=i[0]||{},o=`${this.service}/${e}`,l=this.errors[e],d=l?l.replace(h,(e,i)=>{let o=s[i];return null!=o?String(o):`<${i}?>`}):"Error",f=`${this.serviceName}: ${d} (${o}).`,_=new FirebaseError(o,f,s);return _}};let h=/\{\$([^}]+)}/g;function isEmpty(e){for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function querystring(e){let i=[];for(let[s,o]of Object.entries(e))Array.isArray(o)?o.forEach(e=>{i.push(encodeURIComponent(s)+"="+encodeURIComponent(e))}):i.push(encodeURIComponent(s)+"="+encodeURIComponent(o));return i.length?"&"+i.join("&"):""}function querystringDecode(e){let i={},s=e.replace(/^\?/,"").split("&");return s.forEach(e=>{if(e){let[s,o]=e.split("=");i[decodeURIComponent(s)]=decodeURIComponent(o)}}),i}function extractQuerystring(e){let i=e.indexOf("?");if(!i)return"";let s=e.indexOf("#",i);return e.substring(i,s>0?s:void 0)}function createSubscribe(e,i){let s=new ObserverProxy(e,i);return s.subscribe.bind(s)}let ObserverProxy=class ObserverProxy{constructor(e,i){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=i,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(e){this.forEachObserver(i=>{i.next(e)})}error(e){this.forEachObserver(i=>{i.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,i,s){let o;if(void 0===e&&void 0===i&&void 0===s)throw Error("Missing Observer.");void 0===(o=!function(e,i){if("object"!=typeof e||null===e)return!1;for(let s of i)if(s in e&&"function"==typeof e[s])return!0;return!1}(e,["next","error","complete"])?{next:e,error:i,complete:s}:e).next&&(o.next=noop),void 0===o.error&&(o.error=noop),void 0===o.complete&&(o.complete=noop);let l=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?o.error(this.finalError):o.complete()}catch(e){}}),this.observers.push(o),l}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 i=0;i<this.observers.length;i++)this.sendOne(i,e)}sendOne(e,i){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{i(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 noop(){}/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function getModularInstance(e){return e&&e._delegate?e._delegate:e}},9742:function(e,i){"use strict";i.byteLength=function(e){var i=getLens(e),s=i[0],o=i[1];return(s+o)*3/4-o},i.toByteArray=function(e){var i,s,h=getLens(e),d=h[0],f=h[1],_=new l((d+f)*3/4-f),g=0,b=f>0?d-4:d;for(s=0;s<b;s+=4)i=o[e.charCodeAt(s)]<<18|o[e.charCodeAt(s+1)]<<12|o[e.charCodeAt(s+2)]<<6|o[e.charCodeAt(s+3)],_[g++]=i>>16&255,_[g++]=i>>8&255,_[g++]=255&i;return 2===f&&(i=o[e.charCodeAt(s)]<<2|o[e.charCodeAt(s+1)]>>4,_[g++]=255&i),1===f&&(i=o[e.charCodeAt(s)]<<10|o[e.charCodeAt(s+1)]<<4|o[e.charCodeAt(s+2)]>>2,_[g++]=i>>8&255,_[g++]=255&i),_},i.fromByteArray=function(e){for(var i,o=e.length,l=o%3,h=[],d=0,f=o-l;d<f;d+=16383)h.push(function(e,i,o){for(var l,h=[],d=i;d<o;d+=3)h.push(s[(l=(e[d]<<16&16711680)+(e[d+1]<<8&65280)+(255&e[d+2]))>>18&63]+s[l>>12&63]+s[l>>6&63]+s[63&l]);return h.join("")}(e,d,d+16383>f?f:d+16383));return 1===l?h.push(s[(i=e[o-1])>>2]+s[i<<4&63]+"=="):2===l&&h.push(s[(i=(e[o-2]<<8)+e[o-1])>>10]+s[i>>4&63]+s[i<<2&63]+"="),h.join("")};for(var s=[],o=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",d=0,f=h.length;d<f;++d)s[d]=h[d],o[h.charCodeAt(d)]=d;function getLens(e){var i=e.length;if(i%4>0)throw Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");-1===s&&(s=i);var o=s===i?0:4-s%4;return[s,o]}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},8764:function(e,i,s){"use strict";/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */var o=s(9742),l=s(645),h="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function createBuffer(e){if(e>2147483647)throw RangeError('The value "'+e+'" is invalid for option "size"');var i=new Uint8Array(e);return Object.setPrototypeOf(i,Buffer.prototype),i}function Buffer(e,i,s){if("number"==typeof e){if("string"==typeof i)throw TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(e)}return from(e,i,s)}function from(e,i,s){if("string"==typeof e)return function(e,i){if(("string"!=typeof i||""===i)&&(i="utf8"),!Buffer.isEncoding(i))throw TypeError("Unknown encoding: "+i);var s=0|byteLength(e,i),o=createBuffer(s),l=o.write(e,i);return l!==s&&(o=o.slice(0,l)),o}(e,i);if(ArrayBuffer.isView(e))return function(e){if(isInstance(e,Uint8Array)){var i=new Uint8Array(e);return fromArrayBuffer(i.buffer,i.byteOffset,i.byteLength)}return fromArrayLike(e)}(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(isInstance(e,ArrayBuffer)||e&&isInstance(e.buffer,ArrayBuffer)||"undefined"!=typeof SharedArrayBuffer&&(isInstance(e,SharedArrayBuffer)||e&&isInstance(e.buffer,SharedArrayBuffer)))return fromArrayBuffer(e,i,s);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');var o=e.valueOf&&e.valueOf();if(null!=o&&o!==e)return Buffer.from(o,i,s);var l=function(e){if(Buffer.isBuffer(e)){var i,s=0|checked(e.length),o=createBuffer(s);return 0===o.length||e.copy(o,0,0,s),o}return void 0!==e.length?"number"!=typeof e.length||(i=e.length)!=i?createBuffer(0):fromArrayLike(e):"Buffer"===e.type&&Array.isArray(e.data)?fromArrayLike(e.data):void 0}(e);if(l)return l;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return Buffer.from(e[Symbol.toPrimitive]("string"),i,s);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function assertSize(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function allocUnsafe(e){return assertSize(e),createBuffer(e<0?0:0|checked(e))}function fromArrayLike(e){for(var i=e.length<0?0:0|checked(e.length),s=createBuffer(i),o=0;o<i;o+=1)s[o]=255&e[o];return s}function fromArrayBuffer(e,i,s){var o;if(i<0||e.byteLength<i)throw RangeError('"offset" is outside of buffer bounds');if(e.byteLength<i+(s||0))throw RangeError('"length" is outside of buffer bounds');return Object.setPrototypeOf(o=void 0===i&&void 0===s?new Uint8Array(e):void 0===s?new Uint8Array(e,i):new Uint8Array(e,i,s),Buffer.prototype),o}function checked(e){if(e>=2147483647)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function byteLength(e,i){if(Buffer.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||isInstance(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var s=e.length,o=arguments.length>2&&!0===arguments[2];if(!o&&0===s)return 0;for(var l=!1;;)switch(i){case"ascii":case"latin1":case"binary":return s;case"utf8":case"utf-8":return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*s;case"hex":return s>>>1;case"base64":return base64ToBytes(e).length;default:if(l)return o?-1:utf8ToBytes(e).length;i=(""+i).toLowerCase(),l=!0}}function slowToString(e,i,s){var l,h,d=!1;if((void 0===i||i<0)&&(i=0),i>this.length||((void 0===s||s>this.length)&&(s=this.length),s<=0||(s>>>=0)<=(i>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,i,s){var o=e.length;(!i||i<0)&&(i=0),(!s||s<0||s>o)&&(s=o);for(var l="",h=i;h<s;++h)l+=f[e[h]];return l}(this,i,s);case"utf8":case"utf-8":return utf8Slice(this,i,s);case"ascii":return function(e,i,s){var o="";s=Math.min(e.length,s);for(var l=i;l<s;++l)o+=String.fromCharCode(127&e[l]);return o}(this,i,s);case"latin1":case"binary":return function(e,i,s){var o="";s=Math.min(e.length,s);for(var l=i;l<s;++l)o+=String.fromCharCode(e[l]);return o}(this,i,s);case"base64":return l=i,h=s,0===l&&h===this.length?o.fromByteArray(this):o.fromByteArray(this.slice(l,h));case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(e,i,s){for(var o=e.slice(i,s),l="",h=0;h<o.length-1;h+=2)l+=String.fromCharCode(o[h]+256*o[h+1]);return l}(this,i,s);default:if(d)throw TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),d=!0}}function swap(e,i,s){var o=e[i];e[i]=e[s],e[s]=o}function bidirectionalIndexOf(e,i,s,o,l){var h;if(0===e.length)return -1;if("string"==typeof s?(o=s,s=0):s>2147483647?s=2147483647:s<-2147483648&&(s=-2147483648),(h=s=+s)!=h&&(s=l?0:e.length-1),s<0&&(s=e.length+s),s>=e.length){if(l)return -1;s=e.length-1}else if(s<0){if(!l)return -1;s=0}if("string"==typeof i&&(i=Buffer.from(i,o)),Buffer.isBuffer(i))return 0===i.length?-1:arrayIndexOf(e,i,s,o,l);if("number"==typeof i)return(i&=255,"function"==typeof Uint8Array.prototype.indexOf)?l?Uint8Array.prototype.indexOf.call(e,i,s):Uint8Array.prototype.lastIndexOf.call(e,i,s):arrayIndexOf(e,[i],s,o,l);throw TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,i,s,o,l){var h,d=1,f=e.length,_=i.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||i.length<2)return -1;d=2,f/=2,_/=2,s/=2}function read(e,i){return 1===d?e[i]:e.readUInt16BE(i*d)}if(l){var g=-1;for(h=s;h<f;h++)if(read(e,h)===read(i,-1===g?0:h-g)){if(-1===g&&(g=h),h-g+1===_)return g*d}else -1!==g&&(h-=h-g),g=-1}else for(s+_>f&&(s=f-_),h=s;h>=0;h--){for(var b=!0,w=0;w<_;w++)if(read(e,h+w)!==read(i,w)){b=!1;break}if(b)return h}return -1}function utf8Slice(e,i,s){s=Math.min(e.length,s);for(var o=[],l=i;l<s;){var h,d,f,_,g=e[l],b=null,w=g>239?4:g>223?3:g>191?2:1;if(l+w<=s)switch(w){case 1:g<128&&(b=g);break;case 2:(192&(h=e[l+1]))==128&&(_=(31&g)<<6|63&h)>127&&(b=_);break;case 3:h=e[l+1],d=e[l+2],(192&h)==128&&(192&d)==128&&(_=(15&g)<<12|(63&h)<<6|63&d)>2047&&(_<55296||_>57343)&&(b=_);break;case 4:h=e[l+1],d=e[l+2],f=e[l+3],(192&h)==128&&(192&d)==128&&(192&f)==128&&(_=(15&g)<<18|(63&h)<<12|(63&d)<<6|63&f)>65535&&_<1114112&&(b=_)}null===b?(b=65533,w=1):b>65535&&(b-=65536,o.push(b>>>10&1023|55296),b=56320|1023&b),o.push(b),l+=w}return function(e){var i=e.length;if(i<=4096)return String.fromCharCode.apply(String,e);for(var s="",o=0;o<i;)s+=String.fromCharCode.apply(String,e.slice(o,o+=4096));return s}(o)}function checkOffset(e,i,s){if(e%1!=0||e<0)throw RangeError("offset is not uint");if(e+i>s)throw RangeError("Trying to access beyond buffer length")}function checkInt(e,i,s,o,l,h){if(!Buffer.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(i>l||i<h)throw RangeError('"value" argument is out of bounds');if(s+o>e.length)throw RangeError("Index out of range")}function checkIEEE754(e,i,s,o,l,h){if(s+o>e.length||s<0)throw RangeError("Index out of range")}function writeFloat(e,i,s,o,h){return i=+i,s>>>=0,h||checkIEEE754(e,i,s,4,34028234663852886e22,-34028234663852886e22),l.write(e,i,s,o,23,4),s+4}function writeDouble(e,i,s,o,h){return i=+i,s>>>=0,h||checkIEEE754(e,i,s,8,17976931348623157e292,-17976931348623157e292),l.write(e,i,s,o,52,8),s+8}i.lW=Buffer,i.h2=50,Buffer.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1),i={foo:function(){return 42}};return Object.setPrototypeOf(i,Uint8Array.prototype),Object.setPrototypeOf(e,i),42===e.foo()}catch(e){return!1}}(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.buffer}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.byteOffset}}),Buffer.poolSize=8192,Buffer.from=function(e,i,s){return from(e,i,s)},Object.setPrototypeOf(Buffer.prototype,Uint8Array.prototype),Object.setPrototypeOf(Buffer,Uint8Array),Buffer.alloc=function(e,i,s){return(assertSize(e),e<=0)?createBuffer(e):void 0!==i?"string"==typeof s?createBuffer(e).fill(i,s):createBuffer(e).fill(i):createBuffer(e)},Buffer.allocUnsafe=function(e){return allocUnsafe(e)},Buffer.allocUnsafeSlow=function(e){return allocUnsafe(e)},Buffer.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==Buffer.prototype},Buffer.compare=function(e,i){if(isInstance(e,Uint8Array)&&(e=Buffer.from(e,e.offset,e.byteLength)),isInstance(i,Uint8Array)&&(i=Buffer.from(i,i.offset,i.byteLength)),!Buffer.isBuffer(e)||!Buffer.isBuffer(i))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===i)return 0;for(var s=e.length,o=i.length,l=0,h=Math.min(s,o);l<h;++l)if(e[l]!==i[l]){s=e[l],o=i[l];break}return s<o?-1:o<s?1:0},Buffer.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Buffer.concat=function(e,i){if(!Array.isArray(e))throw TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return Buffer.alloc(0);if(void 0===i)for(s=0,i=0;s<e.length;++s)i+=e[s].length;var s,o=Buffer.allocUnsafe(i),l=0;for(s=0;s<e.length;++s){var h=e[s];if(isInstance(h,Uint8Array))l+h.length>o.length?Buffer.from(h).copy(o,l):Uint8Array.prototype.set.call(o,h,l);else if(Buffer.isBuffer(h))h.copy(o,l);else throw TypeError('"list" argument must be an Array of Buffers');l+=h.length}return o},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var i=0;i<e;i+=2)swap(this,i,i+1);return this},Buffer.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var i=0;i<e;i+=4)swap(this,i,i+3),swap(this,i+1,i+2);return this},Buffer.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var i=0;i<e;i+=8)swap(this,i,i+7),swap(this,i+1,i+6),swap(this,i+2,i+5),swap(this,i+3,i+4);return this},Buffer.prototype.toString=function(){var e=this.length;return 0===e?"":0==arguments.length?utf8Slice(this,0,e):slowToString.apply(this,arguments)},Buffer.prototype.toLocaleString=Buffer.prototype.toString,Buffer.prototype.equals=function(e){if(!Buffer.isBuffer(e))throw TypeError("Argument must be a Buffer");return this===e||0===Buffer.compare(this,e)},Buffer.prototype.inspect=function(){var e="",s=i.h2;return e=this.toString("hex",0,s).replace(/(.{2})/g,"$1 ").trim(),this.length>s&&(e+=" ... "),"<Buffer "+e+">"},h&&(Buffer.prototype[h]=Buffer.prototype.inspect),Buffer.prototype.compare=function(e,i,s,o,l){if(isInstance(e,Uint8Array)&&(e=Buffer.from(e,e.offset,e.byteLength)),!Buffer.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===i&&(i=0),void 0===s&&(s=e?e.length:0),void 0===o&&(o=0),void 0===l&&(l=this.length),i<0||s>e.length||o<0||l>this.length)throw RangeError("out of range index");if(o>=l&&i>=s)return 0;if(o>=l)return -1;if(i>=s)return 1;if(i>>>=0,s>>>=0,o>>>=0,l>>>=0,this===e)return 0;for(var h=l-o,d=s-i,f=Math.min(h,d),_=this.slice(o,l),g=e.slice(i,s),b=0;b<f;++b)if(_[b]!==g[b]){h=_[b],d=g[b];break}return h<d?-1:d<h?1:0},Buffer.prototype.includes=function(e,i,s){return -1!==this.indexOf(e,i,s)},Buffer.prototype.indexOf=function(e,i,s){return bidirectionalIndexOf(this,e,i,s,!0)},Buffer.prototype.lastIndexOf=function(e,i,s){return bidirectionalIndexOf(this,e,i,s,!1)},Buffer.prototype.write=function(e,i,s,o){if(void 0===i)o="utf8",s=this.length,i=0;else if(void 0===s&&"string"==typeof i)o=i,s=this.length,i=0;else if(isFinite(i))i>>>=0,isFinite(s)?(s>>>=0,void 0===o&&(o="utf8")):(o=s,s=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var l,h,d,f,_,g,b,w,k=this.length-i;if((void 0===s||s>k)&&(s=k),e.length>0&&(s<0||i<0)||i>this.length)throw RangeError("Attempt to write outside buffer bounds");o||(o="utf8");for(var O=!1;;)switch(o){case"hex":return function(e,i,s,o){s=Number(s)||0;var l=e.length-s;o?(o=Number(o))>l&&(o=l):o=l;var h=i.length;o>h/2&&(o=h/2);for(var d=0;d<o;++d){var f=parseInt(i.substr(2*d,2),16);if(f!=f)break;e[s+d]=f}return d}(this,e,i,s);case"utf8":case"utf-8":return l=i,h=s,blitBuffer(utf8ToBytes(e,this.length-l),this,l,h);case"ascii":case"latin1":case"binary":return d=i,f=s,blitBuffer(function(e){for(var i=[],s=0;s<e.length;++s)i.push(255&e.charCodeAt(s));return i}(e),this,d,f);case"base64":return _=i,g=s,blitBuffer(base64ToBytes(e),this,_,g);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return b=i,w=s,blitBuffer(function(e,i){for(var s,o,l=[],h=0;h<e.length&&!((i-=2)<0);++h)o=(s=e.charCodeAt(h))>>8,l.push(s%256),l.push(o);return l}(e,this.length-b),this,b,w);default:if(O)throw TypeError("Unknown encoding: "+o);o=(""+o).toLowerCase(),O=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},Buffer.prototype.slice=function(e,i){var s=this.length;e=~~e,i=void 0===i?s:~~i,e<0?(e+=s)<0&&(e=0):e>s&&(e=s),i<0?(i+=s)<0&&(i=0):i>s&&(i=s),i<e&&(i=e);var o=this.subarray(e,i);return Object.setPrototypeOf(o,Buffer.prototype),o},Buffer.prototype.readUintLE=Buffer.prototype.readUIntLE=function(e,i,s){e>>>=0,i>>>=0,s||checkOffset(e,i,this.length);for(var o=this[e],l=1,h=0;++h<i&&(l*=256);)o+=this[e+h]*l;return o},Buffer.prototype.readUintBE=Buffer.prototype.readUIntBE=function(e,i,s){e>>>=0,i>>>=0,s||checkOffset(e,i,this.length);for(var o=this[e+--i],l=1;i>0&&(l*=256);)o+=this[e+--i]*l;return o},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function(e,i){return e>>>=0,i||checkOffset(e,1,this.length),this[e]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function(e,i){return e>>>=0,i||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function(e,i){return e>>>=0,i||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function(e,i){return e>>>=0,i||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function(e,i){return e>>>=0,i||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer.prototype.readIntLE=function(e,i,s){e>>>=0,i>>>=0,s||checkOffset(e,i,this.length);for(var o=this[e],l=1,h=0;++h<i&&(l*=256);)o+=this[e+h]*l;return o>=(l*=128)&&(o-=Math.pow(2,8*i)),o},Buffer.prototype.readIntBE=function(e,i,s){e>>>=0,i>>>=0,s||checkOffset(e,i,this.length);for(var o=i,l=1,h=this[e+--o];o>0&&(l*=256);)h+=this[e+--o]*l;return h>=(l*=128)&&(h-=Math.pow(2,8*i)),h},Buffer.prototype.readInt8=function(e,i){return(e>>>=0,i||checkOffset(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},Buffer.prototype.readInt16LE=function(e,i){e>>>=0,i||checkOffset(e,2,this.length);var s=this[e]|this[e+1]<<8;return 32768&s?4294901760|s:s},Buffer.prototype.readInt16BE=function(e,i){e>>>=0,i||checkOffset(e,2,this.length);var s=this[e+1]|this[e]<<8;return 32768&s?4294901760|s:s},Buffer.prototype.readInt32LE=function(e,i){return e>>>=0,i||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer.prototype.readInt32BE=function(e,i){return e>>>=0,i||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer.prototype.readFloatLE=function(e,i){return e>>>=0,i||checkOffset(e,4,this.length),l.read(this,e,!0,23,4)},Buffer.prototype.readFloatBE=function(e,i){return e>>>=0,i||checkOffset(e,4,this.length),l.read(this,e,!1,23,4)},Buffer.prototype.readDoubleLE=function(e,i){return e>>>=0,i||checkOffset(e,8,this.length),l.read(this,e,!0,52,8)},Buffer.prototype.readDoubleBE=function(e,i){return e>>>=0,i||checkOffset(e,8,this.length),l.read(this,e,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function(e,i,s,o){if(e=+e,i>>>=0,s>>>=0,!o){var l=Math.pow(2,8*s)-1;checkInt(this,e,i,s,l,0)}var h=1,d=0;for(this[i]=255&e;++d<s&&(h*=256);)this[i+d]=e/h&255;return i+s},Buffer.prototype.writeUintBE=Buffer.prototype.writeUIntBE=function(e,i,s,o){if(e=+e,i>>>=0,s>>>=0,!o){var l=Math.pow(2,8*s)-1;checkInt(this,e,i,s,l,0)}var h=s-1,d=1;for(this[i+h]=255&e;--h>=0&&(d*=256);)this[i+h]=e/d&255;return i+s},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,1,255,0),this[i]=255&e,i+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,2,65535,0),this[i]=255&e,this[i+1]=e>>>8,i+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,2,65535,0),this[i]=e>>>8,this[i+1]=255&e,i+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,4,4294967295,0),this[i+3]=e>>>24,this[i+2]=e>>>16,this[i+1]=e>>>8,this[i]=255&e,i+4},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,4,4294967295,0),this[i]=e>>>24,this[i+1]=e>>>16,this[i+2]=e>>>8,this[i+3]=255&e,i+4},Buffer.prototype.writeIntLE=function(e,i,s,o){if(e=+e,i>>>=0,!o){var l=Math.pow(2,8*s-1);checkInt(this,e,i,s,l-1,-l)}var h=0,d=1,f=0;for(this[i]=255&e;++h<s&&(d*=256);)e<0&&0===f&&0!==this[i+h-1]&&(f=1),this[i+h]=(e/d>>0)-f&255;return i+s},Buffer.prototype.writeIntBE=function(e,i,s,o){if(e=+e,i>>>=0,!o){var l=Math.pow(2,8*s-1);checkInt(this,e,i,s,l-1,-l)}var h=s-1,d=1,f=0;for(this[i+h]=255&e;--h>=0&&(d*=256);)e<0&&0===f&&0!==this[i+h+1]&&(f=1),this[i+h]=(e/d>>0)-f&255;return i+s},Buffer.prototype.writeInt8=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,1,127,-128),e<0&&(e=255+e+1),this[i]=255&e,i+1},Buffer.prototype.writeInt16LE=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,2,32767,-32768),this[i]=255&e,this[i+1]=e>>>8,i+2},Buffer.prototype.writeInt16BE=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,2,32767,-32768),this[i]=e>>>8,this[i+1]=255&e,i+2},Buffer.prototype.writeInt32LE=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,4,2147483647,-2147483648),this[i]=255&e,this[i+1]=e>>>8,this[i+2]=e>>>16,this[i+3]=e>>>24,i+4},Buffer.prototype.writeInt32BE=function(e,i,s){return e=+e,i>>>=0,s||checkInt(this,e,i,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[i]=e>>>24,this[i+1]=e>>>16,this[i+2]=e>>>8,this[i+3]=255&e,i+4},Buffer.prototype.writeFloatLE=function(e,i,s){return writeFloat(this,e,i,!0,s)},Buffer.prototype.writeFloatBE=function(e,i,s){return writeFloat(this,e,i,!1,s)},Buffer.prototype.writeDoubleLE=function(e,i,s){return writeDouble(this,e,i,!0,s)},Buffer.prototype.writeDoubleBE=function(e,i,s){return writeDouble(this,e,i,!1,s)},Buffer.prototype.copy=function(e,i,s,o){if(!Buffer.isBuffer(e))throw TypeError("argument should be a Buffer");if(s||(s=0),o||0===o||(o=this.length),i>=e.length&&(i=e.length),i||(i=0),o>0&&o<s&&(o=s),o===s||0===e.length||0===this.length)return 0;if(i<0)throw RangeError("targetStart out of bounds");if(s<0||s>=this.length)throw RangeError("Index out of range");if(o<0)throw RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-i<o-s&&(o=e.length-i+s);var l=o-s;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(i,s,o):Uint8Array.prototype.set.call(e,this.subarray(s,o),i),l},Buffer.prototype.fill=function(e,i,s,o){if("string"==typeof e){if("string"==typeof i?(o=i,i=0,s=this.length):"string"==typeof s&&(o=s,s=this.length),void 0!==o&&"string"!=typeof o)throw TypeError("encoding must be a string");if("string"==typeof o&&!Buffer.isEncoding(o))throw TypeError("Unknown encoding: "+o);if(1===e.length){var l,h=e.charCodeAt(0);("utf8"===o&&h<128||"latin1"===o)&&(e=h)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(i<0||this.length<i||this.length<s)throw RangeError("Out of range index");if(s<=i)return this;if(i>>>=0,s=void 0===s?this.length:s>>>0,e||(e=0),"number"==typeof e)for(l=i;l<s;++l)this[l]=e;else{var d=Buffer.isBuffer(e)?e:Buffer.from(e,o),f=d.length;if(0===f)throw TypeError('The value "'+e+'" is invalid for argument "value"');for(l=0;l<s-i;++l)this[l+i]=d[l%f]}return this};var d=/[^+/0-9A-Za-z-_]/g;function utf8ToBytes(e,i){i=i||1/0;for(var s,o=e.length,l=null,h=[],d=0;d<o;++d){if((s=e.charCodeAt(d))>55295&&s<57344){if(!l){if(s>56319||d+1===o){(i-=3)>-1&&h.push(239,191,189);continue}l=s;continue}if(s<56320){(i-=3)>-1&&h.push(239,191,189),l=s;continue}s=(l-55296<<10|s-56320)+65536}else l&&(i-=3)>-1&&h.push(239,191,189);if(l=null,s<128){if((i-=1)<0)break;h.push(s)}else if(s<2048){if((i-=2)<0)break;h.push(s>>6|192,63&s|128)}else if(s<65536){if((i-=3)<0)break;h.push(s>>12|224,s>>6&63|128,63&s|128)}else if(s<1114112){if((i-=4)<0)break;h.push(s>>18|240,s>>12&63|128,s>>6&63|128,63&s|128)}else throw Error("Invalid code point")}return h}function base64ToBytes(e){return o.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(d,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function blitBuffer(e,i,s,o){for(var l=0;l<o&&!(l+s>=i.length)&&!(l>=e.length);++l)i[l+s]=e[l];return l}function isInstance(e,i){return e instanceof i||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===i.name}var f=function(){for(var e="0123456789abcdef",i=Array(256),s=0;s<16;++s)for(var o=16*s,l=0;l<16;++l)i[o+l]=e[s]+e[l];return i}()},645:function(e,i){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */i.read=function(e,i,s,o,l){var h,d,f=8*l-o-1,_=(1<<f)-1,g=_>>1,b=-7,w=s?l-1:0,k=s?-1:1,O=e[i+w];for(w+=k,h=O&(1<<-b)-1,O>>=-b,b+=f;b>0;h=256*h+e[i+w],w+=k,b-=8);for(d=h&(1<<-b)-1,h>>=-b,b+=o;b>0;d=256*d+e[i+w],w+=k,b-=8);if(0===h)h=1-g;else{if(h===_)return d?NaN:(O?-1:1)*(1/0);d+=Math.pow(2,o),h-=g}return(O?-1:1)*d*Math.pow(2,h-o)},i.write=function(e,i,s,o,l,h){var d,f,_,g=8*h-l-1,b=(1<<g)-1,w=b>>1,k=23===l?5960464477539062e-23:0,O=o?0:h-1,j=o?1:-1,q=i<0||0===i&&1/i<0?1:0;for(isNaN(i=Math.abs(i))||i===1/0?(f=isNaN(i)?1:0,d=b):(d=Math.floor(Math.log(i)/Math.LN2),i*(_=Math.pow(2,-d))<1&&(d--,_*=2),d+w>=1?i+=k/_:i+=k*Math.pow(2,1-w),i*_>=2&&(d++,_/=2),d+w>=b?(f=0,d=b):d+w>=1?(f=(i*_-1)*Math.pow(2,l),d+=w):(f=i*Math.pow(2,w-1)*Math.pow(2,l),d=0));l>=8;e[s+O]=255&f,O+=j,f/=256,l-=8);for(d=d<<l|f,g+=l;g>0;e[s+O]=255&d,O+=j,d/=256,g-=8);e[s+O-j]|=128*q}},3454:function(e,i,s){"use strict";var o,l;e.exports=(null==(o=s.g.process)?void 0:o.env)&&"object"==typeof(null==(l=s.g.process)?void 0:l.env)?s.g.process:s(7663)},1118:function(e,i,s){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_app",function(){return s(7948)}])},6349:function(e,i,s){"use strict";s.d(i,{Ho:function(){return AuthProvider},QL:function(){return useRequireAuth},aC:function(){return useAuth}});var o=s(1010),l=s(2253),h=s(4932),d=s(1309),f=s(7582),_=s(5893),g=s(2497),b=s(7743),w=s(7294),k=s(1163),O=(0,w.createContext)();function useAuth(){return(0,w.useContext)(O)}function AuthProvider(e){var i,s,k=e.children,j=(0,d._)((0,w.useState)(null),2),q=j[0],$=j[1],ee=(0,d._)((0,w.useState)(!0),2),et=ee[0],er=ee[1],en=(0,d._)((0,w.useState)(!1),2),ei=en[0],es=en[1];(0,w.useEffect)(function(){var e,i=0,s=(e=(0,o._)(function(){var e;return(0,f.Jh)(this,function(o){switch(o.label){case 0:return o.trys.push([0,6,,7]),i++,console.log("\uD83D\uDD0D Auth Init Versuch ".concat(i,"/").concat(10)),[4,new Promise(function(e){return setTimeout(e,50)})];case 1:if(o.sent(),!(e=(0,g.yL)())){if(i<10)return console.log("Firebase Auth noch nicht bereit, versuche erneut..."),setTimeout(s,200),[2];return console.warn("Firebase Auth konnte nach mehreren Versuchen nicht initialisiert werden"),er(!1),es(!0),[2]}console.log("✅ Firebase Auth erfolgreich initialisiert!"),o.label=2;case 2:return o.trys.push([2,4,,5]),[4,(0,b.Fb)(e,b.a$)];case 3:return o.sent(),console.log("✅ Auth-Persistence gesetzt"),[3,5];case 4:return console.warn("⚠️ Persistence-Fehler (nicht kritisch):",o.sent()),[3,5];case 5:return[2,(0,b.Aj)(e,function(e){console.log("\uD83D\uDD0D Auth State Changed:",e?"User: ".concat(e.uid):"Logged out"),window.authStateDebug={timestamp:new Date().toISOString(),hasUser:!!e,userId:(null==e?void 0:e.uid)||null,userEmail:(null==e?void 0:e.email)||null,initialized:!0,staticSite:!0,attempts:i},$(e),er(!1),es(!0)},function(e){console.error("\uD83D\uDD0D Auth State Error:",e),$(null),er(!1),es(!0)})];case 6:return console.error("\uD83D\uDD0D Auth Init Error:",o.sent()),i<10?setTimeout(s,300):(er(!1),es(!0)),[3,7];case 7:return[2]}})}),function(){return e.apply(this,arguments)}),l=setTimeout(function(){ei||(console.warn("⚠️ Auth-Initialisierung Timeout - setze als initialisiert"),er(!1),es(!0))},5e3),h=s();return function(){clearTimeout(l),h&&"function"==typeof h.then&&h.then(function(e){e&&"function"==typeof e&&e()})}},[]);var ea=(i=(0,o._)(function(e,i){var s,o,d,_,w,k;return(0,f.Jh)(this,function(f){switch(f.label){case 0:if(f.trys.push([0,6,,7]),s=(0,g.yL)(),console.log("\uD83D\uDD0D AUTH SERVICE DEBUG:",o={timestamp:new Date().toISOString(),email:e,authInitialized:!!s,isClient:!0,windowFirebaseDebug:window.firebaseDebug}),!s)throw console.error("❌ AUTH ERROR:",d="Firebase Auth ist nicht initialisiert"),window.debugAuth=(0,h._)((0,l._)({},o),{error:d,success:!1}),Error(d);console.log("\uD83D\uDD0D Attempting login with:",e),f.label=1;case 1:return f.trys.push([1,3,,4]),[4,(0,b.Fb)(s,b.a$)];case 2:return f.sent(),console.log("✅ Auth-Persistence gesetzt"),[3,4];case 3:return console.warn("⚠️ Persistence-Fehler (nicht kritisch):",f.sent()),[3,4];case 4:return window.debugAuth=(0,h._)((0,l._)({},o),{step:"attempting-login",persistence:"local",success:null}),[4,(0,b.e5)(s,e,i)];case 5:return console.log("✅ Login successful:",(_=f.sent()).user.uid),window.debugAuth=(0,h._)((0,l._)({},window.debugAuth),{step:"login-successful",userId:_.user.uid,success:!0}),[2,_];case 6:switch(console.error("❌ Login fehlgeschlagen:",w=f.sent()),window.debugAuth=(0,h._)((0,l._)({},window.debugAuth),{error:w.code,errorMessage:w.message,errorStack:w.stack,step:"login-failed",success:!1}),k="Anmeldung fehlgeschlagen. Bitte versuchen Sie es erneut.",w.code){case"auth/user-not-found":k="Kein Benutzer mit dieser E-Mail-Adresse gefunden.";break;case"auth/wrong-password":k="Falsches Passwort. Bitte versuchen Sie es erneut.";break;case"auth/invalid-email":k="Ung\xfcltige E-Mail-Adresse.";break;case"auth/user-disabled":k="Dieser Benutzer wurde deaktiviert.";break;case"auth/network-request-failed":k="Netzwerkfehler. Bitte \xfcberpr\xfcfen Sie Ihre Internetverbindung.";break;case"auth/too-many-requests":k="Zu viele Anmeldeversuche. Bitte warten Sie einen Moment.";break;default:k="Fehler: ".concat(w.message)}throw Error(k);case 7:return[2]}})}),function(e,s){return i.apply(this,arguments)}),eo=(s=(0,o._)(function(){var e,i;return(0,f.Jh)(this,function(s){switch(s.label){case 0:if(s.trys.push([0,3,,4]),!(e=(0,g.yL)()))return[3,2];return[4,(0,b.w7)(e)];case 1:s.sent(),console.log("✅ Logout successful"),s.label=2;case 2:return[3,4];case 3:throw console.error("❌ Logout fehlgeschlagen:",i=s.sent()),i;case 4:return[2]}})}),function(){return s.apply(this,arguments)});return(0,_.jsx)(O.Provider,{value:{user:q,login:ea,logout:eo,loading:et,initialized:ei},children:k})}function useRequireAuth(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/admin/login",i=useAuth(),s=i.user,o=i.loading,l=i.initialized,h=(0,k.useRouter)();return(0,w.useEffect)(function(){if(!l){console.log("Auth noch nicht initialisiert, warte...");return}o||s||(console.log("Kein User gefunden, leite um zu:",e),h.push(e))},[s,o,l,h,e]),{user:s,loading:o||!l}}},2497:function(e,i,s){"use strict";s.d(i,{cr:function(){return getFirebaseStorage},db:function(){return w},hL:function(){return getFirestoreDB},yL:function(){return getFirebaseAuth}});var o=s(2253),l=s(4932),h=s(3977),d=s(2793),f=s(7743),_=s(6650),g={apiKey:"AIzaSyAQankC8Ey-YGLaOrpzsRLoJZpUqk8xUyA",authDomain:"platz-im-herzen-ch-67261.firebaseapp.com",projectId:"platz-im-herzen-ch-67261",storageBucket:"platz-im-herzen-ch-67261.firebasestorage.app",messagingSenderId:"840782134268",appId:"1:840782134268:web:df8d24f9a00cea05e21079",measurementId:"G-PFEW1T9QKP"},b=null,w=null,k=null,O=null,initializeFirebase=function(){try{return(window.firebaseDebug={step:"starting",existingApps:(0,h.C6)().length,isClient:!0},(0,h.C6)().length)?(b=(0,h.C6)()[0],window.firebaseDebug.step="app-existing"):(b=(0,h.ZF)(g),window.firebaseDebug.step="app-initialized"),w=(0,d.ad)(b),window.firebaseDebug.step="firestore-initialized",k=(0,f.v0)(b),(0,f.Fb)(k,f.a$).then(function(){console.log("✅ Auth-Persistence auf LOCAL gesetzt"),window.firebaseDebug.authPersistence="local"}).catch(function(e){console.error("❌ Auth-Persistence-Fehler:",e),window.firebaseDebug.authPersistenceError=e.message}),O=(0,_.cF)(b),window.firebaseDebug.step="auth-storage-initialized",console.log("Firebase erfolgreich initialisiert"),window.firebaseDebug.step="complete",window.firebaseDebug.success=!0,{app:b,db:w,auth:k,storage:O}}catch(e){return console.error("Firebase-Initialisierungsfehler:",e),window.firebaseDebug=(0,l._)((0,o._)({},window.firebaseDebug),{error:e.message,success:!1}),{app:null,db:null,auth:null,storage:null}}},j=initializeFirebase(),q=j.app,$=j.db,ee=j.auth,et=j.storage;b=q,w=$,k=ee,O=et;var getFirestoreDB=function(){return w||initializeFirebase().db},getFirebaseAuth=function(){if(!k){console.log("Auth nicht initialisiert, versuche Neuinitialisierung...");var e=initializeFirebase().auth;return k=e,e}return k},getFirebaseStorage=function(){if(!O){console.log("Storage nicht initialisiert, versuche Neuinitialisierung...");var e=initializeFirebase().storage;return O=e,e}return O}},1228:function(e,i,s){"use strict";s.d(i,{F:function(){return useTheme},f:function(){return ThemeProvider}});var o=s(1309),l=s(5893),h=s(7294),d=(0,h.createContext)({theme:"system",effectiveTheme:"light",systemPrefersDark:!1,toggleTheme:function(){},setTheme:function(){}}),getStorageValue=function(e,i){try{var s=localStorage.getItem(e);return null!==s?s:i}catch(e){return console.error("localStorage error:",e),i}},setDocumentTheme=function(e){if("undefined"!=typeof document)try{document.documentElement.setAttribute("data-theme",e)}catch(e){console.error("setAttribute error:",e)}};function ThemeProvider(e){var i=e.children,s=(0,o._)((0,h.useState)("system"),2),f=s[0],_=s[1],g=(0,o._)((0,h.useState)(!1),2),b=g[0],w=g[1],k=(0,o._)((0,h.useState)("light"),2),O=k[0],j=k[1],q=(0,o._)((0,h.useState)(!1),2),$=q[0],ee=q[1];(0,h.useEffect)(function(){var e=window.matchMedia("(prefers-color-scheme: dark)"),i=e.matches?"dark":"light";w(e.matches);var handleChange=function(e){w(e.matches),"system"===f&&j(e.matches?"dark":"light")};e.addEventListener("change",handleChange);var s=getStorageValue("theme","system");return _(s),j("system"===s?i:s),ee(!0),function(){return e.removeEventListener("change",handleChange)}},[]),(0,h.useEffect)(function(){if($){var e="system"===f?b?"dark":"light":f;j(e),document.documentElement.classList.add("theme-transition"),setDocumentTheme(e);try{localStorage.setItem("theme",f)}catch(e){console.error("localStorage error:",e)}setTimeout(function(){document.documentElement.classList.remove("theme-transition")},300)}},[f,b,$]);var et=(0,h.useCallback)(function(){_(function(e){return"light"===("system"===e?b?"dark":"light":e)?"dark":"light"})},[b]);return $?(0,l.jsx)(d.Provider,{value:{theme:f,effectiveTheme:O,toggleTheme:et,setTheme:_,systemPrefersDark:b},children:i}):(0,l.jsx)(d.Provider,{value:{theme:"system",effectiveTheme:"light",toggleTheme:function(){},setTheme:function(){},systemPrefersDark:!1},children:i})}function useTheme(){var e=(0,h.useContext)(d);if(void 0===e)throw Error("useTheme muss innerhalb eines ThemeProviders verwendet werden");return e}},597:function(e,i,s){var o=s(3454);s(1479);var l=s(7294),h=l&&"object"==typeof l&&"default"in l?l:{default:l};function _defineProperties(e,i){for(var s=0;s<i.length;s++){var o=i[s];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}var d=void 0!==o&&o.env&&!0,isString=function(e){return"[object String]"===Object.prototype.toString.call(e)},f=function(){function StyleSheet(e){var i=void 0===e?{}:e,s=i.name,o=void 0===s?"stylesheet":s,l=i.optimizeForSpeed,h=void 0===l?d:l;invariant$1(isString(o),"`name` must be a string"),this._name=o,this._deletedRulePlaceholder="#"+o+"-deleted-rule____{}",invariant$1("boolean"==typeof h,"`optimizeForSpeed` must be a boolean"),this._optimizeForSpeed=h,this._serverSheet=void 0,this._tags=[],this._injected=!1,this._rulesCount=0;var f=document.querySelector('meta[property="csp-nonce"]');this._nonce=f?f.getAttribute("content"):null}var e,i=StyleSheet.prototype;return i.setOptimizeForSpeed=function(e){invariant$1("boolean"==typeof e,"`setOptimizeForSpeed` accepts a boolean"),invariant$1(0===this._rulesCount,"optimizeForSpeed cannot be when rules have already been inserted"),this.flush(),this._optimizeForSpeed=e,this.inject()},i.isOptimizeForSpeed=function(){return this._optimizeForSpeed},i.inject=function(){var e=this;if(invariant$1(!this._injected,"sheet already injected"),this._injected=!0,this._optimizeForSpeed){this._tags[0]=this.makeStyleTag(this._name),this._optimizeForSpeed="insertRule"in this.getSheet(),this._optimizeForSpeed||(d||console.warn("StyleSheet: optimizeForSpeed mode not supported falling back to standard mode."),this.flush(),this._injected=!0);return}this._serverSheet={cssRules:[],insertRule:function(i,s){return"number"==typeof s?e._serverSheet.cssRules[s]={cssText:i}:e._serverSheet.cssRules.push({cssText:i}),s},deleteRule:function(i){e._serverSheet.cssRules[i]=null}}},i.getSheetForTag=function(e){if(e.sheet)return e.sheet;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].ownerNode===e)return document.styleSheets[i]},i.getSheet=function(){return this.getSheetForTag(this._tags[this._tags.length-1])},i.insertRule=function(e,i){if(invariant$1(isString(e),"`insertRule` accepts only strings"),this._optimizeForSpeed){var s=this.getSheet();"number"!=typeof i&&(i=s.cssRules.length);try{s.insertRule(e,i)}catch(i){return d||console.warn("StyleSheet: illegal rule: \n\n"+e+"\n\nSee https://stackoverflow.com/q/20007992 for more info"),-1}}else{var o=this._tags[i];this._tags.push(this.makeStyleTag(this._name,e,o))}return this._rulesCount++},i.replaceRule=function(e,i){if(this._optimizeForSpeed){var s=this.getSheet();if(i.trim()||(i=this._deletedRulePlaceholder),!s.cssRules[e])return e;s.deleteRule(e);try{s.insertRule(i,e)}catch(o){d||console.warn("StyleSheet: illegal rule: \n\n"+i+"\n\nSee https://stackoverflow.com/q/20007992 for more info"),s.insertRule(this._deletedRulePlaceholder,e)}}else{var o=this._tags[e];invariant$1(o,"old rule at index `"+e+"` not found"),o.textContent=i}return e},i.deleteRule=function(e){if(this._optimizeForSpeed)this.replaceRule(e,"");else{var i=this._tags[e];invariant$1(i,"rule at index `"+e+"` not found"),i.parentNode.removeChild(i),this._tags[e]=null}},i.flush=function(){this._injected=!1,this._rulesCount=0,this._tags.forEach(function(e){return e&&e.parentNode.removeChild(e)}),this._tags=[]},i.cssRules=function(){var e=this;return this._tags.reduce(function(i,s){return s?i=i.concat(Array.prototype.map.call(e.getSheetForTag(s).cssRules,function(i){return i.cssText===e._deletedRulePlaceholder?null:i})):i.push(null),i},[])},i.makeStyleTag=function(e,i,s){i&&invariant$1(isString(i),"makeStyleTag accepts only strings as second parameter");var o=document.createElement("style");this._nonce&&o.setAttribute("nonce",this._nonce),o.type="text/css",o.setAttribute("data-"+e,""),i&&o.appendChild(document.createTextNode(i));var l=document.head||document.getElementsByTagName("head")[0];return s?l.insertBefore(o,s):l.appendChild(o),o},_defineProperties(StyleSheet.prototype,[{key:"length",get:function(){return this._rulesCount}}]),e&&_defineProperties(StyleSheet,e),StyleSheet}();function invariant$1(e,i){if(!e)throw Error("StyleSheet: "+i+".")}var stringHash=function(e){for(var i=5381,s=e.length;s;)i=33*i^e.charCodeAt(--s);return i>>>0},_={};function computeId(e,i){if(!i)return"jsx-"+e;var s=String(i),o=e+s;return _[o]||(_[o]="jsx-"+stringHash(e+"-"+s)),_[o]}function computeSelector(e,i){var s=e+i;return _[s]||(_[s]=i.replace(/__jsx-style-dynamic-selector/g,e)),_[s]}var g=function(){function StyleSheetRegistry(e){var i=void 0===e?{}:e,s=i.styleSheet,o=void 0===s?null:s,l=i.optimizeForSpeed,h=void 0!==l&&l;this._sheet=o||new f({name:"styled-jsx",optimizeForSpeed:h}),this._sheet.inject(),o&&"boolean"==typeof h&&(this._sheet.setOptimizeForSpeed(h),this._optimizeForSpeed=this._sheet.isOptimizeForSpeed()),this._fromServer=void 0,this._indices={},this._instancesCounts={}}var e=StyleSheetRegistry.prototype;return e.add=function(e){var i=this;void 0===this._optimizeForSpeed&&(this._optimizeForSpeed=Array.isArray(e.children),this._sheet.setOptimizeForSpeed(this._optimizeForSpeed),this._optimizeForSpeed=this._sheet.isOptimizeForSpeed()),this._fromServer||(this._fromServer=this.selectFromServer(),this._instancesCounts=Object.keys(this._fromServer).reduce(function(e,i){return e[i]=0,e},{}));var s=this.getIdAndRules(e),o=s.styleId,l=s.rules;if(o in this._instancesCounts){this._instancesCounts[o]+=1;return}var h=l.map(function(e){return i._sheet.insertRule(e)}).filter(function(e){return -1!==e});this._indices[o]=h,this._instancesCounts[o]=1},e.remove=function(e){var i=this,s=this.getIdAndRules(e).styleId;if(function(e,i){if(!e)throw Error("StyleSheetRegistry: "+i+".")}(s in this._instancesCounts,"styleId: `"+s+"` not found"),this._instancesCounts[s]-=1,this._instancesCounts[s]<1){var o=this._fromServer&&this._fromServer[s];o?(o.parentNode.removeChild(o),delete this._fromServer[s]):(this._indices[s].forEach(function(e){return i._sheet.deleteRule(e)}),delete this._indices[s]),delete this._instancesCounts[s]}},e.update=function(e,i){this.add(i),this.remove(e)},e.flush=function(){this._sheet.flush(),this._sheet.inject(),this._fromServer=void 0,this._indices={},this._instancesCounts={}},e.cssRules=function(){var e=this,i=this._fromServer?Object.keys(this._fromServer).map(function(i){return[i,e._fromServer[i]]}):[],s=this._sheet.cssRules();return i.concat(Object.keys(this._indices).map(function(i){return[i,e._indices[i].map(function(e){return s[e].cssText}).join(e._optimizeForSpeed?"":"\n")]}).filter(function(e){return!!e[1]}))},e.styles=function(e){var i,s;return i=this.cssRules(),void 0===(s=e)&&(s={}),i.map(function(e){var i=e[0],o=e[1];return h.default.createElement("style",{id:"__"+i,key:"__"+i,nonce:s.nonce?s.nonce:void 0,dangerouslySetInnerHTML:{__html:o}})})},e.getIdAndRules=function(e){var i=e.children,s=e.dynamic,o=e.id;if(s){var l=computeId(o,s);return{styleId:l,rules:Array.isArray(i)?i.map(function(e){return computeSelector(l,e)}):[computeSelector(l,i)]}}return{styleId:computeId(o),rules:Array.isArray(i)?i:[i]}},e.selectFromServer=function(){return Array.prototype.slice.call(document.querySelectorAll('[id^="__jsx-"]')).reduce(function(e,i){return e[i.id.slice(2)]=i,e},{})},StyleSheetRegistry}(),b=l.createContext(null);b.displayName="StyleSheetContext";var w=h.default.useInsertionEffect||h.default.useLayoutEffect,k=new g;function JSXStyle(e){var i=k||l.useContext(b);return i&&w(function(){return i.add(e),function(){i.remove(e)}},[e.id,String(e.dynamic)]),null}JSXStyle.dynamic=function(e){return e.map(function(e){return computeId(e[0],e[1])}).join(" ")},i.style=JSXStyle},5379:function(e,i,s){"use strict";e.exports=s(597).style},7948:function(e,i,s){"use strict";s.r(i),s.d(i,{default:function(){return _app}});var o=s(2253),l=s(4932),h=s(1309),d=s(5893);s(415),s(3059),s(2637);var f=s(6349),_=s(1228),g=s(8564),b=s(2267),w=s(8007),k=s(9735),O=s(7294),j=function(e){(0,w._)(ErrorBoundary,e);var i=(0,k._)(ErrorBoundary);function ErrorBoundary(e){var s;return(0,g._)(this,ErrorBoundary),(s=i.call(this,e)).state={hasError:!1,error:null},s}return(0,b._)(ErrorBoundary,[{key:"componentDidCatch",value:function(e,i){console.error("Theme error caught by ErrorBoundary:",e,i)}},{key:"render",value:function(){var e=this;return this.state.hasError?(0,d.jsxs)("div",{style:{padding:"20px",margin:"20px",backgroundColor:"#fff8f8",border:"1px solid #ffcdd2",borderRadius:"10px"},children:[(0,d.jsx)("h2",{children:"Ein unerwarteter Fehler ist aufgetreten"}),(0,d.jsx)("p",{children:"Wir arbeiten daran, das Problem zu beheben. Bitte laden Sie die Seite neu oder versuchen Sie es sp\xe4ter noch einmal."}),(0,d.jsx)("button",{onClick:function(){e.setState({hasError:!1}),window.location.reload()},style:{padding:"8px 16px",backgroundColor:"#0071e3",color:"white",border:"none",borderRadius:"999px",cursor:"pointer"},children:"Seite neu laden"})]}):this.props.children}}],[{key:"getDerivedStateFromError",value:function(e){return{hasError:!0,error:e}}}]),ErrorBoundary}(O.Component),q=s(5379),$=s.n(q),ee=s(9008),et=s.n(ee),er=s(1163),lib_useDeviceDetect=function(){var e=(0,h._)((0,O.useState)(!1),2),i=e[0],s=e[1];return(0,O.useEffect)(function(){var handleResize=function(){s(window.innerWidth<768)};return handleResize(),window.addEventListener("resize",handleResize),function(){return window.removeEventListener("resize",handleResize)}},[]),{isMobile:i,isDesktop:!i}};function Sidebar(){var e=(0,er.useRouter)(),i=(0,h._)((0,O.useState)(!1),2),s=i[0],o=i[1],l=(0,h._)((0,O.useState)(!1),2),f=l[0],_=l[1],g=lib_useDeviceDetect(),b=g.isMobile;g.isDesktop;var toggleSidebar=function(){o(!s)},toggleSidebarHidden=function(){var e=!f;_(e),localStorage.setItem("sidebarHidden",e);var i=new CustomEvent("sidebarStateChange",{detail:{hidden:e}});window.dispatchEvent(i)};(0,O.useEffect)(function(){var e=localStorage.getItem("sidebarHidden");null!==e&&_("true"===e)},[]);var isActive=function(i){return"/menu"===i?e.pathname===i||b&&"/menu2"===e.pathname:e.pathname===i};return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)("aside",{className:"jsx-4d3f3180a350a68d "+"sidebar ".concat(s?"visible":""," ").concat(f?"hidden":""),children:[(0,d.jsxs)("div",{className:"jsx-4d3f3180a350a68d sidebarHeader",children:[(0,d.jsx)("div",{className:"jsx-4d3f3180a350a68d logo",children:(0,d.jsx)("img",{src:"https://firebasestorage.googleapis.com/v0/b/platz-im-herzen-ch-67261.firebasestorage.app/o/Platz%20im%20Herzen%20Logo%20white.png?alt=media",alt:"Platz im Herzen Logo",style:{width:"35px",height:"35px",objectFit:"contain"},className:"jsx-4d3f3180a350a68d"})}),(0,d.jsx)("button",{onClick:toggleSidebar,className:"jsx-4d3f3180a350a68d closeSidebar",children:(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d material-symbols-rounded",children:"close"})}),(0,d.jsx)("button",{onClick:toggleSidebarHidden,title:f?"Sidebar anzeigen":"Sidebar ausblenden",className:"jsx-4d3f3180a350a68d toggleButton",children:(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d material-symbols-rounded",children:"chevron_left"})})]}),(0,d.jsxs)("nav",{className:"jsx-4d3f3180a350a68d mainNav",children:[(0,d.jsx)("button",{onClick:function(){e.push("/"),o(!1)},"data-label":"Startseite",className:"jsx-4d3f3180a350a68d "+"navButton ".concat(isActive("/")?"active":""),children:(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d material-symbols-rounded",children:"home"})}),(0,d.jsx)("button",{onClick:function(){b?e.push("/menu2"):e.push("/menu"),o(!1)},"data-label":"Men\xfc",className:"jsx-4d3f3180a350a68d "+"navButton ".concat(isActive("/menu")?"active":""),children:(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d material-symbols-rounded",children:"restaurant"})}),(0,d.jsx)("button",{"data-label":"\xdcber uns","data-sublabel":"coming soon",style:{opacity:.5,cursor:"default"},className:"jsx-4d3f3180a350a68d navButton disabled",children:(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d material-symbols-rounded",children:"info"})}),(0,d.jsx)("button",{onClick:function(){window.open("https://app.resmio.com/platz-im-herzen-ch/widget","_blank"),o(!1)},"data-label":"Reservierung",className:"jsx-4d3f3180a350a68d "+"navButton ".concat(isActive("/reservation")?"active":""),children:(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d material-symbols-rounded",children:"calendar_month"})})]}),(0,d.jsx)("button",{className:"jsx-4d3f3180a350a68d addButton",children:(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d material-symbols-rounded",children:"add"})})]}),s&&(0,d.jsx)("div",{onClick:toggleSidebar,className:"jsx-4d3f3180a350a68d sidebarBackdrop"}),(0,d.jsx)("button",{onClick:f?toggleSidebarHidden:toggleSidebar,"aria-label":f?"Men\xfc anzeigen":"Men\xfc \xf6ffnen",className:"jsx-4d3f3180a350a68d "+"mobileMenuButton ".concat(f?"show-sidebar-button":""),children:(0,d.jsxs)("div",{className:"jsx-4d3f3180a350a68d hamburgerIcon",children:[(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d hamburgerLine"}),(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d hamburgerLine"}),(0,d.jsx)("span",{className:"jsx-4d3f3180a350a68d hamburgerLine"})]})}),(0,d.jsx)($(),{id:"4d3f3180a350a68d",children:'.sidebar.jsx-4d3f3180a350a68d{width:80px;border-right:1px solid#2a2a2a;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;-moz-box-orient:vertical;-moz-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-align:center;-webkit-align-items:center;-moz-box-align:center;-ms-flex-align:center;align-items:center;padding:40px 0;height:100vh;position:fixed;top:0;left:0;z-index:50;background-color:#121212;-webkit-transition:-webkit-transform.3s ease,width.3s ease,margin-left.3s ease;-moz-transition:-moz-transform.3s ease,width.3s ease,margin-left.3s ease;-o-transition:-o-transform.3s ease,width.3s ease,margin-left.3s ease;transition:-webkit-transform.3s ease,width.3s ease,margin-left.3s ease;transition:-moz-transform.3s ease,width.3s ease,margin-left.3s ease;transition:-o-transform.3s ease,width.3s ease,margin-left.3s ease;transition:transform.3s ease,width.3s ease,margin-left.3s ease}.sidebar.hidden.jsx-4d3f3180a350a68d{-webkit-transform:translatex(-100%);-moz-transform:translatex(-100%);-ms-transform:translatex(-100%);-o-transform:translatex(-100%);transform:translatex(-100%);margin-left:-80px}.sidebarHeader.jsx-4d3f3180a350a68d{width:100%;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-webkit-justify-content:center;-moz-box-pack:center;-ms-flex-pack:center;justify-content:center;position:relative;margin-bottom:40px}.closeSidebar.jsx-4d3f3180a350a68d{display:none;position:absolute;right:10px;top:10px;background:none;border:none;color:#777;cursor:pointer;padding:8px}.closeSidebar.jsx-4d3f3180a350a68d:hover{color:#fff}.toggleButton.jsx-4d3f3180a350a68d{position:absolute;right:-18px;top:50%;-webkit-transform:translatey(-50%);-moz-transform:translatey(-50%);-ms-transform:translatey(-50%);-o-transform:translatey(-50%);transform:translatey(-50%);background-color:#232323;border:1px solid#333;-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%;color:#999;width:32px;height:32px;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-moz-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-moz-box-pack:center;-ms-flex-pack:center;justify-content:center;cursor:pointer;-webkit-transition:all.2s ease;-moz-transition:all.2s ease;-o-transition:all.2s ease;transition:all.2s ease;z-index:52;-webkit-box-shadow:0 2px 8px rgba(0,0,0,.2);-moz-box-shadow:0 2px 8px rgba(0,0,0,.2);box-shadow:0 2px 8px rgba(0,0,0,.2)}.toggleButton.jsx-4d3f3180a350a68d:hover{background-color:#2a2a2a;color:#a2e05a;-webkit-transform:translatey(-50%)scale(1.05);-moz-transform:translatey(-50%)scale(1.05);-ms-transform:translatey(-50%)scale(1.05);-o-transform:translatey(-50%)scale(1.05);transform:translatey(-50%)scale(1.05);-webkit-box-shadow:0 3px 10px rgba(0,0,0,.3);-moz-box-shadow:0 3px 10px rgba(0,0,0,.3);box-shadow:0 3px 10px rgba(0,0,0,.3)}.toggleButton.jsx-4d3f3180a350a68d:active{-webkit-transform:translatey(-50%)scale(.95);-moz-transform:translatey(-50%)scale(.95);-ms-transform:translatey(-50%)scale(.95);-o-transform:translatey(-50%)scale(.95);transform:translatey(-50%)scale(.95)}.toggleButton.jsx-4d3f3180a350a68d .material-symbols-rounded.jsx-4d3f3180a350a68d{font-size:22px}.sidebarBackdrop.jsx-4d3f3180a350a68d{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(0,0,0,.5);z-index:45;backdrop-filter:blur(3px);-webkit-backdrop-filter:blur(3px)}.mobileMenuButton.jsx-4d3f3180a350a68d{display:none;position:fixed;top:15px;left:15px;background-color:rgba(35,35,35,.9);border:none;color:white;width:42px;height:42px;-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%;z-index:40;cursor:pointer;-webkit-box-shadow:0 2px 8px rgba(0,0,0,.3);-moz-box-shadow:0 2px 8px rgba(0,0,0,.3);box-shadow:0 2px 8px rgba(0,0,0,.3);-webkit-box-align:center;-webkit-align-items:center;-moz-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-moz-box-pack:center;-ms-flex-pack:center;justify-content:center;-webkit-transition:all.2s ease;-moz-transition:all.2s ease;-o-transition:all.2s ease;transition:all.2s ease;backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px)}.mobileMenuButton.show-sidebar-button.jsx-4d3f3180a350a68d{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex}.mobileMenuButton.jsx-4d3f3180a350a68d:hover{background-color:rgba(45,45,45,.95);-webkit-transform:scale(1.05);-moz-transform:scale(1.05);-ms-transform:scale(1.05);-o-transform:scale(1.05);transform:scale(1.05)}.mobileMenuButton.jsx-4d3f3180a350a68d:active{-webkit-transform:scale(.95);-moz-transform:scale(.95);-ms-transform:scale(.95);-o-transform:scale(.95);transform:scale(.95)}.hamburgerIcon.jsx-4d3f3180a350a68d{width:20px;height:16px;position:relative;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;-moz-box-orient:vertical;-moz-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-pack:justify;-webkit-justify-content:space-between;-moz-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between}.hamburgerLine.jsx-4d3f3180a350a68d{width:100%;height:2px;background-color:white;-webkit-border-radius:2px;-moz-border-radius:2px;border-radius:2px;-webkit-transition:all.3s ease;-moz-transition:all.3s ease;-o-transition:all.3s ease;transition:all.3s ease}.hamburgerIcon.jsx-4d3f3180a350a68d:hover .hamburgerLine.jsx-4d3f3180a350a68d{background-color:#a2e05a}.logo.jsx-4d3f3180a350a68d{background-color:transparent;color:#fff;width:60px;height:60px;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-moz-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-moz-box-pack:center;-ms-flex-pack:center;justify-content:center;-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%;margin-bottom:50px;-webkit-transition:-webkit-transform.2s ease;-moz-transition:-moz-transform.2s ease;-o-transition:-o-transform.2s ease;transition:-webkit-transform.2s ease;transition:-moz-transform.2s ease;transition:-o-transform.2s ease;transition:transform.2s ease}.logo.jsx-4d3f3180a350a68d:hover{-webkit-transform:scale(1.05);-moz-transform:scale(1.05);-ms-transform:scale(1.05);-o-transform:scale(1.05);transform:scale(1.05)}.logo.jsx-4d3f3180a350a68d img.jsx-4d3f3180a350a68d{-webkit-filter:brightness(0)invert(1);filter:brightness(0)invert(1);-webkit-transition:-webkit-filter.2s ease;-moz-transition:filter.2s ease;-o-transition:filter.2s ease;transition:-webkit-filter.2s ease;transition:filter.2s ease;width:35px;height:35px}.logo.jsx-4d3f3180a350a68d:hover img.jsx-4d3f3180a350a68d{-webkit-filter:brightness(0)invert(.9);filter:brightness(0)invert(.9)}.logo.jsx-4d3f3180a350a68d .material-symbols-rounded.jsx-4d3f3180a350a68d{font-size:28px;font-weight:bold}.mainNav.jsx-4d3f3180a350a68d{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;-moz-box-orient:vertical;-moz-box-direction:normal;-ms-flex-direction:column;flex-direction:column;gap:30px;margin-bottom:auto}.navButton.jsx-4d3f3180a350a68d{background:none;border:none;color:#999;width:45px;height:45px;-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-moz-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-moz-box-pack:center;-ms-flex-pack:center;justify-content:center;position:relative;cursor:pointer;-webkit-transition:all.2s ease;-moz-transition:all.2s ease;-o-transition:all.2s ease;transition:all.2s ease}.navButton.jsx-4d3f3180a350a68d .material-symbols-rounded.jsx-4d3f3180a350a68d{font-size:24px}.navButton.jsx-4d3f3180a350a68d:hover{background-color:rgba(255,255,255,.05);color:#fff}.navButton.active.jsx-4d3f3180a350a68d{color:#a2e05a;background-color:rgba(162,224,90,.1)}.navButton.jsx-4d3f3180a350a68d::after{content:attr(data-label);position:absolute;left:60px;top:50%;-webkit-transform:translatey(-50%);-moz-transform:translatey(-50%);-ms-transform:translatey(-50%);-o-transform:translatey(-50%);transform:translatey(-50%);background-color:#232323;color:#fff;padding:8px 12px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;font-size:14px;opacity:0;visibility:hidden;-webkit-transition:all.2s ease;-moz-transition:all.2s ease;-o-transition:all.2s ease;transition:all.2s ease;white-space:nowrap;-webkit-box-shadow:0 2px 8px rgba(0,0,0,.2);-moz-box-shadow:0 2px 8px rgba(0,0,0,.2);box-shadow:0 2px 8px rgba(0,0,0,.2);pointer-events:none;z-index:52}.navButton.jsx-4d3f3180a350a68d::before{content:"";position:absolute;left:55px;top:50%;-webkit-transform:translatey(-50%);-moz-transform:translatey(-50%);-ms-transform:translatey(-50%);-o-transform:translatey(-50%);transform:translatey(-50%);border-style:solid;border-width:5px 5px 5px 0;border-color:transparent#232323 transparent transparent;opacity:0;visibility:hidden;-webkit-transition:all.2s ease;-moz-transition:all.2s ease;-o-transition:all.2s ease;transition:all.2s ease;pointer-events:none;z-index:52}.navButton.jsx-4d3f3180a350a68d:hover::after,.navButton.jsx-4d3f3180a350a68d:hover::before{opacity:1;visibility:visible}.navButton.disabled.jsx-4d3f3180a350a68d{opacity:.5;cursor:default}.navButton.disabled.jsx-4d3f3180a350a68d:hover{background:none;color:#999}.navButton.disabled.jsx-4d3f3180a350a68d::after{content:attr(data-label)" ("attr(data-sublabel)")"}.addButton.jsx-4d3f3180a350a68d{background-color:#1e1e1e;border:1px solid#333;color:#999;width:45px;height:45px;-webkit-border-radius:50%;-moz-border-radius:50%;border-radius:50%;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-moz-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-moz-box-pack:center;-ms-flex-pack:center;justify-content:center;margin-top:20px;cursor:pointer;-webkit-transition:all.2s ease;-moz-transition:all.2s ease;-o-transition:all.2s ease;transition:all.2s ease}.addButton.jsx-4d3f3180a350a68d:hover{background-color:#2a2a2a;-webkit-transform:translatey(-2px);-moz-transform:translatey(-2px);-ms-transform:translatey(-2px);-o-transform:translatey(-2px);transform:translatey(-2px);color:#fff}.addButton.jsx-4d3f3180a350a68d:active{-webkit-transform:translatey(0);-moz-transform:translatey(0);-ms-transform:translatey(0);-o-transform:translatey(0);transform:translatey(0)}@media(max-width:768px){.sidebar.jsx-4d3f3180a350a68d{-webkit-transform:translatex(-100%);-moz-transform:translatex(-100%);-ms-transform:translatex(-100%);-o-transform:translatex(-100%);transform:translatex(-100%);width:250px;padding:20px;-webkit-box-align:start;-webkit-align-items:flex-start;-moz-box-align:start;-ms-flex-align:start;align-items:flex-start}.sidebar.visible.jsx-4d3f3180a350a68d{-webkit-transform:translatex(0);-moz-transform:translatex(0);-ms-transform:translatex(0);-o-transform:translatex(0);transform:translatex(0)}.sidebar.hidden.jsx-4d3f3180a350a68d{-webkit-transform:translatex(-100%);-moz-transform:translatex(-100%);-ms-transform:translatex(-100%);-o-transform:translatex(-100%);transform:translatex(-100%)}.toggleButton.jsx-4d3f3180a350a68d{display:none}.sidebarHeader.jsx-4d3f3180a350a68d{-webkit-box-pack:start;-webkit-justify-content:flex-start;-moz-box-pack:start;-ms-flex-pack:start;justify-content:flex-start;margin-bottom:30px}.logo.jsx-4d3f3180a350a68d{margin-bottom:0}.closeSidebar.jsx-4d3f3180a350a68d{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex}.mobileMenuButton.jsx-4d3f3180a350a68d{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex}.mainNav.jsx-4d3f3180a350a68d{width:100%}.navButton.jsx-4d3f3180a350a68d{width:100%;height:50px;-webkit-border-radius:8px;-moz-border-radius:8px;border-radius:8px;-webkit-box-pack:start;-webkit-justify-content:flex-start;-moz-box-pack:start;-ms-flex-pack:start;justify-content:flex-start;padding:0 15px}.navButton.jsx-4d3f3180a350a68d .material-symbols-rounded.jsx-4d3f3180a350a68d{margin-right:15px}.navButton.jsx-4d3f3180a350a68d::after{content:attr(data-label);position:static;background:none;padding:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;opacity:1;visibility:visible;-webkit-transform:none;-moz-transform:none;-ms-transform:none;-o-transform:none;transform:none;color:inherit;font-size:16px}.navButton.jsx-4d3f3180a350a68d::before{display:none}.navButton.disabled.jsx-4d3f3180a350a68d::after{content:attr(data-label)" ("attr(data-sublabel)")";opacity:1;visibility:visible}.addButton.jsx-4d3f3180a350a68d{width:100%;height:50px;-webkit-border-radius:8px;-moz-border-radius:8px;border-radius:8px;margin-top:30px}.addButton.jsx-4d3f3180a350a68d::after{content:"Neu hinzuf\xfcgen";margin-left:10px}}@media(min-width:769px){main{margin-left:80px;-webkit-transition:margin-left.3s ease;-moz-transition:margin-left.3s ease;-o-transition:margin-left.3s ease;transition:margin-left.3s ease}.sidebar.hidden+main{margin-left:0}}'})]})}function MainLayout(e){var i=e.children,s=e.title,o=(0,h._)((0,O.useState)(!1),2),l=o[0],f=o[1];return(0,O.useEffect)(function(){var checkSidebarState=function(){var e=localStorage.getItem("sidebarHidden");e&&f("true"===e)};checkSidebarState();var handleStorageChange=function(){checkSidebarState()};window.addEventListener("storage",handleStorageChange);var handleSidebarChange=function(e){e.detail&&f(e.detail.hidden)};return window.addEventListener("sidebarStateChange",handleSidebarChange),function(){window.removeEventListener("storage",handleStorageChange),window.removeEventListener("sidebarStateChange",handleSidebarChange)}},[]),(0,d.jsxs)("div",{className:"jsx-c8b436ab838beded rootLayout",children:[(0,d.jsxs)(et(),{children:[(0,d.jsx)("title",{className:"jsx-c8b436ab838beded",children:void 0===s?"Platz im Herzen":s}),(0,d.jsx)("meta",{name:"description",content:"Speisekarte App - Platz im Herzen",className:"jsx-c8b436ab838beded"}),(0,d.jsx)("meta",{name:"viewport",content:"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no",className:"jsx-c8b436ab838beded"}),(0,d.jsx)("link",{rel:"icon",href:"/favicon.ico",className:"jsx-c8b436ab838beded"}),(0,d.jsx)("link",{rel:"stylesheet",href:"https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200",className:"jsx-c8b436ab838beded"})]}),(0,d.jsx)(Sidebar,{}),(0,d.jsx)("main",{className:"jsx-c8b436ab838beded "+"mainContentWithSidebar ".concat(l?"sidebar-hidden":""),children:i}),(0,d.jsx)($(),{id:"c8b436ab838beded",children:".rootLayout.jsx-c8b436ab838beded{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;min-height:100vh;background-color:#121212;color:#fff}.mainContentWithSidebar.jsx-c8b436ab838beded{-webkit-box-flex:1;-webkit-flex:1;-moz-box-flex:1;-ms-flex:1;flex:1;margin-left:80px;width:-webkit-calc(100% - 80px);width:-moz-calc(100% - 80px);width:calc(100% - 80px);-webkit-transition:margin-left.3s ease,width.3s ease;-moz-transition:margin-left.3s ease,width.3s ease;-o-transition:margin-left.3s ease,width.3s ease;transition:margin-left.3s ease,width.3s ease}.mainContentWithSidebar.sidebar-hidden.jsx-c8b436ab838beded{margin-left:0;width:100%}@media(max-width:768px){.mainContentWithSidebar.jsx-c8b436ab838beded{margin-left:0;width:100%}}"})]})}var en=s(7702);function CustomImage(e){var i=e.src,s=e.alt,l=e.fallback,f=void 0===l?"food":l,_=e.className,g=void 0===_?"":_,b=e.style,w=void 0===b?{}:b,k=(0,en._)(e,["src","alt","fallback","className","style"]),j=(0,h._)((0,O.useState)(i),2),q=j[0],$=j[1],ee=(0,h._)((0,O.useState)(!1),2),et=ee[0],er=ee[1],ei=(0,h._)((0,O.useState)(!1),2),es=ei[0],ea=ei[1];(0,O.useEffect)(function(){ea(!0)},[]);var processImageUrl=function(e){return e?e.includes("firebasestorage.googleapis.com")?"/api/proxy-image?url=".concat(encodeURIComponent(e),"&fallback=").concat(f):e:null};if((0,O.useEffect)(function(){if(i&&!et){var e=processImageUrl(i);e!==q&&$(e)}},[i,f,et]),!es){var eo=processImageUrl(i);return(0,d.jsx)("img",(0,o._)({src:eo,alt:s,className:g,style:w},k))}return(0,d.jsx)("img",(0,o._)({src:q,alt:s,className:g,style:w,onError:function(){if(!et){er(!0);var e={food:"/images/food_placeholder.webp",drink:"/images/drink_placeholder.webp",logo:"/images/placeholder.jpg",default:"/images/placeholder.jpg"},i=e[f]||e.default;console.log("\uD83D\uDD04 CustomImage Fallback:",i),$(i)}}},k))}function SplashScreen(){var e=(0,_.F)().theme,i="dark"===e?"#121212":"#ffffff",s="dark"===e?"#1a1a1a":"#f5f5f5",o="dark"===e?"#121212":"#ffffff";return(0,d.jsxs)("div",{className:$().dynamic([["b6468143d3ddaf46",[i,"dark"===e?"brightness(0) invert(1)":"none",s,o]]])+" splashScreen",children:[(0,d.jsx)("div",{className:$().dynamic([["b6468143d3ddaf46",[i,"dark"===e?"brightness(0) invert(1)":"none",s,o]]])+" logoContainer",children:(0,d.jsx)(CustomImage,{src:"https://firebasestorage.googleapis.com/v0/b/platz-im-herzen-ch-67261.firebasestorage.app/o/Platz%20im%20Herzen%20Logo%20white.png?alt=media",alt:"Platz im Herzen Logo",fallback:"logo",width:200,height:200,className:"logo",loading:"eager"})}),(0,d.jsx)($(),{id:"b6468143d3ddaf46",dynamic:[i,"dark"===e?"brightness(0) invert(1)":"none",s,o],children:".splashScreen{position:fixed;top:0;left:0;width:100vw;height:100vh;background-color:".concat(i,";display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-webkit-justify-content:center;-moz-box-pack:center;-ms-flex-pack:center;justify-content:center;-webkit-box-align:center;-webkit-align-items:center;-moz-box-align:center;-ms-flex-align:center;align-items:center;z-index:99999;-webkit-transition:background-color.3s;-moz-transition:background-color.3s;-o-transition:background-color.3s;transition:background-color.3s}.logoContainer{position:relative;width:200px;height:200px;-webkit-animation:scaleIn.5s ease-out forwards;-moz-animation:scaleIn.5s ease-out forwards;-o-animation:scaleIn.5s ease-out forwards;animation:scaleIn.5s ease-out forwards}.logo{width:100%!important;height:100%!important;-o-object-fit:contain!important;object-fit:contain!important;-webkit-filter:").concat("dark"===e?"brightness(0) invert(1)":"none",";filter:").concat("dark"===e?"brightness(0) invert(1)":"none",';-webkit-animation:pulse 2s infinite;-moz-animation:pulse 2s infinite;-o-animation:pulse 2s infinite;animation:pulse 2s infinite}@-webkit-keyframes scaleIn{0%{-webkit-transform:scale(.3);transform:scale(.3);opacity:0}100%{-webkit-transform:scale(1);transform:scale(1);opacity:1}}@-moz-keyframes scaleIn{0%{-moz-transform:scale(.3);transform:scale(.3);opacity:0}100%{-moz-transform:scale(1);transform:scale(1);opacity:1}}@-o-keyframes scaleIn{0%{-o-transform:scale(.3);transform:scale(.3);opacity:0}100%{-o-transform:scale(1);transform:scale(1);opacity:1}}@keyframes scaleIn{0%{-webkit-transform:scale(.3);-moz-transform:scale(.3);-o-transform:scale(.3);transform:scale(.3);opacity:0}100%{-webkit-transform:scale(1);-moz-transform:scale(1);-o-transform:scale(1);transform:scale(1);opacity:1}}@-webkit-keyframes pulse{0%{opacity:.8;-webkit-transform:scale(.95);transform:scale(.95)}50%{opacity:1;-webkit-transform:scale(1.05);transform:scale(1.05)}100%{opacity:.8;-webkit-transform:scale(.95);transform:scale(.95)}}@-moz-keyframes pulse{0%{opacity:.8;-moz-transform:scale(.95);transform:scale(.95)}50%{opacity:1;-moz-transform:scale(1.05);transform:scale(1.05)}100%{opacity:.8;-moz-transform:scale(.95);transform:scale(.95)}}@-o-keyframes pulse{0%{opacity:.8;-o-transform:scale(.95);transform:scale(.95)}50%{opacity:1;-o-transform:scale(1.05);transform:scale(1.05)}100%{opacity:.8;-o-transform:scale(.95);transform:scale(.95)}}@keyframes pulse{0%{opacity:.8;-webkit-transform:scale(.95);-moz-transform:scale(.95);-o-transform:scale(.95);transform:scale(.95)}50%{opacity:1;-webkit-transform:scale(1.05);-moz-transform:scale(1.05);-o-transform:scale(1.05);transform:scale(1.05)}100%{opacity:.8;-webkit-transform:scale(.95);-moz-transform:scale(.95);-o-transform:scale(.95);transform:scale(.95)}}.splashScreen::before{content:"";position:absolute;top:0;left:0;right:0;bottom:0;background:-webkit-radial-gradient(center,circle,').concat(s," 0%,").concat(o," 70%);background:-moz-radial-gradient(center,circle,").concat(s," 0%,").concat(o," 70%);background:-o-radial-gradient(center,circle,").concat(s," 0%,").concat(o," 70%);background:radial-gradient(circle at center,").concat(s," 0%,").concat(o," 70%);-webkit-animation:gradient 2s ease infinite;-moz-animation:gradient 2s ease infinite;-o-animation:gradient 2s ease infinite;animation:gradient 2s ease infinite}@-webkit-keyframes gradient{0%{opacity:.3}50%{opacity:.5}100%{opacity:.3}}@-moz-keyframes gradient{0%{opacity:.3}50%{opacity:.5}100%{opacity:.3}}@-o-keyframes gradient{0%{opacity:.3}50%{opacity:.5}100%{opacity:.3}}@keyframes gradient{0%{opacity:.3}50%{opacity:.5}100%{opacity:.3}}")})]})}var ei=window.fetch;window.fetch=function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e&&(e.includes("firebasestorage.googleapis.com")||e.includes("firebasestorage.app"))){var s=(0,l._)((0,o._)({},i),{mode:"cors",credentials:"omit",headers:(0,o._)({Accept:"image/webp,image/png,image/jpeg,image/*,*/*;q=0.8","Accept-Language":"de-DE,de;q=0.9,en;q=0.8","Cache-Control":"no-cache",Pragma:"no-cache"},i.headers)});return delete s.headers["Access-Control-Allow-Origin"],ei(e,s).catch(function(i){return(console.warn("Firebase Storage Fetch-Fehler:",i),i.message.includes("412")||i.message.includes("Failed to fetch"))?(console.log("Verwende Fallback-Mechanismus f\xfcr:",e),Promise.reject(Error("Firebase Storage nicht verf\xfcgbar - Fallback wird verwendet"))):Promise.reject(i)})}return ei(e,i)},window.addEventListener("unhandledrejection",function(e){e.reason&&e.reason.message&&e.reason.message.includes("Firebase Storage")&&(console.warn("Unbehandelte Firebase Storage Promise-Rejection:",e.reason),e.preventDefault())}),window.addEventListener("error",function(e){if(e.target&&"IMG"===e.target.tagName){var i=e.target,s=i.src;if(s&&(s.includes("firebasestorage.googleapis.com")||s.includes("firebasestorage.app"))&&(console.warn("Globaler Bild-Load-Fehler f\xfcr Firebase Storage:",s),!i.dataset.fallbackAttempted)){i.dataset.fallbackAttempted="true";var o="food";if(i.alt&&i.alt.toLowerCase().includes("drink")&&(o="drink"),s.includes("/api/proxy-image"))console.log("\uD83D\uDEA8 Verhindere Proxy-Rekursion, verwende direktes Fallback"),i.src="/images/".concat(o,"_placeholder.webp");else{var l="/api/proxy-image?url=".concat(encodeURIComponent(s),"&fallback=").concat(o);console.log("Verwende Proxy-URL:",l),i.src=l}}}},!0);var _app=function(e){var i=e.Component,s=e.pageProps,l=(0,h._)((0,O.useState)(!0),2),g=l[0],b=l[1];(0,O.useEffect)(function(){var e=setTimeout(function(){b(!1)},3e3);return function(){return clearTimeout(e)}},[]);var w=i.getLayout||function(e){return(0,d.jsx)(MainLayout,{children:e})};return g?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(et(),{children:[(0,d.jsx)("link",{rel:"icon",href:"/icons/icon-192x192.png"}),(0,d.jsx)("link",{rel:"apple-touch-icon",href:"/icons/icon-192x192.png"}),(0,d.jsx)("meta",{name:"viewport",content:"width=device-width, initial-scale=1.0"}),(0,d.jsx)("meta",{name:"description",content:"Platz im Herzen - Restaurant & Bar"}),(0,d.jsx)("title",{children:"Platz im Herzen"})]}),(0,d.jsx)(SplashScreen,{})]}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(et(),{children:[(0,d.jsx)("link",{rel:"icon",href:"/icons/icon-192x192.png"}),(0,d.jsx)("link",{rel:"apple-touch-icon",href:"/icons/icon-192x192.png"}),(0,d.jsx)("meta",{name:"viewport",content:"width=device-width, initial-scale=1.0"}),(0,d.jsx)("meta",{name:"description",content:"Platz im Herzen - Restaurant & Bar"}),(0,d.jsx)("title",{children:"Platz im Herzen"}),(0,d.jsx)("link",{rel:"preload",href:"/images/food_placeholder.webp",as:"image",type:"image/webp"}),(0,d.jsx)("link",{rel:"preload",href:"/images/drink_placeholder.webp",as:"image",type:"image/webp"}),(0,d.jsx)("link",{rel:"preload",href:"/images/placeholder.jpg",as:"image",type:"image/jpeg"})]}),(0,d.jsx)(j,{children:(0,d.jsx)(f.Ho,{children:(0,d.jsx)(_.f,{children:w((0,d.jsx)(i,(0,o._)({},s)))})})})]})}},1479:function(){},3059:function(){},2637:function(){},415:function(){},7663:function(e){!function(){var i={229:function(e){var i,s,o,l=e.exports={};function defaultSetTimout(){throw Error("setTimeout has not been defined")}function defaultClearTimeout(){throw Error("clearTimeout has not been defined")}function runTimeout(e){if(i===setTimeout)return setTimeout(e,0);if((i===defaultSetTimout||!i)&&setTimeout)return i=setTimeout,setTimeout(e,0);try{return i(e,0)}catch(s){try{return i.call(null,e,0)}catch(s){return i.call(this,e,0)}}}!function(){try{i="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){i=defaultSetTimout}try{s="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){s=defaultClearTimeout}}();var h=[],d=!1,f=-1;function cleanUpNextTick(){d&&o&&(d=!1,o.length?h=o.concat(h):f=-1,h.length&&drainQueue())}function drainQueue(){if(!d){var e=runTimeout(cleanUpNextTick);d=!0;for(var i=h.length;i;){for(o=h,h=[];++f<i;)o&&o[f].run();f=-1,i=h.length}o=null,d=!1,function(e){if(s===clearTimeout)return clearTimeout(e);if((s===defaultClearTimeout||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(e);try{s(e)}catch(i){try{return s.call(null,e)}catch(i){return s.call(this,e)}}}(e)}}function Item(e,i){this.fun=e,this.array=i}function noop(){}l.nextTick=function(e){var i=Array(arguments.length-1);if(arguments.length>1)for(var s=1;s<arguments.length;s++)i[s-1]=arguments[s];h.push(new Item(e,i)),1!==h.length||d||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},l.title="browser",l.browser=!0,l.env={},l.argv=[],l.version="",l.versions={},l.on=noop,l.addListener=noop,l.once=noop,l.off=noop,l.removeListener=noop,l.removeAllListeners=noop,l.emit=noop,l.prependListener=noop,l.prependOnceListener=noop,l.listeners=function(e){return[]},l.binding=function(e){throw Error("process.binding is not supported")},l.cwd=function(){return"/"},l.chdir=function(e){throw Error("process.chdir is not supported")},l.umask=function(){return 0}}},s={};function __nccwpck_require__(e){var o=s[e];if(void 0!==o)return o.exports;var l=s[e]={exports:{}},h=!0;try{i[e](l,l.exports,__nccwpck_require__),h=!1}finally{h&&delete s[e]}return l.exports}__nccwpck_require__.ab="//";var o=__nccwpck_require__(229);e.exports=o}()},9008:function(e,i,s){e.exports=s(9201)},1163:function(e,i,s){e.exports=s(9974)},5816:function(e,i,s){"use strict";let o,l;s.d(i,{Jn:function(){return eh},qX:function(){return _getProvider},rh:function(){return _isFirebaseServerApp},Xd:function(){return _registerComponent},Mq:function(){return getApp},C6:function(){return getApps},ZF:function(){return initializeApp},KN:function(){return registerVersion}});var h,d=s(8463),f=s(3333),_=s(4444);let instanceOfAny=(e,i)=>i.some(i=>e instanceof i),g=new WeakMap,b=new WeakMap,w=new WeakMap,k=new WeakMap,O=new WeakMap,j={get(e,i,s){if(e instanceof IDBTransaction){if("done"===i)return b.get(e);if("objectStoreNames"===i)return e.objectStoreNames||w.get(e);if("store"===i)return s.objectStoreNames[1]?void 0:s.objectStore(s.objectStoreNames[0])}return wrap_idb_value_wrap(e[i])},set:(e,i,s)=>(e[i]=s,!0),has:(e,i)=>e instanceof IDBTransaction&&("done"===i||"store"===i)||i in e};function wrap_idb_value_wrap(e){var i;if(e instanceof IDBRequest)return function(e){let i=new Promise((i,s)=>{let unlisten=()=>{e.removeEventListener("success",success),e.removeEventListener("error",error)},success=()=>{i(wrap_idb_value_wrap(e.result)),unlisten()},error=()=>{s(e.error),unlisten()};e.addEventListener("success",success),e.addEventListener("error",error)});return i.then(i=>{i instanceof IDBCursor&&g.set(i,e)}).catch(()=>{}),O.set(i,e),i}(e);if(k.has(e))return k.get(e);let s="function"==typeof(i=e)?i!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(l||(l=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(i)?function(...e){return i.apply(unwrap(this),e),wrap_idb_value_wrap(g.get(this))}:function(...e){return wrap_idb_value_wrap(i.apply(unwrap(this),e))}:function(e,...s){let o=i.call(unwrap(this),e,...s);return w.set(o,e.sort?e.sort():[e]),wrap_idb_value_wrap(o)}:(i instanceof IDBTransaction&&function(e){if(b.has(e))return;let i=new Promise((i,s)=>{let unlisten=()=>{e.removeEventListener("complete",complete),e.removeEventListener("error",error),e.removeEventListener("abort",error)},complete=()=>{i(),unlisten()},error=()=>{s(e.error||new DOMException("AbortError","AbortError")),unlisten()};e.addEventListener("complete",complete),e.addEventListener("error",error),e.addEventListener("abort",error)});b.set(e,i)}(i),instanceOfAny(i,o||(o=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])))?new Proxy(i,j):i;return s!==e&&(k.set(e,s),O.set(s,e)),s}let unwrap=e=>O.get(e),q=["get","getKey","getAll","getAllKeys","count"],$=["put","add","delete","clear"],ee=new Map;function getMethod(e,i){if(!(e instanceof IDBDatabase&&!(i in e)&&"string"==typeof i))return;if(ee.get(i))return ee.get(i);let s=i.replace(/FromIndex$/,""),o=i!==s,l=$.includes(s);if(!(s in(o?IDBIndex:IDBObjectStore).prototype)||!(l||q.includes(s)))return;let method=async function(e,...i){let h=this.transaction(e,l?"readwrite":"readonly"),d=h.store;return o&&(d=d.index(i.shift())),(await Promise.all([d[s](...i),l&&h.done]))[0]};return ee.set(i,method),method}j={...h=j,get:(e,i,s)=>getMethod(e,i)||h.get(e,i,s),has:(e,i)=>!!getMethod(e,i)||h.has(e,i)};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let PlatformLoggerServiceImpl=class PlatformLoggerServiceImpl{constructor(e){this.container=e}getPlatformInfoString(){let e=this.container.getProviders();return e.map(e=>{if(!function(e){let i=e.getComponent();return(null==i?void 0:i.type)==="VERSION"}(e))return null;{let i=e.getImmediate();return`${i.library}/${i.version}`}}).filter(e=>e).join(" ")}};let et="@firebase/app",er="0.10.13",en=new f.Yd("@firebase/app"),ei="[DEFAULT]",es={[et]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/data-connect":"fire-data-connect","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","@firebase/vertexai-preview":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},ea=new Map,eo=new Map,el=new Map;function _addComponent(e,i){try{e.container.addComponent(i)}catch(s){en.debug(`Component ${i.name} failed to register with FirebaseApp ${e.name}`,s)}}function _registerComponent(e){let i=e.name;if(el.has(i))return en.debug(`There were multiple attempts to register component ${i}.`),!1;for(let s of(el.set(i,e),ea.values()))_addComponent(s,e);for(let i of eo.values())_addComponent(i,e);return!0}function _getProvider(e,i){let s=e.container.getProvider("heartbeat").getImmediate({optional:!0});return s&&s.triggerHeartbeat(),e.container.getProvider(i)}function _isFirebaseServerApp(e){return void 0!==e.settings}let eu=new _.LL("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."});/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FirebaseAppImpl=class FirebaseAppImpl{constructor(e,i,s){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},i),this._name=i.name,this._automaticDataCollectionEnabled=i.automaticDataCollectionEnabled,this._container=s,this.container.addComponent(new d.wA("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 eu.create("app-deleted",{appName:this._name})}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let eh="10.14.1";function initializeApp(e,i={}){let s=e;if("object"!=typeof i){let e=i;i={name:e}}let o=Object.assign({name:ei,automaticDataCollectionEnabled:!1},i),l=o.name;if("string"!=typeof l||!l)throw eu.create("bad-app-name",{appName:String(l)});if(s||(s=(0,_.aH)()),!s)throw eu.create("no-options");let h=ea.get(l);if(h){if((0,_.vZ)(s,h.options)&&(0,_.vZ)(o,h.config))return h;throw eu.create("duplicate-app",{appName:l})}let f=new d.H0(l);for(let e of el.values())f.addComponent(e);let g=new FirebaseAppImpl(s,o,f);return ea.set(l,g),g}function getApp(e=ei){let i=ea.get(e);if(!i&&e===ei&&(0,_.aH)())return initializeApp();if(!i)throw eu.create("no-app",{appName:e});return i}function getApps(){return Array.from(ea.values())}function registerVersion(e,i,s){var o;let l=null!==(o=es[e])&&void 0!==o?o:e;s&&(l+=`-${s}`);let h=l.match(/\s|\//),f=i.match(/\s|\//);if(h||f){let e=[`Unable to register library "${l}" with version "${i}":`];h&&e.push(`library name "${l}" contains illegal characters (whitespace or "/")`),h&&f&&e.push("and"),f&&e.push(`version name "${i}" contains illegal characters (whitespace or "/")`),en.warn(e.join(" "));return}_registerComponent(new d.wA(`${l}-version`,()=>({library:l,version:i}),"VERSION"))}let ef="firebase-heartbeat-store",e_=null;function getDbPromise(){return e_||(e_=(function(e,i,{blocked:s,upgrade:o,blocking:l,terminated:h}={}){let d=indexedDB.open(e,1),f=wrap_idb_value_wrap(d);return o&&d.addEventListener("upgradeneeded",e=>{o(wrap_idb_value_wrap(d.result),e.oldVersion,e.newVersion,wrap_idb_value_wrap(d.transaction),e)}),s&&d.addEventListener("blocked",e=>s(e.oldVersion,e.newVersion,e)),f.then(e=>{h&&e.addEventListener("close",()=>h()),l&&e.addEventListener("versionchange",e=>l(e.oldVersion,e.newVersion,e))}).catch(()=>{}),f})("firebase-heartbeat-database",0,{upgrade:(e,i)=>{if(0===i)try{e.createObjectStore(ef)}catch(e){console.warn(e)}}}).catch(e=>{throw eu.create("idb-open",{originalErrorMessage:e.message})})),e_}async function readHeartbeatsFromIndexedDB(e){try{let i=await getDbPromise(),s=i.transaction(ef),o=await s.objectStore(ef).get(computeKey(e));return await s.done,o}catch(e){if(e instanceof _.ZR)en.warn(e.message);else{let i=eu.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});en.warn(i.message)}}}async function writeHeartbeatsToIndexedDB(e,i){try{let s=await getDbPromise(),o=s.transaction(ef,"readwrite"),l=o.objectStore(ef);await l.put(i,computeKey(e)),await o.done}catch(e){if(e instanceof _.ZR)en.warn(e.message);else{let i=eu.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});en.warn(i.message)}}}function computeKey(e){return`${e.name}!${e.options.appId}`}let HeartbeatServiceImpl=class HeartbeatServiceImpl{constructor(e){this.container=e,this._heartbeatsCache=null;let i=this.container.getProvider("app").getImmediate();this._storage=new HeartbeatStorageImpl(i),this._heartbeatsCachePromise=this._storage.read().then(e=>(this._heartbeatsCache=e,e))}async triggerHeartbeat(){var e,i;try{let s=this.container.getProvider("platform-logger").getImmediate(),o=s.getPlatformInfoString(),l=getUTCDateString();if((null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,(null===(i=this._heartbeatsCache)||void 0===i?void 0:i.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===l||this._heartbeatsCache.heartbeats.some(e=>e.date===l))return;return this._heartbeatsCache.heartbeats.push({date:l,agent:o}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{let i=new Date(e.date).valueOf(),s=Date.now();return s-i<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}catch(e){en.warn(e)}}async getHeartbeatsHeader(){var e;try{if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)==null||0===this._heartbeatsCache.heartbeats.length)return"";let i=getUTCDateString(),{heartbeatsToSend:s,unsentEntries:o}=function(e,i=1024){let s=[],o=e.slice();for(let l of e){let e=s.find(e=>e.agent===l.agent);if(e){if(e.dates.push(l.date),countBytes(s)>i){e.dates.pop();break}}else if(s.push({agent:l.agent,dates:[l.date]}),countBytes(s)>i){s.pop();break}o=o.slice(1)}return{heartbeatsToSend:s,unsentEntries:o}}(this._heartbeatsCache.heartbeats),l=(0,_.L)(JSON.stringify({version:2,heartbeats:s}));return this._heartbeatsCache.lastSentHeartbeatDate=i,o.length>0?(this._heartbeatsCache.heartbeats=o,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),l}catch(e){return en.warn(e),""}}};function getUTCDateString(){let e=new Date;return e.toISOString().substring(0,10)}let HeartbeatStorageImpl=class HeartbeatStorageImpl{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!(0,_.hl)()&&(0,_.eu)().then(()=>!0).catch(()=>!1)}async read(){let e=await this._canUseIndexedDBPromise;if(!e)return{heartbeats:[]};{let e=await readHeartbeatsFromIndexedDB(this.app);return(null==e?void 0:e.heartbeats)?e:{heartbeats:[]}}}async overwrite(e){var i;let s=await this._canUseIndexedDBPromise;if(s){let s=await this.read();return writeHeartbeatsToIndexedDB(this.app,{lastSentHeartbeatDate:null!==(i=e.lastSentHeartbeatDate)&&void 0!==i?i:s.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var i;let s=await this._canUseIndexedDBPromise;if(s){let s=await this.read();return writeHeartbeatsToIndexedDB(this.app,{lastSentHeartbeatDate:null!==(i=e.lastSentHeartbeatDate)&&void 0!==i?i:s.lastSentHeartbeatDate,heartbeats:[...s.heartbeats,...e.heartbeats]})}}};function countBytes(e){return(0,_.L)(JSON.stringify({version:2,heartbeats:e})).length}_registerComponent(new d.wA("platform-logger",e=>new PlatformLoggerServiceImpl(e),"PRIVATE")),_registerComponent(new d.wA("heartbeat",e=>new HeartbeatServiceImpl(e),"PRIVATE")),registerVersion(et,er,""),registerVersion(et,er,"esm2017"),registerVersion("fire-js","")},8463:function(e,i,s){"use strict";s.d(i,{H0:function(){return ComponentContainer},wA:function(){return Component}});var o=s(4444);let Component=class Component{constructor(e,i,s){this.name=e,this.instanceFactory=i,this.type=s,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}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let l="[DEFAULT]";/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Provider=class Provider{constructor(e,i){this.name=e,this.container=i,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){let i=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(i)){let e=new o.BH;if(this.instancesDeferred.set(i,e),this.isInitialized(i)||this.shouldAutoInitialize())try{let s=this.getOrInitializeService({instanceIdentifier:i});s&&e.resolve(s)}catch(e){}}return this.instancesDeferred.get(i).promise}getImmediate(e){var i;let s=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),o=null!==(i=null==e?void 0:e.optional)&&void 0!==i&&i;if(this.isInitialized(s)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:s})}catch(e){if(o)return null;throw e}else{if(o)return null;throw Error(`Service ${this.name} is not available`)}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:l})}catch(e){}for(let[e,i]of this.instancesDeferred.entries()){let s=this.normalizeInstanceIdentifier(e);try{let e=this.getOrInitializeService({instanceIdentifier:s});i.resolve(e)}catch(e){}}}}clearInstance(e=l){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){let e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=l){return this.instances.has(e)}getOptions(e=l){return this.instancesOptions.get(e)||{}}initialize(e={}){let{options:i={}}=e,s=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(s))throw Error(`${this.name}(${s}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);let o=this.getOrInitializeService({instanceIdentifier:s,options:i});for(let[e,i]of this.instancesDeferred.entries()){let l=this.normalizeInstanceIdentifier(e);s===l&&i.resolve(o)}return o}onInit(e,i){var s;let o=this.normalizeInstanceIdentifier(i),l=null!==(s=this.onInitCallbacks.get(o))&&void 0!==s?s:new Set;l.add(e),this.onInitCallbacks.set(o,l);let h=this.instances.get(o);return h&&e(h,o),()=>{l.delete(e)}}invokeOnInitCallbacks(e,i){let s=this.onInitCallbacks.get(i);if(s)for(let o of s)try{o(e,i)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:i={}}){let s=this.instances.get(e);if(!s&&this.component&&(s=this.component.instanceFactory(this.container,{instanceIdentifier:e===l?void 0:e,options:i}),this.instances.set(e,s),this.instancesOptions.set(e,i),this.invokeOnInitCallbacks(s,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,s)}catch(e){}return s||null}normalizeInstanceIdentifier(e=l){return this.component?this.component.multipleInstances?e:l:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ComponentContainer=class ComponentContainer{constructor(e){this.name=e,this.providers=new Map}addComponent(e){let i=this.getProvider(e.name);if(i.isComponentSet())throw Error(`Component ${e.name} has already been registered with ${this.name}`);i.setComponent(e)}addOrOverwriteComponent(e){let i=this.getProvider(e.name);i.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);let i=new Provider(e,this);return this.providers.set(e,i),i}getProviders(){return Array.from(this.providers.values())}}},3333:function(e,i,s){"use strict";var o,l;s.d(i,{Yd:function(){return Logger},in:function(){return o}});/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let h=[];(l=o||(o={}))[l.DEBUG=0]="DEBUG",l[l.VERBOSE=1]="VERBOSE",l[l.INFO=2]="INFO",l[l.WARN=3]="WARN",l[l.ERROR=4]="ERROR",l[l.SILENT=5]="SILENT";let d={debug:o.DEBUG,verbose:o.VERBOSE,info:o.INFO,warn:o.WARN,error:o.ERROR,silent:o.SILENT},f=o.INFO,_={[o.DEBUG]:"log",[o.VERBOSE]:"log",[o.INFO]:"info",[o.WARN]:"warn",[o.ERROR]:"error"},defaultLogHandler=(e,i,...s)=>{if(i<e.logLevel)return;let o=new Date().toISOString(),l=_[i];if(l)console[l](`[${o}]  ${e.name}:`,...s);else throw Error(`Attempted to log a message with an invalid logType (value: ${i})`)};let Logger=class Logger{constructor(e){this.name=e,this._logLevel=f,this._logHandler=defaultLogHandler,this._userLogHandler=null,h.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in o))throw TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?d[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,o.DEBUG,...e),this._logHandler(this,o.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,o.VERBOSE,...e),this._logHandler(this,o.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,o.INFO,...e),this._logHandler(this,o.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,o.WARN,...e),this._logHandler(this,o.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,o.ERROR,...e),this._logHandler(this,o.ERROR,...e)}}},3977:function(e,i,s){"use strict";s.d(i,{C6:function(){return o.C6},ZF:function(){return o.ZF}});var o=s(5816);/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */(0,o.KN)("firebase","10.14.1","app")},7743:function(e,i,s){"use strict";s.d(i,{a$:function(){return ee},v0:function(){return getAuth},Aj:function(){return onAuthStateChanged},Fb:function(){return setPersistence},e5:function(){return signInWithEmailAndPassword},w7:function(){return signOut}});var o,l=s(5816),h=s(4444),d=s(3333),f=s(7582),_=s(8463);function _prodErrorMap(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}let g=new h.LL("auth","Firebase",_prodErrorMap()),b=new d.Yd("@firebase/auth");function _logError(e,...i){b.logLevel<=d.in.ERROR&&b.error(`Auth (${l.Jn}): ${e}`,...i)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function _fail(e,...i){throw createErrorInternal(e,...i)}function _createError(e,...i){return createErrorInternal(e,...i)}function _errorWithCustomMessage(e,i,s){let o=Object.assign(Object.assign({},_prodErrorMap()),{[i]:s}),l=new h.LL("auth","Firebase",o);return l.create(i,{appName:e.name})}function _serverAppCurrentUserOperationNotSupportedError(e){return _errorWithCustomMessage(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function createErrorInternal(e,...i){if("string"!=typeof e){let s=i[0],o=[...i.slice(1)];return o[0]&&(o[0].appName=e.name),e._errorFactory.create(s,...o)}return g.create(e,...i)}function _assert(e,i,...s){if(!e)throw createErrorInternal(i,...s)}function debugFail(e){let i="INTERNAL ASSERTION FAILED: "+e;throw _logError(i),Error(i)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function _getCurrentUrl(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function _getCurrentScheme(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Delay=class Delay{constructor(e,i){this.shortDelay=e,this.longDelay=i,i>e||debugFail("Short delay should be less than long delay!"),this.isMobile=(0,h.uI)()||(0,h.b$)()}get(){return!("undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===_getCurrentScheme()||"https:"===_getCurrentScheme()||(0,h.ru)()||"connection"in navigator))||navigator.onLine?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function _emulatorUrl(e,i){e.emulator||debugFail("Emulator should always be set here");let{url:s}=e.emulator;return i?`${s}${i.startsWith("/")?i.slice(1):i}`:s}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FetchProvider=class FetchProvider{static initialize(e,i,s){this.fetchImpl=e,i&&(this.headersImpl=i),s&&(this.responseImpl=s)}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 debugFail("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 debugFail("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 debugFail("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let w={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"},k=new Delay(3e4,6e4);function _addTidIfNecessary(e,i){return e.tenantId&&!i.tenantId?Object.assign(Object.assign({},i),{tenantId:e.tenantId}):i}async function _performApiRequest(e,i,s,o,l={}){return _performFetchWithErrorHandling(e,l,async()=>{let l={},d={};o&&("GET"===i?d=o:l={body:JSON.stringify(o)});let f=(0,h.xO)(Object.assign({key:e.config.apiKey},d)).slice(1),_=await e._getAdditionalHeaders();_["Content-Type"]="application/json",e.languageCode&&(_["X-Firebase-Locale"]=e.languageCode);let g=Object.assign({method:i,headers:_},l);return(0,h.L_)()||(g.referrerPolicy="no-referrer"),FetchProvider.fetch()(_getFinalTarget(e,e.config.apiHost,s,f),g)})}async function _performFetchWithErrorHandling(e,i,s){e._canInitEmulator=!1;let o=Object.assign(Object.assign({},w),i);try{let i=new NetworkTimeout(e),l=await Promise.race([s(),i.promise]);i.clearNetworkTimeout();let h=await l.json();if("needConfirmation"in h)throw _makeTaggedError(e,"account-exists-with-different-credential",h);if(l.ok&&!("errorMessage"in h))return h;{let i=l.ok?h.errorMessage:h.error.message,[s,d]=i.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===s)throw _makeTaggedError(e,"credential-already-in-use",h);if("EMAIL_EXISTS"===s)throw _makeTaggedError(e,"email-already-in-use",h);if("USER_DISABLED"===s)throw _makeTaggedError(e,"user-disabled",h);let f=o[s]||s.toLowerCase().replace(/[_\s]+/g,"-");if(d)throw _errorWithCustomMessage(e,f,d);_fail(e,f)}}catch(i){if(i instanceof h.ZR)throw i;_fail(e,"network-request-failed",{message:String(i)})}}async function _performSignInRequest(e,i,s,o,l={}){let h=await _performApiRequest(e,i,s,o,l);return"mfaPendingCredential"in h&&_fail(e,"multi-factor-auth-required",{_serverResponse:h}),h}function _getFinalTarget(e,i,s,o){let l=`${i}${s}?${o}`;return e.config.emulator?_emulatorUrl(e.config,l):`${e.config.apiScheme}://${l}`}let NetworkTimeout=class NetworkTimeout{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,i)=>{this.timer=setTimeout(()=>i(_createError(this.auth,"network-request-failed")),k.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}};function _makeTaggedError(e,i,s){let o={appName:e.name};s.email&&(o.email=s.email),s.phoneNumber&&(o.phoneNumber=s.phoneNumber);let l=_createError(e,i,o);return l.customData._tokenResponse=s,l}function isEnterprise(e){return void 0!==e&&void 0!==e.enterprise}let RecaptchaConfig=class RecaptchaConfig{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(let i of this.recaptchaEnforcementState)if(i.provider&&i.provider===e)return function(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}(i.enforcementState);return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}};async function getRecaptchaConfig(e,i){return _performApiRequest(e,"GET","/v2/recaptchaConfig",_addTidIfNecessary(e,i))}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function deleteAccount(e,i){return _performApiRequest(e,"POST","/v1/accounts:delete",i)}async function getAccountInfo(e,i){return _performApiRequest(e,"POST","/v1/accounts:lookup",i)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function utcTimestampToDateString(e){if(e)try{let i=new Date(Number(e));if(!isNaN(i.getTime()))return i.toUTCString()}catch(e){}}async function getIdTokenResult(e,i=!1){let s=(0,h.m9)(e),o=await s.getIdToken(i),l=_parseToken(o);_assert(l&&l.exp&&l.auth_time&&l.iat,s.auth,"internal-error");let d="object"==typeof l.firebase?l.firebase:void 0,f=null==d?void 0:d.sign_in_provider;return{claims:l,token:o,authTime:utcTimestampToDateString(secondsStringToMilliseconds(l.auth_time)),issuedAtTime:utcTimestampToDateString(secondsStringToMilliseconds(l.iat)),expirationTime:utcTimestampToDateString(secondsStringToMilliseconds(l.exp)),signInProvider:f||null,signInSecondFactor:(null==d?void 0:d.sign_in_second_factor)||null}}function secondsStringToMilliseconds(e){return 1e3*Number(e)}function _parseToken(e){let[i,s,o]=e.split(".");if(void 0===i||void 0===s||void 0===o)return _logError("JWT malformed, contained fewer than 3 sections"),null;try{let e=(0,h.tV)(s);if(!e)return _logError("Failed to decode base64 JWT payload"),null;return JSON.parse(e)}catch(e){return _logError("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}function _tokenExpiresIn(e){let i=_parseToken(e);return _assert(i,"internal-error"),_assert(void 0!==i.exp,"internal-error"),_assert(void 0!==i.iat,"internal-error"),Number(i.exp)-Number(i.iat)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function _logoutIfInvalidated(e,i,s=!1){if(s)return i;try{return await i}catch(i){throw i instanceof h.ZR&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(i)&&e.auth.currentUser===e&&await e.auth.signOut(),i}}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ProactiveRefresh=class ProactiveRefresh{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 i;if(e){let e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;let e=null!==(i=this.user.stsTokenManager.expirationTime)&&void 0!==i?i:0,s=e-Date.now()-3e5;return Math.max(0,s)}}schedule(e=!1){if(!this.isRunning)return;let i=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},i)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){(null==e?void 0:e.code)==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let UserMetadata=class UserMetadata{constructor(e,i){this.createdAt=e,this.lastLoginAt=i,this._initializeTime()}_initializeTime(){this.lastSignInTime=utcTimestampToDateString(this.lastLoginAt),this.creationTime=utcTimestampToDateString(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function _reloadWithoutSaving(e){var i;let s=e.auth,o=await e.getIdToken(),l=await _logoutIfInvalidated(e,getAccountInfo(s,{idToken:o}));_assert(null==l?void 0:l.users.length,s,"internal-error");let h=l.users[0];e._notifyReloadListener(h);let d=(null===(i=h.providerUserInfo)||void 0===i?void 0:i.length)?extractProviderData(h.providerUserInfo):[],f=function(e,i){let s=e.filter(e=>!i.some(i=>i.providerId===e.providerId));return[...s,...i]}(e.providerData,d),_=e.isAnonymous,g=!(e.email&&h.passwordHash)&&!(null==f?void 0:f.length),b={uid:h.localId,displayName:h.displayName||null,photoURL:h.photoUrl||null,email:h.email||null,emailVerified:h.emailVerified||!1,phoneNumber:h.phoneNumber||null,tenantId:h.tenantId||null,providerData:f,metadata:new UserMetadata(h.createdAt,h.lastLoginAt),isAnonymous:!!_&&g};Object.assign(e,b)}async function reload(e){let i=(0,h.m9)(e);await _reloadWithoutSaving(i),await i.auth._persistUserIfCurrent(i),i.auth._notifyListenersIfCurrent(i)}function extractProviderData(e){return e.map(e=>{var{providerId:i}=e,s=(0,f._T)(e,["providerId"]);return{providerId:i,uid:s.rawId||"",displayName:s.displayName||null,email:s.email||null,phoneNumber:s.phoneNumber||null,photoURL:s.photoUrl||null}})}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function requestStsToken(e,i){let s=await _performFetchWithErrorHandling(e,{},async()=>{let s=(0,h.xO)({grant_type:"refresh_token",refresh_token:i}).slice(1),{tokenApiHost:o,apiKey:l}=e.config,d=_getFinalTarget(e,o,"/v1/token",`key=${l}`),f=await e._getAdditionalHeaders();return f["Content-Type"]="application/x-www-form-urlencoded",FetchProvider.fetch()(d,{method:"POST",headers:f,body:s})});return{accessToken:s.access_token,expiresIn:s.expires_in,refreshToken:s.refresh_token}}async function revokeToken(e,i){return _performApiRequest(e,"POST","/v2/accounts:revokeToken",_addTidIfNecessary(e,i))}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let StsTokenManager=class StsTokenManager{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){_assert(e.idToken,"internal-error"),_assert(void 0!==e.idToken,"internal-error"),_assert(void 0!==e.refreshToken,"internal-error");let i="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):_tokenExpiresIn(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,i)}updateFromIdToken(e){_assert(0!==e.length,"internal-error");let i=_tokenExpiresIn(e);this.updateTokensAndExpiration(e,null,i)}async getToken(e,i=!1){return i||!this.accessToken||this.isExpired?(_assert(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,i){let{accessToken:s,refreshToken:o,expiresIn:l}=await requestStsToken(e,i);this.updateTokensAndExpiration(s,o,Number(l))}updateTokensAndExpiration(e,i,s){this.refreshToken=i||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*s}static fromJSON(e,i){let{refreshToken:s,accessToken:o,expirationTime:l}=i,h=new StsTokenManager;return s&&(_assert("string"==typeof s,"internal-error",{appName:e}),h.refreshToken=s),o&&(_assert("string"==typeof o,"internal-error",{appName:e}),h.accessToken=o),l&&(_assert("number"==typeof l,"internal-error",{appName:e}),h.expirationTime=l),h}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new StsTokenManager,this.toJSON())}_performRefresh(){return debugFail("not implemented")}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function assertStringOrUndefined(e,i){_assert("string"==typeof e||void 0===e,"internal-error",{appName:i})}let UserImpl=class UserImpl{constructor(e){var{uid:i,auth:s,stsTokenManager:o}=e,l=(0,f._T)(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new ProactiveRefresh(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=i,this.auth=s,this.stsTokenManager=o,this.accessToken=o.accessToken,this.displayName=l.displayName||null,this.email=l.email||null,this.emailVerified=l.emailVerified||!1,this.phoneNumber=l.phoneNumber||null,this.photoURL=l.photoURL||null,this.isAnonymous=l.isAnonymous||!1,this.tenantId=l.tenantId||null,this.providerData=l.providerData?[...l.providerData]:[],this.metadata=new UserMetadata(l.createdAt||void 0,l.lastLoginAt||void 0)}async getIdToken(e){let i=await _logoutIfInvalidated(this,this.stsTokenManager.getToken(this.auth,e));return _assert(i,this.auth,"internal-error"),this.accessToken!==i&&(this.accessToken=i,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),i}getIdTokenResult(e){return getIdTokenResult(this,e)}reload(){return reload(this)}_assign(e){this!==e&&(_assert(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(e=>Object.assign({},e)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let i=new UserImpl(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return i.metadata._copy(this.metadata),i}_onReload(e){_assert(!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,i=!1){let s=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),s=!0),i&&await _reloadWithoutSaving(this),await this.auth._persistUserIfCurrent(this),s&&this.auth._notifyListenersIfCurrent(this)}async delete(){if((0,l.rh)(this.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));let e=await this.getIdToken();return await _logoutIfInvalidated(this,deleteAccount(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,i){var s,o,l,h,d,f,_,g;let b=null!==(s=i.displayName)&&void 0!==s?s:void 0,w=null!==(o=i.email)&&void 0!==o?o:void 0,k=null!==(l=i.phoneNumber)&&void 0!==l?l:void 0,O=null!==(h=i.photoURL)&&void 0!==h?h:void 0,j=null!==(d=i.tenantId)&&void 0!==d?d:void 0,q=null!==(f=i._redirectEventId)&&void 0!==f?f:void 0,$=null!==(_=i.createdAt)&&void 0!==_?_:void 0,ee=null!==(g=i.lastLoginAt)&&void 0!==g?g:void 0,{uid:et,emailVerified:er,isAnonymous:en,providerData:ei,stsTokenManager:es}=i;_assert(et&&es,e,"internal-error");let ea=StsTokenManager.fromJSON(this.name,es);_assert("string"==typeof et,e,"internal-error"),assertStringOrUndefined(b,e.name),assertStringOrUndefined(w,e.name),_assert("boolean"==typeof er,e,"internal-error"),_assert("boolean"==typeof en,e,"internal-error"),assertStringOrUndefined(k,e.name),assertStringOrUndefined(O,e.name),assertStringOrUndefined(j,e.name),assertStringOrUndefined(q,e.name),assertStringOrUndefined($,e.name),assertStringOrUndefined(ee,e.name);let eo=new UserImpl({uid:et,auth:e,email:w,emailVerified:er,displayName:b,isAnonymous:en,photoURL:O,phoneNumber:k,tenantId:j,stsTokenManager:ea,createdAt:$,lastLoginAt:ee});return ei&&Array.isArray(ei)&&(eo.providerData=ei.map(e=>Object.assign({},e))),q&&(eo._redirectEventId=q),eo}static async _fromIdTokenResponse(e,i,s=!1){let o=new StsTokenManager;o.updateFromServerResponse(i);let l=new UserImpl({uid:i.localId,auth:e,stsTokenManager:o,isAnonymous:s});return await _reloadWithoutSaving(l),l}static async _fromGetAccountInfoResponse(e,i,s){let o=i.users[0];_assert(void 0!==o.localId,"internal-error");let l=void 0!==o.providerUserInfo?extractProviderData(o.providerUserInfo):[],h=!(o.email&&o.passwordHash)&&!(null==l?void 0:l.length),d=new StsTokenManager;d.updateFromIdToken(s);let f=new UserImpl({uid:o.localId,auth:e,stsTokenManager:d,isAnonymous:h}),_={uid:o.localId,displayName:o.displayName||null,photoURL:o.photoUrl||null,email:o.email||null,emailVerified:o.emailVerified||!1,phoneNumber:o.phoneNumber||null,tenantId:o.tenantId||null,providerData:l,metadata:new UserMetadata(o.createdAt,o.lastLoginAt),isAnonymous:!(o.email&&o.passwordHash)&&!(null==l?void 0:l.length)};return Object.assign(f,_),f}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let O=new Map;function _getInstance(e){e instanceof Function||debugFail("Expected a class definition");let i=O.get(e);return i?i instanceof e||debugFail("Instance stored in cache mismatched with class"):(i=new e,O.set(e,i)),i}/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let InMemoryPersistence=class InMemoryPersistence{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,i){this.storage[e]=i}async _get(e){let i=this.storage[e];return void 0===i?null:i}async _remove(e){delete this.storage[e]}_addListener(e,i){}_removeListener(e,i){}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function _persistenceKeyName(e,i,s){return`firebase:${e}:${i}:${s}`}InMemoryPersistence.type="NONE";let PersistenceUserManager=class PersistenceUserManager{constructor(e,i,s){this.persistence=e,this.auth=i,this.userKey=s;let{config:o,name:l}=this.auth;this.fullUserKey=_persistenceKeyName(this.userKey,o.apiKey,l),this.fullPersistenceKey=_persistenceKeyName("persistence",o.apiKey,l),this.boundEventHandler=i._onStorageEvent.bind(i),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){let e=await this.persistence._get(this.fullUserKey);return e?UserImpl._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;let i=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,i)return this.setCurrentUser(i)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,i,s="authUser"){if(!i.length)return new PersistenceUserManager(_getInstance(InMemoryPersistence),e,s);let o=(await Promise.all(i.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e),l=o[0]||_getInstance(InMemoryPersistence),h=_persistenceKeyName(s,e.config.apiKey,e.name),d=null;for(let s of i)try{let i=await s._get(h);if(i){let o=UserImpl._fromJSON(e,i);s!==l&&(d=o),l=s;break}}catch(e){}let f=o.filter(e=>e._shouldAllowMigration);return l._shouldAllowMigration&&f.length&&(l=f[0],d&&await l._set(h,d.toJSON()),await Promise.all(i.map(async e=>{if(e!==l)try{await e._remove(h)}catch(e){}}))),new PersistenceUserManager(l,e,s)}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function _getBrowserName(e){let i=e.toLowerCase();if(i.includes("opera/")||i.includes("opr/")||i.includes("opios/"))return"Opera";if(_isIEMobile(i))return"IEMobile";if(i.includes("msie")||i.includes("trident/"))return"IE";{if(i.includes("edge/"))return"Edge";if(_isFirefox(i))return"Firefox";if(i.includes("silk/"))return"Silk";if(_isBlackBerry(i))return"Blackberry";if(_isWebOS(i))return"Webos";if(_isSafari(i))return"Safari";if((i.includes("chrome/")||_isChromeIOS(i))&&!i.includes("edge/"))return"Chrome";if(_isAndroid(i))return"Android";let s=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);if((null==s?void 0:s.length)===2)return s[1]}return"Other"}function _isFirefox(e=(0,h.z$)()){return/firefox\//i.test(e)}function _isSafari(e=(0,h.z$)()){let i=e.toLowerCase();return i.includes("safari/")&&!i.includes("chrome/")&&!i.includes("crios/")&&!i.includes("android")}function _isChromeIOS(e=(0,h.z$)()){return/crios\//i.test(e)}function _isIEMobile(e=(0,h.z$)()){return/iemobile/i.test(e)}function _isAndroid(e=(0,h.z$)()){return/android/i.test(e)}function _isBlackBerry(e=(0,h.z$)()){return/blackberry/i.test(e)}function _isWebOS(e=(0,h.z$)()){return/webos/i.test(e)}function _isIOS(e=(0,h.z$)()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function _isMobileBrowser(e=(0,h.z$)()){return _isIOS(e)||_isAndroid(e)||_isWebOS(e)||_isBlackBerry(e)||/windows phone/i.test(e)||_isIEMobile(e)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function _getClientVersion(e,i=[]){let s;switch(e){case"Browser":s=_getBrowserName((0,h.z$)());break;case"Worker":s=`${_getBrowserName((0,h.z$)())}-${e}`;break;default:s=e}let o=i.length?i.join(","):"FirebaseCore-web";return`${s}/JsCore/${l.Jn}/${o}`}/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let AuthMiddlewareQueue=class AuthMiddlewareQueue{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,i){let wrappedCallback=i=>new Promise((s,o)=>{try{let o=e(i);s(o)}catch(e){o(e)}});wrappedCallback.onAbort=i,this.queue.push(wrappedCallback);let s=this.queue.length-1;return()=>{this.queue[s]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let i=[];try{for(let s of this.queue)await s(e),s.onAbort&&i.push(s.onAbort)}catch(e){for(let e of(i.reverse(),i))try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==e?void 0:e.message})}}};/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function _getPasswordPolicy(e,i={}){return _performApiRequest(e,"GET","/v2/passwordPolicy",_addTidIfNecessary(e,i))}let PasswordPolicyImpl=class PasswordPolicyImpl{constructor(e){var i,s,o,l;let h=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(i=h.minPasswordLength)&&void 0!==i?i:6,h.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=h.maxPasswordLength),void 0!==h.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=h.containsLowercaseCharacter),void 0!==h.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=h.containsUppercaseCharacter),void 0!==h.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=h.containsNumericCharacter),void 0!==h.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=h.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!==(o=null===(s=e.allowedNonAlphanumericCharacters)||void 0===s?void 0:s.join(""))&&void 0!==o?o:"",this.forceUpgradeOnSignin=null!==(l=e.forceUpgradeOnSignin)&&void 0!==l&&l,this.schemaVersion=e.schemaVersion}validatePassword(e){var i,s,o,l,h,d;let f={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,f),this.validatePasswordCharacterOptions(e,f),f.isValid&&(f.isValid=null===(i=f.meetsMinPasswordLength)||void 0===i||i),f.isValid&&(f.isValid=null===(s=f.meetsMaxPasswordLength)||void 0===s||s),f.isValid&&(f.isValid=null===(o=f.containsLowercaseLetter)||void 0===o||o),f.isValid&&(f.isValid=null===(l=f.containsUppercaseLetter)||void 0===l||l),f.isValid&&(f.isValid=null===(h=f.containsNumericCharacter)||void 0===h||h),f.isValid&&(f.isValid=null===(d=f.containsNonAlphanumericCharacter)||void 0===d||d),f}validatePasswordLengthOptions(e,i){let s=this.customStrengthOptions.minPasswordLength,o=this.customStrengthOptions.maxPasswordLength;s&&(i.meetsMinPasswordLength=e.length>=s),o&&(i.meetsMaxPasswordLength=e.length<=o)}validatePasswordCharacterOptions(e,i){let s;this.updatePasswordCharacterOptionsStatuses(i,!1,!1,!1,!1);for(let o=0;o<e.length;o++)s=e.charAt(o),this.updatePasswordCharacterOptionsStatuses(i,s>="a"&&s<="z",s>="A"&&s<="Z",s>="0"&&s<="9",this.allowedNonAlphanumericCharacters.includes(s))}updatePasswordCharacterOptionsStatuses(e,i,s,o,l){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=i)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=s)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=o)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=l))}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let AuthImpl=class AuthImpl{constructor(e,i,s,o){this.app=e,this.heartbeatServiceProvider=i,this.appCheckServiceProvider=s,this.config=o,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Subscription(this),this.idTokenSubscription=new Subscription(this),this.beforeStateQueue=new AuthMiddlewareQueue(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!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=g,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=o.sdkClientVersion}_initializeWithPersistence(e,i){return i&&(this._popupRedirectResolver=_getInstance(i)),this._initializationPromise=this.queue(async()=>{var s,o;if(!this._deleted&&(this.persistenceManager=await PersistenceUserManager.create(this,e),!this._deleted)){if(null===(s=this._popupRedirectResolver)||void 0===s?void 0:s._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(i),this.lastNotifiedUid=(null===(o=this.currentUser)||void 0===o?void 0:o.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;let e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{let i=await getAccountInfo(this,{idToken:e}),s=await UserImpl._fromGetAccountInfoResponse(this,i,e);await this.directlySetCurrentUser(s)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){var i;if((0,l.rh)(this.app)){let e=this.app.settings.authIdToken;return e?new Promise(i=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(e).then(i,i))}):this.directlySetCurrentUser(null)}let s=await this.assertedPersistence.getCurrentUser(),o=s,h=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let s=null===(i=this.redirectUser)||void 0===i?void 0:i._redirectEventId,l=null==o?void 0:o._redirectEventId,d=await this.tryRedirectSignIn(e);(!s||s===l)&&(null==d?void 0:d.user)&&(o=d.user,h=!0)}if(!o)return this.directlySetCurrentUser(null);if(!o._redirectEventId){if(h)try{await this.beforeStateQueue.runMiddleware(o)}catch(e){o=s,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return o?this.reloadAndSetCurrentUserOrClear(o):this.directlySetCurrentUser(null)}return(_assert(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===o._redirectEventId)?this.directlySetCurrentUser(o):this.reloadAndSetCurrentUserOrClear(o)}async tryRedirectSignIn(e){let i=null;try{i=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return i}async reloadAndSetCurrentUserOrClear(e){try{await _reloadWithoutSaving(e)}catch(e){if((null==e?void 0:e.code)!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;let e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if((0,l.rh)(this.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));let i=e?(0,h.m9)(e):null;return i&&_assert(i.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(i&&i._clone(this))}async _updateCurrentUser(e,i=!1){if(!this._deleted)return e&&_assert(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),i||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return(0,l.rh)(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return(0,l.rh)(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(_getInstance(e))})}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let i=this._getPasswordPolicyInternal();return i.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):i.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=await _getPasswordPolicy(this),i=new PasswordPolicyImpl(e);null===this.tenantId?this._projectPasswordPolicy=i:this._tenantPasswordPolicies[this.tenantId]=i}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new h.LL("auth","Firebase",e())}onAuthStateChanged(e,i,s){return this.registerStateListener(this.authStateSubscription,e,i,s)}beforeAuthStateChanged(e,i){return this.beforeStateQueue.pushCallback(e,i)}onIdTokenChanged(e,i,s){return this.registerStateListener(this.idTokenSubscription,e,i,s)}authStateReady(){return new Promise((e,i)=>{if(this.currentUser)e();else{let s=this.onAuthStateChanged(()=>{s(),e()},i)}})}async revokeAccessToken(e){if(this.currentUser){let i=await this.currentUser.getIdToken(),s={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:i};null!=this.tenantId&&(s.tenantId=this.tenantId),await revokeToken(this,s)}}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,i){let s=await this.getOrInitRedirectPersistenceManager(i);return null===e?s.removeCurrentUser():s.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let i=e&&_getInstance(e)||this._popupRedirectResolver;_assert(i,this,"argument-error"),this.redirectPersistenceManager=await PersistenceUserManager.create(this,[_getInstance(i._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var i,s;return(this._isInitialized&&await this.queue(async()=>{}),(null===(i=this._currentUser)||void 0===i?void 0:i._redirectEventId)===e)?this._currentUser:(null===(s=this.redirectUser)||void 0===s?void 0:s._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,i;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);let s=null!==(i=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==i?i:null;this.lastNotifiedUid!==s&&(this.lastNotifiedUid=s,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,i,s,o){if(this._deleted)return()=>{};let l="function"==typeof i?i:i.next.bind(i),h=!1,d=this._isInitialized?Promise.resolve():this._initializationPromise;if(_assert(d,this,"internal-error"),d.then(()=>{h||l(this.currentUser)}),"function"==typeof i){let l=e.addObserver(i,s,o);return()=>{h=!0,l()}}{let s=e.addObserver(i);return()=>{h=!0,s()}}}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 _assert(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=_getClientVersion(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;let i={"X-Client-Version":this.clientVersion};this.app.options.appId&&(i["X-Firebase-gmpid"]=this.app.options.appId);let s=await (null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());s&&(i["X-Firebase-Client"]=s);let o=await this._getAppCheckToken();return o&&(i["X-Firebase-AppCheck"]=o),i}async _getAppCheckToken(){var e;let i=await (null===(e=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getToken());return(null==i?void 0:i.error)&&function(e,...i){b.logLevel<=d.in.WARN&&b.warn(`Auth (${l.Jn}): ${e}`,...i)}(`Error while retrieving App Check token: ${i.error}`),null==i?void 0:i.token}};function _castAuth(e){return(0,h.m9)(e)}let Subscription=class Subscription{constructor(e){this.auth=e,this.observer=null,this.addObserver=(0,h.ne)(e=>this.observer=e)}get next(){return _assert(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let j={async loadJS(){throw Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function _generateCallbackName(e){return`__${e}${Math.floor(1e6*Math.random())}`}let RecaptchaEnterpriseVerifier=class RecaptchaEnterpriseVerifier{constructor(e){this.type="recaptcha-enterprise",this.auth=_castAuth(e)}async verify(e="verify",i=!1){async function retrieveSiteKey(e){if(!i){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(i,s)=>{getRecaptchaConfig(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(o=>{if(void 0===o.recaptchaKey)s(Error("recaptcha Enterprise site key undefined"));else{let s=new RecaptchaConfig(o);return null==e.tenantId?e._agentRecaptchaConfig=s:e._tenantRecaptchaConfigs[e.tenantId]=s,i(s.siteKey)}}).catch(e=>{s(e)})})}function retrieveRecaptchaToken(i,s,o){let l=window.grecaptcha;isEnterprise(l)?l.enterprise.ready(()=>{l.enterprise.execute(i,{action:e}).then(e=>{s(e)}).catch(()=>{s("NO_RECAPTCHA")})}):o(Error("No reCAPTCHA enterprise script loaded."))}return new Promise((e,s)=>{retrieveSiteKey(this.auth).then(o=>{if(!i&&isEnterprise(window.grecaptcha))retrieveRecaptchaToken(o,e,s);else{var l;if("undefined"==typeof window){s(Error("RecaptchaVerifier is only supported in browser"));return}let i=j.recaptchaEnterpriseScript;0!==i.length&&(i+=o),(l=i,j.loadJS(l)).then(()=>{retrieveRecaptchaToken(o,e,s)}).catch(e=>{s(e)})}}).catch(e=>{s(e)})})}};async function injectRecaptchaFields(e,i,s,o=!1){let l;let h=new RecaptchaEnterpriseVerifier(e);try{l=await h.verify(s)}catch(e){l=await h.verify(s,!0)}let d=Object.assign({},i);return o?Object.assign(d,{captchaResp:l}):Object.assign(d,{captchaResponse:l}),Object.assign(d,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(d,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),d}async function handleRecaptchaFlow(e,i,s,o){var l;if(null===(l=e._getRecaptchaConfig())||void 0===l||!l.isProviderEnabled("EMAIL_PASSWORD_PROVIDER"))return o(e,i).catch(async l=>{if("auth/missing-recaptcha-token"!==l.code)return Promise.reject(l);{console.log(`${s} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);let l=await injectRecaptchaFields(e,i,s,"getOobCode"===s);return o(e,l)}});{let l=await injectRecaptchaFields(e,i,s,"getOobCode"===s);return o(e,l)}}function extractProtocol(e){let i=e.indexOf(":");return i<0?"":e.substr(0,i+1)}function parsePort(e){if(!e)return null;let i=Number(e);return isNaN(i)?null:i}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let AuthCredential=class AuthCredential{constructor(e,i){this.providerId=e,this.signInMethod=i}toJSON(){return debugFail("not implemented")}_getIdTokenResponse(e){return debugFail("not implemented")}_linkToIdToken(e,i){return debugFail("not implemented")}_getReauthenticationResolver(e){return debugFail("not implemented")}};async function linkEmailPassword(e,i){return _performApiRequest(e,"POST","/v1/accounts:signUp",i)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function signInWithPassword(e,i){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPassword",_addTidIfNecessary(e,i))}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function signInWithEmailLink$1(e,i){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,i))}async function signInWithEmailLinkForLinking(e,i){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,i))}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let EmailAuthCredential=class EmailAuthCredential extends AuthCredential{constructor(e,i,s,o=null){super("password",s),this._email=e,this._password=i,this._tenantId=o}static _fromEmailAndPassword(e,i){return new EmailAuthCredential(e,i,"password")}static _fromEmailAndCode(e,i,s=null){return new EmailAuthCredential(e,i,"emailLink",s)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let i="string"==typeof e?JSON.parse(e):e;if((null==i?void 0:i.email)&&(null==i?void 0:i.password)){if("password"===i.signInMethod)return this._fromEmailAndPassword(i.email,i.password);if("emailLink"===i.signInMethod)return this._fromEmailAndCode(i.email,i.password,i.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":let i={returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return handleRecaptchaFlow(e,i,"signInWithPassword",signInWithPassword);case"emailLink":return signInWithEmailLink$1(e,{email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}async _linkToIdToken(e,i){switch(this.signInMethod){case"password":let s={idToken:i,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return handleRecaptchaFlow(e,s,"signUpPassword",linkEmailPassword);case"emailLink":return signInWithEmailLinkForLinking(e,{idToken:i,email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function signInWithIdp(e,i){return _performSignInRequest(e,"POST","/v1/accounts:signInWithIdp",_addTidIfNecessary(e,i))}let OAuthCredential=class OAuthCredential extends AuthCredential{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let i=new OAuthCredential(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(i.idToken=e.idToken),e.accessToken&&(i.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(i.nonce=e.nonce),e.pendingToken&&(i.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(i.accessToken=e.oauthToken,i.secret=e.oauthTokenSecret):_fail("argument-error"),i}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){let i="string"==typeof e?JSON.parse(e):e,{providerId:s,signInMethod:o}=i,l=(0,f._T)(i,["providerId","signInMethod"]);if(!s||!o)return null;let h=new OAuthCredential(s,o);return h.idToken=l.idToken||void 0,h.accessToken=l.accessToken||void 0,h.secret=l.secret,h.nonce=l.nonce,h.pendingToken=l.pendingToken||null,h}_getIdTokenResponse(e){let i=this.buildRequest();return signInWithIdp(e,i)}_linkToIdToken(e,i){let s=this.buildRequest();return s.idToken=i,signInWithIdp(e,s)}_getReauthenticationResolver(e){let i=this.buildRequest();return i.autoCreate=!1,signInWithIdp(e,i)}buildRequest(){let e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let i={};this.idToken&&(i.id_token=this.idToken),this.accessToken&&(i.access_token=this.accessToken),this.secret&&(i.oauth_token_secret=this.secret),i.providerId=this.providerId,this.nonce&&!this.pendingToken&&(i.nonce=this.nonce),e.postBody=(0,h.xO)(i)}return e}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function sendPhoneVerificationCode(e,i){return _performApiRequest(e,"POST","/v1/accounts:sendVerificationCode",_addTidIfNecessary(e,i))}async function signInWithPhoneNumber$1(e,i){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,i))}async function linkWithPhoneNumber$1(e,i){let s=await _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,i));if(s.temporaryProof)throw _makeTaggedError(e,"account-exists-with-different-credential",s);return s}let q={USER_NOT_FOUND:"user-not-found"};async function verifyPhoneNumberForExisting(e,i){let s=Object.assign(Object.assign({},i),{operation:"REAUTH"});return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,s),q)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let PhoneAuthCredential=class PhoneAuthCredential extends AuthCredential{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,i){return new PhoneAuthCredential({verificationId:e,verificationCode:i})}static _fromTokenResponse(e,i){return new PhoneAuthCredential({phoneNumber:e,temporaryProof:i})}_getIdTokenResponse(e){return signInWithPhoneNumber$1(e,this._makeVerificationRequest())}_linkToIdToken(e,i){return linkWithPhoneNumber$1(e,Object.assign({idToken:i},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return verifyPhoneNumberForExisting(e,this._makeVerificationRequest())}_makeVerificationRequest(){let{temporaryProof:e,phoneNumber:i,verificationId:s,verificationCode:o}=this.params;return e&&i?{temporaryProof:e,phoneNumber:i}:{sessionInfo:s,code:o}}toJSON(){let e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));let{verificationId:i,verificationCode:s,phoneNumber:o,temporaryProof:l}=e;return s||i||o||l?new PhoneAuthCredential({verificationId:i,verificationCode:s,phoneNumber:o,temporaryProof:l}):null}};let ActionCodeURL=class ActionCodeURL{constructor(e){var i,s,o,l,d,f;let _=(0,h.zd)((0,h.pd)(e)),g=null!==(i=_.apiKey)&&void 0!==i?i:null,b=null!==(s=_.oobCode)&&void 0!==s?s:null,w=/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */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!==(o=_.mode)&&void 0!==o?o:null);_assert(g&&b&&w,"argument-error"),this.apiKey=g,this.operation=w,this.code=b,this.continueUrl=null!==(l=_.continueUrl)&&void 0!==l?l:null,this.languageCode=null!==(d=_.languageCode)&&void 0!==d?d:null,this.tenantId=null!==(f=_.tenantId)&&void 0!==f?f:null}static parseLink(e){let i=function(e){let i=(0,h.zd)((0,h.pd)(e)).link,s=i?(0,h.zd)((0,h.pd)(i)).deep_link_id:null,o=(0,h.zd)((0,h.pd)(e)).deep_link_id,l=o?(0,h.zd)((0,h.pd)(o)).link:null;return l||o||s||i||e}(e);try{return new ActionCodeURL(i)}catch(e){return null}}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let EmailAuthProvider=class EmailAuthProvider{constructor(){this.providerId=EmailAuthProvider.PROVIDER_ID}static credential(e,i){return EmailAuthCredential._fromEmailAndPassword(e,i)}static credentialWithLink(e,i){let s=ActionCodeURL.parseLink(i);return _assert(s,"argument-error"),EmailAuthCredential._fromEmailAndCode(e,s.code,s.tenantId)}};EmailAuthProvider.PROVIDER_ID="password",EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD="password",EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD="emailLink";/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FederatedAuthProvider=class FederatedAuthProvider{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}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let BaseOAuthProvider=class BaseOAuthProvider extends FederatedAuthProvider{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FacebookAuthProvider=class FacebookAuthProvider extends BaseOAuthProvider{constructor(){super("facebook.com")}static credential(e){return OAuthCredential._fromParams({providerId:FacebookAuthProvider.PROVIDER_ID,signInMethod:FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return FacebookAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return FacebookAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return FacebookAuthProvider.credential(e.oauthAccessToken)}catch(e){return null}}};FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD="facebook.com",FacebookAuthProvider.PROVIDER_ID="facebook.com";/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let GoogleAuthProvider=class GoogleAuthProvider extends BaseOAuthProvider{constructor(){super("google.com"),this.addScope("profile")}static credential(e,i){return OAuthCredential._fromParams({providerId:GoogleAuthProvider.PROVIDER_ID,signInMethod:GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:i})}static credentialFromResult(e){return GoogleAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GoogleAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthIdToken:i,oauthAccessToken:s}=e;if(!i&&!s)return null;try{return GoogleAuthProvider.credential(i,s)}catch(e){return null}}};GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD="google.com",GoogleAuthProvider.PROVIDER_ID="google.com";/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let GithubAuthProvider=class GithubAuthProvider extends BaseOAuthProvider{constructor(){super("github.com")}static credential(e){return OAuthCredential._fromParams({providerId:GithubAuthProvider.PROVIDER_ID,signInMethod:GithubAuthProvider.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return GithubAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GithubAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return GithubAuthProvider.credential(e.oauthAccessToken)}catch(e){return null}}};GithubAuthProvider.GITHUB_SIGN_IN_METHOD="github.com",GithubAuthProvider.PROVIDER_ID="github.com";/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let TwitterAuthProvider=class TwitterAuthProvider extends BaseOAuthProvider{constructor(){super("twitter.com")}static credential(e,i){return OAuthCredential._fromParams({providerId:TwitterAuthProvider.PROVIDER_ID,signInMethod:TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:i})}static credentialFromResult(e){return TwitterAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return TwitterAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthAccessToken:i,oauthTokenSecret:s}=e;if(!i||!s)return null;try{return TwitterAuthProvider.credential(i,s)}catch(e){return null}}};TwitterAuthProvider.TWITTER_SIGN_IN_METHOD="twitter.com",TwitterAuthProvider.PROVIDER_ID="twitter.com";/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let UserCredentialImpl=class UserCredentialImpl{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,i,s,o=!1){let l=await UserImpl._fromIdTokenResponse(e,s,o),h=providerIdForResponse(s),d=new UserCredentialImpl({user:l,providerId:h,_tokenResponse:s,operationType:i});return d}static async _forOperation(e,i,s){await e._updateTokensIfNecessary(s,!0);let o=providerIdForResponse(s);return new UserCredentialImpl({user:e,providerId:o,_tokenResponse:s,operationType:i})}};function providerIdForResponse(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let MultiFactorError=class MultiFactorError extends h.ZR{constructor(e,i,s,o){var l;super(i.code,i.message),this.operationType=s,this.user=o,Object.setPrototypeOf(this,MultiFactorError.prototype),this.customData={appName:e.name,tenantId:null!==(l=e.tenantId)&&void 0!==l?l:void 0,_serverResponse:i.customData._serverResponse,operationType:s}}static _fromErrorAndOperation(e,i,s,o){return new MultiFactorError(e,i,s,o)}};function _processCredentialSavingMfaContextIfNecessary(e,i,s,o){let l="reauthenticate"===i?s._getReauthenticationResolver(e):s._getIdTokenResponse(e);return l.catch(s=>{if("auth/multi-factor-auth-required"===s.code)throw MultiFactorError._fromErrorAndOperation(e,s,i,o);throw s})}async function _link$1(e,i,s=!1){let o=await _logoutIfInvalidated(e,i._linkToIdToken(e.auth,await e.getIdToken()),s);return UserCredentialImpl._forOperation(e,"link",o)}/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function _reauthenticate(e,i,s=!1){let{auth:o}=e;if((0,l.rh)(o.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(o));let h="reauthenticate";try{let l=await _logoutIfInvalidated(e,_processCredentialSavingMfaContextIfNecessary(o,h,i,e),s);_assert(l.idToken,o,"internal-error");let d=_parseToken(l.idToken);_assert(d,o,"internal-error");let{sub:f}=d;return _assert(e.uid===f,o,"user-mismatch"),UserCredentialImpl._forOperation(e,h,l)}catch(e){throw(null==e?void 0:e.code)==="auth/user-not-found"&&_fail(o,"user-mismatch"),e}}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function _signInWithCredential(e,i,s=!1){if((0,l.rh)(e.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e));let o="signIn",h=await _processCredentialSavingMfaContextIfNecessary(e,o,i),d=await UserCredentialImpl._fromIdTokenResponse(e,o,h);return s||await e._updateCurrentUser(d.user),d}async function signInWithCredential(e,i){return _signInWithCredential(_castAuth(e),i)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function recachePasswordPolicy(e){let i=_castAuth(e);i._getPasswordPolicyInternal()&&await i._updatePasswordPolicy()}function signInWithEmailAndPassword(e,i,s){return(0,l.rh)(e.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e)):signInWithCredential((0,h.m9)(e),EmailAuthProvider.credential(i,s)).catch(async i=>{throw"auth/password-does-not-meet-requirements"===i.code&&recachePasswordPolicy(e),i})}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function setPersistence(e,i){return(0,h.m9)(e).setPersistence(i)}function onAuthStateChanged(e,i,s,o){return(0,h.m9)(e).onAuthStateChanged(i,s,o)}function signOut(e){return(0,h.m9)(e).signOut()}new WeakMap;let $="__sak";/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let BrowserPersistenceClass=class BrowserPersistenceClass{constructor(e,i){this.storageRetriever=e,this.type=i}_isAvailable(){try{if(!this.storage)return Promise.resolve(!1);return this.storage.setItem($,"1"),this.storage.removeItem($),Promise.resolve(!0)}catch(e){return Promise.resolve(!1)}}_set(e,i){return this.storage.setItem(e,JSON.stringify(i)),Promise.resolve()}_get(e){let i=this.storage.getItem(e);return Promise.resolve(i?JSON.parse(i):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}};let BrowserLocalPersistence=class BrowserLocalPersistence extends BrowserPersistenceClass{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,i)=>this.onStorageEvent(e,i),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=_isMobileBrowser(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(let i of Object.keys(this.listeners)){let s=this.storage.getItem(i),o=this.localCache[i];s!==o&&e(i,o,s)}}onStorageEvent(e,i=!1){if(!e.key){this.forAllChangedKeys((e,i,s)=>{this.notifyListeners(e,s)});return}let s=e.key;i?this.detachListener():this.stopPolling();let triggerListeners=()=>{let e=this.storage.getItem(s);(i||this.localCache[s]!==e)&&this.notifyListeners(s,e)},o=this.storage.getItem(s);(0,h.w1)()&&10===document.documentMode&&o!==e.newValue&&e.newValue!==e.oldValue?setTimeout(triggerListeners,10):triggerListeners()}notifyListeners(e,i){this.localCache[e]=i;let s=this.listeners[e];if(s)for(let e of Array.from(s))e(i?JSON.parse(i):i)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,i,s)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:i,newValue:s}),!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,i){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(i)}_removeListener(e,i){this.listeners[e]&&(this.listeners[e].delete(i),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,i){await super._set(e,i),this.localCache[e]=JSON.stringify(i)}async _get(e){let i=await super._get(e);return this.localCache[e]=JSON.stringify(i),i}async _remove(e){await super._remove(e),delete this.localCache[e]}};BrowserLocalPersistence.type="LOCAL";let ee=BrowserLocalPersistence;/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let BrowserSessionPersistence=class BrowserSessionPersistence extends BrowserPersistenceClass{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,i){}_removeListener(e,i){}};BrowserSessionPersistence.type="SESSION";/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Receiver=class Receiver{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){let i=this.receivers.find(i=>i.isListeningto(e));if(i)return i;let s=new Receiver(e);return this.receivers.push(s),s}isListeningto(e){return this.eventTarget===e}async handleEvent(e){let{eventId:i,eventType:s,data:o}=e.data,l=this.handlersMap[s];if(!(null==l?void 0:l.size))return;e.ports[0].postMessage({status:"ack",eventId:i,eventType:s});let h=Array.from(l).map(async i=>i(e.origin,o)),d=await Promise.all(h.map(async e=>{try{let i=await e;return{fulfilled:!0,value:i}}catch(e){return{fulfilled:!1,reason:e}}}));e.ports[0].postMessage({status:"done",eventId:i,eventType:s,response:d})}_subscribe(e,i){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(i)}_unsubscribe(e,i){this.handlersMap[e]&&i&&this.handlersMap[e].delete(i),i&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function _generateEventId(e="",i=10){let s="";for(let e=0;e<i;e++)s+=Math.floor(10*Math.random());return e+s}Receiver.receivers=[];/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Sender=class Sender{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,i,s=50){let o,l;let h="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!h)throw Error("connection_unavailable");return new Promise((d,f)=>{let _=_generateEventId("",20);h.port1.start();let g=setTimeout(()=>{f(Error("unsupported_event"))},s);l={messageChannel:h,onMessage(e){if(e.data.eventId===_)switch(e.data.status){case"ack":clearTimeout(g),o=setTimeout(()=>{f(Error("timeout"))},3e3);break;case"done":clearTimeout(o),d(e.data.response);break;default:clearTimeout(g),clearTimeout(o),f(Error("invalid_response"))}}},this.handlers.add(l),h.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:e,eventId:_,data:i},[h.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function _window(){return window}/**
 * @license
 * Copyright 2020 Google LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function _isWorker(){return void 0!==_window().WorkerGlobalScope&&"function"==typeof _window().importScripts}async function _getActiveServiceWorker(){if(!(null==navigator?void 0:navigator.serviceWorker))return null;try{let e=await navigator.serviceWorker.ready;return e.active}catch(e){return null}}/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let et="firebaseLocalStorageDb",er="firebaseLocalStorage",en="fbase_key";let DBPromise=class DBPromise{constructor(e){this.request=e}toPromise(){return new Promise((e,i)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{i(this.request.error)})})}};function getObjectStore(e,i){return e.transaction([er],i?"readwrite":"readonly").objectStore(er)}function _openDatabase(){let e=indexedDB.open(et,1);return new Promise((i,s)=>{e.addEventListener("error",()=>{s(e.error)}),e.addEventListener("upgradeneeded",()=>{let i=e.result;try{i.createObjectStore(er,{keyPath:en})}catch(e){s(e)}}),e.addEventListener("success",async()=>{let s=e.result;s.objectStoreNames.contains(er)?i(s):(s.close(),await function(){let e=indexedDB.deleteDatabase(et);return new DBPromise(e).toPromise()}(),i(await _openDatabase()))})})}async function _putObject(e,i,s){let o=getObjectStore(e,!0).put({[en]:i,value:s});return new DBPromise(o).toPromise()}async function getObject(e,i){let s=getObjectStore(e,!1).get(i),o=await new DBPromise(s).toPromise();return void 0===o?null:o.value}function _deleteObject(e,i){let s=getObjectStore(e,!0).delete(i);return new DBPromise(s).toPromise()}let IndexedDBLocalPersistence=class IndexedDBLocalPersistence{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 _openDatabase()),this.db}async _withRetries(e){let i=0;for(;;)try{let i=await this._openDb();return await e(i)}catch(e){if(i++>3)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return _isWorker()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Receiver._getInstance(_isWorker()?self:null),this.receiver._subscribe("keyChanged",async(e,i)=>{let s=await this._poll();return{keyProcessed:s.includes(i.key)}}),this.receiver._subscribe("ping",async(e,i)=>["keyChanged"])}async initializeSender(){var e,i;if(this.activeServiceWorker=await _getActiveServiceWorker(),!this.activeServiceWorker)return;this.sender=new Sender(this.activeServiceWorker);let s=await this.sender._send("ping",{},800);s&&(null===(e=s[0])||void 0===e?void 0:e.fulfilled)&&(null===(i=s[0])||void 0===i?void 0:i.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){var i;if(this.sender&&this.activeServiceWorker&&((null===(i=null==navigator?void 0:navigator.serviceWorker)||void 0===i?void 0:i.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;let e=await _openDatabase();return await _putObject(e,$,"1"),await _deleteObject(e,$),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,i){return this._withPendingWrite(async()=>(await this._withRetries(s=>_putObject(s,e,i)),this.localCache[e]=i,this.notifyServiceWorker(e)))}async _get(e){let i=await this._withRetries(i=>getObject(i,e));return this.localCache[e]=i,i}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(i=>_deleteObject(i,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){let e=await this._withRetries(e=>{let i=getObjectStore(e,!1).getAll();return new DBPromise(i).toPromise()});if(!e||0!==this.pendingWrites)return[];let i=[],s=new Set;if(0!==e.length)for(let{fbase_key:o,value:l}of e)s.add(o),JSON.stringify(this.localCache[o])!==JSON.stringify(l)&&(this.notifyListeners(o,l),i.push(o));for(let e of Object.keys(this.localCache))this.localCache[e]&&!s.has(e)&&(this.notifyListeners(e,null),i.push(e));return i}notifyListeners(e,i){this.localCache[e]=i;let s=this.listeners[e];if(s)for(let e of Array.from(s))e(i)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,i){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(i)}_removeListener(e,i){this.listeners[e]&&(this.listeners[e].delete(i),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}};async function _verifyPhoneNumber(e,i,s){var o,l,h;let d=await s.verify();try{let f;if(_assert("string"==typeof d,e,"argument-error"),_assert("recaptcha"===s.type,e,"argument-error"),f="string"==typeof i?{phoneNumber:i}:i,"session"in f){let i=f.session;if("phoneNumber"in f){_assert("enroll"===i.type,e,"internal-error");let s=await (l={idToken:i.credential,phoneEnrollmentInfo:{phoneNumber:f.phoneNumber,recaptchaToken:d}},_performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,l)));return s.phoneSessionInfo.sessionInfo}{_assert("signin"===i.type,e,"internal-error");let s=(null===(o=f.multiFactorHint)||void 0===o?void 0:o.uid)||f.multiFactorUid;_assert(s,e,"missing-multi-factor-info");let l=await (h={mfaPendingCredential:i.credential,mfaEnrollmentId:s,phoneSignInInfo:{recaptchaToken:d}},_performApiRequest(e,"POST","/v2/accounts/mfaSignIn:start",_addTidIfNecessary(e,h)));return l.phoneResponseInfo.sessionInfo}}{let{sessionInfo:i}=await sendPhoneVerificationCode(e,{phoneNumber:f.phoneNumber,recaptchaToken:d});return i}}finally{s._reset()}}IndexedDBLocalPersistence.type="LOCAL",_generateCallbackName("rcb"),new Delay(3e4,6e4);/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let PhoneAuthProvider=class PhoneAuthProvider{constructor(e){this.providerId=PhoneAuthProvider.PROVIDER_ID,this.auth=_castAuth(e)}verifyPhoneNumber(e,i){return _verifyPhoneNumber(this.auth,e,(0,h.m9)(i))}static credential(e,i){return PhoneAuthCredential._fromVerification(e,i)}static credentialFromResult(e){return PhoneAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return PhoneAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{phoneNumber:i,temporaryProof:s}=e;return i&&s?PhoneAuthCredential._fromTokenResponse(i,s):null}};PhoneAuthProvider.PROVIDER_ID="phone",PhoneAuthProvider.PHONE_SIGN_IN_METHOD="phone";/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let IdpCredential=class IdpCredential extends AuthCredential{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return signInWithIdp(e,this._buildIdpRequest())}_linkToIdToken(e,i){return signInWithIdp(e,this._buildIdpRequest(i))}_getReauthenticationResolver(e){return signInWithIdp(e,this._buildIdpRequest())}_buildIdpRequest(e){let i={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&&(i.idToken=e),i}};function _signIn(e){return _signInWithCredential(e.auth,new IdpCredential(e),e.bypassAuthState)}function _reauth(e){let{auth:i,user:s}=e;return _assert(s,i,"internal-error"),_reauthenticate(s,new IdpCredential(e),e.bypassAuthState)}async function _link(e){let{auth:i,user:s}=e;return _assert(s,i,"internal-error"),_link$1(s,new IdpCredential(e),e.bypassAuthState)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let AbstractPopupRedirectOperation=class AbstractPopupRedirectOperation{constructor(e,i,s,o,l=!1){this.auth=e,this.resolver=s,this.user=o,this.bypassAuthState=l,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(i)?i:[i]}execute(){return new Promise(async(e,i)=>{this.pendingPromise={resolve:e,reject:i};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){let{urlResponse:i,sessionId:s,postBody:o,tenantId:l,error:h,type:d}=e;if(h){this.reject(h);return}let f={auth:this.auth,requestUri:i,sessionId:s,tenantId:l||void 0,postBody:o||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(d)(f))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return _signIn;case"linkViaPopup":case"linkViaRedirect":return _link;case"reauthViaPopup":case"reauthViaRedirect":return _reauth;default:_fail(this.auth,"internal-error")}}resolve(e){this.pendingPromise||debugFail("Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){this.pendingPromise||debugFail("Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ei=new Delay(2e3,1e4);let PopupOperation=class PopupOperation extends AbstractPopupRedirectOperation{constructor(e,i,s,o,l){super(e,i,o,l),this.provider=s,this.authWindow=null,this.pollId=null,PopupOperation.currentPopupAction&&PopupOperation.currentPopupAction.cancel(),PopupOperation.currentPopupAction=this}async executeNotNull(){let e=await this.execute();return _assert(e,this.auth,"internal-error"),e}async onExecution(){1===this.filter.length||debugFail("Popup operations only handle one event");let e=_generateEventId();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(_createError(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(_createError(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,PopupOperation.currentPopupAction=null}pollUserCancellation(){let poll=()=>{var e,i;if(null===(i=null===(e=this.authWindow)||void 0===e?void 0:e.window)||void 0===i?void 0:i.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(_createError(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(poll,ei.get())};poll()}};PopupOperation.currentPopupAction=null;let es=new Map;let RedirectAction=class RedirectAction extends AbstractPopupRedirectOperation{constructor(e,i,s=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],i,void 0,s),this.eventId=null}async execute(){let e=es.get(this.auth._key());if(!e){try{let i=await _getAndClearPendingRedirectStatus(this.resolver,this.auth),s=i?await super.execute():null;e=()=>Promise.resolve(s)}catch(i){e=()=>Promise.reject(i)}es.set(this.auth._key(),e)}return this.bypassAuthState||es.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"===e.type){this.resolve(null);return}if(e.eventId){let i=await this.auth._redirectUserForId(e.eventId);if(i)return this.user=i,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}};async function _getAndClearPendingRedirectStatus(e,i){let s=_persistenceKeyName("pendingRedirect",i.config.apiKey,i.name),o=_getInstance(e._redirectPersistence);if(!await o._isAvailable())return!1;let l=await o._get(s)==="true";return await o._remove(s),l}function _overrideRedirectResult(e,i){es.set(e._key(),i)}async function _getRedirectResult(e,i,s=!1){if((0,l.rh)(e.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e));let o=_castAuth(e),h=i?_getInstance(i):(_assert(o._popupRedirectResolver,o,"argument-error"),o._popupRedirectResolver),d=new RedirectAction(o,h,s),f=await d.execute();return f&&!s&&(delete f.user._redirectEventId,await o._persistUserIfCurrent(f.user),await o._setRedirectUser(null,i)),f}let AuthEventManager=class AuthEventManager{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 i=!1;return this.consumers.forEach(s=>{this.isEventForConsumer(e,s)&&(i=!0,this.sendToConsumer(e,s),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return isNullRedirectEvent(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,i||(this.queuedRedirectEvent=e,i=!0)),i}sendToConsumer(e,i){var s;if(e.error&&!isNullRedirectEvent(e)){let o=(null===(s=e.error.code)||void 0===s?void 0:s.split("auth/")[1])||"internal-error";i.onError(_createError(this.auth,o))}else i.onAuthEvent(e)}isEventForConsumer(e,i){let s=null===i.eventId||!!e.eventId&&e.eventId===i.eventId;return i.filter.includes(e.type)&&s}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(eventUid(e))}saveEventToCache(e){this.cachedEventUids.add(eventUid(e)),this.lastProcessedEventTime=Date.now()}};function eventUid(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function isNullRedirectEvent({type:e,error:i}){return"unknown"===e&&(null==i?void 0:i.code)==="auth/no-auth-event"}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function _getProjectConfig(e,i={}){return _performApiRequest(e,"GET","/v1/projects",i)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ea=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,eo=/^https?/;async function _validateOrigin(e){if(e.config.emulator)return;let{authorizedDomains:i}=await _getProjectConfig(e);for(let e of i)try{if(function(e){let i=_getCurrentUrl(),{protocol:s,hostname:o}=new URL(i);if(e.startsWith("chrome-extension://")){let l=new URL(e);return""===l.hostname&&""===o?"chrome-extension:"===s&&e.replace("chrome-extension://","")===i.replace("chrome-extension://",""):"chrome-extension:"===s&&l.hostname===o}if(!eo.test(s))return!1;if(ea.test(e))return o===e;let l=e.replace(/\./g,"\\."),h=RegExp("^(.+\\."+l+"|"+l+")$","i");return h.test(o)}(e))return}catch(e){}_fail(e,"unauthorized-domain")}/**
 * @license
 * Copyright 2020 Google LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let el=new Delay(3e4,6e4);function resetUnloadedGapiModules(){let e=_window().___jsl;if(null==e?void 0:e.H){for(let i of Object.keys(e.H))if(e.H[i].r=e.H[i].r||[],e.H[i].L=e.H[i].L||[],e.H[i].r=[...e.H[i].L],e.CP)for(let i=0;i<e.CP.length;i++)e.CP[i]=null}}let eu=null,eh=new Delay(5e3,15e3),ef={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},e_=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function _openIframe(e){let i=await (eu=eu||new Promise((i,s)=>{var o,l,h,d;function loadGapiIframe(){resetUnloadedGapiModules(),gapi.load("gapi.iframes",{callback:()=>{i(gapi.iframes.getContext())},ontimeout:()=>{resetUnloadedGapiModules(),s(_createError(e,"network-request-failed"))},timeout:el.get()})}if(null===(l=null===(o=_window().gapi)||void 0===o?void 0:o.iframes)||void 0===l?void 0:l.Iframe)i(gapi.iframes.getContext());else if(null===(h=_window().gapi)||void 0===h?void 0:h.load)loadGapiIframe();else{let i=_generateCallbackName("iframefcb");return _window()[i]=()=>{gapi.load?loadGapiIframe():s(_createError(e,"network-request-failed"))},(d=`${j.gapiScript}?onload=${i}`,j.loadJS(d)).catch(e=>s(e))}}).catch(e=>{throw eu=null,e})),s=_window().gapi;return _assert(s,e,"internal-error"),i.open({where:document.body,url:function(e){let i=e.config;_assert(i.authDomain,e,"auth-domain-config-required");let s=i.emulator?_emulatorUrl(i,"emulator/auth/iframe"):`https://${e.config.authDomain}/__/auth/iframe`,o={apiKey:i.apiKey,appName:e.name,v:l.Jn},d=e_.get(e.config.apiHost);d&&(o.eid=d);let f=e._getFrameworks();return f.length&&(o.fw=f.join(",")),`${s}?${(0,h.xO)(o).slice(1)}`}(e),messageHandlersFilter:s.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:ef,dontclear:!0},i=>new Promise(async(s,o)=>{await i.restyle({setHideOnLeave:!1});let l=_createError(e,"network-request-failed"),h=_window().setTimeout(()=>{o(l)},eh.get());function clearTimerAndResolve(){_window().clearTimeout(h),s(i)}i.ping(clearTimerAndResolve).then(clearTimerAndResolve,()=>{o(l)})}))}/**
 * @license
 * Copyright 2020 Google LLC.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ep={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};let AuthPopup=class AuthPopup{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}};let em=encodeURIComponent("fac");async function _getRedirectUrl(e,i,s,o,d,f){_assert(e.config.authDomain,e,"auth-domain-config-required"),_assert(e.config.apiKey,e,"invalid-api-key");let _={apiKey:e.config.apiKey,appName:e.name,authType:s,redirectUrl:o,v:l.Jn,eventId:d};if(i instanceof FederatedAuthProvider)for(let[s,o]of(i.setDefaultLanguage(e.languageCode),_.providerId=i.providerId||"",(0,h.xb)(i.getCustomParameters())||(_.customParameters=JSON.stringify(i.getCustomParameters())),Object.entries(f||{})))_[s]=o;if(i instanceof BaseOAuthProvider){let e=i.getScopes().filter(e=>""!==e);e.length>0&&(_.scopes=e.join(","))}for(let i of(e.tenantId&&(_.tid=e.tenantId),Object.keys(_)))void 0===_[i]&&delete _[i];let g=await e._getAppCheckToken(),b=g?`#${em}=${encodeURIComponent(g)}`:"";return`${function({config:e}){return e.emulator?_emulatorUrl(e,"emulator/auth/handler"):`https://${e.authDomain}/__/auth/handler`}(e)}?${(0,h.xO)(_).slice(1)}${b}`}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let eg="webStorageSupport",ey=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=BrowserSessionPersistence,this._completeRedirectFn=_getRedirectResult,this._overrideRedirectResult=_overrideRedirectResult}async _openPopup(e,i,s,o){var l;(null===(l=this.eventManagers[e._key()])||void 0===l?void 0:l.manager)||debugFail("_initialize() not called before _openPopup()");let d=await _getRedirectUrl(e,i,s,_getCurrentUrl(),o);return function(e,i,s,o=500,l=600){let d=Math.max((window.screen.availHeight-l)/2,0).toString(),f=Math.max((window.screen.availWidth-o)/2,0).toString(),_="",g=Object.assign(Object.assign({},ep),{width:o.toString(),height:l.toString(),top:d,left:f}),b=(0,h.z$)().toLowerCase();s&&(_=_isChromeIOS(b)?"_blank":s),_isFirefox(b)&&(i=i||"http://localhost",g.scrollbars="yes");let w=Object.entries(g).reduce((e,[i,s])=>`${e}${i}=${s},`,"");if(function(e=(0,h.z$)()){var i;return _isIOS(e)&&!!(null===(i=window.navigator)||void 0===i?void 0:i.standalone)}(b)&&"_self"!==_)return function(e,i){let s=document.createElement("a");s.href=e,s.target=i;let o=document.createEvent("MouseEvent");o.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),s.dispatchEvent(o)}(i||"",_),new AuthPopup(null);let k=window.open(i||"",_,w);_assert(k,e,"popup-blocked");try{k.focus()}catch(e){}return new AuthPopup(k)}(e,d,_generateEventId())}async _openRedirect(e,i,s,o){await this._originValidation(e);let l=await _getRedirectUrl(e,i,s,_getCurrentUrl(),o);return _window().location.href=l,new Promise(()=>{})}_initialize(e){let i=e._key();if(this.eventManagers[i]){let{manager:e,promise:s}=this.eventManagers[i];return e?Promise.resolve(e):(s||debugFail("If manager is not set, promise should be"),s)}let s=this.initAndGetManager(e);return this.eventManagers[i]={promise:s},s.catch(()=>{delete this.eventManagers[i]}),s}async initAndGetManager(e){let i=await _openIframe(e),s=new AuthEventManager(e);return i.register("authEvent",i=>{_assert(null==i?void 0:i.authEvent,e,"invalid-auth-event");let o=s.onEvent(i.authEvent);return{status:o?"ACK":"ERROR"}},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:s},this.iframes[e._key()]=i,s}_isIframeWebStorageSupported(e,i){let s=this.iframes[e._key()];s.send(eg,{type:eg},s=>{var o;let l=null===(o=null==s?void 0:s[0])||void 0===o?void 0:o[eg];void 0!==l&&i(!!l),_fail(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){let i=e._key();return this.originValidationPromises[i]||(this.originValidationPromises[i]=_validateOrigin(e)),this.originValidationPromises[i]}get _shouldInitProactively(){return _isMobileBrowser()||_isSafari()||_isIOS()}};let MultiFactorAssertionImpl=class MultiFactorAssertionImpl{constructor(e){this.factorId=e}_process(e,i,s){switch(i.type){case"enroll":return this._finalizeEnroll(e,i.credential,s);case"signin":return this._finalizeSignIn(e,i.credential);default:return debugFail("unexpected MultiFactorSessionType")}}};let PhoneMultiFactorAssertionImpl=class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new PhoneMultiFactorAssertionImpl(e)}_finalizeEnroll(e,i,s){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,{idToken:i,displayName:s,phoneVerificationInfo:this.credential._makeVerificationRequest()}))}_finalizeSignIn(e,i){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,{mfaPendingCredential:i,phoneVerificationInfo:this.credential._makeVerificationRequest()}))}};let TotpMultiFactorAssertionImpl=class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e,i,s){super("totp"),this.otp=e,this.enrollmentId=i,this.secret=s}static _fromSecret(e,i){return new TotpMultiFactorAssertionImpl(i,void 0,e)}static _fromEnrollmentId(e,i){return new TotpMultiFactorAssertionImpl(i,e)}async _finalizeEnroll(e,i,s){return _assert(void 0!==this.secret,e,"argument-error"),_performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,{idToken:i,displayName:s,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)}))}async _finalizeSignIn(e,i){_assert(void 0!==this.enrollmentId&&void 0!==this.otp,e,"argument-error");let s={verificationCode:this.otp};return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,{mfaPendingCredential:i,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:s}))}};let TotpSecret=class TotpSecret{constructor(e,i,s,o,l,h,d){this.sessionInfo=h,this.auth=d,this.secretKey=e,this.hashingAlgorithm=i,this.codeLength=s,this.codeIntervalSeconds=o,this.enrollmentCompletionDeadline=l}static _fromStartTotpMfaEnrollmentResponse(e,i){return new TotpSecret(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,i)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,i){var s;let o=!1;return(_isEmptyString(e)||_isEmptyString(i))&&(o=!0),o&&(_isEmptyString(e)&&(e=(null===(s=this.auth.currentUser)||void 0===s?void 0:s.email)||"unknownuser"),_isEmptyString(i)&&(i=this.auth.name)),`otpauth://totp/${i}:${e}?secret=${this.secretKey}&issuer=${i}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}};function _isEmptyString(e){return void 0===e||(null==e?void 0:e.length)===0}var eE="@firebase/auth",ev="1.7.9";/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let AuthInterop=class AuthInterop{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){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;let i=await this.auth.currentUser.getIdToken(e);return{accessToken:i}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;let i=this.auth.onIdTokenChanged(i=>{e((null==i?void 0:i.stsTokenManager.accessToken)||null)});this.internalListeners.set(e,i),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let i=this.internalListeners.get(e);i&&(this.internalListeners.delete(e),i(),this.updateProactiveRefresh())}assertAuthConfigured(){_assert(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}};let eT=(0,h.Pz)("authIdTokenMaxAge")||300,eI=null,mintCookieFactory=e=>async i=>{let s=i&&await i.getIdTokenResult(),o=s&&(new Date().getTime()-Date.parse(s.issuedAtTime))/1e3;if(o&&o>eT)return;let l=null==s?void 0:s.token;eI!==l&&(eI=l,await fetch(e,{method:l?"POST":"DELETE",headers:l?{Authorization:`Bearer ${l}`}:{}}))};function getAuth(e=(0,l.Mq)()){let i=(0,l.qX)(e,"auth");if(i.isInitialized())return i.getImmediate();let s=/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function(e,i){let s=(0,l.qX)(e,"auth");if(s.isInitialized()){let e=s.getImmediate(),o=s.getOptions();if((0,h.vZ)(o,null!=i?i:{}))return e;_fail(e,"already-initialized")}let o=s.initialize({options:i});return o}(e,{popupRedirectResolver:ey,persistence:[IndexedDBLocalPersistence,ee,BrowserSessionPersistence]}),o=(0,h.Pz)("authTokenSyncURL");if(o&&"boolean"==typeof isSecureContext&&isSecureContext){let e=new URL(o,location.origin);if(location.origin===e.origin){let i=mintCookieFactory(e.toString());(0,h.m9)(s).beforeAuthStateChanged(i,()=>i(s.currentUser)),(0,h.m9)(s).onIdTokenChanged(e=>i(e),void 0,void 0)}}let d=(0,h.q4)("auth");return d&&function(e,i,s){let o=_castAuth(e);_assert(o._canInitEmulator,o,"emulator-config-failed"),_assert(/^https?:\/\//.test(i),o,"invalid-emulator-scheme");let l=!!(null==s?void 0:s.disableWarnings),h=extractProtocol(i),{host:d,port:f}=function(e){let i=extractProtocol(e),s=/(\/\/)?([^?#/]+)/.exec(e.substr(i.length));if(!s)return{host:"",port:null};let o=s[2].split("@").pop()||"",l=/^(\[[^\]]+\])(:|$)/.exec(o);if(l){let e=l[1];return{host:e,port:parsePort(o.substr(e.length+1))}}{let[e,i]=o.split(":");return{host:e,port:parsePort(i)}}}(i),_=null===f?"":`:${f}`;o.config.emulator={url:`${h}//${d}${_}/`},o.settings.appVerificationDisabledForTesting=!0,o.emulatorConfig=Object.freeze({host:d,port:f,protocol:h.replace(":",""),options:Object.freeze({disableWarnings:l})}),l||function(){function attachBanner(){let e=document.createElement("p"),i=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",i.position="fixed",i.width="100%",i.backgroundColor="#ffffff",i.border=".1em solid #000000",i.color="#b50000",i.bottom="0px",i.left="0px",i.margin="0px",i.zIndex="10000",i.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",attachBanner):attachBanner())}()}(s,`http://${d}`),s}j={loadJS:e=>new Promise((i,s)=>{var o,l;let h=document.createElement("script");h.setAttribute("src",e),h.onload=i,h.onerror=e=>{let i=_createError("internal-error");i.customData=e,s(i)},h.type="text/javascript",h.charset="UTF-8",(null!==(l=null===(o=document.getElementsByTagName("head"))||void 0===o?void 0:o[0])&&void 0!==l?l:document).appendChild(h)}),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="},o="Browser",(0,l.Xd)(new _.wA("auth",(e,{options:i})=>{let s=e.getProvider("app").getImmediate(),l=e.getProvider("heartbeat"),h=e.getProvider("app-check-internal"),{apiKey:d,authDomain:f}=s.options;_assert(d&&!d.includes(":"),"invalid-api-key",{appName:s.name});let _={apiKey:d,authDomain:f,clientPlatform:o,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:_getClientVersion(o)},g=new AuthImpl(s,l,h,_);return function(e,i){let s=(null==i?void 0:i.persistence)||[],o=(Array.isArray(s)?s:[s]).map(_getInstance);(null==i?void 0:i.errorMap)&&e._updateErrorMap(i.errorMap),e._initializeWithPersistence(o,null==i?void 0:i.popupRedirectResolver)}(g,i),g},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,i,s)=>{let o=e.getProvider("auth-internal");o.initialize()})),(0,l.Xd)(new _.wA("auth-internal",e=>{let i=_castAuth(e.getProvider("auth").getImmediate());return new AuthInterop(i)},"PRIVATE").setInstantiationMode("EXPLICIT")),(0,l.KN)(eE,ev,/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */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}}(o)),(0,l.KN)(eE,ev,"esm2017")},2793:function(e,i,s){"use strict";s.d(i,{ET:function(){return addDoc},hJ:function(){return collection},oe:function(){return deleteDoc},JU:function(){return doc},QT:function(){return getDoc},PL:function(){return getDocs},ad:function(){return getFirestore},Bt:function(){return serverTimestamp},r7:function(){return updateDoc},qs:function(){return writeBatch}});var o,l,h,d,f,_,g,b,w,k,O,j,q,$,ee=s(5816),et=s(8463),er=s(3333),en=s(4444),ei="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},es={};(function(){function m(){this.blockSize=-1,this.blockSize=64,this.g=[,,,,],this.B=Array(this.blockSize),this.o=this.h=0,this.s()}function n(e,i,s){s||(s=0);var o=Array(16);if("string"==typeof i)for(var l=0;16>l;++l)o[l]=i.charCodeAt(s++)|i.charCodeAt(s++)<<8|i.charCodeAt(s++)<<16|i.charCodeAt(s++)<<24;else for(l=0;16>l;++l)o[l]=i[s++]|i[s++]<<8|i[s++]<<16|i[s++]<<24;i=e.g[0],s=e.g[1],l=e.g[2];var h=e.g[3],d=i+(h^s&(l^h))+o[0]+3614090360&4294967295;d=h+(l^(i=s+(d<<7&4294967295|d>>>25))&(s^l))+o[1]+3905402710&4294967295,d=l+(s^(h=i+(d<<12&4294967295|d>>>20))&(i^s))+o[2]+606105819&4294967295,d=s+(i^(l=h+(d<<17&4294967295|d>>>15))&(h^i))+o[3]+3250441966&4294967295,d=i+(h^(s=l+(d<<22&4294967295|d>>>10))&(l^h))+o[4]+4118548399&4294967295,d=h+(l^(i=s+(d<<7&4294967295|d>>>25))&(s^l))+o[5]+1200080426&4294967295,d=l+(s^(h=i+(d<<12&4294967295|d>>>20))&(i^s))+o[6]+2821735955&4294967295,d=s+(i^(l=h+(d<<17&4294967295|d>>>15))&(h^i))+o[7]+4249261313&4294967295,d=i+(h^(s=l+(d<<22&4294967295|d>>>10))&(l^h))+o[8]+1770035416&4294967295,d=h+(l^(i=s+(d<<7&4294967295|d>>>25))&(s^l))+o[9]+2336552879&4294967295,d=l+(s^(h=i+(d<<12&4294967295|d>>>20))&(i^s))+o[10]+4294925233&4294967295,d=s+(i^(l=h+(d<<17&4294967295|d>>>15))&(h^i))+o[11]+2304563134&4294967295,d=i+(h^(s=l+(d<<22&4294967295|d>>>10))&(l^h))+o[12]+1804603682&4294967295,d=h+(l^(i=s+(d<<7&4294967295|d>>>25))&(s^l))+o[13]+4254626195&4294967295,d=l+(s^(h=i+(d<<12&4294967295|d>>>20))&(i^s))+o[14]+2792965006&4294967295,d=s+(i^(l=h+(d<<17&4294967295|d>>>15))&(h^i))+o[15]+1236535329&4294967295,s=l+(d<<22&4294967295|d>>>10),d=i+(l^h&(s^l))+o[1]+4129170786&4294967295,i=s+(d<<5&4294967295|d>>>27),d=h+(s^l&(i^s))+o[6]+3225465664&4294967295,h=i+(d<<9&4294967295|d>>>23),d=l+(i^s&(h^i))+o[11]+643717713&4294967295,l=h+(d<<14&4294967295|d>>>18),d=s+(h^i&(l^h))+o[0]+3921069994&4294967295,s=l+(d<<20&4294967295|d>>>12),d=i+(l^h&(s^l))+o[5]+3593408605&4294967295,i=s+(d<<5&4294967295|d>>>27),d=h+(s^l&(i^s))+o[10]+38016083&4294967295,h=i+(d<<9&4294967295|d>>>23),d=l+(i^s&(h^i))+o[15]+3634488961&4294967295,l=h+(d<<14&4294967295|d>>>18),d=s+(h^i&(l^h))+o[4]+3889429448&4294967295,s=l+(d<<20&4294967295|d>>>12),d=i+(l^h&(s^l))+o[9]+568446438&4294967295,i=s+(d<<5&4294967295|d>>>27),d=h+(s^l&(i^s))+o[14]+3275163606&4294967295,h=i+(d<<9&4294967295|d>>>23),d=l+(i^s&(h^i))+o[3]+4107603335&4294967295,l=h+(d<<14&4294967295|d>>>18),d=s+(h^i&(l^h))+o[8]+1163531501&4294967295,s=l+(d<<20&4294967295|d>>>12),d=i+(l^h&(s^l))+o[13]+2850285829&4294967295,i=s+(d<<5&4294967295|d>>>27),d=h+(s^l&(i^s))+o[2]+4243563512&4294967295,h=i+(d<<9&4294967295|d>>>23),d=l+(i^s&(h^i))+o[7]+1735328473&4294967295,l=h+(d<<14&4294967295|d>>>18),d=s+(h^i&(l^h))+o[12]+2368359562&4294967295,d=i+((s=l+(d<<20&4294967295|d>>>12))^l^h)+o[5]+4294588738&4294967295,d=h+((i=s+(d<<4&4294967295|d>>>28))^s^l)+o[8]+2272392833&4294967295,d=l+((h=i+(d<<11&4294967295|d>>>21))^i^s)+o[11]+1839030562&4294967295,d=s+((l=h+(d<<16&4294967295|d>>>16))^h^i)+o[14]+4259657740&4294967295,d=i+((s=l+(d<<23&4294967295|d>>>9))^l^h)+o[1]+2763975236&4294967295,d=h+((i=s+(d<<4&4294967295|d>>>28))^s^l)+o[4]+1272893353&4294967295,d=l+((h=i+(d<<11&4294967295|d>>>21))^i^s)+o[7]+4139469664&4294967295,d=s+((l=h+(d<<16&4294967295|d>>>16))^h^i)+o[10]+3200236656&4294967295,d=i+((s=l+(d<<23&4294967295|d>>>9))^l^h)+o[13]+681279174&4294967295,d=h+((i=s+(d<<4&4294967295|d>>>28))^s^l)+o[0]+3936430074&4294967295,d=l+((h=i+(d<<11&4294967295|d>>>21))^i^s)+o[3]+3572445317&4294967295,d=s+((l=h+(d<<16&4294967295|d>>>16))^h^i)+o[6]+76029189&4294967295,d=i+((s=l+(d<<23&4294967295|d>>>9))^l^h)+o[9]+3654602809&4294967295,d=h+((i=s+(d<<4&4294967295|d>>>28))^s^l)+o[12]+3873151461&4294967295,d=l+((h=i+(d<<11&4294967295|d>>>21))^i^s)+o[15]+530742520&4294967295,d=s+((l=h+(d<<16&4294967295|d>>>16))^h^i)+o[2]+3299628645&4294967295,s=l+(d<<23&4294967295|d>>>9),d=i+(l^(s|~h))+o[0]+4096336452&4294967295,i=s+(d<<6&4294967295|d>>>26),d=h+(s^(i|~l))+o[7]+1126891415&4294967295,h=i+(d<<10&4294967295|d>>>22),d=l+(i^(h|~s))+o[14]+2878612391&4294967295,l=h+(d<<15&4294967295|d>>>17),d=s+(h^(l|~i))+o[5]+4237533241&4294967295,s=l+(d<<21&4294967295|d>>>11),d=i+(l^(s|~h))+o[12]+1700485571&4294967295,i=s+(d<<6&4294967295|d>>>26),d=h+(s^(i|~l))+o[3]+2399980690&4294967295,h=i+(d<<10&4294967295|d>>>22),d=l+(i^(h|~s))+o[10]+4293915773&4294967295,l=h+(d<<15&4294967295|d>>>17),d=s+(h^(l|~i))+o[1]+2240044497&4294967295,s=l+(d<<21&4294967295|d>>>11),d=i+(l^(s|~h))+o[8]+1873313359&4294967295,i=s+(d<<6&4294967295|d>>>26),d=h+(s^(i|~l))+o[15]+4264355552&4294967295,h=i+(d<<10&4294967295|d>>>22),d=l+(i^(h|~s))+o[6]+2734768916&4294967295,l=h+(d<<15&4294967295|d>>>17),d=s+(h^(l|~i))+o[13]+1309151649&4294967295,s=l+(d<<21&4294967295|d>>>11),d=i+(l^(s|~h))+o[4]+4149444226&4294967295,i=s+(d<<6&4294967295|d>>>26),d=h+(s^(i|~l))+o[11]+3174756917&4294967295,h=i+(d<<10&4294967295|d>>>22),d=l+(i^(h|~s))+o[2]+718787259&4294967295,l=h+(d<<15&4294967295|d>>>17),d=s+(h^(l|~i))+o[9]+3951481745&4294967295,e.g[0]=e.g[0]+i&4294967295,e.g[1]=e.g[1]+(l+(d<<21&4294967295|d>>>11))&4294967295,e.g[2]=e.g[2]+l&4294967295,e.g[3]=e.g[3]+h&4294967295}function t(e,i){this.h=i;for(var s=[],o=!0,l=e.length-1;0<=l;l--){var h=0|e[l];o&&h==i||(s[l]=h,o=!1)}this.g=s}!function(e,i){function c(){}c.prototype=i.prototype,e.D=i.prototype,e.prototype=new c,e.prototype.constructor=e,e.C=function(e,s,o){for(var l=Array(arguments.length-2),h=2;h<arguments.length;h++)l[h-2]=arguments[h];return i.prototype[s].apply(e,l)}}(m,function(){this.blockSize=-1}),m.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},m.prototype.u=function(e,i){void 0===i&&(i=e.length);for(var s=i-this.blockSize,o=this.B,l=this.h,h=0;h<i;){if(0==l)for(;h<=s;)n(this,e,h),h+=this.blockSize;if("string"==typeof e){for(;h<i;)if(o[l++]=e.charCodeAt(h++),l==this.blockSize){n(this,o),l=0;break}}else for(;h<i;)if(o[l++]=e[h++],l==this.blockSize){n(this,o),l=0;break}}this.h=l,this.o+=i},m.prototype.v=function(){var e=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var i=1;i<e.length-8;++i)e[i]=0;var s=8*this.o;for(i=e.length-8;i<e.length;++i)e[i]=255&s,s/=256;for(this.u(e),e=Array(16),i=s=0;4>i;++i)for(var o=0;32>o;o+=8)e[s++]=this.g[i]>>>o&255;return e};var e,i={};function u(e){return -128<=e&&128>e?Object.prototype.hasOwnProperty.call(i,e)?i[e]:i[e]=new t([0|e],0>e?-1:0):new t([0|e],0>e?-1:0)}function v(e){if(isNaN(e)||!isFinite(e))return s;if(0>e)return x(v(-e));for(var i=[],o=1,l=0;e>=o;l++)i[l]=e/o|0,o*=4294967296;return new t(i,0)}var s=u(0),h=u(1),d=u(16777216);function C(e){if(0!=e.h)return!1;for(var i=0;i<e.g.length;i++)if(0!=e.g[i])return!1;return!0}function B(e){return -1==e.h}function x(e){for(var i=e.g.length,s=[],o=0;o<i;o++)s[o]=~e.g[o];return new t(s,~e.h).add(h)}function F(e,i){return e.add(x(i))}function G(e,i){for(;(65535&e[i])!=e[i];)e[i+1]+=e[i]>>>16,e[i]&=65535,i++}function H(e,i){this.g=e,this.h=i}function D(e,i){if(C(i))throw Error("division by zero");if(C(e))return new H(s,s);if(B(e))return i=D(x(e),i),new H(x(i.g),x(i.h));if(B(i))return i=D(e,x(i)),new H(x(i.g),i.h);if(30<e.g.length){if(B(e)||B(i))throw Error("slowDivide_ only works with positive integers.");for(var o=h,l=i;0>=l.l(e);)o=I(o),l=I(l);var d=J(o,1),f=J(l,1);for(l=J(l,2),o=J(o,2);!C(l);){var _=f.add(l);0>=_.l(e)&&(d=d.add(o),f=_),l=J(l,1),o=J(o,1)}return i=F(e,d.j(i)),new H(d,i)}for(d=s;0<=e.l(i);){for(l=48>=(l=Math.ceil(Math.log(o=Math.max(1,Math.floor(e.m()/i.m())))/Math.LN2))?1:Math.pow(2,l-48),_=(f=v(o)).j(i);B(_)||0<_.l(e);)o-=l,_=(f=v(o)).j(i);C(f)&&(f=h),d=d.add(f),e=F(e,_)}return new H(d,e)}function I(e){for(var i=e.g.length+1,s=[],o=0;o<i;o++)s[o]=e.i(o)<<1|e.i(o-1)>>>31;return new t(s,e.h)}function J(e,i){var s=i>>5;i%=32;for(var o=e.g.length-s,l=[],h=0;h<o;h++)l[h]=0<i?e.i(h+s)>>>i|e.i(h+s+1)<<32-i:e.i(h+s);return new t(l,e.h)}(e=t.prototype).m=function(){if(B(this))return-x(this).m();for(var e=0,i=1,s=0;s<this.g.length;s++){var o=this.i(s);e+=(0<=o?o:4294967296+o)*i,i*=4294967296}return e},e.toString=function(e){if(2>(e=e||10)||36<e)throw Error("radix out of range: "+e);if(C(this))return"0";if(B(this))return"-"+x(this).toString(e);for(var i=v(Math.pow(e,6)),s=this,o="";;){var l=D(s,i).g,h=((0<(s=F(s,l.j(i))).g.length?s.g[0]:s.h)>>>0).toString(e);if(C(s=l))return h+o;for(;6>h.length;)h="0"+h;o=h+o}},e.i=function(e){return 0>e?0:e<this.g.length?this.g[e]:this.h},e.l=function(e){return B(e=F(this,e))?-1:C(e)?0:1},e.abs=function(){return B(this)?x(this):this},e.add=function(e){for(var i=Math.max(this.g.length,e.g.length),s=[],o=0,l=0;l<=i;l++){var h=o+(65535&this.i(l))+(65535&e.i(l)),d=(h>>>16)+(this.i(l)>>>16)+(e.i(l)>>>16);o=d>>>16,h&=65535,d&=65535,s[l]=d<<16|h}return new t(s,-2147483648&s[s.length-1]?-1:0)},e.j=function(e){if(C(this)||C(e))return s;if(B(this))return B(e)?x(this).j(x(e)):x(x(this).j(e));if(B(e))return x(this.j(x(e)));if(0>this.l(d)&&0>e.l(d))return v(this.m()*e.m());for(var i=this.g.length+e.g.length,o=[],l=0;l<2*i;l++)o[l]=0;for(l=0;l<this.g.length;l++)for(var h=0;h<e.g.length;h++){var f=this.i(l)>>>16,_=65535&this.i(l),g=e.i(h)>>>16,b=65535&e.i(h);o[2*l+2*h]+=_*b,G(o,2*l+2*h),o[2*l+2*h+1]+=f*b,G(o,2*l+2*h+1),o[2*l+2*h+1]+=_*g,G(o,2*l+2*h+1),o[2*l+2*h+2]+=f*g,G(o,2*l+2*h+2)}for(l=0;l<i;l++)o[l]=o[2*l+1]<<16|o[2*l];for(l=i;l<2*i;l++)o[l]=0;return new t(o,0)},e.A=function(e){return D(this,e).h},e.and=function(e){for(var i=Math.max(this.g.length,e.g.length),s=[],o=0;o<i;o++)s[o]=this.i(o)&e.i(o);return new t(s,this.h&e.h)},e.or=function(e){for(var i=Math.max(this.g.length,e.g.length),s=[],o=0;o<i;o++)s[o]=this.i(o)|e.i(o);return new t(s,this.h|e.h)},e.xor=function(e){for(var i=Math.max(this.g.length,e.g.length),s=[],o=0;o<i;o++)s[o]=this.i(o)^e.i(o);return new t(s,this.h^e.h)},m.prototype.digest=m.prototype.v,m.prototype.reset=m.prototype.s,m.prototype.update=m.prototype.u,l=es.Md5=m,t.prototype.add=t.prototype.add,t.prototype.multiply=t.prototype.j,t.prototype.modulo=t.prototype.A,t.prototype.compare=t.prototype.l,t.prototype.toNumber=t.prototype.m,t.prototype.toString=t.prototype.toString,t.prototype.getBits=t.prototype.i,t.fromNumber=v,t.fromString=function y(e,i){if(0==e.length)throw Error("number format error: empty string");if(2>(i=i||10)||36<i)throw Error("radix out of range: "+i);if("-"==e.charAt(0))return x(y(e.substring(1),i));if(0<=e.indexOf("-"))throw Error('number format error: interior "-" character');for(var o=v(Math.pow(i,8)),l=s,h=0;h<e.length;h+=8){var d=Math.min(8,e.length-h),f=parseInt(e.substring(h,h+d),i);8>d?(d=v(Math.pow(i,d)),l=l.j(d).add(v(f))):l=(l=l.j(o)).add(v(f))}return l},o=es.Integer=t}).apply(void 0!==ei?ei:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});var ea="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},eo={};(function(){var e,i,s,o="function"==typeof Object.defineProperties?Object.defineProperty:function(e,i,s){return e==Array.prototype||e==Object.prototype||(e[i]=s.value),e},l=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof ea&&ea];for(var i=0;i<e.length;++i){var s=e[i];if(s&&s.Math==Math)return s}throw Error("Cannot find global object")}(this);!function(e,i){if(i)e:{var s=l;e=e.split(".");for(var h=0;h<e.length-1;h++){var d=e[h];if(!(d in s))break e;s=s[d]}(i=i(h=s[e=e[e.length-1]]))!=h&&null!=i&&o(s,e,{configurable:!0,writable:!0,value:i})}}("Array.prototype.values",function(e){return e||function(){var e,i,s,o;return e=this,e instanceof String&&(e+=""),i=0,s=!1,(o={next:function(){if(!s&&i<e.length)return{value:e[i++],done:!1};return s=!0,{done:!0,value:void 0}}})[Symbol.iterator]=function(){return o},o}});var O=O||{},j=this||self;function ha(e){var i=typeof e;return"array"==(i="object"!=i?i:e?Array.isArray(e)?"array":i:"null")||"object"==i&&"number"==typeof e.length}function n(e){var i=typeof e;return"object"==i&&null!=e||"function"==i}function ia(e,i,s){return e.call.apply(e.bind,arguments)}function ja(e,i,s){if(!e)throw Error();if(2<arguments.length){var o=Array.prototype.slice.call(arguments,2);return function(){var s=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(s,o),e.apply(i,s)}}return function(){return e.apply(i,arguments)}}function p(e,i,s){return(p=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?ia:ja).apply(null,arguments)}function ka(e,i){var s=Array.prototype.slice.call(arguments,1);return function(){var i=s.slice();return i.push.apply(i,arguments),e.apply(this,i)}}function r(e,i){function c(){}c.prototype=i.prototype,e.aa=i.prototype,e.prototype=new c,e.prototype.constructor=e,e.Qb=function(e,s,o){for(var l=Array(arguments.length-2),h=2;h<arguments.length;h++)l[h-2]=arguments[h];return i.prototype[s].apply(e,l)}}function la(e){let i=e.length;if(0<i){let s=Array(i);for(let o=0;o<i;o++)s[o]=e[o];return s}return[]}function ma(e,i){for(let i=1;i<arguments.length;i++){let s=arguments[i];if(ha(s)){let i=e.length||0,o=s.length||0;e.length=i+o;for(let l=0;l<o;l++)e[i+l]=s[l]}else e.push(s)}}function t(e){return/^[\s\xa0]*$/.test(e)}function u(){var e=j.navigator;return e&&(e=e.userAgent)?e:""}function oa(e){return oa[" "](e),e}oa[" "]=function(){};var q=-1!=u().indexOf("Gecko")&&!(-1!=u().toLowerCase().indexOf("webkit")&&-1==u().indexOf("Edge"))&&!(-1!=u().indexOf("Trident")||-1!=u().indexOf("MSIE"))&&-1==u().indexOf("Edge");function qa(e,i,s){for(let o in e)i.call(s,e[o],o,e)}function sa(e){let i={};for(let s in e)i[s]=e[s];return i}let $="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function ua(e,i){let s,o;for(let i=1;i<arguments.length;i++){for(s in o=arguments[i])e[s]=o[s];for(let i=0;i<$.length;i++)s=$[i],Object.prototype.hasOwnProperty.call(o,s)&&(e[s]=o[s])}}var ee=new class{constructor(e,i){this.i=e,this.j=i,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new Ca,e=>e.reset());let Ca=class Ca{constructor(){this.next=this.g=this.h=null}set(e,i){this.h=e,this.g=i,this.next=null}reset(){this.next=this.g=this.h=null}};let et,er=!1,en=new class{constructor(){this.h=this.g=null}add(e,i){let s=ee.get();s.set(e,i),this.h?this.h.next=s:this.g=s,this.h=s}},Ea=()=>{let e=j.Promise.resolve(void 0);et=()=>{e.then(Da)}};var Da=()=>{let e;for(var i;e=null,en.g&&(e=en.g,en.g=en.g.next,en.g||(en.h=null),e.next=null),i=e;){try{i.h.call(i.g)}catch(e){!function(e){j.setTimeout(()=>{throw e},0)}(e)}ee.j(i),100>ee.h&&(ee.h++,i.next=ee.g,ee.g=i)}er=!1};function z(){this.s=this.s,this.C=this.C}function A(e,i){this.type=e,this.g=this.target=i,this.defaultPrevented=!1}z.prototype.s=!1,z.prototype.ma=function(){this.s||(this.s=!0,this.N())},z.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},A.prototype.h=function(){this.defaultPrevented=!0};var ei=function(){if(!j.addEventListener||!Object.defineProperty)return!1;var e=!1,i=Object.defineProperty({},"passive",{get:function(){e=!0}});try{let c=()=>{};j.addEventListener("test",c,i),j.removeEventListener("test",c,i)}catch(e){}return e}();function C(e,i){if(A.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var s=this.type=e.type,o=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=i,i=e.relatedTarget){if(q){e:{try{oa(i.nodeName);var l=!0;break e}catch(e){}l=!1}l||(i=null)}}else"mouseover"==s?i=e.fromElement:"mouseout"==s&&(i=e.toElement);this.relatedTarget=i,o?(this.clientX=void 0!==o.clientX?o.clientX:o.pageX,this.clientY=void 0!==o.clientY?o.clientY:o.pageY,this.screenX=o.screenX||0,this.screenY=o.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:es[e.pointerType]||"",this.state=e.state,this.i=e,e.defaultPrevented&&C.aa.h.call(this)}}r(C,A);var es={2:"touch",3:"pen",4:"mouse"};C.prototype.h=function(){C.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var el="closure_listenable_"+(1e6*Math.random()|0),eu=0;function Ia(e,i,s,o,l){this.listener=e,this.proxy=null,this.src=i,this.type=s,this.capture=!!o,this.ha=l,this.key=++eu,this.da=this.fa=!1}function Ja(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function Ka(e){this.src=e,this.g={},this.h=0}function Ma(e,i){var s=i.type;if(s in e.g){var o,l=e.g[s],h=Array.prototype.indexOf.call(l,i,void 0);(o=0<=h)&&Array.prototype.splice.call(l,h,1),o&&(Ja(i),0==e.g[s].length&&(delete e.g[s],e.h--))}}function La(e,i,s,o){for(var l=0;l<e.length;++l){var h=e[l];if(!h.da&&h.listener==i&&!!s==h.capture&&h.ha==o)return l}return -1}Ka.prototype.add=function(e,i,s,o,l){var h=e.toString();(e=this.g[h])||(e=this.g[h]=[],this.h++);var d=La(e,i,o,l);return -1<d?(i=e[d],s||(i.fa=!1)):((i=new Ia(i,this.src,h,!!o,l)).fa=s,e.push(i)),i};var eh="closure_lm_"+(1e6*Math.random()|0),ef={};function Ta(e,i,s,o,l,h){if(!i)throw Error("Invalid event type");var d=n(l)?!!l.capture:!!l,f=Ua(e);if(f||(e[eh]=f=new Ka(e)),(s=f.add(i,s,o,d,h)).proxy)return s;if(o=function a(e){return Xa.call(a.src,a.listener,e)},s.proxy=o,o.src=e,o.listener=s,e.addEventListener)ei||(l=d),void 0===l&&(l=!1),e.addEventListener(i.toString(),o,l);else if(e.attachEvent)e.attachEvent(Wa(i.toString()),o);else if(e.addListener&&e.removeListener)e.addListener(o);else throw Error("addEventListener and attachEvent are unavailable.");return s}function Za(e){if("number"!=typeof e&&e&&!e.da){var i=e.src;if(i&&i[el])Ma(i.i,e);else{var s=e.type,o=e.proxy;i.removeEventListener?i.removeEventListener(s,o,e.capture):i.detachEvent?i.detachEvent(Wa(s),o):i.addListener&&i.removeListener&&i.removeListener(o),(s=Ua(i))?(Ma(s,e),0==s.h&&(s.src=null,i[eh]=null)):Ja(e)}}}function Wa(e){return e in ef?ef[e]:ef[e]="on"+e}function Xa(e,i){if(e.da)e=!0;else{i=new C(i,this);var s=e.listener,o=e.ha||e.src;e.fa&&Za(e),e=s.call(o,i)}return e}function Ua(e){return(e=e[eh])instanceof Ka?e:null}var e_="__closure_events_fn_"+(1e9*Math.random()>>>0);function Sa(e){return"function"==typeof e?e:(e[e_]||(e[e_]=function(i){return e.handleEvent(i)}),e[e_])}function E(){z.call(this),this.i=new Ka(this),this.M=this,this.F=null}function F(e,i){var s,o=e.F;if(o)for(s=[];o;o=o.F)s.push(o);if(e=e.M,o=i.type||i,"string"==typeof i)i=new A(i,e);else if(i instanceof A)i.target=i.target||e;else{var l=i;ua(i=new A(o,e),l)}if(l=!0,s)for(var h=s.length-1;0<=h;h--){var d=i.g=s[h];l=ab(d,o,!0,i)&&l}if(l=ab(d=i.g=e,o,!0,i)&&l,l=ab(d,o,!1,i)&&l,s)for(h=0;h<s.length;h++)l=ab(d=i.g=s[h],o,!1,i)&&l}function ab(e,i,s,o){if(!(i=e.i.g[String(i)]))return!0;i=i.concat();for(var l=!0,h=0;h<i.length;++h){var d=i[h];if(d&&!d.da&&d.capture==s){var f=d.listener,_=d.ha||d.src;d.fa&&Ma(e.i,d),l=!1!==f.call(_,o)&&l}}return l&&!o.defaultPrevented}function bb(e,i,s){if("function"==typeof e)s&&(e=p(e,s));else if(e&&"function"==typeof e.handleEvent)e=p(e.handleEvent,e);else throw Error("Invalid listener argument");return 2147483647<Number(i)?-1:j.setTimeout(e,i||0)}r(E,z),E.prototype[el]=!0,E.prototype.removeEventListener=function(e,i,s,o){!function Ya(e,i,s,o,l){if(Array.isArray(i))for(var h=0;h<i.length;h++)Ya(e,i[h],s,o,l);else(o=n(o)?!!o.capture:!!o,s=Sa(s),e&&e[el])?(e=e.i,(i=String(i).toString())in e.g&&-1<(s=La(h=e.g[i],s,o,l))&&(Ja(h[s]),Array.prototype.splice.call(h,s,1),0==h.length&&(delete e.g[i],e.h--))):e&&(e=Ua(e))&&(i=e.g[i.toString()],e=-1,i&&(e=La(i,s,o,l)),(s=-1<e?i[e]:null)&&Za(s))}(this,e,i,s,o)},E.prototype.N=function(){if(E.aa.N.call(this),this.i){var e,i=this.i;for(e in i.g){for(var s=i.g[e],o=0;o<s.length;o++)Ja(s[o]);delete i.g[e],i.h--}}this.F=null},E.prototype.K=function(e,i,s,o){return this.i.add(String(e),i,!1,s,o)},E.prototype.L=function(e,i,s,o){return this.i.add(String(e),i,!0,s,o)};let eb=class eb extends z{constructor(e,i){super(),this.m=e,this.l=i,this.h=null,this.i=!1,this.g=null}j(e){this.h=arguments,this.g?this.i=!0:function cb(e){e.g=bb(()=>{e.g=null,e.i&&(e.i=!1,cb(e))},e.l);let i=e.h;e.h=null,e.m.apply(null,i)}(this)}N(){super.N(),this.g&&(j.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}};function G(e){z.call(this),this.h=e,this.g={}}r(G,z);var ep=[];function gb(e){qa(e.g,function(e,i){this.g.hasOwnProperty(i)&&Za(e)},e),e.g={}}G.prototype.N=function(){G.aa.N.call(this),gb(this)},G.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var em=j.JSON.stringify,eg=j.JSON.parse,ey=class{stringify(e){return j.JSON.stringify(e,void 0)}parse(e){return j.JSON.parse(e,void 0)}};function kb(){}function lb(e){return e.h||(e.h=e.i())}function mb(){}kb.prototype.h=null;var eE={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function nb(){A.call(this,"d")}function ob(){A.call(this,"c")}r(nb,A),r(ob,A);var ev={},eT=null;function qb(){return eT=eT||new E}function rb(e){A.call(this,ev.La,e)}function J(e){let i=qb();F(i,new rb(i))}function sb(e,i){A.call(this,ev.STAT_EVENT,e),this.stat=i}function K(e){let i=qb();F(i,new sb(i,e))}function tb(e,i){A.call(this,ev.Ma,e),this.size=i}function ub(e,i){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return j.setTimeout(function(){e()},i)}function vb(){this.g=!0}function L(e,i,s,o){e.info(function(){return"XMLHTTP TEXT ("+i+"): "+function(e,i){if(!e.g)return i;if(!i)return null;try{var s=JSON.parse(i);if(s){for(e=0;e<s.length;e++)if(Array.isArray(s[e])){var o=s[e];if(!(2>o.length)){var l=o[1];if(Array.isArray(l)&&!(1>l.length)){var h=l[0];if("noop"!=h&&"stop"!=h&&"close"!=h)for(var d=1;d<l.length;d++)l[d]=""}}}}return em(s)}catch(e){return i}}(e,s)+(o?" "+o:"")})}ev.La="serverreachability",r(rb,A),ev.STAT_EVENT="statevent",r(sb,A),ev.Ma="timingevent",r(tb,A),vb.prototype.xa=function(){this.g=!1},vb.prototype.info=function(){};var eI={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},eA={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function Db(){}function M(e,i,s,o){this.j=e,this.i=i,this.l=s,this.R=o||1,this.U=new G(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Eb}function Eb(){this.i=null,this.g="",this.h=!1}r(Db,kb),Db.prototype.g=function(){return new XMLHttpRequest},Db.prototype.i=function(){return{}},i=new Db;var eP={},eR={};function Hb(e,i,s){e.L=1,e.v=Ib(N(i)),e.m=s,e.P=!0,Jb(e,null)}function Jb(e,i){e.F=Date.now(),Kb(e),e.A=N(e.v);var s=e.A,o=e.R;Array.isArray(o)||(o=[String(o)]),Lb(s.i,"t",o),e.C=0,s=e.j.J,e.h=new Eb,e.g=Mb(e.j,s?i:null,!e.m),0<e.O&&(e.M=new eb(p(e.Y,e,e.g),e.O)),i=e.U,s=e.g,o=e.ca;var l="readystatechange";Array.isArray(l)||(l&&(ep[0]=l.toString()),l=ep);for(var h=0;h<l.length;h++){var d=function Qa(e,i,s,o,l){if(o&&o.once)return function Ra(e,i,s,o,l){if(Array.isArray(i)){for(var h=0;h<i.length;h++)Ra(e,i[h],s,o,l);return null}return s=Sa(s),e&&e[el]?e.L(i,s,n(o)?!!o.capture:!!o,l):Ta(e,i,s,!0,o,l)}(e,i,s,o,l);if(Array.isArray(i)){for(var h=0;h<i.length;h++)Qa(e,i[h],s,o,l);return null}return s=Sa(s),e&&e[el]?e.K(i,s,n(o)?!!o.capture:!!o,l):Ta(e,i,s,!1,o,l)}(s,l[h],o||i.handleEvent,!1,i.h||i);if(!d)break;i.g[d.key]=d}i=e.H?sa(e.H):{},e.m?(e.u||(e.u="POST"),i["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.m,i)):(e.u="GET",e.g.ea(e.A,e.u,null,i)),J(),function(e,i,s,o,l,h){e.info(function(){if(e.g){if(h)for(var d="",f=h.split("&"),_=0;_<f.length;_++){var g=f[_].split("=");if(1<g.length){var b=g[0];g=g[1];var w=b.split("_");d=2<=w.length&&"type"==w[1]?d+(b+"=")+g+"&":d+(b+"=redacted&")}}else d=null}else d=h;return"XMLHTTP REQ ("+o+") [attempt "+l+"]: "+i+"\n"+s+"\n"+d})}(e.i,e.u,e.A,e.l,e.R,e.m)}function Pb(e){return!!e.g&&"GET"==e.u&&2!=e.L&&e.j.Ca}function Kb(e){e.S=Date.now()+e.I,Wb(e,e.I)}function Wb(e,i){if(null!=e.B)throw Error("WatchDog timer not null");e.B=ub(p(e.ba,e),i)}function Ob(e){e.B&&(j.clearTimeout(e.B),e.B=null)}function Qb(e){0==e.j.G||e.J||Ub(e.j,e)}function Q(e){Ob(e);var i=e.M;i&&"function"==typeof i.ma&&i.ma(),e.M=null,gb(e.U),e.g&&(i=e.g,e.g=null,i.abort(),i.ma())}function Rb(e,i){try{var s=e.j;if(0!=s.G&&(s.g==e||Xb(s.h,e))){if(!e.K&&Xb(s.h,e)&&3==s.G){try{var o=s.Da.g.parse(i)}catch(e){o=null}if(Array.isArray(o)&&3==o.length){var l=o;if(0==l[0]){e:if(!s.u){if(s.g){if(s.g.F+3e3<e.F)Yb(s),Zb(s);else break e}$b(s),K(18)}}else s.za=l[1],0<s.za-s.T&&37500>l[2]&&s.F&&0==s.v&&!s.C&&(s.C=ub(p(s.Za,s),6e3));if(1>=ac(s.h)&&s.ca){try{s.ca()}catch(e){}s.ca=void 0}}else R(s,11)}else if((e.K||s.g==e)&&Yb(s),!t(i))for(l=s.Da.g.parse(i),i=0;i<l.length;i++){let f=l[i];if(s.T=f[0],f=f[1],2==s.G){if("c"==f[0]){s.K=f[1],s.ia=f[2];let i=f[3];null!=i&&(s.la=i,s.j.info("VER="+s.la));let l=f[4];null!=l&&(s.Aa=l,s.j.info("SVER="+s.Aa));let _=f[5];null!=_&&"number"==typeof _&&0<_&&(o=1.5*_,s.L=o,s.j.info("backChannelRequestTimeoutMs_="+o)),o=s;let g=e.g;if(g){let e=g.g?g.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(e){var h=o.h;h.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(h.j=h.l,h.g=new Set,h.h&&(bc(h,h.h),h.h=null))}if(o.D){let e=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(o.ya=e,S(o.I,o.D,e))}}if(s.G=3,s.l&&s.l.ua(),s.ba&&(s.R=Date.now()-e.F,s.j.info("Handshake RTT: "+s.R+"ms")),(o=s).qa=cc(o,o.J?o.ia:null,o.W),e.K){dc(o.h,e);var d=o.L;d&&(e.I=d),e.B&&(Ob(e),Kb(e)),o.g=e}else ec(o);0<s.i.length&&fc(s)}else"stop"!=f[0]&&"close"!=f[0]||R(s,7)}else 3==s.G&&("stop"==f[0]||"close"==f[0]?"stop"==f[0]?R(s,7):gc(s):"noop"!=f[0]&&s.l&&s.l.ta(f),s.v=0)}}J(4)}catch(e){}}M.prototype.ca=function(e){e=e.target;let i=this.M;i&&3==P(e)?i.j():this.Y(e)},M.prototype.Y=function(e){try{if(e==this.g)e:{let w=P(this.g);var i=this.g.Ba();let k=this.g.Z();if(!(3>w)&&(3!=w||this.g&&(this.h.h||this.g.oa()||Nb(this.g)))){this.J||4!=w||7==i||(8==i||0>=k?J(3):J(2)),Ob(this);var s=this.g.Z();this.X=s;t:if(Pb(this)){var o=Nb(this.g);e="";var l=o.length,h=4==P(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){Q(this),Qb(this);var d="";break t}this.h.i=new j.TextDecoder}for(i=0;i<l;i++)this.h.h=!0,e+=this.h.i.decode(o[i],{stream:!(h&&i==l-1)});o.length=0,this.h.g+=e,this.C=0,d=this.h.g}else d=this.g.oa();if(this.o=200==s,function(e,i,s,o,l,h,d){e.info(function(){return"XMLHTTP RESP ("+o+") [ attempt "+l+"]: "+i+"\n"+s+"\n"+h+" "+d})}(this.i,this.u,this.A,this.l,this.R,w,s),this.o){if(this.T&&!this.K){t:{if(this.g){var f,_=this.g;if((f=_.g?_.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!t(f)){var g=f;break t}}g=null}if(s=g)L(this.i,this.l,s,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Rb(this,s);else{this.o=!1,this.s=3,K(12),Q(this),Qb(this);break e}}if(this.P){let e;for(s=!0;!this.J&&this.C<d.length;)if((e=function(e,i){var s=e.C,o=i.indexOf("\n",s);return -1==o?eR:isNaN(s=Number(i.substring(s,o)))?eP:(o+=1)+s>i.length?eR:(i=i.slice(o,o+s),e.C=o+s,i)}(this,d))==eR){4==w&&(this.s=4,K(14),s=!1),L(this.i,this.l,null,"[Incomplete Response]");break}else if(e==eP){this.s=4,K(15),L(this.i,this.l,d,"[Invalid Chunk]"),s=!1;break}else L(this.i,this.l,e,null),Rb(this,e);if(Pb(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=w||0!=d.length||this.h.h||(this.s=1,K(16),s=!1),this.o=this.o&&s,s){if(0<d.length&&!this.W){this.W=!0;var b=this.j;b.g==this&&b.ba&&!b.M&&(b.j.info("Great, no buffering proxy detected. Bytes received: "+d.length),Tb(b),b.M=!0,K(11))}}else L(this.i,this.l,d,"[Invalid Chunked Response]"),Q(this),Qb(this)}else L(this.i,this.l,d,null),Rb(this,d);4==w&&Q(this),this.o&&!this.J&&(4==w?Ub(this.j,this):(this.o=!1,Kb(this)))}else(function(e){let i={};e=(e.g&&2<=P(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let o=0;o<e.length;o++){if(t(e[o]))continue;var s=function(e){var i=1;e=e.split(":");let s=[];for(;0<i&&e.length;)s.push(e.shift()),i--;return e.length&&s.push(e.join(":")),s}(e[o]);let l=s[0];if("string"!=typeof(s=s[1]))continue;s=s.trim();let h=i[l]||[];i[l]=h,h.push(s)}!function(e,i){for(let s in e)i.call(void 0,e[s],s,e)}(i,function(e){return e.join(", ")})})(this.g),400==s&&0<d.indexOf("Unknown SID")?(this.s=3,K(12)):(this.s=0,K(13)),Q(this),Qb(this)}}}catch(e){}finally{}},M.prototype.cancel=function(){this.J=!0,Q(this)},M.prototype.ba=function(){this.B=null;let e=Date.now();0<=e-this.S?(function(e,i){e.info(function(){return"TIMEOUT: "+i})}(this.i,this.A),2!=this.L&&(J(),K(17)),Q(this),this.s=2,Qb(this)):Wb(this,this.S-e)};var ew=class{constructor(e,i){this.g=e,this.map=i}};function ic(e){this.l=e||10,e=j.PerformanceNavigationTiming?0<(e=j.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(j.chrome&&j.chrome.loadTimes&&j.chrome.loadTimes()&&j.chrome.loadTimes().wasFetchedViaSpdy),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function jc(e){return!!e.h||!!e.g&&e.g.size>=e.j}function ac(e){return e.h?1:e.g?e.g.size:0}function Xb(e,i){return e.h?e.h==i:!!e.g&&e.g.has(i)}function bc(e,i){e.g?e.g.add(i):e.h=i}function dc(e,i){e.h&&e.h==i?e.h=null:e.g&&e.g.has(i)&&e.g.delete(i)}function kc(e){if(null!=e.h)return e.i.concat(e.h.D);if(null!=e.g&&0!==e.g.size){let i=e.i;for(let s of e.g.values())i=i.concat(s.D);return i}return la(e.i)}function nc(e,i){if(e.forEach&&"function"==typeof e.forEach)e.forEach(i,void 0);else if(ha(e)||"string"==typeof e)Array.prototype.forEach.call(e,i,void 0);else for(var s=function(e){if(e.na&&"function"==typeof e.na)return e.na();if(!e.V||"function"!=typeof e.V){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(ha(e)||"string"==typeof e){var i=[];e=e.length;for(var s=0;s<e;s++)i.push(s);return i}for(let o in i=[],s=0,e)i[s++]=o;return i}}}(e),o=function(e){if(e.V&&"function"==typeof e.V)return e.V();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(ha(e)){for(var i=[],s=e.length,o=0;o<s;o++)i.push(e[o]);return i}for(o in i=[],s=0,e)i[s++]=e[o];return i}(e),l=o.length,h=0;h<l;h++)i.call(void 0,o[h],s&&s[h],e)}ic.prototype.cancel=function(){if(this.i=kc(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(let e of this.g.values())e.cancel();this.g.clear()}};var eS=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function T(e){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof T){this.h=e.h,qc(this,e.j),this.o=e.o,this.g=e.g,rc(this,e.s),this.l=e.l;var i=e.i,s=new sc;s.i=i.i,i.g&&(s.g=new Map(i.g),s.h=i.h),tc(this,s),this.m=e.m}else e&&(i=String(e).match(eS))?(this.h=!1,qc(this,i[1]||"",!0),this.o=uc(i[2]||""),this.g=uc(i[3]||"",!0),rc(this,i[4]),this.l=uc(i[5]||"",!0),tc(this,i[6]||"",!0),this.m=uc(i[7]||"")):(this.h=!1,this.i=new sc(null,this.h))}function N(e){return new T(e)}function qc(e,i,s){e.j=s?uc(i,!0):i,e.j&&(e.j=e.j.replace(/:$/,""))}function rc(e,i){if(i){if(isNaN(i=Number(i))||0>i)throw Error("Bad port number "+i);e.s=i}else e.s=null}function tc(e,i,s){var o,l;i instanceof sc?(e.i=i,o=e.i,(l=e.h)&&!o.j&&(U(o),o.i=null,o.g.forEach(function(e,i){var s=i.toLowerCase();i!=s&&(Dc(this,i),Lb(this,s,e))},o)),o.j=l):(s||(i=vc(i,eD)),e.i=new sc(i,e.h))}function S(e,i,s){e.i.set(i,s)}function Ib(e){return S(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function uc(e,i){return e?i?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function vc(e,i,s){return"string"==typeof e?(e=encodeURI(e).replace(i,Cc),s&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function Cc(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}T.prototype.toString=function(){var e=[],i=this.j;i&&e.push(vc(i,eV,!0),":");var s=this.g;return(s||"file"==i)&&(e.push("//"),(i=this.o)&&e.push(vc(i,eV,!0),"@"),e.push(encodeURIComponent(String(s)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(s=this.s)&&e.push(":",String(s))),(s=this.l)&&(this.g&&"/"!=s.charAt(0)&&e.push("/"),e.push(vc(s,"/"==s.charAt(0)?ek:eC,!0))),(s=this.i.toString())&&e.push("?",s),(s=this.m)&&e.push("#",vc(s,ex)),e.join("")};var eV=/[#\/\?@]/g,eC=/[#\?:]/g,ek=/[#\?]/g,eD=/[#\?@]/g,ex=/#/g;function sc(e,i){this.h=this.g=null,this.i=e||null,this.j=!!i}function U(e){e.g||(e.g=new Map,e.h=0,e.i&&function(e,i){if(e){e=e.split("&");for(var s=0;s<e.length;s++){var o=e[s].indexOf("="),l=null;if(0<=o){var h=e[s].substring(0,o);l=e[s].substring(o+1)}else h=e[s];i(h,l?decodeURIComponent(l.replace(/\+/g," ")):"")}}}(e.i,function(i,s){e.add(decodeURIComponent(i.replace(/\+/g," ")),s)}))}function Dc(e,i){U(e),i=V(e,i),e.g.has(i)&&(e.i=null,e.h-=e.g.get(i).length,e.g.delete(i))}function Ec(e,i){return U(e),i=V(e,i),e.g.has(i)}function Lb(e,i,s){Dc(e,i),0<s.length&&(e.i=null,e.g.set(V(e,i),la(s)),e.h+=s.length)}function V(e,i){return i=String(i),e.j&&(i=i.toLowerCase()),i}function W(e,i,s,o,l){try{l&&(l.onload=null,l.onerror=null,l.onabort=null,l.ontimeout=null),o(s)}catch(e){}}function Hc(){this.g=new ey}function Jc(e){this.l=e.Ub||null,this.j=e.eb||!1}function Kc(e,i){E.call(this),this.D=e,this.o=i,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}function Nc(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function Mc(e){e.readyState=4,e.l=null,e.j=null,e.v=null,Lc(e)}function Lc(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function Oc(e){let i="";return qa(e,function(e,s){i+=s+":"+e+"\r\n"}),i}function Pc(e,i,s){e:{for(o in s){var o=!1;break e}o=!0}o||(s=Oc(s),"string"==typeof e?null!=s&&encodeURIComponent(String(s)):S(e,i,s))}function X(e){E.call(this),this.headers=new Map,this.o=e||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}(s=sc.prototype).add=function(e,i){U(this),this.i=null,e=V(this,e);var s=this.g.get(e);return s||this.g.set(e,s=[]),s.push(i),this.h+=1,this},s.forEach=function(e,i){U(this),this.g.forEach(function(s,o){s.forEach(function(s){e.call(i,s,o,this)},this)},this)},s.na=function(){U(this);let e=Array.from(this.g.values()),i=Array.from(this.g.keys()),s=[];for(let o=0;o<i.length;o++){let l=e[o];for(let e=0;e<l.length;e++)s.push(i[o])}return s},s.V=function(e){U(this);let i=[];if("string"==typeof e)Ec(this,e)&&(i=i.concat(this.g.get(V(this,e))));else{e=Array.from(this.g.values());for(let s=0;s<e.length;s++)i=i.concat(e[s])}return i},s.set=function(e,i){return U(this),this.i=null,Ec(this,e=V(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[i]),this.h+=1,this},s.get=function(e,i){return e&&0<(e=this.V(e)).length?String(e[0]):i},s.toString=function(){if(this.i)return this.i;if(!this.g)return"";let e=[],i=Array.from(this.g.keys());for(var s=0;s<i.length;s++){var o=i[s];let h=encodeURIComponent(String(o)),d=this.V(o);for(o=0;o<d.length;o++){var l=h;""!==d[o]&&(l+="="+encodeURIComponent(String(d[o]))),e.push(l)}}return this.i=e.join("&")},r(Jc,kb),Jc.prototype.g=function(){return new Kc(this.l,this.j)},Jc.prototype.i=(e={},function(){return e}),r(Kc,E),(s=Kc.prototype).open=function(e,i){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.B=e,this.A=i,this.readyState=1,Lc(this)},s.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;let i={headers:this.u,method:this.B,credentials:this.m,cache:void 0};e&&(i.body=e),(this.D||j).fetch(new Request(this.A,i)).then(this.Sa.bind(this),this.ga.bind(this))},s.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Mc(this)),this.readyState=0},s.Sa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,Lc(this)),this.g&&(this.readyState=3,Lc(this),this.g))){if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==j.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;Nc(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))}},s.Pa=function(e){if(this.g){if(this.o&&e.value)this.response.push(e.value);else if(!this.o){var i=e.value?e.value:new Uint8Array(0);(i=this.v.decode(i,{stream:!e.done}))&&(this.response=this.responseText+=i)}e.done?Mc(this):Lc(this),3==this.readyState&&Nc(this)}},s.Ra=function(e){this.g&&(this.response=this.responseText=e,Mc(this))},s.Qa=function(e){this.g&&(this.response=e,Mc(this))},s.ga=function(){this.g&&Mc(this)},s.setRequestHeader=function(e,i){this.u.append(e,i)},s.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},s.getAllResponseHeaders=function(){if(!this.h)return"";let e=[],i=this.h.entries();for(var s=i.next();!s.done;)e.push((s=s.value)[0]+": "+s[1]),s=i.next();return e.join("\r\n")},Object.defineProperty(Kc.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),r(X,E);var eN=/^https?$/i,eO=["POST","PUT"];function Sc(e,i){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=i,e.m=5,Uc(e),Vc(e)}function Uc(e){e.A||(e.A=!0,F(e,"complete"),F(e,"error"))}function Wc(e){if(e.h&&void 0!==O&&(!e.v[1]||4!=P(e)||2!=e.Z())){if(e.u&&4==P(e))bb(e.Ea,0,e);else if(F(e,"readystatechange"),4==P(e)){e.h=!1;try{let d=e.Z();switch(d){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var i,s,o=!0;break;default:o=!1}if(!(i=o)){if(s=0===d){var l=String(e.D).match(eS)[1]||null;!l&&j.self&&j.self.location&&(l=j.self.location.protocol.slice(0,-1)),s=!eN.test(l?l.toLowerCase():"")}i=s}if(i)F(e,"complete"),F(e,"success");else{e.m=6;try{var h=2<P(e)?e.g.statusText:""}catch(e){h=""}e.l=h+" ["+e.Z()+"]",Uc(e)}}finally{Vc(e)}}}}function Vc(e,i){if(e.g){Tc(e);let s=e.g,o=e.v[0]?()=>{}:null;e.g=null,e.v=null,i||F(e,"ready");try{s.onreadystatechange=o}catch(e){}}}function Tc(e){e.I&&(j.clearTimeout(e.I),e.I=null)}function P(e){return e.g?e.g.readyState:0}function Nb(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.H){case"":case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Xc(e,i,s){return s&&s.internalChannelParams&&s.internalChannelParams[e]||i}function Yc(e){this.Aa=0,this.i=[],this.j=new vb,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=Xc("failFast",!1,e),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=Xc("baseRetryDelayMs",5e3,e),this.cb=Xc("retryDelaySeedMs",1e4,e),this.Wa=Xc("forwardChannelMaxRetries",2,e),this.wa=Xc("forwardChannelRequestTimeoutMs",2e4,e),this.pa=e&&e.xmlHttpFactory||void 0,this.Xa=e&&e.Tb||void 0,this.Ca=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.h=new ic(e&&e.concurrentRequestLimit),this.Da=new Hc,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=e&&e.Rb||!1,e&&e.xa&&this.j.xa(),e&&e.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&e&&e.detectBufferingProxy||!1,this.ja=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ja=e.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}function gc(e){if(Zc(e),3==e.G){var i=e.U++,s=N(e.I);if(S(s,"SID",e.K),S(s,"RID",i),S(s,"TYPE","terminate"),$c(e,s),(i=new M(e,e.j,i)).L=2,i.v=Ib(N(s)),s=!1,j.navigator&&j.navigator.sendBeacon)try{s=j.navigator.sendBeacon(i.v.toString(),"")}catch(e){}!s&&j.Image&&((new Image).src=i.v,s=!0),s||(i.g=Mb(i.j,null),i.g.ea(i.v)),i.F=Date.now(),Kb(i)}ad(e)}function Zb(e){e.g&&(Tb(e),e.g.cancel(),e.g=null)}function Zc(e){Zb(e),e.u&&(j.clearTimeout(e.u),e.u=null),Yb(e),e.h.cancel(),e.s&&("number"==typeof e.s&&j.clearTimeout(e.s),e.s=null)}function fc(e){if(!jc(e.h)&&!e.s){e.s=!0;var i=e.Ga;et||Ea(),er||(et(),er=!0),en.add(i,e),e.B=0}}function ed(e,i){var s;s=i?i.l:e.U++;let o=N(e.I);S(o,"SID",e.K),S(o,"RID",s),S(o,"AID",e.T),$c(e,o),e.m&&e.o&&Pc(o,e.m,e.o),s=new M(e,e.j,s,e.B+1),null===e.m&&(s.H=e.o),i&&(e.i=i.D.concat(e.i)),i=dd(e,s,1e3),s.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),bc(e.h,s),Hb(s,o,i)}function $c(e,i){e.H&&qa(e.H,function(e,s){S(i,s,e)}),e.l&&nc({},function(e,s){S(i,s,e)})}function dd(e,i,s){s=Math.min(e.i.length,s);var o=e.l?p(e.l.Na,e.l,e):null;e:{var l=e.i;let i=-1;for(;;){let e=["count="+s];-1==i?0<s?(i=l[0].g,e.push("ofs="+i)):i=0:e.push("ofs="+i);let h=!0;for(let d=0;d<s;d++){let s=l[d].g,f=l[d].map;if(0>(s-=i))i=Math.max(0,l[d].g-100),h=!1;else try{!function(e,i,s){let o=s||"";try{nc(e,function(e,s){let l=e;n(e)&&(l=em(e)),i.push(o+s+"="+encodeURIComponent(l))})}catch(e){throw i.push(o+"type="+encodeURIComponent("_badmap")),e}}(f,e,"req"+s+"_")}catch(e){o&&o(f)}}if(h){o=e.join("&");break e}}}return e=e.i.splice(0,s),i.D=e,o}function ec(e){if(!e.g&&!e.u){e.Y=1;var i=e.Fa;et||Ea(),er||(et(),er=!0),en.add(i,e),e.v=0}}function $b(e){return!e.g&&!e.u&&!(3<=e.v)&&(e.Y++,e.u=ub(p(e.Fa,e),cd(e,e.v)),e.v++,!0)}function Tb(e){null!=e.A&&(j.clearTimeout(e.A),e.A=null)}function fd(e){e.g=new M(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var i=N(e.qa);S(i,"RID","rpc"),S(i,"SID",e.K),S(i,"AID",e.T),S(i,"CI",e.F?"0":"1"),!e.F&&e.ja&&S(i,"TO",e.ja),S(i,"TYPE","xmlhttp"),$c(e,i),e.m&&e.o&&Pc(i,e.m,e.o),e.L&&(e.g.I=e.L);var s=e.g;e=e.ia,s.L=1,s.v=Ib(N(i)),s.m=null,s.P=!0,Jb(s,e)}function Yb(e){null!=e.C&&(j.clearTimeout(e.C),e.C=null)}function Ub(e,i){var s=null;if(e.g==i){Yb(e),Tb(e),e.g=null;var o=2}else{if(!Xb(e.h,i))return;s=i.D,dc(e.h,i),o=1}if(0!=e.G){if(i.o){if(1==o){s=i.m?i.m.length:0,i=Date.now()-i.F;var l,h=e.B;F(o=qb(),new tb(o,s)),fc(e)}else ec(e)}else if(3==(h=i.s)||0==h&&0<i.X||!(1==o&&(l=i,!(ac(e.h)>=e.h.j-(e.s?1:0))&&(e.s?(e.i=l.D.concat(e.i),!0):1!=e.G&&2!=e.G&&!(e.B>=(e.Va?0:e.Wa))&&(e.s=ub(p(e.Ga,e,l),cd(e,e.B)),e.B++,!0)))||2==o&&$b(e)))switch(s&&0<s.length&&((i=e.h).i=i.i.concat(s)),h){case 1:R(e,5);break;case 4:R(e,10);break;case 3:R(e,6);break;default:R(e,2)}}}function cd(e,i){let s=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(s*=2),s*i}function R(e,i){if(e.j.info("Error code "+i),2==i){var s=p(e.fb,e),o=e.Xa;let i=!o;o=new T(o||"//www.google.com/images/cleardot.gif"),j.location&&"http"==j.location.protocol||qc(o,"https"),Ib(o),i?function(e,i){let s=new vb;if(j.Image){let o=new Image;o.onload=ka(W,s,"TestLoadImage: loaded",!0,i,o),o.onerror=ka(W,s,"TestLoadImage: error",!1,i,o),o.onabort=ka(W,s,"TestLoadImage: abort",!1,i,o),o.ontimeout=ka(W,s,"TestLoadImage: timeout",!1,i,o),j.setTimeout(function(){o.ontimeout&&o.ontimeout()},1e4),o.src=e}else i(!1)}(o.toString(),s):function(e,i){let s=new vb,o=new AbortController,l=setTimeout(()=>{o.abort(),W(s,"TestPingServer: timeout",!1,i)},1e4);fetch(e,{signal:o.signal}).then(e=>{clearTimeout(l),e.ok?W(s,"TestPingServer: ok",!0,i):W(s,"TestPingServer: server error",!1,i)}).catch(()=>{clearTimeout(l),W(s,"TestPingServer: error",!1,i)})}(o.toString(),s)}else K(2);e.G=0,e.l&&e.l.sa(i),ad(e),Zc(e)}function ad(e){if(e.G=0,e.ka=[],e.l){let i=kc(e.h);(0!=i.length||0!=e.i.length)&&(ma(e.ka,i),ma(e.ka,e.i),e.h.i.length=0,la(e.i),e.i.length=0),e.l.ra()}}function cc(e,i,s){var o=s instanceof T?N(s):new T(s);if(""!=o.g)i&&(o.g=i+"."+o.g),rc(o,o.s);else{var l=j.location;o=l.protocol,i=i?i+"."+l.hostname:l.hostname,l=+l.port;var h=new T(null);o&&qc(h,o),i&&(h.g=i),l&&rc(h,l),s&&(h.l=s),o=h}return s=e.D,i=e.ya,s&&i&&S(o,s,i),S(o,"VER",e.la),$c(e,o),o}function Mb(e,i,s){if(i&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(i=new X(e.Ca&&!e.pa?new Jc({eb:s}):e.pa)).Ha(e.J),i}function gd(){}function hd(){}function Y(e,i){E.call(this),this.g=new Yc(i),this.l=e,this.h=i&&i.messageUrlParams||null,e=i&&i.messageHeaders||null,i&&i.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.o=e,e=i&&i.initMessageHeaders||null,i&&i.messageContentType&&(e?e["X-WebChannel-Content-Type"]=i.messageContentType:e={"X-WebChannel-Content-Type":i.messageContentType}),i&&i.va&&(e?e["X-WebChannel-Client-Profile"]=i.va:e={"X-WebChannel-Client-Profile":i.va}),this.g.S=e,(e=i&&i.Sb)&&!t(e)&&(this.g.m=e),this.v=i&&i.supportsCrossDomainXhr||!1,this.u=i&&i.sendRawJson||!1,(i=i&&i.httpSessionIdParam)&&!t(i)&&(this.g.D=i,null!==(e=this.h)&&i in e&&i in(e=this.h)&&delete e[i]),this.j=new Z(this)}function id(e){nb.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var i=e.__sm__;if(i){e:{for(let s in i){e=s;break e}e=void 0}(this.i=e)&&(e=this.i,i=null!==i&&e in i?i[e]:void 0),this.data=i}else this.data=e}function jd(){ob.call(this),this.status=1}function Z(e){this.g=e}(s=X.prototype).Ha=function(e){this.J=e},s.ea=function(e,s,o,l){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+e);s=s?s.toUpperCase():"GET",this.D=e,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=this.o?this.o.g():i.g(),this.v=this.o?lb(this.o):lb(i),this.g.onreadystatechange=p(this.Ea,this);try{this.B=!0,this.g.open(s,String(e),!0),this.B=!1}catch(e){Sc(this,e);return}if(e=o||"",o=new Map(this.headers),l){if(Object.getPrototypeOf(l)===Object.prototype)for(var h in l)o.set(h,l[h]);else if("function"==typeof l.keys&&"function"==typeof l.get)for(let e of l.keys())o.set(e,l.get(e));else throw Error("Unknown input type for opt_headers: "+String(l))}for(let[i,d]of(l=Array.from(o.keys()).find(e=>"content-type"==e.toLowerCase()),h=j.FormData&&e instanceof j.FormData,!(0<=Array.prototype.indexOf.call(eO,s,void 0))||l||h||o.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),o))this.g.setRequestHeader(i,d);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Tc(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){Sc(this,e)}},s.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=e||7,F(this,"complete"),F(this,"abort"),Vc(this))},s.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Vc(this,!0)),X.aa.N.call(this)},s.Ea=function(){this.s||(this.B||this.u||this.j?Wc(this):this.bb())},s.bb=function(){Wc(this)},s.isActive=function(){return!!this.g},s.Z=function(){try{return 2<P(this)?this.g.status:-1}catch(e){return -1}},s.oa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},s.Oa=function(e){if(this.g){var i=this.g.responseText;return e&&0==i.indexOf(e)&&(i=i.substring(e.length)),eg(i)}},s.Ba=function(){return this.m},s.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(s=Yc.prototype).la=8,s.G=1,s.connect=function(e,i,s,o){K(0),this.W=e,this.H=i||{},s&&void 0!==o&&(this.H.OSID=s,this.H.OAID=o),this.F=this.X,this.I=cc(this,null,this.W),fc(this)},s.Ga=function(e){if(this.s){if(this.s=null,1==this.G){if(!e){this.U=Math.floor(1e5*Math.random()),e=this.U++;let l=new M(this,this.j,e),h=this.o;if(this.S&&(h?ua(h=sa(h),this.S):h=this.S),null!==this.m||this.O||(l.H=h,h=null),this.P)e:{for(var i=0,s=0;s<this.i.length;s++){t:{var o=this.i[s];if("__data__"in o.map&&"string"==typeof(o=o.map.__data__)){o=o.length;break t}o=void 0}if(void 0===o)break;if(4096<(i+=o)){i=s;break e}if(4096===i||s===this.i.length-1){i=s+1;break e}}i=1e3}else i=1e3;i=dd(this,l,i),S(s=N(this.I),"RID",e),S(s,"CVER",22),this.D&&S(s,"X-HTTP-Session-Id",this.D),$c(this,s),h&&(this.O?i="headers="+encodeURIComponent(String(Oc(h)))+"&"+i:this.m&&Pc(s,this.m,h)),bc(this.h,l),this.Ua&&S(s,"TYPE","init"),this.P?(S(s,"$req",i),S(s,"SID","null"),l.T=!0,Hb(l,s,null)):Hb(l,s,i),this.G=2}}else 3==this.G&&(e?ed(this,e):0==this.i.length||jc(this.h)||ed(this))}},s.Fa=function(){if(this.u=null,fd(this),this.ba&&!(this.M||null==this.g||0>=this.R)){var e=2*this.R;this.j.info("BP detection timer enabled: "+e),this.A=ub(p(this.ab,this),e)}},s.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,K(10),Zb(this),fd(this))},s.Za=function(){null!=this.C&&(this.C=null,Zb(this),$b(this),K(19))},s.fb=function(e){e?(this.j.info("Successfully pinged google.com"),K(2)):(this.j.info("Failed to ping google.com"),K(1))},s.isActive=function(){return!!this.l&&this.l.isActive(this)},(s=gd.prototype).ua=function(){},s.ta=function(){},s.sa=function(){},s.ra=function(){},s.isActive=function(){return!0},s.Na=function(){},hd.prototype.g=function(e,i){return new Y(e,i)},r(Y,E),Y.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},Y.prototype.close=function(){gc(this.g)},Y.prototype.o=function(e){var i=this.g;if("string"==typeof e){var s={};s.__data__=e,e=s}else this.u&&((s={}).__data__=em(e),e=s);i.i.push(new ew(i.Ya++,e)),3==i.G&&fc(i)},Y.prototype.N=function(){this.g.l=null,delete this.j,gc(this.g),delete this.g,Y.aa.N.call(this)},r(id,nb),r(jd,ob),r(Z,gd),Z.prototype.ua=function(){F(this.g,"a")},Z.prototype.ta=function(e){F(this.g,new id(e))},Z.prototype.sa=function(e){F(this.g,new jd)},Z.prototype.ra=function(){F(this.g,"b")},hd.prototype.createWebChannel=hd.prototype.g,Y.prototype.send=Y.prototype.o,Y.prototype.open=Y.prototype.m,Y.prototype.close=Y.prototype.close,k=eo.createWebChannelTransport=function(){return new hd},w=eo.getStatEventTarget=function(){return qb()},b=eo.Event=ev,g=eo.Stat={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},eI.NO_ERROR=0,eI.TIMEOUT=8,eI.HTTP_ERROR=6,_=eo.ErrorCode=eI,eA.COMPLETE="complete",f=eo.EventType=eA,mb.EventType=eE,eE.OPEN="a",eE.CLOSE="b",eE.ERROR="c",eE.MESSAGE="d",E.prototype.listen=E.prototype.K,d=eo.WebChannel=mb,eo.FetchXmlHttpFactory=Jc,X.prototype.listenOnce=X.prototype.L,X.prototype.getLastError=X.prototype.Ka,X.prototype.getLastErrorCode=X.prototype.Ba,X.prototype.getStatus=X.prototype.Z,X.prototype.getResponseJson=X.prototype.Oa,X.prototype.getResponseText=X.prototype.oa,X.prototype.send=X.prototype.ea,X.prototype.setWithCredentials=X.prototype.Ha,h=eo.XhrIo=X}).apply(void 0!==ea?ea:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{}),s(3454);var el=s(8764).lW;let eu="@firebase/firestore";/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let User=class User{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}};User.UNAUTHENTICATED=new User(null),User.GOOGLE_CREDENTIALS=new User("google-credentials-uid"),User.FIRST_PARTY=new User("first-party-uid"),User.MOCK_USER=new User("mock-user");/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let eh="10.14.0",ef=new er.Yd("@firebase/firestore");function __PRIVATE_getLogLevel(){return ef.logLevel}function __PRIVATE_logDebug(e,...i){if(ef.logLevel<=er.in.DEBUG){let s=i.map(__PRIVATE_argToString);ef.debug(`Firestore (${eh}): ${e}`,...s)}}function __PRIVATE_logError(e,...i){if(ef.logLevel<=er.in.ERROR){let s=i.map(__PRIVATE_argToString);ef.error(`Firestore (${eh}): ${e}`,...s)}}function __PRIVATE_logWarn(e,...i){if(ef.logLevel<=er.in.WARN){let s=i.map(__PRIVATE_argToString);ef.warn(`Firestore (${eh}): ${e}`,...s)}}function __PRIVATE_argToString(e){if("string"==typeof e)return e;try{/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */return JSON.stringify(e)}catch(i){return e}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function fail(e="Unexpected state"){let i=`FIRESTORE (${eh}) INTERNAL ASSERTION FAILED: `+e;throw __PRIVATE_logError(i),Error(i)}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let e_={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};let FirestoreError=class FirestoreError extends en.ZR{constructor(e,i){super(e,i),this.code=e,this.message=i,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_Deferred=class __PRIVATE_Deferred{constructor(){this.promise=new Promise((e,i)=>{this.resolve=e,this.reject=i})}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_OAuthToken=class __PRIVATE_OAuthToken{constructor(e,i){this.user=i,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}};let __PRIVATE_EmptyAuthCredentialsProvider=class __PRIVATE_EmptyAuthCredentialsProvider{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,i){e.enqueueRetryable(()=>i(User.UNAUTHENTICATED))}shutdown(){}};let __PRIVATE_EmulatorAuthCredentialsProvider=class __PRIVATE_EmulatorAuthCredentialsProvider{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,i){this.changeListener=i,e.enqueueRetryable(()=>i(this.token.user))}shutdown(){this.changeListener=null}};let __PRIVATE_FirebaseAuthCredentialsProvider=class __PRIVATE_FirebaseAuthCredentialsProvider{constructor(e){this.t=e,this.currentUser=User.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,i){void 0===this.o||fail();let s=this.i,__PRIVATE_guardedChangeListener=e=>this.i!==s?(s=this.i,i(e)):Promise.resolve(),o=new __PRIVATE_Deferred;this.o=()=>{this.i++,this.currentUser=this.u(),o.resolve(),o=new __PRIVATE_Deferred,e.enqueueRetryable(()=>__PRIVATE_guardedChangeListener(this.currentUser))};let __PRIVATE_awaitNextToken=()=>{let i=o;e.enqueueRetryable(async()=>{await i.promise,await __PRIVATE_guardedChangeListener(this.currentUser)})},__PRIVATE_registerAuth=e=>{__PRIVATE_logDebug("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),__PRIVATE_awaitNextToken())};this.t.onInit(e=>__PRIVATE_registerAuth(e)),setTimeout(()=>{if(!this.auth){let e=this.t.getImmediate({optional:!0});e?__PRIVATE_registerAuth(e):(__PRIVATE_logDebug("FirebaseAuthCredentialsProvider","Auth not yet detected"),o.resolve(),o=new __PRIVATE_Deferred)}},0),__PRIVATE_awaitNextToken()}getToken(){let e=this.i,i=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(i).then(i=>this.i!==e?(__PRIVATE_logDebug("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):i?("string"==typeof i.accessToken||fail(),new __PRIVATE_OAuthToken(i.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){let e=this.auth&&this.auth.getUid();return null===e||"string"==typeof e||fail(),new User(e)}};let __PRIVATE_FirstPartyToken=class __PRIVATE_FirstPartyToken{constructor(e,i,s){this.l=e,this.h=i,this.P=s,this.type="FirstParty",this.user=User.FIRST_PARTY,this.I=new Map}T(){return this.P?this.P():null}get headers(){this.I.set("X-Goog-AuthUser",this.l);let e=this.T();return e&&this.I.set("Authorization",e),this.h&&this.I.set("X-Goog-Iam-Authorization-Token",this.h),this.I}};let __PRIVATE_FirstPartyAuthCredentialsProvider=class __PRIVATE_FirstPartyAuthCredentialsProvider{constructor(e,i,s){this.l=e,this.h=i,this.P=s}getToken(){return Promise.resolve(new __PRIVATE_FirstPartyToken(this.l,this.h,this.P))}start(e,i){e.enqueueRetryable(()=>i(User.FIRST_PARTY))}shutdown(){}invalidateToken(){}};let AppCheckToken=class AppCheckToken{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}};let __PRIVATE_FirebaseAppCheckTokenProvider=class __PRIVATE_FirebaseAppCheckTokenProvider{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(e,i){void 0===this.o||fail();let onTokenChanged=e=>{null!=e.error&&__PRIVATE_logDebug("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);let s=e.token!==this.R;return this.R=e.token,__PRIVATE_logDebug("FirebaseAppCheckTokenProvider",`Received ${s?"new":"existing"} token.`),s?i(e.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable(()=>onTokenChanged(i))};let __PRIVATE_registerAppCheck=e=>{__PRIVATE_logDebug("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit(e=>__PRIVATE_registerAppCheck(e)),setTimeout(()=>{if(!this.appCheck){let e=this.A.getImmediate({optional:!0});e?__PRIVATE_registerAppCheck(e):__PRIVATE_logDebug("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?("string"==typeof e.token||fail(),this.R=e.token,new AppCheckToken(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_AutoId=class __PRIVATE_AutoId{static newId(){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=Math.floor(256/e.length)*e.length,s="";for(;s.length<20;){let o=/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function(e){let i="undefined"!=typeof self&&(self.crypto||self.msCrypto),s=new Uint8Array(e);if(i&&"function"==typeof i.getRandomValues)i.getRandomValues(s);else for(let i=0;i<e;i++)s[i]=Math.floor(256*Math.random());return s}(40);for(let l=0;l<o.length;++l)s.length<20&&o[l]<i&&(s+=e.charAt(o[l]%e.length))}return s}};function __PRIVATE_primitiveComparator(e,i){return e<i?-1:e>i?1:0}function __PRIVATE_arrayEquals(e,i,s){return e.length===i.length&&e.every((e,o)=>s(e,i[o]))}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Timestamp=class Timestamp{constructor(e,i){if(this.seconds=e,this.nanoseconds=i,i<0||i>=1e9)throw new FirestoreError(e_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+i);if(e<-62135596800||e>=253402300800)throw new FirestoreError(e_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return Timestamp.fromMillis(Date.now())}static fromDate(e){return Timestamp.fromMillis(e.getTime())}static fromMillis(e){let i=Math.floor(e/1e3),s=Math.floor(1e6*(e-1e3*i));return new Timestamp(i,s)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?__PRIVATE_primitiveComparator(this.nanoseconds,e.nanoseconds):__PRIVATE_primitiveComparator(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){let e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let SnapshotVersion=class SnapshotVersion{constructor(e){this.timestamp=e}static fromTimestamp(e){return new SnapshotVersion(e)}static min(){return new SnapshotVersion(new Timestamp(0,0))}static max(){return new SnapshotVersion(new Timestamp(253402300799,999999999))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let BasePath=class BasePath{constructor(e,i,s){void 0===i?i=0:i>e.length&&fail(),void 0===s?s=e.length-i:s>e.length-i&&fail(),this.segments=e,this.offset=i,this.len=s}get length(){return this.len}isEqual(e){return 0===BasePath.comparator(this,e)}child(e){let i=this.segments.slice(this.offset,this.limit());return e instanceof BasePath?e.forEach(e=>{i.push(e)}):i.push(e),this.construct(i)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let i=0;i<this.length;i++)if(this.get(i)!==e.get(i))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let i=0;i<this.length;i++)if(this.get(i)!==e.get(i))return!1;return!0}forEach(e){for(let i=this.offset,s=this.limit();i<s;i++)e(this.segments[i])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,i){let s=Math.min(e.length,i.length);for(let o=0;o<s;o++){let s=e.get(o),l=i.get(o);if(s<l)return -1;if(s>l)return 1}return e.length<i.length?-1:e.length>i.length?1:0}};let ResourcePath=class ResourcePath extends BasePath{construct(e,i,s){return new ResourcePath(e,i,s)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let i=[];for(let s of e){if(s.indexOf("//")>=0)throw new FirestoreError(e_.INVALID_ARGUMENT,`Invalid segment (${s}). Paths must not contain // in them.`);i.push(...s.split("/").filter(e=>e.length>0))}return new ResourcePath(i)}static emptyPath(){return new ResourcePath([])}};let ep=/^[_a-zA-Z][_a-zA-Z0-9]*$/;let FieldPath$1=class FieldPath$1 extends BasePath{construct(e,i,s){return new FieldPath$1(e,i,s)}static isValidIdentifier(e){return ep.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),FieldPath$1.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new FieldPath$1(["__name__"])}static fromServerFormat(e){let i=[],s="",o=0,__PRIVATE_addCurrentSegment=()=>{if(0===s.length)throw new FirestoreError(e_.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);i.push(s),s=""},l=!1;for(;o<e.length;){let i=e[o];if("\\"===i){if(o+1===e.length)throw new FirestoreError(e_.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let i=e[o+1];if("\\"!==i&&"."!==i&&"`"!==i)throw new FirestoreError(e_.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);s+=i,o+=2}else"`"===i?l=!l:"."!==i||l?s+=i:__PRIVATE_addCurrentSegment(),o++}if(__PRIVATE_addCurrentSegment(),l)throw new FirestoreError(e_.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new FieldPath$1(i)}static emptyPath(){return new FieldPath$1([])}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let DocumentKey=class DocumentKey{constructor(e){this.path=e}static fromPath(e){return new DocumentKey(ResourcePath.fromString(e))}static fromName(e){return new DocumentKey(ResourcePath.fromString(e).popFirst(5))}static empty(){return new DocumentKey(ResourcePath.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===ResourcePath.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,i){return ResourcePath.comparator(e.path,i.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new DocumentKey(new ResourcePath(e.slice()))}};let IndexOffset=class IndexOffset{constructor(e,i,s){this.readTime=e,this.documentKey=i,this.largestBatchId=s}static min(){return new IndexOffset(SnapshotVersion.min(),DocumentKey.empty(),-1)}static max(){return new IndexOffset(SnapshotVersion.max(),DocumentKey.empty(),-1)}};let PersistenceTransaction=class PersistenceTransaction{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e){if(e.code!==e_.FAILED_PRECONDITION||"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab."!==e.message)throw e;__PRIVATE_logDebug("LocalStore","Unexpectedly lost primary lease")}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let PersistencePromise=class PersistencePromise{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(e,i){return this.callbackAttached&&fail(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(e,this.result):new PersistencePromise((s,o)=>{this.nextCallback=i=>{this.wrapSuccess(e,i).next(s,o)},this.catchCallback=e=>{this.wrapFailure(i,e).next(s,o)}})}toPromise(){return new Promise((e,i)=>{this.next(e,i)})}wrapUserFunction(e){try{let i=e();return i instanceof PersistencePromise?i:PersistencePromise.resolve(i)}catch(e){return PersistencePromise.reject(e)}}wrapSuccess(e,i){return e?this.wrapUserFunction(()=>e(i)):PersistencePromise.resolve(i)}wrapFailure(e,i){return e?this.wrapUserFunction(()=>e(i)):PersistencePromise.reject(i)}static resolve(e){return new PersistencePromise((i,s)=>{i(e)})}static reject(e){return new PersistencePromise((i,s)=>{s(e)})}static waitFor(e){return new PersistencePromise((i,s)=>{let o=0,l=0,h=!1;e.forEach(e=>{++o,e.next(()=>{++l,h&&l===o&&i()},e=>s(e))}),h=!0,l===o&&i()})}static or(e){let i=PersistencePromise.resolve(!1);for(let s of e)i=i.next(e=>e?PersistencePromise.resolve(e):s());return i}static forEach(e,i){let s=[];return e.forEach((e,o)=>{s.push(i.call(this,e,o))}),this.waitFor(s)}static mapArray(e,i){return new PersistencePromise((s,o)=>{let l=e.length,h=Array(l),d=0;for(let f=0;f<l;f++){let _=f;i(e[_]).next(e=>{h[_]=e,++d===l&&s(h)},e=>o(e))}})}static doWhile(e,i){return new PersistencePromise((s,o)=>{let process=()=>{!0===e()?i().next(()=>{process()},o):s()};process()})}};function __PRIVATE_isIndexedDbTransactionError(e){return"IndexedDbTransactionError"===e.name}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_ListenSequence=class __PRIVATE_ListenSequence{constructor(e,i){this.previousValue=e,i&&(i.sequenceNumberHandler=e=>this.ie(e),this.se=e=>i.writeSequenceNumber(e))}ie(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.se&&this.se(e),e}};function __PRIVATE_isNegativeZero(e){return 0===e&&1/e==-1/0}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function __PRIVATE_objectSize(e){let i=0;for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&i++;return i}function forEach(e,i){for(let s in e)Object.prototype.hasOwnProperty.call(e,s)&&i(s,e[s])}function isEmpty(e){for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i))return!1;return!0}__PRIVATE_ListenSequence.oe=-1;/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let SortedMap=class SortedMap{constructor(e,i){this.comparator=e,this.root=i||LLRBNode.EMPTY}insert(e,i){return new SortedMap(this.comparator,this.root.insert(e,i,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}remove(e){return new SortedMap(this.comparator,this.root.remove(e,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}get(e){let i=this.root;for(;!i.isEmpty();){let s=this.comparator(e,i.key);if(0===s)return i.value;s<0?i=i.left:s>0&&(i=i.right)}return null}indexOf(e){let i=0,s=this.root;for(;!s.isEmpty();){let o=this.comparator(e,s.key);if(0===o)return i+s.left.size;o<0?s=s.left:(i+=s.left.size+1,s=s.right)}return -1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((i,s)=>(e(i,s),!1))}toString(){let e=[];return this.inorderTraversal((i,s)=>(e.push(`${i}:${s}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new SortedMapIterator(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!1)}getReverseIterator(){return new SortedMapIterator(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!0)}};let SortedMapIterator=class SortedMapIterator{constructor(e,i,s,o){this.isReverse=o,this.nodeStack=[];let l=1;for(;!e.isEmpty();)if(l=i?s(e.key,i):1,i&&o&&(l*=-1),l<0)e=this.isReverse?e.left:e.right;else{if(0===l){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),i={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return i}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}};let LLRBNode=class LLRBNode{constructor(e,i,s,o,l){this.key=e,this.value=i,this.color=null!=s?s:LLRBNode.RED,this.left=null!=o?o:LLRBNode.EMPTY,this.right=null!=l?l:LLRBNode.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,i,s,o,l){return new LLRBNode(null!=e?e:this.key,null!=i?i:this.value,null!=s?s:this.color,null!=o?o:this.left,null!=l?l:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,i,s){let o=this,l=s(e,o.key);return(o=l<0?o.copy(null,null,null,o.left.insert(e,i,s),null):0===l?o.copy(null,i,null,null,null):o.copy(null,null,null,null,o.right.insert(e,i,s))).fixUp()}removeMin(){if(this.left.isEmpty())return LLRBNode.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),(e=e.copy(null,null,null,e.left.removeMin(),null)).fixUp()}remove(e,i){let s,o=this;if(0>i(e,o.key))o.left.isEmpty()||o.left.isRed()||o.left.left.isRed()||(o=o.moveRedLeft()),o=o.copy(null,null,null,o.left.remove(e,i),null);else{if(o.left.isRed()&&(o=o.rotateRight()),o.right.isEmpty()||o.right.isRed()||o.right.left.isRed()||(o=o.moveRedRight()),0===i(e,o.key)){if(o.right.isEmpty())return LLRBNode.EMPTY;s=o.right.min(),o=o.copy(s.key,s.value,null,null,o.right.removeMin())}o=o.copy(null,null,null,null,o.right.remove(e,i))}return o.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=(e=e.rotateRight()).colorFlip()),e}rotateLeft(){let e=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),i=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,i)}checkMaxDepth(){let e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed()||this.right.isRed())throw fail();let e=this.left.check();if(e!==this.right.check())throw fail();return e+(this.isRed()?0:1)}};LLRBNode.EMPTY=null,LLRBNode.RED=!0,LLRBNode.BLACK=!1,LLRBNode.EMPTY=new class{constructor(){this.size=0}get key(){throw fail()}get value(){throw fail()}get color(){throw fail()}get left(){throw fail()}get right(){throw fail()}copy(e,i,s,o,l){return this}insert(e,i,s){return new LLRBNode(e,i)}remove(e,i){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let SortedSet=class SortedSet{constructor(e){this.comparator=e,this.data=new SortedMap(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal((i,s)=>(e(i),!1))}forEachInRange(e,i){let s=this.data.getIteratorFrom(e[0]);for(;s.hasNext();){let o=s.getNext();if(this.comparator(o.key,e[1])>=0)return;i(o.key)}}forEachWhile(e,i){let s;for(s=void 0!==i?this.data.getIteratorFrom(i):this.data.getIterator();s.hasNext();)if(!e(s.getNext().key))return}firstAfterOrEqual(e){let i=this.data.getIteratorFrom(e);return i.hasNext()?i.getNext().key:null}getIterator(){return new SortedSetIterator(this.data.getIterator())}getIteratorFrom(e){return new SortedSetIterator(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let i=this;return i.size<e.size&&(i=e,e=this),e.forEach(e=>{i=i.add(e)}),i}isEqual(e){if(!(e instanceof SortedSet)||this.size!==e.size)return!1;let i=this.data.getIterator(),s=e.data.getIterator();for(;i.hasNext();){let e=i.getNext().key,o=s.getNext().key;if(0!==this.comparator(e,o))return!1}return!0}toArray(){let e=[];return this.forEach(i=>{e.push(i)}),e}toString(){let e=[];return this.forEach(i=>e.push(i)),"SortedSet("+e.toString()+")"}copy(e){let i=new SortedSet(this.comparator);return i.data=e,i}};let SortedSetIterator=class SortedSetIterator{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FieldMask=class FieldMask{constructor(e){this.fields=e,e.sort(FieldPath$1.comparator)}static empty(){return new FieldMask([])}unionWith(e){let i=new SortedSet(FieldPath$1.comparator);for(let e of this.fields)i=i.add(e);for(let s of e)i=i.add(s);return new FieldMask(i.toArray())}covers(e){for(let i of this.fields)if(i.isPrefixOf(e))return!0;return!1}isEqual(e){return __PRIVATE_arrayEquals(this.fields,e.fields,(e,i)=>e.isEqual(i))}};/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_Base64DecodeError=class __PRIVATE_Base64DecodeError extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ByteString=class ByteString{constructor(e){this.binaryString=e}static fromBase64String(e){let i=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new __PRIVATE_Base64DecodeError("Invalid base64 string: "+e):e}}(e);return new ByteString(i)}static fromUint8Array(e){let i=function(e){let i="";for(let s=0;s<e.length;++s)i+=String.fromCharCode(e[s]);return i}(e);return new ByteString(i)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return btoa(this.binaryString)}toUint8Array(){return function(e){let i=new Uint8Array(e.length);for(let s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return i}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return __PRIVATE_primitiveComparator(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}};ByteString.EMPTY_BYTE_STRING=new ByteString("");let em=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function __PRIVATE_normalizeTimestamp(e){if(e||fail(),"string"==typeof e){let i=0,s=em.exec(e);if(s||fail(),s[1]){let e=s[1];i=Number(e=(e+"000000000").substr(0,9))}let o=new Date(e);return{seconds:Math.floor(o.getTime()/1e3),nanos:i}}return{seconds:__PRIVATE_normalizeNumber(e.seconds),nanos:__PRIVATE_normalizeNumber(e.nanos)}}function __PRIVATE_normalizeNumber(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function __PRIVATE_normalizeByteString(e){return"string"==typeof e?ByteString.fromBase64String(e):ByteString.fromUint8Array(e)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function __PRIVATE_isServerTimestamp(e){var i,s;return"server_timestamp"===(null===(s=((null===(i=null==e?void 0:e.mapValue)||void 0===i?void 0:i.fields)||{}).__type__)||void 0===s?void 0:s.stringValue)}function __PRIVATE_getPreviousValue(e){let i=e.mapValue.fields.__previous_value__;return __PRIVATE_isServerTimestamp(i)?__PRIVATE_getPreviousValue(i):i}function __PRIVATE_getLocalWriteTime(e){let i=__PRIVATE_normalizeTimestamp(e.mapValue.fields.__local_write_time__.timestampValue);return new Timestamp(i.seconds,i.nanos)}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let DatabaseInfo=class DatabaseInfo{constructor(e,i,s,o,l,h,d,f,_){this.databaseId=e,this.appId=i,this.persistenceKey=s,this.host=o,this.ssl=l,this.forceLongPolling=h,this.autoDetectLongPolling=d,this.longPollingOptions=f,this.useFetchStreams=_}};let DatabaseId=class DatabaseId{constructor(e,i){this.projectId=e,this.database=i||"(default)"}static empty(){return new DatabaseId("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof DatabaseId&&e.projectId===this.projectId&&e.database===this.database}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let eg={mapValue:{fields:{__type__:{stringValue:"__max__"}}}};function __PRIVATE_typeOrder(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?__PRIVATE_isServerTimestamp(e)?4:__PRIVATE_isMaxValue(e)?9007199254740991:__PRIVATE_isVectorValue(e)?10:11:fail()}function __PRIVATE_valueEquals(e,i){if(e===i)return!0;let s=__PRIVATE_typeOrder(e);if(s!==__PRIVATE_typeOrder(i))return!1;switch(s){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===i.booleanValue;case 4:return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(i));case 3:return function(e,i){if("string"==typeof e.timestampValue&&"string"==typeof i.timestampValue&&e.timestampValue.length===i.timestampValue.length)return e.timestampValue===i.timestampValue;let s=__PRIVATE_normalizeTimestamp(e.timestampValue),o=__PRIVATE_normalizeTimestamp(i.timestampValue);return s.seconds===o.seconds&&s.nanos===o.nanos}(e,i);case 5:return e.stringValue===i.stringValue;case 6:return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(i.bytesValue));case 7:return e.referenceValue===i.referenceValue;case 8:return __PRIVATE_normalizeNumber(e.geoPointValue.latitude)===__PRIVATE_normalizeNumber(i.geoPointValue.latitude)&&__PRIVATE_normalizeNumber(e.geoPointValue.longitude)===__PRIVATE_normalizeNumber(i.geoPointValue.longitude);case 2:return function(e,i){if("integerValue"in e&&"integerValue"in i)return __PRIVATE_normalizeNumber(e.integerValue)===__PRIVATE_normalizeNumber(i.integerValue);if("doubleValue"in e&&"doubleValue"in i){let s=__PRIVATE_normalizeNumber(e.doubleValue),o=__PRIVATE_normalizeNumber(i.doubleValue);return s===o?__PRIVATE_isNegativeZero(s)===__PRIVATE_isNegativeZero(o):isNaN(s)&&isNaN(o)}return!1}(e,i);case 9:return __PRIVATE_arrayEquals(e.arrayValue.values||[],i.arrayValue.values||[],__PRIVATE_valueEquals);case 10:case 11:return function(e,i){let s=e.mapValue.fields||{},o=i.mapValue.fields||{};if(__PRIVATE_objectSize(s)!==__PRIVATE_objectSize(o))return!1;for(let e in s)if(s.hasOwnProperty(e)&&(void 0===o[e]||!__PRIVATE_valueEquals(s[e],o[e])))return!1;return!0}(e,i);default:return fail()}}function __PRIVATE_arrayValueContains(e,i){return void 0!==(e.values||[]).find(e=>__PRIVATE_valueEquals(e,i))}function __PRIVATE_valueCompare(e,i){if(e===i)return 0;let s=__PRIVATE_typeOrder(e),o=__PRIVATE_typeOrder(i);if(s!==o)return __PRIVATE_primitiveComparator(s,o);switch(s){case 0:case 9007199254740991:return 0;case 1:return __PRIVATE_primitiveComparator(e.booleanValue,i.booleanValue);case 2:return function(e,i){let s=__PRIVATE_normalizeNumber(e.integerValue||e.doubleValue),o=__PRIVATE_normalizeNumber(i.integerValue||i.doubleValue);return s<o?-1:s>o?1:s===o?0:isNaN(s)?isNaN(o)?0:-1:1}(e,i);case 3:return __PRIVATE_compareTimestamps(e.timestampValue,i.timestampValue);case 4:return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e),__PRIVATE_getLocalWriteTime(i));case 5:return __PRIVATE_primitiveComparator(e.stringValue,i.stringValue);case 6:return function(e,i){let s=__PRIVATE_normalizeByteString(e),o=__PRIVATE_normalizeByteString(i);return s.compareTo(o)}(e.bytesValue,i.bytesValue);case 7:return function(e,i){let s=e.split("/"),o=i.split("/");for(let e=0;e<s.length&&e<o.length;e++){let i=__PRIVATE_primitiveComparator(s[e],o[e]);if(0!==i)return i}return __PRIVATE_primitiveComparator(s.length,o.length)}(e.referenceValue,i.referenceValue);case 8:return function(e,i){let s=__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(i.latitude));return 0!==s?s:__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude),__PRIVATE_normalizeNumber(i.longitude))}(e.geoPointValue,i.geoPointValue);case 9:return __PRIVATE_compareArrays(e.arrayValue,i.arrayValue);case 10:return function(e,i){var s,o,l,h;let d=e.fields||{},f=i.fields||{},_=null===(s=d.value)||void 0===s?void 0:s.arrayValue,g=null===(o=f.value)||void 0===o?void 0:o.arrayValue,b=__PRIVATE_primitiveComparator((null===(l=null==_?void 0:_.values)||void 0===l?void 0:l.length)||0,(null===(h=null==g?void 0:g.values)||void 0===h?void 0:h.length)||0);return 0!==b?b:__PRIVATE_compareArrays(_,g)}(e.mapValue,i.mapValue);case 11:return function(e,i){if(e===eg.mapValue&&i===eg.mapValue)return 0;if(e===eg.mapValue)return 1;if(i===eg.mapValue)return -1;let s=e.fields||{},o=Object.keys(s),l=i.fields||{},h=Object.keys(l);o.sort(),h.sort();for(let e=0;e<o.length&&e<h.length;++e){let i=__PRIVATE_primitiveComparator(o[e],h[e]);if(0!==i)return i;let d=__PRIVATE_valueCompare(s[o[e]],l[h[e]]);if(0!==d)return d}return __PRIVATE_primitiveComparator(o.length,h.length)}(e.mapValue,i.mapValue);default:throw fail()}}function __PRIVATE_compareTimestamps(e,i){if("string"==typeof e&&"string"==typeof i&&e.length===i.length)return __PRIVATE_primitiveComparator(e,i);let s=__PRIVATE_normalizeTimestamp(e),o=__PRIVATE_normalizeTimestamp(i),l=__PRIVATE_primitiveComparator(s.seconds,o.seconds);return 0!==l?l:__PRIVATE_primitiveComparator(s.nanos,o.nanos)}function __PRIVATE_compareArrays(e,i){let s=e.values||[],o=i.values||[];for(let e=0;e<s.length&&e<o.length;++e){let i=__PRIVATE_valueCompare(s[e],o[e]);if(i)return i}return __PRIVATE_primitiveComparator(s.length,o.length)}function __PRIVATE_canonifyValue(e){var i,s;return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){let i=__PRIVATE_normalizeTimestamp(e);return`time(${i.seconds},${i.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?__PRIVATE_normalizeByteString(e.bytesValue).toBase64():"referenceValue"in e?(i=e.referenceValue,DocumentKey.fromName(i).toString()):"geoPointValue"in e?(s=e.geoPointValue,`geo(${s.latitude},${s.longitude})`):"arrayValue"in e?function(e){let i="[",s=!0;for(let o of e.values||[])s?s=!1:i+=",",i+=__PRIVATE_canonifyValue(o);return i+"]"}(e.arrayValue):"mapValue"in e?function(e){let i=Object.keys(e.fields||{}).sort(),s="{",o=!0;for(let l of i)o?o=!1:s+=",",s+=`${l}:${__PRIVATE_canonifyValue(e.fields[l])}`;return s+"}"}(e.mapValue):fail()}function isInteger(e){return!!e&&"integerValue"in e}function isArray(e){return!!e&&"arrayValue"in e}function __PRIVATE_isNullValue(e){return!!e&&"nullValue"in e}function __PRIVATE_isNanValue(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function __PRIVATE_isMapValue(e){return!!e&&"mapValue"in e}function __PRIVATE_isVectorValue(e){var i,s;return"__vector__"===(null===(s=((null===(i=null==e?void 0:e.mapValue)||void 0===i?void 0:i.fields)||{}).__type__)||void 0===s?void 0:s.stringValue)}function __PRIVATE_deepClone(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){let i={mapValue:{fields:{}}};return forEach(e.mapValue.fields,(e,s)=>i.mapValue.fields[e]=__PRIVATE_deepClone(s)),i}if(e.arrayValue){let i={arrayValue:{values:[]}};for(let s=0;s<(e.arrayValue.values||[]).length;++s)i.arrayValue.values[s]=__PRIVATE_deepClone(e.arrayValue.values[s]);return i}return Object.assign({},e)}function __PRIVATE_isMaxValue(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ObjectValue=class ObjectValue{constructor(e){this.value=e}static empty(){return new ObjectValue({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let i=this.value;for(let s=0;s<e.length-1;++s)if(!__PRIVATE_isMapValue(i=(i.mapValue.fields||{})[e.get(s)]))return null;return(i=(i.mapValue.fields||{})[e.lastSegment()])||null}}set(e,i){this.getFieldsMap(e.popLast())[e.lastSegment()]=__PRIVATE_deepClone(i)}setAll(e){let i=FieldPath$1.emptyPath(),s={},o=[];e.forEach((e,l)=>{if(!i.isImmediateParentOf(l)){let e=this.getFieldsMap(i);this.applyChanges(e,s,o),s={},o=[],i=l.popLast()}e?s[l.lastSegment()]=__PRIVATE_deepClone(e):o.push(l.lastSegment())});let l=this.getFieldsMap(i);this.applyChanges(l,s,o)}delete(e){let i=this.field(e.popLast());__PRIVATE_isMapValue(i)&&i.mapValue.fields&&delete i.mapValue.fields[e.lastSegment()]}isEqual(e){return __PRIVATE_valueEquals(this.value,e.value)}getFieldsMap(e){let i=this.value;i.mapValue.fields||(i.mapValue={fields:{}});for(let s=0;s<e.length;++s){let o=i.mapValue.fields[e.get(s)];__PRIVATE_isMapValue(o)&&o.mapValue.fields||(o={mapValue:{fields:{}}},i.mapValue.fields[e.get(s)]=o),i=o}return i.mapValue.fields}applyChanges(e,i,s){for(let o of(forEach(i,(i,s)=>e[i]=s),s))delete e[o]}clone(){return new ObjectValue(__PRIVATE_deepClone(this.value))}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let MutableDocument=class MutableDocument{constructor(e,i,s,o,l,h,d){this.key=e,this.documentType=i,this.version=s,this.readTime=o,this.createTime=l,this.data=h,this.documentState=d}static newInvalidDocument(e){return new MutableDocument(e,0,SnapshotVersion.min(),SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newFoundDocument(e,i,s,o){return new MutableDocument(e,1,i,SnapshotVersion.min(),s,o,0)}static newNoDocument(e,i){return new MutableDocument(e,2,i,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newUnknownDocument(e,i){return new MutableDocument(e,3,i,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),2)}convertToFoundDocument(e,i){return this.createTime.isEqual(SnapshotVersion.min())&&(2===this.documentType||0===this.documentType)&&(this.createTime=e),this.version=e,this.documentType=1,this.data=i,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=ObjectValue.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ObjectValue.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=SnapshotVersion.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof MutableDocument&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new MutableDocument(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}};/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Bound=class Bound{constructor(e,i){this.position=e,this.inclusive=i}};function __PRIVATE_boundCompareToDocument(e,i,s){let o=0;for(let l=0;l<e.position.length;l++){let h=i[l],d=e.position[l];if(o=h.field.isKeyField()?DocumentKey.comparator(DocumentKey.fromName(d.referenceValue),s.key):__PRIVATE_valueCompare(d,s.data.field(h.field)),"desc"===h.dir&&(o*=-1),0!==o)break}return o}function __PRIVATE_boundEquals(e,i){if(null===e)return null===i;if(null===i||e.inclusive!==i.inclusive||e.position.length!==i.position.length)return!1;for(let s=0;s<e.position.length;s++)if(!__PRIVATE_valueEquals(e.position[s],i.position[s]))return!1;return!0}/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let OrderBy=class OrderBy{constructor(e,i="asc"){this.field=e,this.dir=i}};/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Filter=class Filter{};let FieldFilter=class FieldFilter extends Filter{constructor(e,i,s){super(),this.field=e,this.op=i,this.value=s}static create(e,i,s){return e.isKeyField()?"in"===i||"not-in"===i?this.createKeyFieldInFilter(e,i,s):new __PRIVATE_KeyFieldFilter(e,i,s):"array-contains"===i?new __PRIVATE_ArrayContainsFilter(e,s):"in"===i?new __PRIVATE_InFilter(e,s):"not-in"===i?new __PRIVATE_NotInFilter(e,s):"array-contains-any"===i?new __PRIVATE_ArrayContainsAnyFilter(e,s):new FieldFilter(e,i,s)}static createKeyFieldInFilter(e,i,s){return"in"===i?new __PRIVATE_KeyFieldInFilter(e,s):new __PRIVATE_KeyFieldNotInFilter(e,s)}matches(e){let i=e.data.field(this.field);return"!="===this.op?null!==i&&this.matchesComparison(__PRIVATE_valueCompare(i,this.value)):null!==i&&__PRIVATE_typeOrder(this.value)===__PRIVATE_typeOrder(i)&&this.matchesComparison(__PRIVATE_valueCompare(i,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return fail()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}};let CompositeFilter=class CompositeFilter extends Filter{constructor(e,i){super(),this.filters=e,this.op=i,this.ae=null}static create(e,i){return new CompositeFilter(e,i)}matches(e){return __PRIVATE_compositeFilterIsConjunction(this)?void 0===this.filters.find(i=>!i.matches(e)):void 0!==this.filters.find(i=>i.matches(e))}getFlattenedFilters(){return null!==this.ae||(this.ae=this.filters.reduce((e,i)=>e.concat(i.getFlattenedFilters()),[])),this.ae}getFilters(){return Object.assign([],this.filters)}};function __PRIVATE_compositeFilterIsConjunction(e){return"and"===e.op}function __PRIVATE_compositeFilterIsFlat(e){for(let i of e.filters)if(i instanceof CompositeFilter)return!1;return!0}let __PRIVATE_KeyFieldFilter=class __PRIVATE_KeyFieldFilter extends FieldFilter{constructor(e,i,s){super(e,i,s),this.key=DocumentKey.fromName(s.referenceValue)}matches(e){let i=DocumentKey.comparator(e.key,this.key);return this.matchesComparison(i)}};let __PRIVATE_KeyFieldInFilter=class __PRIVATE_KeyFieldInFilter extends FieldFilter{constructor(e,i){super(e,"in",i),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("in",i)}matches(e){return this.keys.some(i=>i.isEqual(e.key))}};let __PRIVATE_KeyFieldNotInFilter=class __PRIVATE_KeyFieldNotInFilter extends FieldFilter{constructor(e,i){super(e,"not-in",i),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("not-in",i)}matches(e){return!this.keys.some(i=>i.isEqual(e.key))}};function __PRIVATE_extractDocumentKeysFromArrayValue(e,i){var s;return((null===(s=i.arrayValue)||void 0===s?void 0:s.values)||[]).map(e=>DocumentKey.fromName(e.referenceValue))}let __PRIVATE_ArrayContainsFilter=class __PRIVATE_ArrayContainsFilter extends FieldFilter{constructor(e,i){super(e,"array-contains",i)}matches(e){let i=e.data.field(this.field);return isArray(i)&&__PRIVATE_arrayValueContains(i.arrayValue,this.value)}};let __PRIVATE_InFilter=class __PRIVATE_InFilter extends FieldFilter{constructor(e,i){super(e,"in",i)}matches(e){let i=e.data.field(this.field);return null!==i&&__PRIVATE_arrayValueContains(this.value.arrayValue,i)}};let __PRIVATE_NotInFilter=class __PRIVATE_NotInFilter extends FieldFilter{constructor(e,i){super(e,"not-in",i)}matches(e){if(__PRIVATE_arrayValueContains(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let i=e.data.field(this.field);return null!==i&&!__PRIVATE_arrayValueContains(this.value.arrayValue,i)}};let __PRIVATE_ArrayContainsAnyFilter=class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter{constructor(e,i){super(e,"array-contains-any",i)}matches(e){let i=e.data.field(this.field);return!(!isArray(i)||!i.arrayValue.values)&&i.arrayValue.values.some(e=>__PRIVATE_arrayValueContains(this.value.arrayValue,e))}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_TargetImpl=class __PRIVATE_TargetImpl{constructor(e,i=null,s=[],o=[],l=null,h=null,d=null){this.path=e,this.collectionGroup=i,this.orderBy=s,this.filters=o,this.limit=l,this.startAt=h,this.endAt=d,this.ue=null}};function __PRIVATE_newTarget(e,i=null,s=[],o=[],l=null,h=null,d=null){return new __PRIVATE_TargetImpl(e,i,s,o,l,h,d)}function __PRIVATE_canonifyTarget(e){if(null===e.ue){let i=e.path.canonicalString();null!==e.collectionGroup&&(i+="|cg:"+e.collectionGroup),i+="|f:"+e.filters.map(e=>(function __PRIVATE_canonifyFilter(e){if(e instanceof FieldFilter)return e.field.canonicalString()+e.op.toString()+__PRIVATE_canonifyValue(e.value);if(__PRIVATE_compositeFilterIsFlat(e)&&__PRIVATE_compositeFilterIsConjunction(e))return e.filters.map(e=>__PRIVATE_canonifyFilter(e)).join(",");{let i=e.filters.map(e=>__PRIVATE_canonifyFilter(e)).join(",");return`${e.op}(${i})`}})(e)).join(",")+"|ob:"+e.orderBy.map(e=>e.field.canonicalString()+e.dir).join(","),null==e.limit||(i+="|l:"+e.limit),e.startAt&&(i+="|lb:"+(e.startAt.inclusive?"b:":"a:")+e.startAt.position.map(e=>__PRIVATE_canonifyValue(e)).join(",")),e.endAt&&(i+="|ub:"+(e.endAt.inclusive?"a:":"b:")+e.endAt.position.map(e=>__PRIVATE_canonifyValue(e)).join(",")),e.ue=i}return e.ue}function __PRIVATE_targetEquals(e,i){if(e.limit!==i.limit||e.orderBy.length!==i.orderBy.length)return!1;for(let l=0;l<e.orderBy.length;l++){var s,o;if(s=e.orderBy[l],o=i.orderBy[l],!(s.dir===o.dir&&s.field.isEqual(o.field)))return!1}if(e.filters.length!==i.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!function __PRIVATE_filterEquals(e,i){return e instanceof FieldFilter?i instanceof FieldFilter&&e.op===i.op&&e.field.isEqual(i.field)&&__PRIVATE_valueEquals(e.value,i.value):e instanceof CompositeFilter?i instanceof CompositeFilter&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce((e,s,o)=>e&&__PRIVATE_filterEquals(s,i.filters[o]),!0):void fail()}(e.filters[s],i.filters[s]))return!1;return e.collectionGroup===i.collectionGroup&&!!e.path.isEqual(i.path)&&!!__PRIVATE_boundEquals(e.startAt,i.startAt)&&__PRIVATE_boundEquals(e.endAt,i.endAt)}function __PRIVATE_targetIsDocumentTarget(e){return DocumentKey.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_QueryImpl=class __PRIVATE_QueryImpl{constructor(e,i=null,s=[],o=[],l=null,h="F",d=null,f=null){this.path=e,this.collectionGroup=i,this.explicitOrderBy=s,this.filters=o,this.limit=l,this.limitType=h,this.startAt=d,this.endAt=f,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}};function __PRIVATE_queryMatchesAllDocuments(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function __PRIVATE_queryNormalizedOrderBy(e){if(null===e.ce){let i;e.ce=[];let s=new Set;for(let i of e.explicitOrderBy)e.ce.push(i),s.add(i.field.canonicalString());let o=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc",l=(i=new SortedSet(FieldPath$1.comparator),e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(i=i.add(e.field))})}),i);l.forEach(i=>{s.has(i.canonicalString())||i.isKeyField()||e.ce.push(new OrderBy(i,o))}),s.has(FieldPath$1.keyField().canonicalString())||e.ce.push(new OrderBy(FieldPath$1.keyField(),o))}return e.ce}function __PRIVATE_queryToTarget(e){return e.le||(e.le=function(e,i){if("F"===e.limitType)return __PRIVATE_newTarget(e.path,e.collectionGroup,i,e.filters,e.limit,e.startAt,e.endAt);{i=i.map(e=>{let i="desc"===e.dir?"asc":"desc";return new OrderBy(e.field,i)});let s=e.endAt?new Bound(e.endAt.position,e.endAt.inclusive):null,o=e.startAt?new Bound(e.startAt.position,e.startAt.inclusive):null;return __PRIVATE_newTarget(e.path,e.collectionGroup,i,e.filters,e.limit,s,o)}}(e,__PRIVATE_queryNormalizedOrderBy(e))),e.le}function __PRIVATE_queryWithLimit(e,i,s){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),i,s,e.startAt,e.endAt)}function __PRIVATE_queryEquals(e,i){return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e),__PRIVATE_queryToTarget(i))&&e.limitType===i.limitType}function __PRIVATE_canonifyQuery(e){return`${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`}function __PRIVATE_stringifyQuery(e){var i;let s;return`Query(target=${s=(i=__PRIVATE_queryToTarget(e)).path.canonicalString(),null!==i.collectionGroup&&(s+=" collectionGroup="+i.collectionGroup),i.filters.length>0&&(s+=`, filters: [${i.filters.map(e=>(function __PRIVATE_stringifyFilter(e){return e instanceof FieldFilter?`${e.field.canonicalString()} ${e.op} ${__PRIVATE_canonifyValue(e.value)}`:e instanceof CompositeFilter?e.op.toString()+" {"+e.getFilters().map(__PRIVATE_stringifyFilter).join(" ,")+"}":"Filter"})(e)).join(", ")}]`),null==i.limit||(s+=", limit: "+i.limit),i.orderBy.length>0&&(s+=`, orderBy: [${i.orderBy.map(e=>`${e.field.canonicalString()} (${e.dir})`).join(", ")}]`),i.startAt&&(s+=", startAt: "+(i.startAt.inclusive?"b:":"a:")+i.startAt.position.map(e=>__PRIVATE_canonifyValue(e)).join(",")),i.endAt&&(s+=", endAt: "+(i.endAt.inclusive?"a:":"b:")+i.endAt.position.map(e=>__PRIVATE_canonifyValue(e)).join(",")),`Target(${s})`}; limitType=${e.limitType})`}function __PRIVATE_queryMatches(e,i){return i.isFoundDocument()&&function(e,i){let s=i.key.path;return null!==e.collectionGroup?i.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(s):DocumentKey.isDocumentKey(e.path)?e.path.isEqual(s):e.path.isImmediateParentOf(s)}(e,i)&&function(e,i){for(let s of __PRIVATE_queryNormalizedOrderBy(e))if(!s.field.isKeyField()&&null===i.data.field(s.field))return!1;return!0}(e,i)&&function(e,i){for(let s of e.filters)if(!s.matches(i))return!1;return!0}(e,i)&&(!e.startAt||!!function(e,i,s){let o=__PRIVATE_boundCompareToDocument(e,i,s);return e.inclusive?o<=0:o<0}(e.startAt,__PRIVATE_queryNormalizedOrderBy(e),i))&&(!e.endAt||!!function(e,i,s){let o=__PRIVATE_boundCompareToDocument(e,i,s);return e.inclusive?o>=0:o>0}(e.endAt,__PRIVATE_queryNormalizedOrderBy(e),i))}function __PRIVATE_newQueryComparator(e){return(i,s)=>{let o=!1;for(let l of __PRIVATE_queryNormalizedOrderBy(e)){let e=function(e,i,s){let o=e.field.isKeyField()?DocumentKey.comparator(i.key,s.key):function(e,i,s){let o=i.data.field(e),l=s.data.field(e);return null!==o&&null!==l?__PRIVATE_valueCompare(o,l):fail()}(e.field,i,s);switch(e.dir){case"asc":return o;case"desc":return -1*o;default:return fail()}}(l,i,s);if(0!==e)return e;o=o||l.field.isKeyField()}return 0}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ObjectMap=class ObjectMap{constructor(e,i){this.mapKeyFn=e,this.equalsFn=i,this.inner={},this.innerSize=0}get(e){let i=this.mapKeyFn(e),s=this.inner[i];if(void 0!==s){for(let[i,o]of s)if(this.equalsFn(i,e))return o}}has(e){return void 0!==this.get(e)}set(e,i){let s=this.mapKeyFn(e),o=this.inner[s];if(void 0===o)return this.inner[s]=[[e,i]],void this.innerSize++;for(let s=0;s<o.length;s++)if(this.equalsFn(o[s][0],e))return void(o[s]=[e,i]);o.push([e,i]),this.innerSize++}delete(e){let i=this.mapKeyFn(e),s=this.inner[i];if(void 0===s)return!1;for(let o=0;o<s.length;o++)if(this.equalsFn(s[o][0],e))return 1===s.length?delete this.inner[i]:s.splice(o,1),this.innerSize--,!0;return!1}forEach(e){forEach(this.inner,(i,s)=>{for(let[i,o]of s)e(i,o)})}isEmpty(){return isEmpty(this.inner)}size(){return this.innerSize}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ey=new SortedMap(DocumentKey.comparator),eE=new SortedMap(DocumentKey.comparator);function documentMap(...e){let i=eE;for(let s of e)i=i.insert(s.key,s);return i}function __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e){let i=eE;return e.forEach((e,s)=>i=i.insert(e,s.overlayedDocument)),i}function __PRIVATE_newDocumentKeyMap(){return new ObjectMap(e=>e.toString(),(e,i)=>e.isEqual(i))}let ev=new SortedMap(DocumentKey.comparator),eT=new SortedSet(DocumentKey.comparator);function __PRIVATE_documentKeySet(...e){let i=eT;for(let s of e)i=i.add(s);return i}let eI=new SortedSet(__PRIVATE_primitiveComparator);/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function __PRIVATE_toDouble(e,i){if(e.useProto3Json){if(isNaN(i))return{doubleValue:"NaN"};if(i===1/0)return{doubleValue:"Infinity"};if(i===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:__PRIVATE_isNegativeZero(i)?"-0":i}}function __PRIVATE_toInteger(e){return{integerValue:""+e}}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let TransformOperation=class TransformOperation{constructor(){this._=void 0}};function __PRIVATE_computeTransformOperationBaseValue(e,i){return e instanceof __PRIVATE_NumericIncrementTransformOperation?isInteger(i)||i&&"doubleValue"in i?i:{integerValue:0}:null}let __PRIVATE_ServerTimestampTransform=class __PRIVATE_ServerTimestampTransform extends TransformOperation{};let __PRIVATE_ArrayUnionTransformOperation=class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}};function __PRIVATE_applyArrayUnionTransformOperation(e,i){let s=__PRIVATE_coercedFieldValuesArray(i);for(let i of e.elements)s.some(e=>__PRIVATE_valueEquals(e,i))||s.push(i);return{arrayValue:{values:s}}}let __PRIVATE_ArrayRemoveTransformOperation=class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}};function __PRIVATE_applyArrayRemoveTransformOperation(e,i){let s=__PRIVATE_coercedFieldValuesArray(i);for(let i of e.elements)s=s.filter(e=>!__PRIVATE_valueEquals(e,i));return{arrayValue:{values:s}}}let __PRIVATE_NumericIncrementTransformOperation=class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation{constructor(e,i){super(),this.serializer=e,this.Pe=i}};function asNumber(e){return __PRIVATE_normalizeNumber(e.integerValue||e.doubleValue)}function __PRIVATE_coercedFieldValuesArray(e){return isArray(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FieldTransform=class FieldTransform{constructor(e,i){this.field=e,this.transform=i}};let MutationResult=class MutationResult{constructor(e,i){this.version=e,this.transformResults=i}};let Precondition=class Precondition{constructor(e,i){this.updateTime=e,this.exists=i}static none(){return new Precondition}static exists(e){return new Precondition(void 0,e)}static updateTime(e){return new Precondition(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}};function __PRIVATE_preconditionIsValidForDocument(e,i){return void 0!==e.updateTime?i.isFoundDocument()&&i.version.isEqual(e.updateTime):void 0===e.exists||e.exists===i.isFoundDocument()}let Mutation=class Mutation{};function __PRIVATE_calculateOverlayMutation(e,i){if(!e.hasLocalMutations||i&&0===i.fields.length)return null;if(null===i)return e.isNoDocument()?new __PRIVATE_DeleteMutation(e.key,Precondition.none()):new __PRIVATE_SetMutation(e.key,e.data,Precondition.none());{let s=e.data,o=ObjectValue.empty(),l=new SortedSet(FieldPath$1.comparator);for(let e of i.fields)if(!l.has(e)){let i=s.field(e);null===i&&e.length>1&&(e=e.popLast(),i=s.field(e)),null===i?o.delete(e):o.set(e,i),l=l.add(e)}return new __PRIVATE_PatchMutation(e.key,o,new FieldMask(l.toArray()),Precondition.none())}}function __PRIVATE_mutationApplyToLocalView(e,i,s,o){return e instanceof __PRIVATE_SetMutation?function(e,i,s,o){if(!__PRIVATE_preconditionIsValidForDocument(e.precondition,i))return s;let l=e.value.clone(),h=__PRIVATE_localTransformResults(e.fieldTransforms,o,i);return l.setAll(h),i.convertToFoundDocument(i.version,l).setHasLocalMutations(),null}(e,i,s,o):e instanceof __PRIVATE_PatchMutation?function(e,i,s,o){if(!__PRIVATE_preconditionIsValidForDocument(e.precondition,i))return s;let l=__PRIVATE_localTransformResults(e.fieldTransforms,o,i),h=i.data;return(h.setAll(__PRIVATE_getPatch(e)),h.setAll(l),i.convertToFoundDocument(i.version,h).setHasLocalMutations(),null===s)?null:s.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,i,s,o):__PRIVATE_preconditionIsValidForDocument(e.precondition,i)?(i.convertToNoDocument(i.version).setHasLocalMutations(),null):s}function __PRIVATE_mutationEquals(e,i){var s,o;return e.type===i.type&&!!e.key.isEqual(i.key)&&!!e.precondition.isEqual(i.precondition)&&(s=e.fieldTransforms,o=i.fieldTransforms,!!(void 0===s&&void 0===o||!(!s||!o)&&__PRIVATE_arrayEquals(s,o,(e,i)=>{var s,o;return e.field.isEqual(i.field)&&(s=e.transform,o=i.transform,s instanceof __PRIVATE_ArrayUnionTransformOperation&&o instanceof __PRIVATE_ArrayUnionTransformOperation||s instanceof __PRIVATE_ArrayRemoveTransformOperation&&o instanceof __PRIVATE_ArrayRemoveTransformOperation?__PRIVATE_arrayEquals(s.elements,o.elements,__PRIVATE_valueEquals):s instanceof __PRIVATE_NumericIncrementTransformOperation&&o instanceof __PRIVATE_NumericIncrementTransformOperation?__PRIVATE_valueEquals(s.Pe,o.Pe):s instanceof __PRIVATE_ServerTimestampTransform&&o instanceof __PRIVATE_ServerTimestampTransform)})))&&(0===e.type?e.value.isEqual(i.value):1!==e.type||e.data.isEqual(i.data)&&e.fieldMask.isEqual(i.fieldMask))}let __PRIVATE_SetMutation=class __PRIVATE_SetMutation extends Mutation{constructor(e,i,s,o=[]){super(),this.key=e,this.value=i,this.precondition=s,this.fieldTransforms=o,this.type=0}getFieldMask(){return null}};let __PRIVATE_PatchMutation=class __PRIVATE_PatchMutation extends Mutation{constructor(e,i,s,o,l=[]){super(),this.key=e,this.data=i,this.fieldMask=s,this.precondition=o,this.fieldTransforms=l,this.type=1}getFieldMask(){return this.fieldMask}};function __PRIVATE_getPatch(e){let i=new Map;return e.fieldMask.fields.forEach(s=>{if(!s.isEmpty()){let o=e.data.field(s);i.set(s,o)}}),i}function __PRIVATE_serverTransformResults(e,i,s){var o;let l=new Map;e.length===s.length||fail();for(let h=0;h<s.length;h++){let d=e[h],f=d.transform,_=i.data.field(d.field);l.set(d.field,(o=s[h],f instanceof __PRIVATE_ArrayUnionTransformOperation?__PRIVATE_applyArrayUnionTransformOperation(f,_):f instanceof __PRIVATE_ArrayRemoveTransformOperation?__PRIVATE_applyArrayRemoveTransformOperation(f,_):o))}return l}function __PRIVATE_localTransformResults(e,i,s){let o=new Map;for(let l of e){let e=l.transform,h=s.data.field(l.field);o.set(l.field,e instanceof __PRIVATE_ServerTimestampTransform?function(e,i){let s={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return i&&__PRIVATE_isServerTimestamp(i)&&(i=__PRIVATE_getPreviousValue(i)),i&&(s.fields.__previous_value__=i),{mapValue:s}}(i,h):e instanceof __PRIVATE_ArrayUnionTransformOperation?__PRIVATE_applyArrayUnionTransformOperation(e,h):e instanceof __PRIVATE_ArrayRemoveTransformOperation?__PRIVATE_applyArrayRemoveTransformOperation(e,h):function(e,i){let s=__PRIVATE_computeTransformOperationBaseValue(e,i),o=asNumber(s)+asNumber(e.Pe);return isInteger(s)&&isInteger(e.Pe)?__PRIVATE_toInteger(o):__PRIVATE_toDouble(e.serializer,o)}(e,h))}return o}let __PRIVATE_DeleteMutation=class __PRIVATE_DeleteMutation extends Mutation{constructor(e,i){super(),this.key=e,this.precondition=i,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}};let __PRIVATE_VerifyMutation=class __PRIVATE_VerifyMutation extends Mutation{constructor(e,i){super(),this.key=e,this.precondition=i,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let MutationBatch=class MutationBatch{constructor(e,i,s,o){this.batchId=e,this.localWriteTime=i,this.baseMutations=s,this.mutations=o}applyToRemoteDocument(e,i){let s=i.mutationResults;for(let i=0;i<this.mutations.length;i++){let l=this.mutations[i];if(l.key.isEqual(e.key)){var o;o=s[i],l instanceof __PRIVATE_SetMutation?function(e,i,s){let o=e.value.clone(),l=__PRIVATE_serverTransformResults(e.fieldTransforms,i,s.transformResults);o.setAll(l),i.convertToFoundDocument(s.version,o).setHasCommittedMutations()}(l,e,o):l instanceof __PRIVATE_PatchMutation?function(e,i,s){if(!__PRIVATE_preconditionIsValidForDocument(e.precondition,i))return void i.convertToUnknownDocument(s.version);let o=__PRIVATE_serverTransformResults(e.fieldTransforms,i,s.transformResults),l=i.data;l.setAll(__PRIVATE_getPatch(e)),l.setAll(o),i.convertToFoundDocument(s.version,l).setHasCommittedMutations()}(l,e,o):function(e,i,s){i.convertToNoDocument(s.version).setHasCommittedMutations()}(0,e,o)}}}applyToLocalView(e,i){for(let s of this.baseMutations)s.key.isEqual(e.key)&&(i=__PRIVATE_mutationApplyToLocalView(s,e,i,this.localWriteTime));for(let s of this.mutations)s.key.isEqual(e.key)&&(i=__PRIVATE_mutationApplyToLocalView(s,e,i,this.localWriteTime));return i}applyToLocalDocumentSet(e,i){let s=__PRIVATE_newDocumentKeyMap();return this.mutations.forEach(o=>{let l=e.get(o.key),h=l.overlayedDocument,d=this.applyToLocalView(h,l.mutatedFields);d=i.has(o.key)?null:d;let f=__PRIVATE_calculateOverlayMutation(h,d);null!==f&&s.set(o.key,f),h.isValidDocument()||h.convertToNoDocument(SnapshotVersion.min())}),s}keys(){return this.mutations.reduce((e,i)=>e.add(i.key),__PRIVATE_documentKeySet())}isEqual(e){return this.batchId===e.batchId&&__PRIVATE_arrayEquals(this.mutations,e.mutations,(e,i)=>__PRIVATE_mutationEquals(e,i))&&__PRIVATE_arrayEquals(this.baseMutations,e.baseMutations,(e,i)=>__PRIVATE_mutationEquals(e,i))}};let MutationBatchResult=class MutationBatchResult{constructor(e,i,s,o){this.batch=e,this.commitVersion=i,this.mutationResults=s,this.docVersions=o}static from(e,i,s){e.mutations.length===s.length||fail();let o=ev,l=e.mutations;for(let e=0;e<l.length;e++)o=o.insert(l[e].key,s[e].version);return new MutationBatchResult(e,i,s,o)}};/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Overlay=class Overlay{constructor(e,i){this.largestBatchId=e,this.mutation=i}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{
      largestBatchId: ${this.largestBatchId},
      mutation: ${this.mutation.toString()}
    }`}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ExistenceFilter=class ExistenceFilter{constructor(e,i){this.count=e,this.unchangedNames=i}};function __PRIVATE_mapCodeFromRpcCode(e){if(void 0===e)return __PRIVATE_logError("GRPC error has no .code"),e_.UNKNOWN;switch(e){case O.OK:return e_.OK;case O.CANCELLED:return e_.CANCELLED;case O.UNKNOWN:return e_.UNKNOWN;case O.DEADLINE_EXCEEDED:return e_.DEADLINE_EXCEEDED;case O.RESOURCE_EXHAUSTED:return e_.RESOURCE_EXHAUSTED;case O.INTERNAL:return e_.INTERNAL;case O.UNAVAILABLE:return e_.UNAVAILABLE;case O.UNAUTHENTICATED:return e_.UNAUTHENTICATED;case O.INVALID_ARGUMENT:return e_.INVALID_ARGUMENT;case O.NOT_FOUND:return e_.NOT_FOUND;case O.ALREADY_EXISTS:return e_.ALREADY_EXISTS;case O.PERMISSION_DENIED:return e_.PERMISSION_DENIED;case O.FAILED_PRECONDITION:return e_.FAILED_PRECONDITION;case O.ABORTED:return e_.ABORTED;case O.OUT_OF_RANGE:return e_.OUT_OF_RANGE;case O.UNIMPLEMENTED:return e_.UNIMPLEMENTED;case O.DATA_LOSS:return e_.DATA_LOSS;default:return fail()}}(j=O||(O={}))[j.OK=0]="OK",j[j.CANCELLED=1]="CANCELLED",j[j.UNKNOWN=2]="UNKNOWN",j[j.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",j[j.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",j[j.NOT_FOUND=5]="NOT_FOUND",j[j.ALREADY_EXISTS=6]="ALREADY_EXISTS",j[j.PERMISSION_DENIED=7]="PERMISSION_DENIED",j[j.UNAUTHENTICATED=16]="UNAUTHENTICATED",j[j.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",j[j.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",j[j.ABORTED=10]="ABORTED",j[j.OUT_OF_RANGE=11]="OUT_OF_RANGE",j[j.UNIMPLEMENTED=12]="UNIMPLEMENTED",j[j.INTERNAL=13]="INTERNAL",j[j.UNAVAILABLE=14]="UNAVAILABLE",j[j.DATA_LOSS=15]="DATA_LOSS";/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let eA=new o([4294967295,4294967295],0);function __PRIVATE_getMd5HashValue(e){let i=(new TextEncoder).encode(e),s=new l;return s.update(i),new Uint8Array(s.digest())}function __PRIVATE_get64BitUints(e){let i=new DataView(e.buffer),s=i.getUint32(0,!0),l=i.getUint32(4,!0),h=i.getUint32(8,!0),d=i.getUint32(12,!0);return[new o([s,l],0),new o([h,d],0)]}let BloomFilter=class BloomFilter{constructor(e,i,s){if(this.bitmap=e,this.padding=i,this.hashCount=s,i<0||i>=8)throw new __PRIVATE_BloomFilterError(`Invalid padding: ${i}`);if(s<0||e.length>0&&0===this.hashCount)throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${s}`);if(0===e.length&&0!==i)throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${i}`);this.Ie=8*e.length-i,this.Te=o.fromNumber(this.Ie)}Ee(e,i,s){let l=e.add(i.multiply(o.fromNumber(s)));return 1===l.compare(eA)&&(l=new o([l.getBits(0),l.getBits(1)],0)),l.modulo(this.Te).toNumber()}de(e){return 0!=(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Ie)return!1;let i=__PRIVATE_getMd5HashValue(e),[s,o]=__PRIVATE_get64BitUints(i);for(let e=0;e<this.hashCount;e++){let i=this.Ee(s,o,e);if(!this.de(i))return!1}return!0}static create(e,i,s){let o=new Uint8Array(Math.ceil(e/8)),l=new BloomFilter(o,e%8==0?0:8-e%8,i);return s.forEach(e=>l.insert(e)),l}insert(e){if(0===this.Ie)return;let i=__PRIVATE_getMd5HashValue(e),[s,o]=__PRIVATE_get64BitUints(i);for(let e=0;e<this.hashCount;e++){let i=this.Ee(s,o,e);this.Ae(i)}}Ae(e){this.bitmap[Math.floor(e/8)]|=1<<e%8}};let __PRIVATE_BloomFilterError=class __PRIVATE_BloomFilterError extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let RemoteEvent=class RemoteEvent{constructor(e,i,s,o,l){this.snapshotVersion=e,this.targetChanges=i,this.targetMismatches=s,this.documentUpdates=o,this.resolvedLimboDocuments=l}static createSynthesizedRemoteEventForCurrentChange(e,i,s){let o=new Map;return o.set(e,TargetChange.createSynthesizedTargetChangeForCurrentChange(e,i,s)),new RemoteEvent(SnapshotVersion.min(),o,new SortedMap(__PRIVATE_primitiveComparator),ey,__PRIVATE_documentKeySet())}};let TargetChange=class TargetChange{constructor(e,i,s,o,l){this.resumeToken=e,this.current=i,this.addedDocuments=s,this.modifiedDocuments=o,this.removedDocuments=l}static createSynthesizedTargetChangeForCurrentChange(e,i,s){return new TargetChange(s,i,__PRIVATE_documentKeySet(),__PRIVATE_documentKeySet(),__PRIVATE_documentKeySet())}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_DocumentWatchChange=class __PRIVATE_DocumentWatchChange{constructor(e,i,s,o){this.Re=e,this.removedTargetIds=i,this.key=s,this.Ve=o}};let __PRIVATE_ExistenceFilterChange=class __PRIVATE_ExistenceFilterChange{constructor(e,i){this.targetId=e,this.me=i}};let __PRIVATE_WatchTargetChange=class __PRIVATE_WatchTargetChange{constructor(e,i,s=ByteString.EMPTY_BYTE_STRING,o=null){this.state=e,this.targetIds=i,this.resumeToken=s,this.cause=o}};let __PRIVATE_TargetState=class __PRIVATE_TargetState{constructor(){this.fe=0,this.ge=__PRIVATE_snapshotChangesMap(),this.pe=ByteString.EMPTY_BYTE_STRING,this.ye=!1,this.we=!0}get current(){return this.ye}get resumeToken(){return this.pe}get Se(){return 0!==this.fe}get be(){return this.we}De(e){e.approximateByteSize()>0&&(this.we=!0,this.pe=e)}ve(){let e=__PRIVATE_documentKeySet(),i=__PRIVATE_documentKeySet(),s=__PRIVATE_documentKeySet();return this.ge.forEach((o,l)=>{switch(l){case 0:e=e.add(o);break;case 2:i=i.add(o);break;case 1:s=s.add(o);break;default:fail()}}),new TargetChange(this.pe,this.ye,e,i,s)}Ce(){this.we=!1,this.ge=__PRIVATE_snapshotChangesMap()}Fe(e,i){this.we=!0,this.ge=this.ge.insert(e,i)}Me(e){this.we=!0,this.ge=this.ge.remove(e)}xe(){this.fe+=1}Oe(){this.fe-=1,this.fe>=0||fail()}Ne(){this.we=!0,this.ye=!0}};let __PRIVATE_WatchChangeAggregator=class __PRIVATE_WatchChangeAggregator{constructor(e){this.Le=e,this.Be=new Map,this.ke=ey,this.qe=__PRIVATE_documentTargetMap(),this.Qe=new SortedMap(__PRIVATE_primitiveComparator)}Ke(e){for(let i of e.Re)e.Ve&&e.Ve.isFoundDocument()?this.$e(i,e.Ve):this.Ue(i,e.key,e.Ve);for(let i of e.removedTargetIds)this.Ue(i,e.key,e.Ve)}We(e){this.forEachTarget(e,i=>{let s=this.Ge(i);switch(e.state){case 0:this.ze(i)&&s.De(e.resumeToken);break;case 1:s.Oe(),s.Se||s.Ce(),s.De(e.resumeToken);break;case 2:s.Oe(),s.Se||this.removeTarget(i);break;case 3:this.ze(i)&&(s.Ne(),s.De(e.resumeToken));break;case 4:this.ze(i)&&(this.je(i),s.De(e.resumeToken));break;default:fail()}})}forEachTarget(e,i){e.targetIds.length>0?e.targetIds.forEach(i):this.Be.forEach((e,s)=>{this.ze(s)&&i(s)})}He(e){let i=e.targetId,s=e.me.count,o=this.Je(i);if(o){let l=o.target;if(__PRIVATE_targetIsDocumentTarget(l)){if(0===s){let e=new DocumentKey(l.path);this.Ue(i,e,MutableDocument.newNoDocument(e,SnapshotVersion.min()))}else 1===s||fail()}else{let o=this.Ye(i);if(o!==s){let s=this.Ze(e),l=s?this.Xe(s,e,o):1;0!==l&&(this.je(i),this.Qe=this.Qe.insert(i,2===l?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch"))}}}}Ze(e){let i,s;let o=e.me.unchangedNames;if(!o||!o.bits)return null;let{bits:{bitmap:l="",padding:h=0},hashCount:d=0}=o;try{i=__PRIVATE_normalizeByteString(l).toUint8Array()}catch(e){if(e instanceof __PRIVATE_Base64DecodeError)return __PRIVATE_logWarn("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{s=new BloomFilter(i,h,d)}catch(e){return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===s.Ie?null:s}Xe(e,i,s){return i.me.count===s-this.nt(e,i.targetId)?0:2}nt(e,i){let s=this.Le.getRemoteKeysForTarget(i),o=0;return s.forEach(s=>{let l=this.Le.tt(),h=`projects/${l.projectId}/databases/${l.database}/documents/${s.path.canonicalString()}`;e.mightContain(h)||(this.Ue(i,s,null),o++)}),o}rt(e){let i=new Map;this.Be.forEach((s,o)=>{let l=this.Je(o);if(l){if(s.current&&__PRIVATE_targetIsDocumentTarget(l.target)){let i=new DocumentKey(l.target.path);null!==this.ke.get(i)||this.it(o,i)||this.Ue(o,i,MutableDocument.newNoDocument(i,e))}s.be&&(i.set(o,s.ve()),s.Ce())}});let s=__PRIVATE_documentKeySet();this.qe.forEach((e,i)=>{let o=!0;i.forEachWhile(e=>{let i=this.Je(e);return!i||"TargetPurposeLimboResolution"===i.purpose||(o=!1,!1)}),o&&(s=s.add(e))}),this.ke.forEach((i,s)=>s.setReadTime(e));let o=new RemoteEvent(e,i,this.Qe,this.ke,s);return this.ke=ey,this.qe=__PRIVATE_documentTargetMap(),this.Qe=new SortedMap(__PRIVATE_primitiveComparator),o}$e(e,i){if(!this.ze(e))return;let s=this.it(e,i.key)?2:0;this.Ge(e).Fe(i.key,s),this.ke=this.ke.insert(i.key,i),this.qe=this.qe.insert(i.key,this.st(i.key).add(e))}Ue(e,i,s){if(!this.ze(e))return;let o=this.Ge(e);this.it(e,i)?o.Fe(i,1):o.Me(i),this.qe=this.qe.insert(i,this.st(i).delete(e)),s&&(this.ke=this.ke.insert(i,s))}removeTarget(e){this.Be.delete(e)}Ye(e){let i=this.Ge(e).ve();return this.Le.getRemoteKeysForTarget(e).size+i.addedDocuments.size-i.removedDocuments.size}xe(e){this.Ge(e).xe()}Ge(e){let i=this.Be.get(e);return i||(i=new __PRIVATE_TargetState,this.Be.set(e,i)),i}st(e){let i=this.qe.get(e);return i||(i=new SortedSet(__PRIVATE_primitiveComparator),this.qe=this.qe.insert(e,i)),i}ze(e){let i=null!==this.Je(e);return i||__PRIVATE_logDebug("WatchChangeAggregator","Detected inactive target",e),i}Je(e){let i=this.Be.get(e);return i&&i.Se?null:this.Le.ot(e)}je(e){this.Be.set(e,new __PRIVATE_TargetState),this.Le.getRemoteKeysForTarget(e).forEach(i=>{this.Ue(e,i,null)})}it(e,i){return this.Le.getRemoteKeysForTarget(e).has(i)}};function __PRIVATE_documentTargetMap(){return new SortedMap(DocumentKey.comparator)}function __PRIVATE_snapshotChangesMap(){return new SortedMap(DocumentKey.comparator)}let eP={asc:"ASCENDING",desc:"DESCENDING"},eR={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},ew={and:"AND",or:"OR"};let JsonProtoSerializer=class JsonProtoSerializer{constructor(e,i){this.databaseId=e,this.useProto3Json=i}};function __PRIVATE_toInt32Proto(e,i){return e.useProto3Json||null==i?i:{value:i}}function toTimestamp(e,i){return e.useProto3Json?`${new Date(1e3*i.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+i.nanoseconds).slice(-9)}Z`:{seconds:""+i.seconds,nanos:i.nanoseconds}}function __PRIVATE_toBytes(e,i){return e.useProto3Json?i.toBase64():i.toUint8Array()}function __PRIVATE_fromVersion(e){return e||fail(),SnapshotVersion.fromTimestamp(function(e){let i=__PRIVATE_normalizeTimestamp(e);return new Timestamp(i.seconds,i.nanos)}(e))}function __PRIVATE_toResourceName(e,i){return __PRIVATE_toResourcePath(e,i).canonicalString()}function __PRIVATE_toResourcePath(e,i){let s=new ResourcePath(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===i?s:s.child(i)}function __PRIVATE_fromResourceName(e){let i=ResourcePath.fromString(e);return __PRIVATE_isValidResourceName(i)||fail(),i}function __PRIVATE_toName(e,i){return __PRIVATE_toResourceName(e.databaseId,i.path)}function fromName(e,i){let s=__PRIVATE_fromResourceName(i);if(s.get(1)!==e.databaseId.projectId)throw new FirestoreError(e_.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+s.get(1)+" vs "+e.databaseId.projectId);if(s.get(3)!==e.databaseId.database)throw new FirestoreError(e_.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+s.get(3)+" vs "+e.databaseId.database);return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(s))}function __PRIVATE_toQueryPath(e,i){return __PRIVATE_toResourceName(e.databaseId,i)}function __PRIVATE_getEncodedDatabaseId(e){return new ResourcePath(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function __PRIVATE_extractLocalPathFromResourceName(e){return e.length>4&&"documents"===e.get(4)||fail(),e.popFirst(5)}function __PRIVATE_toMutationDocument(e,i,s){return{name:__PRIVATE_toName(e,i),fields:s.value.mapValue.fields}}function __PRIVATE_toFieldPathReference(e){return{fieldPath:e.canonicalString()}}function __PRIVATE_fromFieldPathReference(e){return FieldPath$1.fromServerFormat(e.fieldPath)}function __PRIVATE_isValidResourceName(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let TargetData=class TargetData{constructor(e,i,s,o,l=SnapshotVersion.min(),h=SnapshotVersion.min(),d=ByteString.EMPTY_BYTE_STRING,f=null){this.target=e,this.targetId=i,this.purpose=s,this.sequenceNumber=o,this.snapshotVersion=l,this.lastLimboFreeSnapshotVersion=h,this.resumeToken=d,this.expectedCount=f}withSequenceNumber(e){return new TargetData(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,i){return new TargetData(this.target,this.targetId,this.purpose,this.sequenceNumber,i,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new TargetData(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new TargetData(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_LocalSerializer=class __PRIVATE_LocalSerializer{constructor(e){this.ct=e}};/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_FirestoreIndexValueWriter=class __PRIVATE_FirestoreIndexValueWriter{constructor(){}It(e,i){this.Tt(e,i),i.Et()}Tt(e,i){if("nullValue"in e)this.dt(i,5);else if("booleanValue"in e)this.dt(i,10),i.At(e.booleanValue?1:0);else if("integerValue"in e)this.dt(i,15),i.At(__PRIVATE_normalizeNumber(e.integerValue));else if("doubleValue"in e){let s=__PRIVATE_normalizeNumber(e.doubleValue);isNaN(s)?this.dt(i,13):(this.dt(i,15),__PRIVATE_isNegativeZero(s)?i.At(0):i.At(s))}else if("timestampValue"in e){let s=e.timestampValue;this.dt(i,20),"string"==typeof s&&(s=__PRIVATE_normalizeTimestamp(s)),i.Rt(`${s.seconds||""}`),i.At(s.nanos||0)}else if("stringValue"in e)this.Vt(e.stringValue,i),this.ft(i);else if("bytesValue"in e)this.dt(i,30),i.gt(__PRIVATE_normalizeByteString(e.bytesValue)),this.ft(i);else if("referenceValue"in e)this.yt(e.referenceValue,i);else if("geoPointValue"in e){let s=e.geoPointValue;this.dt(i,45),i.At(s.latitude||0),i.At(s.longitude||0)}else"mapValue"in e?__PRIVATE_isMaxValue(e)?this.dt(i,Number.MAX_SAFE_INTEGER):__PRIVATE_isVectorValue(e)?this.wt(e.mapValue,i):(this.St(e.mapValue,i),this.ft(i)):"arrayValue"in e?(this.bt(e.arrayValue,i),this.ft(i)):fail()}Vt(e,i){this.dt(i,25),this.Dt(e,i)}Dt(e,i){i.Rt(e)}St(e,i){let s=e.fields||{};for(let e of(this.dt(i,55),Object.keys(s)))this.Vt(e,i),this.Tt(s[e],i)}wt(e,i){var s,o;let l=e.fields||{};this.dt(i,53);let h="value",d=(null===(o=null===(s=l[h].arrayValue)||void 0===s?void 0:s.values)||void 0===o?void 0:o.length)||0;this.dt(i,15),i.At(__PRIVATE_normalizeNumber(d)),this.Vt(h,i),this.Tt(l[h],i)}bt(e,i){let s=e.values||[];for(let e of(this.dt(i,50),s))this.Tt(e,i)}yt(e,i){this.dt(i,37),DocumentKey.fromName(e).path.forEach(e=>{this.dt(i,60),this.Dt(e,i)})}dt(e,i){e.At(i)}ft(e){e.At(2)}};__PRIVATE_FirestoreIndexValueWriter.vt=new __PRIVATE_FirestoreIndexValueWriter;/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_MemoryIndexManager=class __PRIVATE_MemoryIndexManager{constructor(){this.un=new __PRIVATE_MemoryCollectionParentIndex}addToCollectionParentIndex(e,i){return this.un.add(i),PersistencePromise.resolve()}getCollectionParents(e,i){return PersistencePromise.resolve(this.un.getEntries(i))}addFieldIndex(e,i){return PersistencePromise.resolve()}deleteFieldIndex(e,i){return PersistencePromise.resolve()}deleteAllFieldIndexes(e){return PersistencePromise.resolve()}createTargetIndexes(e,i){return PersistencePromise.resolve()}getDocumentsMatchingTarget(e,i){return PersistencePromise.resolve(null)}getIndexType(e,i){return PersistencePromise.resolve(0)}getFieldIndexes(e,i){return PersistencePromise.resolve([])}getNextCollectionGroupToUpdate(e){return PersistencePromise.resolve(null)}getMinOffset(e,i){return PersistencePromise.resolve(IndexOffset.min())}getMinOffsetFromCollectionGroup(e,i){return PersistencePromise.resolve(IndexOffset.min())}updateCollectionGroup(e,i,s){return PersistencePromise.resolve()}updateIndexEntries(e,i){return PersistencePromise.resolve()}};let __PRIVATE_MemoryCollectionParentIndex=class __PRIVATE_MemoryCollectionParentIndex{constructor(){this.index={}}add(e){let i=e.lastSegment(),s=e.popLast(),o=this.index[i]||new SortedSet(ResourcePath.comparator),l=!o.has(s);return this.index[i]=o.add(s),l}has(e){let i=e.lastSegment(),s=e.popLast(),o=this.index[i];return o&&o.has(s)}getEntries(e){return(this.index[e]||new SortedSet(ResourcePath.comparator)).toArray()}};new Uint8Array(0);let LruParams=class LruParams{constructor(e,i,s){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=i,this.maximumSequenceNumbersToCollect=s}static withCacheSize(e){return new LruParams(e,LruParams.DEFAULT_COLLECTION_PERCENTILE,LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */LruParams.DEFAULT_COLLECTION_PERCENTILE=10,LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,LruParams.DEFAULT=new LruParams(41943040,LruParams.DEFAULT_COLLECTION_PERCENTILE,LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),LruParams.DISABLED=new LruParams(-1,0,0);/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_TargetIdGenerator=class __PRIVATE_TargetIdGenerator{constructor(e){this.Ln=e}next(){return this.Ln+=2,this.Ln}static Bn(){return new __PRIVATE_TargetIdGenerator(0)}static kn(){return new __PRIVATE_TargetIdGenerator(-1)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let RemoteDocumentChangeBuffer=class RemoteDocumentChangeBuffer{constructor(){this.changes=new ObjectMap(e=>e.toString(),(e,i)=>e.isEqual(i)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,i){this.assertNotApplied(),this.changes.set(e,MutableDocument.newInvalidDocument(e).setReadTime(i))}getEntry(e,i){this.assertNotApplied();let s=this.changes.get(i);return void 0!==s?PersistencePromise.resolve(s):this.getFromCache(e,i)}getEntries(e,i){return this.getAllFromCache(e,i)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *//**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let OverlayedDocument=class OverlayedDocument{constructor(e,i){this.overlayedDocument=e,this.mutatedFields=i}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let LocalDocumentsView=class LocalDocumentsView{constructor(e,i,s,o){this.remoteDocumentCache=e,this.mutationQueue=i,this.documentOverlayCache=s,this.indexManager=o}getDocument(e,i){let s=null;return this.documentOverlayCache.getOverlay(e,i).next(o=>(s=o,this.remoteDocumentCache.getEntry(e,i))).next(e=>(null!==s&&__PRIVATE_mutationApplyToLocalView(s.mutation,e,FieldMask.empty(),Timestamp.now()),e))}getDocuments(e,i){return this.remoteDocumentCache.getEntries(e,i).next(i=>this.getLocalViewOfDocuments(e,i,__PRIVATE_documentKeySet()).next(()=>i))}getLocalViewOfDocuments(e,i,s=__PRIVATE_documentKeySet()){let o=__PRIVATE_newDocumentKeyMap();return this.populateOverlays(e,o,i).next(()=>this.computeViews(e,i,o,s).next(e=>{let i=documentMap();return e.forEach((e,s)=>{i=i.insert(e,s.overlayedDocument)}),i}))}getOverlayedDocuments(e,i){let s=__PRIVATE_newDocumentKeyMap();return this.populateOverlays(e,s,i).next(()=>this.computeViews(e,i,s,__PRIVATE_documentKeySet()))}populateOverlays(e,i,s){let o=[];return s.forEach(e=>{i.has(e)||o.push(e)}),this.documentOverlayCache.getOverlays(e,o).next(e=>{e.forEach((e,s)=>{i.set(e,s)})})}computeViews(e,i,s,o){let l=ey,h=__PRIVATE_newDocumentKeyMap(),d=__PRIVATE_newDocumentKeyMap();return i.forEach((e,i)=>{let d=s.get(i.key);o.has(i.key)&&(void 0===d||d.mutation instanceof __PRIVATE_PatchMutation)?l=l.insert(i.key,i):void 0!==d?(h.set(i.key,d.mutation.getFieldMask()),__PRIVATE_mutationApplyToLocalView(d.mutation,i,d.mutation.getFieldMask(),Timestamp.now())):h.set(i.key,FieldMask.empty())}),this.recalculateAndSaveOverlays(e,l).next(e=>(e.forEach((e,i)=>h.set(e,i)),i.forEach((e,i)=>{var s;return d.set(e,new OverlayedDocument(i,null!==(s=h.get(e))&&void 0!==s?s:null))}),d))}recalculateAndSaveOverlays(e,i){let s=__PRIVATE_newDocumentKeyMap(),o=new SortedMap((e,i)=>e-i),l=__PRIVATE_documentKeySet();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,i).next(e=>{for(let l of e)l.keys().forEach(e=>{let h=i.get(e);if(null===h)return;let d=s.get(e)||FieldMask.empty();d=l.applyToLocalView(h,d),s.set(e,d);let f=(o.get(l.batchId)||__PRIVATE_documentKeySet()).add(e);o=o.insert(l.batchId,f)})}).next(()=>{let h=[],d=o.getReverseIterator();for(;d.hasNext();){let o=d.getNext(),f=o.key,_=o.value,g=__PRIVATE_newDocumentKeyMap();_.forEach(e=>{if(!l.has(e)){let o=__PRIVATE_calculateOverlayMutation(i.get(e),s.get(e));null!==o&&g.set(e,o),l=l.add(e)}}),h.push(this.documentOverlayCache.saveOverlays(e,f,g))}return PersistencePromise.waitFor(h)}).next(()=>s)}recalculateAndSaveOverlaysForDocumentKeys(e,i){return this.remoteDocumentCache.getEntries(e,i).next(i=>this.recalculateAndSaveOverlays(e,i))}getDocumentsMatchingQuery(e,i,s,o){return DocumentKey.isDocumentKey(i.path)&&null===i.collectionGroup&&0===i.filters.length?this.getDocumentsMatchingDocumentQuery(e,i.path):null!==i.collectionGroup?this.getDocumentsMatchingCollectionGroupQuery(e,i,s,o):this.getDocumentsMatchingCollectionQuery(e,i,s,o)}getNextDocuments(e,i,s,o){return this.remoteDocumentCache.getAllFromCollectionGroup(e,i,s,o).next(l=>{let h=o-l.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,i,s.largestBatchId,o-l.size):PersistencePromise.resolve(__PRIVATE_newDocumentKeyMap()),d=-1,f=l;return h.next(i=>PersistencePromise.forEach(i,(i,s)=>(d<s.largestBatchId&&(d=s.largestBatchId),l.get(i)?PersistencePromise.resolve():this.remoteDocumentCache.getEntry(e,i).next(e=>{f=f.insert(i,e)}))).next(()=>this.populateOverlays(e,i,l)).next(()=>this.computeViews(e,f,i,__PRIVATE_documentKeySet())).next(e=>({batchId:d,changes:__PRIVATE_convertOverlayedDocumentMapToDocumentMap(e)})))})}getDocumentsMatchingDocumentQuery(e,i){return this.getDocument(e,new DocumentKey(i)).next(e=>{let i=documentMap();return e.isFoundDocument()&&(i=i.insert(e.key,e)),i})}getDocumentsMatchingCollectionGroupQuery(e,i,s,o){let l=i.collectionGroup,h=documentMap();return this.indexManager.getCollectionParents(e,l).next(d=>PersistencePromise.forEach(d,d=>{var f;let _=(f=d.child(l),new __PRIVATE_QueryImpl(f,null,i.explicitOrderBy.slice(),i.filters.slice(),i.limit,i.limitType,i.startAt,i.endAt));return this.getDocumentsMatchingCollectionQuery(e,_,s,o).next(e=>{e.forEach((e,i)=>{h=h.insert(e,i)})})}).next(()=>h))}getDocumentsMatchingCollectionQuery(e,i,s,o){let l;return this.documentOverlayCache.getOverlaysForCollection(e,i.path,s.largestBatchId).next(h=>(l=h,this.remoteDocumentCache.getDocumentsMatchingQuery(e,i,s,l,o))).next(e=>{l.forEach((i,s)=>{let o=s.getKey();null===e.get(o)&&(e=e.insert(o,MutableDocument.newInvalidDocument(o)))});let s=documentMap();return e.forEach((e,o)=>{let h=l.get(e);void 0!==h&&__PRIVATE_mutationApplyToLocalView(h.mutation,o,FieldMask.empty(),Timestamp.now()),__PRIVATE_queryMatches(i,o)&&(s=s.insert(e,o))}),s})}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_MemoryBundleCache=class __PRIVATE_MemoryBundleCache{constructor(e){this.serializer=e,this.hr=new Map,this.Pr=new Map}getBundleMetadata(e,i){return PersistencePromise.resolve(this.hr.get(i))}saveBundleMetadata(e,i){return this.hr.set(i.id,{id:i.id,version:i.version,createTime:__PRIVATE_fromVersion(i.createTime)}),PersistencePromise.resolve()}getNamedQuery(e,i){return PersistencePromise.resolve(this.Pr.get(i))}saveNamedQuery(e,i){return this.Pr.set(i.name,{name:i.name,query:function(e){let i=function(e){var i,s,o,l,h,d,f,_;let g,b=function(e){let i=__PRIVATE_fromResourceName(e);return 4===i.length?ResourcePath.emptyPath():__PRIVATE_extractLocalPathFromResourceName(i)}(e.parent),w=e.structuredQuery,k=w.from?w.from.length:0,O=null;if(k>0){1===k||fail();let e=w.from[0];e.allDescendants?O=e.collectionId:b=b.child(e.collectionId)}let j=[];w.where&&(j=function(e){var i;let s=function __PRIVATE_fromFilter(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let i=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(i,"==",{doubleValue:NaN});case"IS_NULL":let s=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(s,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let o=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(o,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let l=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(l,"!=",{nullValue:"NULL_VALUE"});default:return fail()}}(e):void 0!==e.fieldFilter?FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return fail()}}(e.fieldFilter.op),e.fieldFilter.value):void 0!==e.compositeFilter?CompositeFilter.create(e.compositeFilter.filters.map(e=>__PRIVATE_fromFilter(e)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return fail()}}(e.compositeFilter.op)):fail()}(e);return s instanceof CompositeFilter&&__PRIVATE_compositeFilterIsFlat(i=s)&&__PRIVATE_compositeFilterIsConjunction(i)?s.getFilters():[s]}(w.where));let q=[];w.orderBy&&(q=w.orderBy.map(e=>new OrderBy(__PRIVATE_fromFieldPathReference(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let $=null;w.limit&&($=null==(g="object"==typeof(i=w.limit)?i.value:i)?null:g);let ee=null;w.startAt&&(ee=function(e){let i=!!e.before,s=e.values||[];return new Bound(s,i)}(w.startAt));let et=null;return w.endAt&&(et=function(e){let i=!e.before,s=e.values||[];return new Bound(s,i)}(w.endAt)),s=b,o=O,l=q,h=j,d=$,f=ee,_=et,new __PRIVATE_QueryImpl(s,o,l,h,d,"F",f,_)}({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?__PRIVATE_queryWithLimit(i,i.limit,"L"):i}(i.bundledQuery),readTime:__PRIVATE_fromVersion(i.readTime)}),PersistencePromise.resolve()}};/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_MemoryDocumentOverlayCache=class __PRIVATE_MemoryDocumentOverlayCache{constructor(){this.overlays=new SortedMap(DocumentKey.comparator),this.Ir=new Map}getOverlay(e,i){return PersistencePromise.resolve(this.overlays.get(i))}getOverlays(e,i){let s=__PRIVATE_newDocumentKeyMap();return PersistencePromise.forEach(i,i=>this.getOverlay(e,i).next(e=>{null!==e&&s.set(i,e)})).next(()=>s)}saveOverlays(e,i,s){return s.forEach((s,o)=>{this.ht(e,i,o)}),PersistencePromise.resolve()}removeOverlaysForBatchId(e,i,s){let o=this.Ir.get(s);return void 0!==o&&(o.forEach(e=>this.overlays=this.overlays.remove(e)),this.Ir.delete(s)),PersistencePromise.resolve()}getOverlaysForCollection(e,i,s){let o=__PRIVATE_newDocumentKeyMap(),l=i.length+1,h=new DocumentKey(i.child("")),d=this.overlays.getIteratorFrom(h);for(;d.hasNext();){let e=d.getNext().value,h=e.getKey();if(!i.isPrefixOf(h.path))break;h.path.length===l&&e.largestBatchId>s&&o.set(e.getKey(),e)}return PersistencePromise.resolve(o)}getOverlaysForCollectionGroup(e,i,s,o){let l=new SortedMap((e,i)=>e-i),h=this.overlays.getIterator();for(;h.hasNext();){let e=h.getNext().value;if(e.getKey().getCollectionGroup()===i&&e.largestBatchId>s){let i=l.get(e.largestBatchId);null===i&&(i=__PRIVATE_newDocumentKeyMap(),l=l.insert(e.largestBatchId,i)),i.set(e.getKey(),e)}}let d=__PRIVATE_newDocumentKeyMap(),f=l.getIterator();for(;f.hasNext()&&(f.getNext().value.forEach((e,i)=>d.set(e,i)),!(d.size()>=o)););return PersistencePromise.resolve(d)}ht(e,i,s){let o=this.overlays.get(s.key);if(null!==o){let e=this.Ir.get(o.largestBatchId).delete(s.key);this.Ir.set(o.largestBatchId,e)}this.overlays=this.overlays.insert(s.key,new Overlay(i,s));let l=this.Ir.get(i);void 0===l&&(l=__PRIVATE_documentKeySet(),this.Ir.set(i,l)),this.Ir.set(i,l.add(s.key))}};/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_MemoryGlobalsCache=class __PRIVATE_MemoryGlobalsCache{constructor(){this.sessionToken=ByteString.EMPTY_BYTE_STRING}getSessionToken(e){return PersistencePromise.resolve(this.sessionToken)}setSessionToken(e,i){return this.sessionToken=i,PersistencePromise.resolve()}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_ReferenceSet=class __PRIVATE_ReferenceSet{constructor(){this.Tr=new SortedSet(__PRIVATE_DocReference.Er),this.dr=new SortedSet(__PRIVATE_DocReference.Ar)}isEmpty(){return this.Tr.isEmpty()}addReference(e,i){let s=new __PRIVATE_DocReference(e,i);this.Tr=this.Tr.add(s),this.dr=this.dr.add(s)}Rr(e,i){e.forEach(e=>this.addReference(e,i))}removeReference(e,i){this.Vr(new __PRIVATE_DocReference(e,i))}mr(e,i){e.forEach(e=>this.removeReference(e,i))}gr(e){let i=new DocumentKey(new ResourcePath([])),s=new __PRIVATE_DocReference(i,e),o=new __PRIVATE_DocReference(i,e+1),l=[];return this.dr.forEachInRange([s,o],e=>{this.Vr(e),l.push(e.key)}),l}pr(){this.Tr.forEach(e=>this.Vr(e))}Vr(e){this.Tr=this.Tr.delete(e),this.dr=this.dr.delete(e)}yr(e){let i=new DocumentKey(new ResourcePath([])),s=new __PRIVATE_DocReference(i,e),o=new __PRIVATE_DocReference(i,e+1),l=__PRIVATE_documentKeySet();return this.dr.forEachInRange([s,o],e=>{l=l.add(e.key)}),l}containsKey(e){let i=new __PRIVATE_DocReference(e,0),s=this.Tr.firstAfterOrEqual(i);return null!==s&&e.isEqual(s.key)}};let __PRIVATE_DocReference=class __PRIVATE_DocReference{constructor(e,i){this.key=e,this.wr=i}static Er(e,i){return DocumentKey.comparator(e.key,i.key)||__PRIVATE_primitiveComparator(e.wr,i.wr)}static Ar(e,i){return __PRIVATE_primitiveComparator(e.wr,i.wr)||DocumentKey.comparator(e.key,i.key)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_MemoryMutationQueue=class __PRIVATE_MemoryMutationQueue{constructor(e,i){this.indexManager=e,this.referenceDelegate=i,this.mutationQueue=[],this.Sr=1,this.br=new SortedSet(__PRIVATE_DocReference.Er)}checkEmpty(e){return PersistencePromise.resolve(0===this.mutationQueue.length)}addMutationBatch(e,i,s,o){let l=this.Sr;this.Sr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let h=new MutationBatch(l,i,s,o);for(let i of(this.mutationQueue.push(h),o))this.br=this.br.add(new __PRIVATE_DocReference(i.key,l)),this.indexManager.addToCollectionParentIndex(e,i.key.path.popLast());return PersistencePromise.resolve(h)}lookupMutationBatch(e,i){return PersistencePromise.resolve(this.Dr(i))}getNextMutationBatchAfterBatchId(e,i){let s=this.vr(i+1),o=s<0?0:s;return PersistencePromise.resolve(this.mutationQueue.length>o?this.mutationQueue[o]:null)}getHighestUnacknowledgedBatchId(){return PersistencePromise.resolve(0===this.mutationQueue.length?-1:this.Sr-1)}getAllMutationBatches(e){return PersistencePromise.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,i){let s=new __PRIVATE_DocReference(i,0),o=new __PRIVATE_DocReference(i,Number.POSITIVE_INFINITY),l=[];return this.br.forEachInRange([s,o],e=>{let i=this.Dr(e.wr);l.push(i)}),PersistencePromise.resolve(l)}getAllMutationBatchesAffectingDocumentKeys(e,i){let s=new SortedSet(__PRIVATE_primitiveComparator);return i.forEach(e=>{let i=new __PRIVATE_DocReference(e,0),o=new __PRIVATE_DocReference(e,Number.POSITIVE_INFINITY);this.br.forEachInRange([i,o],e=>{s=s.add(e.wr)})}),PersistencePromise.resolve(this.Cr(s))}getAllMutationBatchesAffectingQuery(e,i){let s=i.path,o=s.length+1,l=s;DocumentKey.isDocumentKey(l)||(l=l.child(""));let h=new __PRIVATE_DocReference(new DocumentKey(l),0),d=new SortedSet(__PRIVATE_primitiveComparator);return this.br.forEachWhile(e=>{let i=e.key.path;return!!s.isPrefixOf(i)&&(i.length===o&&(d=d.add(e.wr)),!0)},h),PersistencePromise.resolve(this.Cr(d))}Cr(e){let i=[];return e.forEach(e=>{let s=this.Dr(e);null!==s&&i.push(s)}),i}removeMutationBatch(e,i){0===this.Fr(i.batchId,"removed")||fail(),this.mutationQueue.shift();let s=this.br;return PersistencePromise.forEach(i.mutations,o=>{let l=new __PRIVATE_DocReference(o.key,i.batchId);return s=s.delete(l),this.referenceDelegate.markPotentiallyOrphaned(e,o.key)}).next(()=>{this.br=s})}On(e){}containsKey(e,i){let s=new __PRIVATE_DocReference(i,0),o=this.br.firstAfterOrEqual(s);return PersistencePromise.resolve(i.isEqual(o&&o.key))}performConsistencyCheck(e){return this.mutationQueue.length,PersistencePromise.resolve()}Fr(e,i){return this.vr(e)}vr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Dr(e){let i=this.vr(e);return i<0||i>=this.mutationQueue.length?null:this.mutationQueue[i]}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_MemoryRemoteDocumentCacheImpl=class __PRIVATE_MemoryRemoteDocumentCacheImpl{constructor(e){this.Mr=e,this.docs=new SortedMap(DocumentKey.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,i){let s=i.key,o=this.docs.get(s),l=o?o.size:0,h=this.Mr(i);return this.docs=this.docs.insert(s,{document:i.mutableCopy(),size:h}),this.size+=h-l,this.indexManager.addToCollectionParentIndex(e,s.path.popLast())}removeEntry(e){let i=this.docs.get(e);i&&(this.docs=this.docs.remove(e),this.size-=i.size)}getEntry(e,i){let s=this.docs.get(i);return PersistencePromise.resolve(s?s.document.mutableCopy():MutableDocument.newInvalidDocument(i))}getEntries(e,i){let s=ey;return i.forEach(e=>{let i=this.docs.get(e);s=s.insert(e,i?i.document.mutableCopy():MutableDocument.newInvalidDocument(e))}),PersistencePromise.resolve(s)}getDocumentsMatchingQuery(e,i,s,o){let l=ey,h=i.path,d=new DocumentKey(h.child("")),f=this.docs.getIteratorFrom(d);for(;f.hasNext();){let{key:e,value:{document:d}}=f.getNext();if(!h.isPrefixOf(e.path))break;e.path.length>h.length+1||0>=function(e,i){let s=e.readTime.compareTo(i.readTime);return 0!==s?s:0!==(s=DocumentKey.comparator(e.documentKey,i.documentKey))?s:__PRIVATE_primitiveComparator(e.largestBatchId,i.largestBatchId)}(new IndexOffset(d.readTime,d.key,-1),s)||(o.has(d.key)||__PRIVATE_queryMatches(i,d))&&(l=l.insert(d.key,d.mutableCopy()))}return PersistencePromise.resolve(l)}getAllFromCollectionGroup(e,i,s,o){fail()}Or(e,i){return PersistencePromise.forEach(this.docs,e=>i(e))}newChangeBuffer(e){return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this)}getSize(e){return PersistencePromise.resolve(this.size)}};let __PRIVATE_MemoryRemoteDocumentChangeBuffer=class __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer{constructor(e){super(),this.cr=e}applyChanges(e){let i=[];return this.changes.forEach((s,o)=>{o.isValidDocument()?i.push(this.cr.addEntry(e,o)):this.cr.removeEntry(s)}),PersistencePromise.waitFor(i)}getFromCache(e,i){return this.cr.getEntry(e,i)}getAllFromCache(e,i){return this.cr.getEntries(e,i)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_MemoryTargetCache=class __PRIVATE_MemoryTargetCache{constructor(e){this.persistence=e,this.Nr=new ObjectMap(e=>__PRIVATE_canonifyTarget(e),__PRIVATE_targetEquals),this.lastRemoteSnapshotVersion=SnapshotVersion.min(),this.highestTargetId=0,this.Lr=0,this.Br=new __PRIVATE_ReferenceSet,this.targetCount=0,this.kr=__PRIVATE_TargetIdGenerator.Bn()}forEachTarget(e,i){return this.Nr.forEach((e,s)=>i(s)),PersistencePromise.resolve()}getLastRemoteSnapshotVersion(e){return PersistencePromise.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return PersistencePromise.resolve(this.Lr)}allocateTargetId(e){return this.highestTargetId=this.kr.next(),PersistencePromise.resolve(this.highestTargetId)}setTargetsMetadata(e,i,s){return s&&(this.lastRemoteSnapshotVersion=s),i>this.Lr&&(this.Lr=i),PersistencePromise.resolve()}Kn(e){this.Nr.set(e.target,e);let i=e.targetId;i>this.highestTargetId&&(this.kr=new __PRIVATE_TargetIdGenerator(i),this.highestTargetId=i),e.sequenceNumber>this.Lr&&(this.Lr=e.sequenceNumber)}addTargetData(e,i){return this.Kn(i),this.targetCount+=1,PersistencePromise.resolve()}updateTargetData(e,i){return this.Kn(i),PersistencePromise.resolve()}removeTargetData(e,i){return this.Nr.delete(i.target),this.Br.gr(i.targetId),this.targetCount-=1,PersistencePromise.resolve()}removeTargets(e,i,s){let o=0,l=[];return this.Nr.forEach((h,d)=>{d.sequenceNumber<=i&&null===s.get(d.targetId)&&(this.Nr.delete(h),l.push(this.removeMatchingKeysForTargetId(e,d.targetId)),o++)}),PersistencePromise.waitFor(l).next(()=>o)}getTargetCount(e){return PersistencePromise.resolve(this.targetCount)}getTargetData(e,i){let s=this.Nr.get(i)||null;return PersistencePromise.resolve(s)}addMatchingKeys(e,i,s){return this.Br.Rr(i,s),PersistencePromise.resolve()}removeMatchingKeys(e,i,s){this.Br.mr(i,s);let o=this.persistence.referenceDelegate,l=[];return o&&i.forEach(i=>{l.push(o.markPotentiallyOrphaned(e,i))}),PersistencePromise.waitFor(l)}removeMatchingKeysForTargetId(e,i){return this.Br.gr(i),PersistencePromise.resolve()}getMatchingKeysForTargetId(e,i){let s=this.Br.yr(i);return PersistencePromise.resolve(s)}containsKey(e,i){return PersistencePromise.resolve(this.Br.containsKey(i))}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_MemoryPersistence=class __PRIVATE_MemoryPersistence{constructor(e,i){this.qr={},this.overlays={},this.Qr=new __PRIVATE_ListenSequence(0),this.Kr=!1,this.Kr=!0,this.$r=new __PRIVATE_MemoryGlobalsCache,this.referenceDelegate=e(this),this.Ur=new __PRIVATE_MemoryTargetCache(this),this.indexManager=new __PRIVATE_MemoryIndexManager,this.remoteDocumentCache=new __PRIVATE_MemoryRemoteDocumentCacheImpl(e=>this.referenceDelegate.Wr(e)),this.serializer=new __PRIVATE_LocalSerializer(i),this.Gr=new __PRIVATE_MemoryBundleCache(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Kr=!1,Promise.resolve()}get started(){return this.Kr}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let i=this.overlays[e.toKey()];return i||(i=new __PRIVATE_MemoryDocumentOverlayCache,this.overlays[e.toKey()]=i),i}getMutationQueue(e,i){let s=this.qr[e.toKey()];return s||(s=new __PRIVATE_MemoryMutationQueue(i,this.referenceDelegate),this.qr[e.toKey()]=s),s}getGlobalsCache(){return this.$r}getTargetCache(){return this.Ur}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Gr}runTransaction(e,i,s){__PRIVATE_logDebug("MemoryPersistence","Starting transaction:",e);let o=new __PRIVATE_MemoryTransaction(this.Qr.next());return this.referenceDelegate.zr(),s(o).next(e=>this.referenceDelegate.jr(o).next(()=>e)).toPromise().then(e=>(o.raiseOnCommittedEvent(),e))}Hr(e,i){return PersistencePromise.or(Object.values(this.qr).map(s=>()=>s.containsKey(e,i)))}};let __PRIVATE_MemoryTransaction=class __PRIVATE_MemoryTransaction extends PersistenceTransaction{constructor(e){super(),this.currentSequenceNumber=e}};let __PRIVATE_MemoryEagerDelegate=class __PRIVATE_MemoryEagerDelegate{constructor(e){this.persistence=e,this.Jr=new __PRIVATE_ReferenceSet,this.Yr=null}static Zr(e){return new __PRIVATE_MemoryEagerDelegate(e)}get Xr(){if(this.Yr)return this.Yr;throw fail()}addReference(e,i,s){return this.Jr.addReference(s,i),this.Xr.delete(s.toString()),PersistencePromise.resolve()}removeReference(e,i,s){return this.Jr.removeReference(s,i),this.Xr.add(s.toString()),PersistencePromise.resolve()}markPotentiallyOrphaned(e,i){return this.Xr.add(i.toString()),PersistencePromise.resolve()}removeTarget(e,i){this.Jr.gr(i.targetId).forEach(e=>this.Xr.add(e.toString()));let s=this.persistence.getTargetCache();return s.getMatchingKeysForTargetId(e,i.targetId).next(e=>{e.forEach(e=>this.Xr.add(e.toString()))}).next(()=>s.removeTargetData(e,i))}zr(){this.Yr=new Set}jr(e){let i=this.persistence.getRemoteDocumentCache().newChangeBuffer();return PersistencePromise.forEach(this.Xr,s=>{let o=DocumentKey.fromPath(s);return this.ei(e,o).next(e=>{e||i.removeEntry(o,SnapshotVersion.min())})}).next(()=>(this.Yr=null,i.apply(e)))}updateLimboDocument(e,i){return this.ei(e,i).next(e=>{e?this.Xr.delete(i.toString()):this.Xr.add(i.toString())})}Wr(e){return 0}ei(e,i){return PersistencePromise.or([()=>PersistencePromise.resolve(this.Jr.containsKey(i)),()=>this.persistence.getTargetCache().containsKey(e,i),()=>this.persistence.Hr(e,i)])}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_LocalViewChanges=class __PRIVATE_LocalViewChanges{constructor(e,i,s,o){this.targetId=e,this.fromCache=i,this.$i=s,this.Ui=o}static Wi(e,i){let s=__PRIVATE_documentKeySet(),o=__PRIVATE_documentKeySet();for(let e of i.docChanges)switch(e.type){case 0:s=s.add(e.doc.key);break;case 1:o=o.add(e.doc.key)}return new __PRIVATE_LocalViewChanges(e,i.fromCache,s,o)}};/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let QueryContext=class QueryContext{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_QueryEngine=class __PRIVATE_QueryEngine{constructor(){this.Gi=!1,this.zi=!1,this.ji=100,this.Hi=(0,en.G6)()?8:function(e){let i=e.match(/Android ([\d.]+)/i),s=i?i[1].split(".").slice(0,2).join("."):"-1";return Number(s)}((0,en.z$)())>0?6:4}initialize(e,i){this.Ji=e,this.indexManager=i,this.Gi=!0}getDocumentsMatchingQuery(e,i,s,o){let l={result:null};return this.Yi(e,i).next(e=>{l.result=e}).next(()=>{if(!l.result)return this.Zi(e,i,o,s).next(e=>{l.result=e})}).next(()=>{if(l.result)return;let s=new QueryContext;return this.Xi(e,i,s).next(o=>{if(l.result=o,this.zi)return this.es(e,i,s,o.size)})}).next(()=>l.result)}es(e,i,s,o){return s.documentReadCount<this.ji?(__PRIVATE_getLogLevel()<=er.in.DEBUG&&__PRIVATE_logDebug("QueryEngine","SDK will not create cache indexes for query:",__PRIVATE_stringifyQuery(i),"since it only creates cache indexes for collection contains","more than or equal to",this.ji,"documents"),PersistencePromise.resolve()):(__PRIVATE_getLogLevel()<=er.in.DEBUG&&__PRIVATE_logDebug("QueryEngine","Query:",__PRIVATE_stringifyQuery(i),"scans",s.documentReadCount,"local documents and returns",o,"documents as results."),s.documentReadCount>this.Hi*o?(__PRIVATE_getLogLevel()<=er.in.DEBUG&&__PRIVATE_logDebug("QueryEngine","The SDK decides to create cache indexes for query:",__PRIVATE_stringifyQuery(i),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,__PRIVATE_queryToTarget(i))):PersistencePromise.resolve())}Yi(e,i){if(__PRIVATE_queryMatchesAllDocuments(i))return PersistencePromise.resolve(null);let s=__PRIVATE_queryToTarget(i);return this.indexManager.getIndexType(e,s).next(o=>0===o?null:(null!==i.limit&&1===o&&(s=__PRIVATE_queryToTarget(i=__PRIVATE_queryWithLimit(i,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,s).next(o=>{let l=__PRIVATE_documentKeySet(...o);return this.Ji.getDocuments(e,l).next(o=>this.indexManager.getMinOffset(e,s).next(s=>{let h=this.ts(i,o);return this.ns(i,h,l,s.readTime)?this.Yi(e,__PRIVATE_queryWithLimit(i,null,"F")):this.rs(e,h,i,s)}))})))}Zi(e,i,s,o){return __PRIVATE_queryMatchesAllDocuments(i)||o.isEqual(SnapshotVersion.min())?PersistencePromise.resolve(null):this.Ji.getDocuments(e,s).next(l=>{let h=this.ts(i,l);return this.ns(i,h,s,o)?PersistencePromise.resolve(null):(__PRIVATE_getLogLevel()<=er.in.DEBUG&&__PRIVATE_logDebug("QueryEngine","Re-using previous result from %s to execute query: %s",o.toString(),__PRIVATE_stringifyQuery(i)),this.rs(e,h,i,function(e,i){let s=e.toTimestamp().seconds,o=e.toTimestamp().nanoseconds+1,l=SnapshotVersion.fromTimestamp(1e9===o?new Timestamp(s+1,0):new Timestamp(s,o));return new IndexOffset(l,DocumentKey.empty(),-1)}(o,0)).next(e=>e))})}ts(e,i){let s=new SortedSet(__PRIVATE_newQueryComparator(e));return i.forEach((i,o)=>{__PRIVATE_queryMatches(e,o)&&(s=s.add(o))}),s}ns(e,i,s,o){if(null===e.limit)return!1;if(s.size!==i.size)return!0;let l="F"===e.limitType?i.last():i.first();return!!l&&(l.hasPendingWrites||l.version.compareTo(o)>0)}Xi(e,i,s){return __PRIVATE_getLogLevel()<=er.in.DEBUG&&__PRIVATE_logDebug("QueryEngine","Using full collection scan to execute query:",__PRIVATE_stringifyQuery(i)),this.Ji.getDocumentsMatchingQuery(e,i,IndexOffset.min(),s)}rs(e,i,s,o){return this.Ji.getDocumentsMatchingQuery(e,s,o).next(e=>(i.forEach(i=>{e=e.insert(i.key,i)}),e))}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_LocalStoreImpl=class __PRIVATE_LocalStoreImpl{constructor(e,i,s,o){this.persistence=e,this.ss=i,this.serializer=o,this.os=new SortedMap(__PRIVATE_primitiveComparator),this._s=new ObjectMap(e=>__PRIVATE_canonifyTarget(e),__PRIVATE_targetEquals),this.us=new Map,this.cs=e.getRemoteDocumentCache(),this.Ur=e.getTargetCache(),this.Gr=e.getBundleCache(),this.ls(s)}ls(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new LocalDocumentsView(this.cs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.cs.setIndexManager(this.indexManager),this.ss.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",i=>e.collect(i,this.os))}};async function __PRIVATE_localStoreHandleUserChange(e,i){return await e.persistence.runTransaction("Handle user change","readonly",s=>{let o;return e.mutationQueue.getAllMutationBatches(s).next(l=>(o=l,e.ls(i),e.mutationQueue.getAllMutationBatches(s))).next(i=>{let l=[],h=[],d=__PRIVATE_documentKeySet();for(let e of o)for(let i of(l.push(e.batchId),e.mutations))d=d.add(i.key);for(let e of i)for(let i of(h.push(e.batchId),e.mutations))d=d.add(i.key);return e.localDocuments.getDocuments(s,d).next(e=>({hs:e,removedBatchIds:l,addedBatchIds:h}))})})}function __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",i=>e.Ur.getLastRemoteSnapshotVersion(i))}async function __PRIVATE_localStoreReleaseTarget(e,i,s){let o=e.os.get(i);try{s||await e.persistence.runTransaction("Release target",s?"readwrite":"readwrite-primary",i=>e.persistence.referenceDelegate.removeTarget(i,o))}catch(e){if(!__PRIVATE_isIndexedDbTransactionError(e))throw e;__PRIVATE_logDebug("LocalStore",`Failed to update sequence numbers for target ${i}: ${e}`)}e.os=e.os.remove(i),e._s.delete(o.target)}function __PRIVATE_localStoreExecuteQuery(e,i,s){let o=SnapshotVersion.min(),l=__PRIVATE_documentKeySet();return e.persistence.runTransaction("Execute query","readwrite",h=>(function(e,i,s){let o=e._s.get(s);return void 0!==o?PersistencePromise.resolve(e.os.get(o)):e.Ur.getTargetData(i,s)})(e,h,__PRIVATE_queryToTarget(i)).next(i=>{if(i)return o=i.lastLimboFreeSnapshotVersion,e.Ur.getMatchingKeysForTargetId(h,i.targetId).next(e=>{l=e})}).next(()=>e.ss.getDocumentsMatchingQuery(h,i,s?o:SnapshotVersion.min(),s?l:__PRIVATE_documentKeySet())).next(s=>{var o;let h;return o=i.collectionGroup||(i.path.length%2==1?i.path.lastSegment():i.path.get(i.path.length-2)),h=e.us.get(o)||SnapshotVersion.min(),s.forEach((e,i)=>{i.readTime.compareTo(h)>0&&(h=i.readTime)}),e.us.set(o,h),{documents:s,Ts:l}}))}let __PRIVATE_LocalClientState=class __PRIVATE_LocalClientState{constructor(){this.activeTargetIds=eI}fs(e){this.activeTargetIds=this.activeTargetIds.add(e)}gs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Vs(){let e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}};let __PRIVATE_MemorySharedClientState=class __PRIVATE_MemorySharedClientState{constructor(){this.so=new __PRIVATE_LocalClientState,this.oo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,i,s){}addLocalQueryTarget(e,i=!0){return i&&this.so.fs(e),this.oo[e]||"not-current"}updateQueryState(e,i,s){this.oo[e]=i}removeLocalQueryTarget(e){this.so.gs(e)}isLocalQueryTarget(e){return this.so.activeTargetIds.has(e)}clearQueryState(e){delete this.oo[e]}getAllActiveQueryTargets(){return this.so.activeTargetIds}isActiveQueryTarget(e){return this.so.activeTargetIds.has(e)}start(){return this.so=new __PRIVATE_LocalClientState,Promise.resolve()}handleUserChange(e,i,s){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_NoopConnectivityMonitor=class __PRIVATE_NoopConnectivityMonitor{_o(e){}shutdown(){}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_BrowserConnectivityMonitor=class __PRIVATE_BrowserConnectivityMonitor{constructor(){this.ao=()=>this.uo(),this.co=()=>this.lo(),this.ho=[],this.Po()}_o(e){this.ho.push(e)}shutdown(){window.removeEventListener("online",this.ao),window.removeEventListener("offline",this.co)}Po(){window.addEventListener("online",this.ao),window.addEventListener("offline",this.co)}uo(){for(let e of(__PRIVATE_logDebug("ConnectivityMonitor","Network connectivity changed: AVAILABLE"),this.ho))e(0)}lo(){for(let e of(__PRIVATE_logDebug("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE"),this.ho))e(1)}static D(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}};/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let eS=null;function __PRIVATE_generateUniqueDebugId(){return null===eS?eS=268435456+Math.round(2147483648*Math.random()):eS++,"0x"+eS.toString(16)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let eV={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_StreamBridge=class __PRIVATE_StreamBridge{constructor(e){this.Io=e.Io,this.To=e.To}Eo(e){this.Ao=e}Ro(e){this.Vo=e}mo(e){this.fo=e}onMessage(e){this.po=e}close(){this.To()}send(e){this.Io(e)}yo(){this.Ao()}wo(){this.Vo()}So(e){this.fo(e)}bo(e){this.po(e)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let eC="WebChannelConnection";let __PRIVATE_WebChannelConnection=class __PRIVATE_WebChannelConnection extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;let i=e.ssl?"https":"http",s=encodeURIComponent(this.databaseId.projectId),o=encodeURIComponent(this.databaseId.database);this.Do=i+"://"+e.host,this.vo=`projects/${s}/databases/${o}`,this.Co="(default)"===this.databaseId.database?`project_id=${s}`:`project_id=${s}&database_id=${o}`}get Fo(){return!1}Mo(e,i,s,o,l){let h=__PRIVATE_generateUniqueDebugId(),d=this.xo(e,i.toUriEncodedString());__PRIVATE_logDebug("RestConnection",`Sending RPC '${e}' ${h}:`,d,s);let f={"google-cloud-resource-prefix":this.vo,"x-goog-request-params":this.Co};return this.Oo(f,o,l),this.No(e,d,f,s).then(i=>(__PRIVATE_logDebug("RestConnection",`Received RPC '${e}' ${h}: `,i),i),i=>{throw __PRIVATE_logWarn("RestConnection",`RPC '${e}' ${h} failed with error: `,i,"url: ",d,"request:",s),i})}Lo(e,i,s,o,l,h){return this.Mo(e,i,s,o,l)}Oo(e,i,s){e["X-Goog-Api-Client"]=function(){return"gl-js/ fire/"+eh}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),i&&i.headers.forEach((i,s)=>e[s]=i),s&&s.headers.forEach((i,s)=>e[s]=i)}xo(e,i){let s=eV[e];return`${this.Do}/v1/${i}:${s}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}No(e,i,s,o){let l=__PRIVATE_generateUniqueDebugId();return new Promise((d,g)=>{let b=new h;b.setWithCredentials(!0),b.listenOnce(f.COMPLETE,()=>{try{switch(b.getLastErrorCode()){case _.NO_ERROR:let i=b.getResponseJson();__PRIVATE_logDebug(eC,`XHR for RPC '${e}' ${l} received:`,JSON.stringify(i)),d(i);break;case _.TIMEOUT:__PRIVATE_logDebug(eC,`RPC '${e}' ${l} timed out`),g(new FirestoreError(e_.DEADLINE_EXCEEDED,"Request time out"));break;case _.HTTP_ERROR:let s=b.getStatus();if(__PRIVATE_logDebug(eC,`RPC '${e}' ${l} failed with status:`,s,"response text:",b.getResponseText()),s>0){let e=b.getResponseJson();Array.isArray(e)&&(e=e[0]);let i=null==e?void 0:e.error;if(i&&i.status&&i.message){let e=function(e){let i=e.toLowerCase().replace(/_/g,"-");return Object.values(e_).indexOf(i)>=0?i:e_.UNKNOWN}(i.status);g(new FirestoreError(e,i.message))}else g(new FirestoreError(e_.UNKNOWN,"Server responded with status "+b.getStatus()))}else g(new FirestoreError(e_.UNAVAILABLE,"Connection failed."));break;default:fail()}}finally{__PRIVATE_logDebug(eC,`RPC '${e}' ${l} completed.`)}});let w=JSON.stringify(o);__PRIVATE_logDebug(eC,`RPC '${e}' ${l} sending request:`,o),b.send(i,"POST",w,s,15)})}Bo(e,i,s){let o=__PRIVATE_generateUniqueDebugId(),l=[this.Do,"/","google.firestore.v1.Firestore","/",e,"/channel"],h=k(),f=w(),_={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},j=this.longPollingOptions.timeoutSeconds;void 0!==j&&(_.longPollingTimeout=Math.round(1e3*j)),this.useFetchStreams&&(_.useFetchStreams=!0),this.Oo(_.initMessageHeaders,i,s),_.encodeInitMessageHeaders=!0;let q=l.join("");__PRIVATE_logDebug(eC,`Creating RPC '${e}' stream ${o}: ${q}`,_);let $=h.createWebChannel(q,_),ee=!1,et=!1,er=new __PRIVATE_StreamBridge({Io:i=>{et?__PRIVATE_logDebug(eC,`Not sending because RPC '${e}' stream ${o} is closed:`,i):(ee||(__PRIVATE_logDebug(eC,`Opening RPC '${e}' stream ${o} transport.`),$.open(),ee=!0),__PRIVATE_logDebug(eC,`RPC '${e}' stream ${o} sending:`,i),$.send(i))},To:()=>$.close()}),__PRIVATE_unguardedEventListen=(e,i,s)=>{e.listen(i,e=>{try{s(e)}catch(e){setTimeout(()=>{throw e},0)}})};return __PRIVATE_unguardedEventListen($,d.EventType.OPEN,()=>{et||(__PRIVATE_logDebug(eC,`RPC '${e}' stream ${o} transport opened.`),er.yo())}),__PRIVATE_unguardedEventListen($,d.EventType.CLOSE,()=>{et||(et=!0,__PRIVATE_logDebug(eC,`RPC '${e}' stream ${o} transport closed`),er.So())}),__PRIVATE_unguardedEventListen($,d.EventType.ERROR,i=>{et||(et=!0,__PRIVATE_logWarn(eC,`RPC '${e}' stream ${o} transport errored:`,i),er.So(new FirestoreError(e_.UNAVAILABLE,"The operation could not be completed")))}),__PRIVATE_unguardedEventListen($,d.EventType.MESSAGE,i=>{var s;if(!et){let l=i.data[0];l||fail();let h=l.error||(null===(s=l[0])||void 0===s?void 0:s.error);if(h){__PRIVATE_logDebug(eC,`RPC '${e}' stream ${o} received error:`,h);let i=h.status,s=function(e){let i=O[e];if(void 0!==i)return __PRIVATE_mapCodeFromRpcCode(i)}(i),l=h.message;void 0===s&&(s=e_.INTERNAL,l="Unknown error status: "+i+" with message "+h.message),et=!0,er.So(new FirestoreError(s,l)),$.close()}else __PRIVATE_logDebug(eC,`RPC '${e}' stream ${o} received:`,l),er.bo(l)}}),__PRIVATE_unguardedEventListen(f,b.STAT_EVENT,i=>{i.stat===g.PROXY?__PRIVATE_logDebug(eC,`RPC '${e}' stream ${o} detected buffering proxy`):i.stat===g.NOPROXY&&__PRIVATE_logDebug(eC,`RPC '${e}' stream ${o} detected no buffering proxy`)}),setTimeout(()=>{er.wo()},0),er}};function getDocument(){return"undefined"!=typeof document?document:null}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function __PRIVATE_newSerializer(e){return new JsonProtoSerializer(e,!0)}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_ExponentialBackoff=class __PRIVATE_ExponentialBackoff{constructor(e,i,s=1e3,o=1.5,l=6e4){this.ui=e,this.timerId=i,this.ko=s,this.qo=o,this.Qo=l,this.Ko=0,this.$o=null,this.Uo=Date.now(),this.reset()}reset(){this.Ko=0}Wo(){this.Ko=this.Qo}Go(e){this.cancel();let i=Math.floor(this.Ko+this.zo()),s=Math.max(0,Date.now()-this.Uo),o=Math.max(0,i-s);o>0&&__PRIVATE_logDebug("ExponentialBackoff",`Backing off for ${o} ms (base delay: ${this.Ko} ms, delay with jitter: ${i} ms, last attempt: ${s} ms ago)`),this.$o=this.ui.enqueueAfterDelay(this.timerId,o,()=>(this.Uo=Date.now(),e())),this.Ko*=this.qo,this.Ko<this.ko&&(this.Ko=this.ko),this.Ko>this.Qo&&(this.Ko=this.Qo)}jo(){null!==this.$o&&(this.$o.skipDelay(),this.$o=null)}cancel(){null!==this.$o&&(this.$o.cancel(),this.$o=null)}zo(){return(Math.random()-.5)*this.Ko}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_PersistentStream=class __PRIVATE_PersistentStream{constructor(e,i,s,o,l,h,d,f){this.ui=e,this.Ho=s,this.Jo=o,this.connection=l,this.authCredentialsProvider=h,this.appCheckCredentialsProvider=d,this.listener=f,this.state=0,this.Yo=0,this.Zo=null,this.Xo=null,this.stream=null,this.e_=0,this.t_=new __PRIVATE_ExponentialBackoff(e,i)}n_(){return 1===this.state||5===this.state||this.r_()}r_(){return 2===this.state||3===this.state}start(){this.e_=0,4!==this.state?this.auth():this.i_()}async stop(){this.n_()&&await this.close(0)}s_(){this.state=0,this.t_.reset()}o_(){this.r_()&&null===this.Zo&&(this.Zo=this.ui.enqueueAfterDelay(this.Ho,6e4,()=>this.__()))}a_(e){this.u_(),this.stream.send(e)}async __(){if(this.r_())return this.close(0)}u_(){this.Zo&&(this.Zo.cancel(),this.Zo=null)}c_(){this.Xo&&(this.Xo.cancel(),this.Xo=null)}async close(e,i){this.u_(),this.c_(),this.t_.cancel(),this.Yo++,4!==e?this.t_.reset():i&&i.code===e_.RESOURCE_EXHAUSTED?(__PRIVATE_logError(i.toString()),__PRIVATE_logError("Using maximum backoff delay to prevent overloading the backend."),this.t_.Wo()):i&&i.code===e_.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.l_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.mo(i)}l_(){}auth(){this.state=1;let e=this.h_(this.Yo),i=this.Yo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,s])=>{this.Yo===i&&this.P_(e,s)},i=>{e(()=>{let e=new FirestoreError(e_.UNKNOWN,"Fetching auth token failed: "+i.message);return this.I_(e)})})}P_(e,i){let s=this.h_(this.Yo);this.stream=this.T_(e,i),this.stream.Eo(()=>{s(()=>this.listener.Eo())}),this.stream.Ro(()=>{s(()=>(this.state=2,this.Xo=this.ui.enqueueAfterDelay(this.Jo,1e4,()=>(this.r_()&&(this.state=3),Promise.resolve())),this.listener.Ro()))}),this.stream.mo(e=>{s(()=>this.I_(e))}),this.stream.onMessage(e=>{s(()=>1==++this.e_?this.E_(e):this.onNext(e))})}i_(){this.state=5,this.t_.Go(async()=>{this.state=0,this.start()})}I_(e){return __PRIVATE_logDebug("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}h_(e){return i=>{this.ui.enqueueAndForget(()=>this.Yo===e?i():(__PRIVATE_logDebug("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}};let __PRIVATE_PersistentListenStream=class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream{constructor(e,i,s,o,l,h){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",i,s,o,h),this.serializer=l}T_(e,i){return this.connection.Bo("Listen",e,i)}E_(e){return this.onNext(e)}onNext(e){this.t_.reset();let i=function(e,i){let s;if("targetChange"in i){var o,l;i.targetChange;let h="NO_CHANGE"===(o=i.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===o?1:"REMOVE"===o?2:"CURRENT"===o?3:"RESET"===o?4:fail(),d=i.targetChange.targetIds||[],f=(l=i.targetChange.resumeToken,e.useProto3Json?(void 0===l||"string"==typeof l||fail(),ByteString.fromBase64String(l||"")):(void 0===l||l instanceof el||l instanceof Uint8Array||fail(),ByteString.fromUint8Array(l||new Uint8Array))),_=i.targetChange.cause,g=_&&function(e){let i=void 0===e.code?e_.UNKNOWN:__PRIVATE_mapCodeFromRpcCode(e.code);return new FirestoreError(i,e.message||"")}(_);s=new __PRIVATE_WatchTargetChange(h,d,f,g||null)}else if("documentChange"in i){i.documentChange;let o=i.documentChange;o.document,o.document.name,o.document.updateTime;let l=fromName(e,o.document.name),h=__PRIVATE_fromVersion(o.document.updateTime),d=o.document.createTime?__PRIVATE_fromVersion(o.document.createTime):SnapshotVersion.min(),f=new ObjectValue({mapValue:{fields:o.document.fields}}),_=MutableDocument.newFoundDocument(l,h,d,f),g=o.targetIds||[],b=o.removedTargetIds||[];s=new __PRIVATE_DocumentWatchChange(g,b,_.key,_)}else if("documentDelete"in i){i.documentDelete;let o=i.documentDelete;o.document;let l=fromName(e,o.document),h=o.readTime?__PRIVATE_fromVersion(o.readTime):SnapshotVersion.min(),d=MutableDocument.newNoDocument(l,h),f=o.removedTargetIds||[];s=new __PRIVATE_DocumentWatchChange([],f,d.key,d)}else if("documentRemove"in i){i.documentRemove;let o=i.documentRemove;o.document;let l=fromName(e,o.document),h=o.removedTargetIds||[];s=new __PRIVATE_DocumentWatchChange([],h,l,null)}else{if(!("filter"in i))return fail();{i.filter;let e=i.filter;e.targetId;let{count:o=0,unchangedNames:l}=e,h=new ExistenceFilter(o,l),d=e.targetId;s=new __PRIVATE_ExistenceFilterChange(d,h)}}return s}(this.serializer,e),s=function(e){if(!("targetChange"in e))return SnapshotVersion.min();let i=e.targetChange;return i.targetIds&&i.targetIds.length?SnapshotVersion.min():i.readTime?__PRIVATE_fromVersion(i.readTime):SnapshotVersion.min()}(e);return this.listener.d_(i,s)}A_(e){let i={};i.database=__PRIVATE_getEncodedDatabaseId(this.serializer),i.addTarget=function(e,i){let s;let o=i.target;if((s=__PRIVATE_targetIsDocumentTarget(o)?{documents:{documents:[__PRIVATE_toQueryPath(e,o.path)]}}:{query:function(e,i){var s,o;let l;let h={structuredQuery:{}},d=i.path;null!==i.collectionGroup?(l=d,h.structuredQuery.from=[{collectionId:i.collectionGroup,allDescendants:!0}]):(l=d.popLast(),h.structuredQuery.from=[{collectionId:d.lastSegment()}]),h.parent=__PRIVATE_toQueryPath(e,l);let f=function(e){if(0!==e.length)return function __PRIVATE_toFilter(e){return e instanceof FieldFilter?function(e){if("=="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:eR[e.op],value:e.value}}}(e):e instanceof CompositeFilter?function(e){let i=e.getFilters().map(e=>__PRIVATE_toFilter(e));return 1===i.length?i[0]:{compositeFilter:{op:ew[e.op],filters:i}}}(e):fail()}(CompositeFilter.create(e,"and"))}(i.filters);f&&(h.structuredQuery.where=f);let _=function(e){if(0!==e.length)return e.map(e=>({field:__PRIVATE_toFieldPathReference(e.field),direction:eP[e.dir]}))}(i.orderBy);_&&(h.structuredQuery.orderBy=_);let g=__PRIVATE_toInt32Proto(e,i.limit);return null!==g&&(h.structuredQuery.limit=g),i.startAt&&(h.structuredQuery.startAt={before:(s=i.startAt).inclusive,values:s.position}),i.endAt&&(h.structuredQuery.endAt={before:!(o=i.endAt).inclusive,values:o.position}),{_t:h,parent:l}}(e,o)._t}).targetId=i.targetId,i.resumeToken.approximateByteSize()>0){s.resumeToken=__PRIVATE_toBytes(e,i.resumeToken);let o=__PRIVATE_toInt32Proto(e,i.expectedCount);null!==o&&(s.expectedCount=o)}else if(i.snapshotVersion.compareTo(SnapshotVersion.min())>0){s.readTime=toTimestamp(e,i.snapshotVersion.toTimestamp());let o=__PRIVATE_toInt32Proto(e,i.expectedCount);null!==o&&(s.expectedCount=o)}return s}(this.serializer,e);let s=function(e,i){let s=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return fail()}}(i.purpose);return null==s?null:{"goog-listen-tags":s}}(this.serializer,e);s&&(i.labels=s),this.a_(i)}R_(e){let i={};i.database=__PRIVATE_getEncodedDatabaseId(this.serializer),i.removeTarget=e,this.a_(i)}};let __PRIVATE_PersistentWriteStream=class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream{constructor(e,i,s,o,l,h){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",i,s,o,h),this.serializer=l}get V_(){return this.e_>0}start(){this.lastStreamToken=void 0,super.start()}l_(){this.V_&&this.m_([])}T_(e,i){return this.connection.Bo("Write",e,i)}E_(e){return e.streamToken||fail(),this.lastStreamToken=e.streamToken,e.writeResults&&0!==e.writeResults.length&&fail(),this.listener.f_()}onNext(e){var i,s;e.streamToken||fail(),this.lastStreamToken=e.streamToken,this.t_.reset();let o=(i=e.writeResults,s=e.commitTime,i&&i.length>0?(void 0!==s||fail(),i.map(e=>{let i;return(i=e.updateTime?__PRIVATE_fromVersion(e.updateTime):__PRIVATE_fromVersion(s)).isEqual(SnapshotVersion.min())&&(i=__PRIVATE_fromVersion(s)),new MutationResult(i,e.transformResults||[])})):[]),l=__PRIVATE_fromVersion(e.commitTime);return this.listener.g_(l,o)}p_(){let e={};e.database=__PRIVATE_getEncodedDatabaseId(this.serializer),this.a_(e)}m_(e){let i={streamToken:this.lastStreamToken,writes:e.map(e=>(function(e,i){var s;let o;if(i instanceof __PRIVATE_SetMutation)o={update:__PRIVATE_toMutationDocument(e,i.key,i.value)};else if(i instanceof __PRIVATE_DeleteMutation)o={delete:__PRIVATE_toName(e,i.key)};else if(i instanceof __PRIVATE_PatchMutation)o={update:__PRIVATE_toMutationDocument(e,i.key,i.data),updateMask:function(e){let i=[];return e.fields.forEach(e=>i.push(e.canonicalString())),{fieldPaths:i}}(i.fieldMask)};else{if(!(i instanceof __PRIVATE_VerifyMutation))return fail();o={verify:__PRIVATE_toName(e,i.key)}}return i.fieldTransforms.length>0&&(o.updateTransforms=i.fieldTransforms.map(e=>(function(e,i){let s=i.transform;if(s instanceof __PRIVATE_ServerTimestampTransform)return{fieldPath:i.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(s instanceof __PRIVATE_ArrayUnionTransformOperation)return{fieldPath:i.field.canonicalString(),appendMissingElements:{values:s.elements}};if(s instanceof __PRIVATE_ArrayRemoveTransformOperation)return{fieldPath:i.field.canonicalString(),removeAllFromArray:{values:s.elements}};if(s instanceof __PRIVATE_NumericIncrementTransformOperation)return{fieldPath:i.field.canonicalString(),increment:s.Pe};throw fail()})(0,e))),i.precondition.isNone||(o.currentDocument=void 0!==(s=i.precondition).updateTime?{updateTime:toTimestamp(e,s.updateTime.toTimestamp())}:void 0!==s.exists?{exists:s.exists}:fail()),o})(this.serializer,e))};this.a_(i)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_DatastoreImpl=class __PRIVATE_DatastoreImpl extends class{}{constructor(e,i,s,o){super(),this.authCredentials=e,this.appCheckCredentials=i,this.connection=s,this.serializer=o,this.y_=!1}w_(){if(this.y_)throw new FirestoreError(e_.FAILED_PRECONDITION,"The client has already been terminated.")}Mo(e,i,s,o){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([l,h])=>this.connection.Mo(e,__PRIVATE_toResourcePath(i,s),o,l,h)).catch(e=>{throw"FirebaseError"===e.name?(e.code===e_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(e_.UNKNOWN,e.toString())})}Lo(e,i,s,o,l){return this.w_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([h,d])=>this.connection.Lo(e,__PRIVATE_toResourcePath(i,s),o,h,d,l)).catch(e=>{throw"FirebaseError"===e.name?(e.code===e_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(e_.UNKNOWN,e.toString())})}terminate(){this.y_=!0,this.connection.terminate()}};let __PRIVATE_OnlineStateTracker=class __PRIVATE_OnlineStateTracker{constructor(e,i){this.asyncQueue=e,this.onlineStateHandler=i,this.state="Unknown",this.S_=0,this.b_=null,this.D_=!0}v_(){0===this.S_&&(this.C_("Unknown"),this.b_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.b_=null,this.F_("Backend didn't respond within 10 seconds."),this.C_("Offline"),Promise.resolve())))}M_(e){"Online"===this.state?this.C_("Unknown"):(this.S_++,this.S_>=1&&(this.x_(),this.F_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.C_("Offline")))}set(e){this.x_(),this.S_=0,"Online"===e&&(this.D_=!1),this.C_(e)}C_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}F_(e){let i=`Could not reach Cloud Firestore backend. ${e}
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.D_?(__PRIVATE_logError(i),this.D_=!1):__PRIVATE_logDebug("OnlineStateTracker",i)}x_(){null!==this.b_&&(this.b_.cancel(),this.b_=null)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_RemoteStoreImpl=class __PRIVATE_RemoteStoreImpl{constructor(e,i,s,o,l){this.localStore=e,this.datastore=i,this.asyncQueue=s,this.remoteSyncer={},this.O_=[],this.N_=new Map,this.L_=new Set,this.B_=[],this.k_=l,this.k_._o(e=>{s.enqueueAndForget(async()=>{__PRIVATE_canUseNetwork(this)&&(__PRIVATE_logDebug("RemoteStore","Restarting streams for network reachability change."),await async function(e){e.L_.add(4),await __PRIVATE_disableNetworkInternal(e),e.q_.set("Unknown"),e.L_.delete(4),await __PRIVATE_enableNetworkInternal(e)}(this))})}),this.q_=new __PRIVATE_OnlineStateTracker(s,o)}};async function __PRIVATE_enableNetworkInternal(e){if(__PRIVATE_canUseNetwork(e))for(let i of e.B_)await i(!0)}async function __PRIVATE_disableNetworkInternal(e){for(let i of e.B_)await i(!1)}function __PRIVATE_remoteStoreListen(e,i){e.N_.has(i.targetId)||(e.N_.set(i.targetId,i),__PRIVATE_shouldStartWatchStream(e)?__PRIVATE_startWatchStream(e):__PRIVATE_ensureWatchStream(e).r_()&&__PRIVATE_sendWatchRequest(e,i))}function __PRIVATE_remoteStoreUnlisten(e,i){let s=__PRIVATE_ensureWatchStream(e);e.N_.delete(i),s.r_()&&__PRIVATE_sendUnwatchRequest(e,i),0===e.N_.size&&(s.r_()?s.o_():__PRIVATE_canUseNetwork(e)&&e.q_.set("Unknown"))}function __PRIVATE_sendWatchRequest(e,i){if(e.Q_.xe(i.targetId),i.resumeToken.approximateByteSize()>0||i.snapshotVersion.compareTo(SnapshotVersion.min())>0){let s=e.remoteSyncer.getRemoteKeysForTarget(i.targetId).size;i=i.withExpectedCount(s)}__PRIVATE_ensureWatchStream(e).A_(i)}function __PRIVATE_sendUnwatchRequest(e,i){e.Q_.xe(i),__PRIVATE_ensureWatchStream(e).R_(i)}function __PRIVATE_startWatchStream(e){e.Q_=new __PRIVATE_WatchChangeAggregator({getRemoteKeysForTarget:i=>e.remoteSyncer.getRemoteKeysForTarget(i),ot:i=>e.N_.get(i)||null,tt:()=>e.datastore.serializer.databaseId}),__PRIVATE_ensureWatchStream(e).start(),e.q_.v_()}function __PRIVATE_shouldStartWatchStream(e){return __PRIVATE_canUseNetwork(e)&&!__PRIVATE_ensureWatchStream(e).n_()&&e.N_.size>0}function __PRIVATE_canUseNetwork(e){return 0===e.L_.size}async function __PRIVATE_onWatchStreamConnected(e){e.q_.set("Online")}async function __PRIVATE_onWatchStreamOpen(e){e.N_.forEach((i,s)=>{__PRIVATE_sendWatchRequest(e,i)})}async function __PRIVATE_onWatchStreamClose(e,i){e.Q_=void 0,__PRIVATE_shouldStartWatchStream(e)?(e.q_.M_(i),__PRIVATE_startWatchStream(e)):e.q_.set("Unknown")}async function __PRIVATE_onWatchStreamChange(e,i,s){if(e.q_.set("Online"),i instanceof __PRIVATE_WatchTargetChange&&2===i.state&&i.cause)try{await async function(e,i){let s=i.cause;for(let o of i.targetIds)e.N_.has(o)&&(await e.remoteSyncer.rejectListen(o,s),e.N_.delete(o),e.Q_.removeTarget(o))}(e,i)}catch(s){__PRIVATE_logDebug("RemoteStore","Failed to remove targets %s: %s ",i.targetIds.join(","),s),await __PRIVATE_disableNetworkUntilRecovery(e,s)}else if(i instanceof __PRIVATE_DocumentWatchChange?e.Q_.Ke(i):i instanceof __PRIVATE_ExistenceFilterChange?e.Q_.He(i):e.Q_.We(i),!s.isEqual(SnapshotVersion.min()))try{let i=await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore);s.compareTo(i)>=0&&await function(e,i){let s=e.Q_.rt(i);return s.targetChanges.forEach((s,o)=>{if(s.resumeToken.approximateByteSize()>0){let l=e.N_.get(o);l&&e.N_.set(o,l.withResumeToken(s.resumeToken,i))}}),s.targetMismatches.forEach((i,s)=>{let o=e.N_.get(i);if(!o)return;e.N_.set(i,o.withResumeToken(ByteString.EMPTY_BYTE_STRING,o.snapshotVersion)),__PRIVATE_sendUnwatchRequest(e,i);let l=new TargetData(o.target,i,s,o.sequenceNumber);__PRIVATE_sendWatchRequest(e,l)}),e.remoteSyncer.applyRemoteEvent(s)}(e,s)}catch(i){__PRIVATE_logDebug("RemoteStore","Failed to raise snapshot:",i),await __PRIVATE_disableNetworkUntilRecovery(e,i)}}async function __PRIVATE_disableNetworkUntilRecovery(e,i,s){if(!__PRIVATE_isIndexedDbTransactionError(i))throw i;e.L_.add(1),await __PRIVATE_disableNetworkInternal(e),e.q_.set("Offline"),s||(s=()=>__PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{__PRIVATE_logDebug("RemoteStore","Retrying IndexedDB access"),await s(),e.L_.delete(1),await __PRIVATE_enableNetworkInternal(e)})}function __PRIVATE_executeWithRecovery(e,i){return i().catch(s=>__PRIVATE_disableNetworkUntilRecovery(e,s,i))}async function __PRIVATE_fillWritePipeline(e){let i=__PRIVATE_ensureWriteStream(e),s=e.O_.length>0?e.O_[e.O_.length-1].batchId:-1;for(;__PRIVATE_canUseNetwork(e)&&e.O_.length<10;)try{let o=await function(e,i){return e.persistence.runTransaction("Get next mutation batch","readonly",s=>(void 0===i&&(i=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(s,i)))}(e.localStore,s);if(null===o){0===e.O_.length&&i.o_();break}s=o.batchId,function(e,i){e.O_.push(i);let s=__PRIVATE_ensureWriteStream(e);s.r_()&&s.V_&&s.m_(i.mutations)}(e,o)}catch(i){await __PRIVATE_disableNetworkUntilRecovery(e,i)}__PRIVATE_shouldStartWriteStream(e)&&__PRIVATE_startWriteStream(e)}function __PRIVATE_shouldStartWriteStream(e){return __PRIVATE_canUseNetwork(e)&&!__PRIVATE_ensureWriteStream(e).n_()&&e.O_.length>0}function __PRIVATE_startWriteStream(e){__PRIVATE_ensureWriteStream(e).start()}async function __PRIVATE_onWriteStreamOpen(e){__PRIVATE_ensureWriteStream(e).p_()}async function __PRIVATE_onWriteHandshakeComplete(e){let i=__PRIVATE_ensureWriteStream(e);for(let s of e.O_)i.m_(s.mutations)}async function __PRIVATE_onMutationResult(e,i,s){let o=e.O_.shift(),l=MutationBatchResult.from(o,i,s);await __PRIVATE_executeWithRecovery(e,()=>e.remoteSyncer.applySuccessfulWrite(l)),await __PRIVATE_fillWritePipeline(e)}async function __PRIVATE_onWriteStreamClose(e,i){i&&__PRIVATE_ensureWriteStream(e).V_&&await async function(e,i){var s;if(function(e){switch(e){default:return fail();case e_.CANCELLED:case e_.UNKNOWN:case e_.DEADLINE_EXCEEDED:case e_.RESOURCE_EXHAUSTED:case e_.INTERNAL:case e_.UNAVAILABLE:case e_.UNAUTHENTICATED:return!1;case e_.INVALID_ARGUMENT:case e_.NOT_FOUND:case e_.ALREADY_EXISTS:case e_.PERMISSION_DENIED:case e_.FAILED_PRECONDITION:case e_.ABORTED:case e_.OUT_OF_RANGE:case e_.UNIMPLEMENTED:case e_.DATA_LOSS:return!0}}(s=i.code)&&s!==e_.ABORTED){let s=e.O_.shift();__PRIVATE_ensureWriteStream(e).s_(),await __PRIVATE_executeWithRecovery(e,()=>e.remoteSyncer.rejectFailedWrite(s.batchId,i)),await __PRIVATE_fillWritePipeline(e)}}(e,i),__PRIVATE_shouldStartWriteStream(e)&&__PRIVATE_startWriteStream(e)}async function __PRIVATE_remoteStoreHandleCredentialChange(e,i){e.asyncQueue.verifyOperationInProgress(),__PRIVATE_logDebug("RemoteStore","RemoteStore received new credentials");let s=__PRIVATE_canUseNetwork(e);e.L_.add(3),await __PRIVATE_disableNetworkInternal(e),s&&e.q_.set("Unknown"),await e.remoteSyncer.handleCredentialChange(i),e.L_.delete(3),await __PRIVATE_enableNetworkInternal(e)}async function __PRIVATE_remoteStoreApplyPrimaryState(e,i){i?(e.L_.delete(2),await __PRIVATE_enableNetworkInternal(e)):i||(e.L_.add(2),await __PRIVATE_disableNetworkInternal(e),e.q_.set("Unknown"))}function __PRIVATE_ensureWatchStream(e){var i,s,o;return e.K_||(e.K_=(i=e.datastore,s=e.asyncQueue,o={Eo:__PRIVATE_onWatchStreamConnected.bind(null,e),Ro:__PRIVATE_onWatchStreamOpen.bind(null,e),mo:__PRIVATE_onWatchStreamClose.bind(null,e),d_:__PRIVATE_onWatchStreamChange.bind(null,e)},i.w_(),new __PRIVATE_PersistentListenStream(s,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,o)),e.B_.push(async i=>{i?(e.K_.s_(),__PRIVATE_shouldStartWatchStream(e)?__PRIVATE_startWatchStream(e):e.q_.set("Unknown")):(await e.K_.stop(),e.Q_=void 0)})),e.K_}function __PRIVATE_ensureWriteStream(e){var i,s,o;return e.U_||(e.U_=(i=e.datastore,s=e.asyncQueue,o={Eo:()=>Promise.resolve(),Ro:__PRIVATE_onWriteStreamOpen.bind(null,e),mo:__PRIVATE_onWriteStreamClose.bind(null,e),f_:__PRIVATE_onWriteHandshakeComplete.bind(null,e),g_:__PRIVATE_onMutationResult.bind(null,e)},i.w_(),new __PRIVATE_PersistentWriteStream(s,i.connection,i.authCredentials,i.appCheckCredentials,i.serializer,o)),e.B_.push(async i=>{i?(e.U_.s_(),await __PRIVATE_fillWritePipeline(e)):(await e.U_.stop(),e.O_.length>0&&(__PRIVATE_logDebug("RemoteStore",`Stopping write stream with ${e.O_.length} pending writes`),e.O_=[]))})),e.U_}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let DelayedOperation=class DelayedOperation{constructor(e,i,s,o,l){this.asyncQueue=e,this.timerId=i,this.targetTimeMs=s,this.op=o,this.removalCallback=l,this.deferred=new __PRIVATE_Deferred,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,i,s,o,l){let h=Date.now()+s,d=new DelayedOperation(e,i,h,o,l);return d.start(s),d}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new FirestoreError(e_.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}};function __PRIVATE_wrapInUserErrorIfRecoverable(e,i){if(__PRIVATE_logError("AsyncQueue",`${i}: ${e}`),__PRIVATE_isIndexedDbTransactionError(e))return new FirestoreError(e_.UNAVAILABLE,`${i}: ${e}`);throw e}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let DocumentSet=class DocumentSet{constructor(e){this.comparator=e?(i,s)=>e(i,s)||DocumentKey.comparator(i.key,s.key):(e,i)=>DocumentKey.comparator(e.key,i.key),this.keyedMap=documentMap(),this.sortedSet=new SortedMap(this.comparator)}static emptySet(e){return new DocumentSet(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){let i=this.keyedMap.get(e);return i?this.sortedSet.indexOf(i):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((i,s)=>(e(i),!1))}add(e){let i=this.delete(e.key);return i.copy(i.keyedMap.insert(e.key,e),i.sortedSet.insert(e,null))}delete(e){let i=this.get(e);return i?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(i)):this}isEqual(e){if(!(e instanceof DocumentSet)||this.size!==e.size)return!1;let i=this.sortedSet.getIterator(),s=e.sortedSet.getIterator();for(;i.hasNext();){let e=i.getNext().key,o=s.getNext().key;if(!e.isEqual(o))return!1}return!0}toString(){let e=[];return this.forEach(i=>{e.push(i.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n  "+e.join("  \n")+"\n)"}copy(e,i){let s=new DocumentSet;return s.comparator=this.comparator,s.keyedMap=e,s.sortedSet=i,s}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_DocumentChangeSet=class __PRIVATE_DocumentChangeSet{constructor(){this.W_=new SortedMap(DocumentKey.comparator)}track(e){let i=e.doc.key,s=this.W_.get(i);s?0!==e.type&&3===s.type?this.W_=this.W_.insert(i,e):3===e.type&&1!==s.type?this.W_=this.W_.insert(i,{type:s.type,doc:e.doc}):2===e.type&&2===s.type?this.W_=this.W_.insert(i,{type:2,doc:e.doc}):2===e.type&&0===s.type?this.W_=this.W_.insert(i,{type:0,doc:e.doc}):1===e.type&&0===s.type?this.W_=this.W_.remove(i):1===e.type&&2===s.type?this.W_=this.W_.insert(i,{type:1,doc:s.doc}):0===e.type&&1===s.type?this.W_=this.W_.insert(i,{type:2,doc:e.doc}):fail():this.W_=this.W_.insert(i,e)}G_(){let e=[];return this.W_.inorderTraversal((i,s)=>{e.push(s)}),e}};let ViewSnapshot=class ViewSnapshot{constructor(e,i,s,o,l,h,d,f,_){this.query=e,this.docs=i,this.oldDocs=s,this.docChanges=o,this.mutatedKeys=l,this.fromCache=h,this.syncStateChanged=d,this.excludesMetadataChanges=f,this.hasCachedResults=_}static fromInitialDocuments(e,i,s,o,l){let h=[];return i.forEach(e=>{h.push({type:0,doc:e})}),new ViewSnapshot(e,i,DocumentSet.emptySet(i),h,s,o,!0,!1,l)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&__PRIVATE_queryEquals(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let i=this.docChanges,s=e.docChanges;if(i.length!==s.length)return!1;for(let e=0;e<i.length;e++)if(i[e].type!==s[e].type||!i[e].doc.isEqual(s[e].doc))return!1;return!0}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_QueryListenersInfo=class __PRIVATE_QueryListenersInfo{constructor(){this.z_=void 0,this.j_=[]}H_(){return this.j_.some(e=>e.J_())}};let __PRIVATE_EventManagerImpl=class __PRIVATE_EventManagerImpl{constructor(){this.queries=__PRIVATE_newQueriesObjectMap(),this.onlineState="Unknown",this.Y_=new Set}terminate(){!function(e,i){let s=e.queries;e.queries=__PRIVATE_newQueriesObjectMap(),s.forEach((e,s)=>{for(let e of s.j_)e.onError(i)})}(this,new FirestoreError(e_.ABORTED,"Firestore shutting down"))}};function __PRIVATE_newQueriesObjectMap(){return new ObjectMap(e=>__PRIVATE_canonifyQuery(e),__PRIVATE_queryEquals)}async function __PRIVATE_eventManagerListen(e,i){let s=3,o=i.query,l=e.queries.get(o);l?!l.H_()&&i.J_()&&(s=2):(l=new __PRIVATE_QueryListenersInfo,s=i.J_()?0:1);try{switch(s){case 0:l.z_=await e.onListen(o,!0);break;case 1:l.z_=await e.onListen(o,!1);break;case 2:await e.onFirstRemoteStoreListen(o)}}catch(s){let e=__PRIVATE_wrapInUserErrorIfRecoverable(s,`Initialization of query '${__PRIVATE_stringifyQuery(i.query)}' failed`);return void i.onError(e)}e.queries.set(o,l),l.j_.push(i),i.Z_(e.onlineState),l.z_&&i.X_(l.z_)&&__PRIVATE_raiseSnapshotsInSyncEvent(e)}async function __PRIVATE_eventManagerUnlisten(e,i){let s=i.query,o=3,l=e.queries.get(s);if(l){let e=l.j_.indexOf(i);e>=0&&(l.j_.splice(e,1),0===l.j_.length?o=i.J_()?0:1:!l.H_()&&i.J_()&&(o=2))}switch(o){case 0:return e.queries.delete(s),e.onUnlisten(s,!0);case 1:return e.queries.delete(s),e.onUnlisten(s,!1);case 2:return e.onLastRemoteStoreUnlisten(s);default:return}}function __PRIVATE_eventManagerOnWatchChange(e,i){let s=!1;for(let o of i){let i=o.query,l=e.queries.get(i);if(l){for(let e of l.j_)e.X_(o)&&(s=!0);l.z_=o}}s&&__PRIVATE_raiseSnapshotsInSyncEvent(e)}function __PRIVATE_eventManagerOnWatchError(e,i,s){let o=e.queries.get(i);if(o)for(let e of o.j_)e.onError(s);e.queries.delete(i)}function __PRIVATE_raiseSnapshotsInSyncEvent(e){e.Y_.forEach(e=>{e.next()})}($=q||(q={})).ea="default",$.Cache="cache";let __PRIVATE_QueryListener=class __PRIVATE_QueryListener{constructor(e,i,s){this.query=e,this.ta=i,this.na=!1,this.ra=null,this.onlineState="Unknown",this.options=s||{}}X_(e){if(!this.options.includeMetadataChanges){let i=[];for(let s of e.docChanges)3!==s.type&&i.push(s);e=new ViewSnapshot(e.query,e.docs,e.oldDocs,i,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let i=!1;return this.na?this.ia(e)&&(this.ta.next(e),i=!0):this.sa(e,this.onlineState)&&(this.oa(e),i=!0),this.ra=e,i}onError(e){this.ta.error(e)}Z_(e){this.onlineState=e;let i=!1;return this.ra&&!this.na&&this.sa(this.ra,e)&&(this.oa(this.ra),i=!0),i}sa(e,i){return!(e.fromCache&&this.J_())||(!this.options._a||!("Offline"!==i))&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===i)}ia(e){if(e.docChanges.length>0)return!0;let i=this.ra&&this.ra.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!i)&&!0===this.options.includeMetadataChanges}oa(e){e=ViewSnapshot.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.na=!0,this.ta.next(e)}J_(){return this.options.source!==q.Cache}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_AddedLimboDocument=class __PRIVATE_AddedLimboDocument{constructor(e){this.key=e}};let __PRIVATE_RemovedLimboDocument=class __PRIVATE_RemovedLimboDocument{constructor(e){this.key=e}};let __PRIVATE_View=class __PRIVATE_View{constructor(e,i){this.query=e,this.Ta=i,this.Ea=null,this.hasCachedResults=!1,this.current=!1,this.da=__PRIVATE_documentKeySet(),this.mutatedKeys=__PRIVATE_documentKeySet(),this.Aa=__PRIVATE_newQueryComparator(e),this.Ra=new DocumentSet(this.Aa)}get Va(){return this.Ta}ma(e,i){let s=i?i.fa:new __PRIVATE_DocumentChangeSet,o=i?i.Ra:this.Ra,l=i?i.mutatedKeys:this.mutatedKeys,h=o,d=!1,f="F"===this.query.limitType&&o.size===this.query.limit?o.last():null,_="L"===this.query.limitType&&o.size===this.query.limit?o.first():null;if(e.inorderTraversal((e,i)=>{let g=o.get(e),b=__PRIVATE_queryMatches(this.query,i)?i:null,w=!!g&&this.mutatedKeys.has(g.key),k=!!b&&(b.hasLocalMutations||this.mutatedKeys.has(b.key)&&b.hasCommittedMutations),O=!1;g&&b?g.data.isEqual(b.data)?w!==k&&(s.track({type:3,doc:b}),O=!0):this.ga(g,b)||(s.track({type:2,doc:b}),O=!0,(f&&this.Aa(b,f)>0||_&&0>this.Aa(b,_))&&(d=!0)):!g&&b?(s.track({type:0,doc:b}),O=!0):g&&!b&&(s.track({type:1,doc:g}),O=!0,(f||_)&&(d=!0)),O&&(b?(h=h.add(b),l=k?l.add(e):l.delete(e)):(h=h.delete(e),l=l.delete(e)))}),null!==this.query.limit)for(;h.size>this.query.limit;){let e="F"===this.query.limitType?h.last():h.first();h=h.delete(e.key),l=l.delete(e.key),s.track({type:1,doc:e})}return{Ra:h,fa:s,ns:d,mutatedKeys:l}}ga(e,i){return e.hasLocalMutations&&i.hasCommittedMutations&&!i.hasLocalMutations}applyChanges(e,i,s,o){let l=this.Ra;this.Ra=e.Ra,this.mutatedKeys=e.mutatedKeys;let h=e.fa.G_();h.sort((e,i)=>(function(e,i){let order=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return fail()}};return order(e)-order(i)})(e.type,i.type)||this.Aa(e.doc,i.doc)),this.pa(s),o=null!=o&&o;let d=i&&!o?this.ya():[],f=0===this.da.size&&this.current&&!o?1:0,_=f!==this.Ea;return(this.Ea=f,0!==h.length||_)?{snapshot:new ViewSnapshot(this.query,e.Ra,l,h,e.mutatedKeys,0===f,_,!1,!!s&&s.resumeToken.approximateByteSize()>0),wa:d}:{wa:d}}Z_(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ra:this.Ra,fa:new __PRIVATE_DocumentChangeSet,mutatedKeys:this.mutatedKeys,ns:!1},!1)):{wa:[]}}Sa(e){return!this.Ta.has(e)&&!!this.Ra.has(e)&&!this.Ra.get(e).hasLocalMutations}pa(e){e&&(e.addedDocuments.forEach(e=>this.Ta=this.Ta.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Ta=this.Ta.delete(e)),this.current=e.current)}ya(){if(!this.current)return[];let e=this.da;this.da=__PRIVATE_documentKeySet(),this.Ra.forEach(e=>{this.Sa(e.key)&&(this.da=this.da.add(e.key))});let i=[];return e.forEach(e=>{this.da.has(e)||i.push(new __PRIVATE_RemovedLimboDocument(e))}),this.da.forEach(s=>{e.has(s)||i.push(new __PRIVATE_AddedLimboDocument(s))}),i}ba(e){this.Ta=e.Ts,this.da=__PRIVATE_documentKeySet();let i=this.ma(e.documents);return this.applyChanges(i,!0)}Da(){return ViewSnapshot.fromInitialDocuments(this.query,this.Ra,this.mutatedKeys,0===this.Ea,this.hasCachedResults)}};let __PRIVATE_QueryView=class __PRIVATE_QueryView{constructor(e,i,s){this.query=e,this.targetId=i,this.view=s}};let LimboResolution=class LimboResolution{constructor(e){this.key=e,this.va=!1}};let __PRIVATE_SyncEngineImpl=class __PRIVATE_SyncEngineImpl{constructor(e,i,s,o,l,h){this.localStore=e,this.remoteStore=i,this.eventManager=s,this.sharedClientState=o,this.currentUser=l,this.maxConcurrentLimboResolutions=h,this.Ca={},this.Fa=new ObjectMap(e=>__PRIVATE_canonifyQuery(e),__PRIVATE_queryEquals),this.Ma=new Map,this.xa=new Set,this.Oa=new SortedMap(DocumentKey.comparator),this.Na=new Map,this.La=new __PRIVATE_ReferenceSet,this.Ba={},this.ka=new Map,this.qa=__PRIVATE_TargetIdGenerator.kn(),this.onlineState="Unknown",this.Qa=void 0}get isPrimaryClient(){return!0===this.Qa}};async function __PRIVATE_syncEngineListen(e,i,s=!0){let o;let l=__PRIVATE_ensureWatchCallbacks(e),h=l.Fa.get(i);return h?(l.sharedClientState.addLocalQueryTarget(h.targetId),o=h.view.Da()):o=await __PRIVATE_allocateTargetAndMaybeListen(l,i,s,!0),o}async function __PRIVATE_triggerRemoteStoreListen(e,i){let s=__PRIVATE_ensureWatchCallbacks(e);await __PRIVATE_allocateTargetAndMaybeListen(s,i,!0,!1)}async function __PRIVATE_allocateTargetAndMaybeListen(e,i,s,o){var l,h;let d;let f=await (l=e.localStore,h=__PRIVATE_queryToTarget(i),l.persistence.runTransaction("Allocate target","readwrite",e=>{let i;return l.Ur.getTargetData(e,h).next(s=>s?(i=s,PersistencePromise.resolve(i)):l.Ur.allocateTargetId(e).next(s=>(i=new TargetData(h,s,"TargetPurposeListen",e.currentSequenceNumber),l.Ur.addTargetData(e,i).next(()=>i))))}).then(e=>{let i=l.os.get(e.targetId);return(null===i||e.snapshotVersion.compareTo(i.snapshotVersion)>0)&&(l.os=l.os.insert(e.targetId,e),l._s.set(h,e.targetId)),e})),_=f.targetId,g=e.sharedClientState.addLocalQueryTarget(_,s);return o&&(d=await __PRIVATE_initializeViewAndComputeSnapshot(e,i,_,"current"===g,f.resumeToken)),e.isPrimaryClient&&s&&__PRIVATE_remoteStoreListen(e.remoteStore,f),d}async function __PRIVATE_initializeViewAndComputeSnapshot(e,i,s,o,l){e.Ka=(i,s,o)=>(async function(e,i,s,o){let l=i.view.ma(s);l.ns&&(l=await __PRIVATE_localStoreExecuteQuery(e.localStore,i.query,!1).then(({documents:e})=>i.view.ma(e,l)));let h=o&&o.targetChanges.get(i.targetId),d=o&&null!=o.targetMismatches.get(i.targetId),f=i.view.applyChanges(l,e.isPrimaryClient,h,d);return __PRIVATE_updateTrackedLimbos(e,i.targetId,f.wa),f.snapshot})(e,i,s,o);let h=await __PRIVATE_localStoreExecuteQuery(e.localStore,i,!0),d=new __PRIVATE_View(i,h.Ts),f=d.ma(h.documents),_=TargetChange.createSynthesizedTargetChangeForCurrentChange(s,o&&"Offline"!==e.onlineState,l),g=d.applyChanges(f,e.isPrimaryClient,_);__PRIVATE_updateTrackedLimbos(e,s,g.wa);let b=new __PRIVATE_QueryView(i,s,d);return e.Fa.set(i,b),e.Ma.has(s)?e.Ma.get(s).push(i):e.Ma.set(s,[i]),g.snapshot}async function __PRIVATE_syncEngineUnlisten(e,i,s){let o=e.Fa.get(i),l=e.Ma.get(o.targetId);if(l.length>1)return e.Ma.set(o.targetId,l.filter(e=>!__PRIVATE_queryEquals(e,i))),void e.Fa.delete(i);e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(o.targetId),e.sharedClientState.isActiveQueryTarget(o.targetId)||await __PRIVATE_localStoreReleaseTarget(e.localStore,o.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(o.targetId),s&&__PRIVATE_remoteStoreUnlisten(e.remoteStore,o.targetId),__PRIVATE_removeAndCleanupTarget(e,o.targetId)}).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)):(__PRIVATE_removeAndCleanupTarget(e,o.targetId),await __PRIVATE_localStoreReleaseTarget(e.localStore,o.targetId,!0))}async function __PRIVATE_triggerRemoteStoreUnlisten(e,i){let s=e.Fa.get(i),o=e.Ma.get(s.targetId);e.isPrimaryClient&&1===o.length&&(e.sharedClientState.removeLocalQueryTarget(s.targetId),__PRIVATE_remoteStoreUnlisten(e.remoteStore,s.targetId))}async function __PRIVATE_syncEngineWrite(e,i,s){var o;let l=(e.remoteStore.remoteSyncer.applySuccessfulWrite=__PRIVATE_syncEngineApplySuccessfulWrite.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=__PRIVATE_syncEngineRejectFailedWrite.bind(null,e),e);try{let e;let h=await function(e,i){let s,o;let l=Timestamp.now(),h=i.reduce((e,i)=>e.add(i.key),__PRIVATE_documentKeySet());return e.persistence.runTransaction("Locally write mutations","readwrite",d=>{let f=ey,_=__PRIVATE_documentKeySet();return e.cs.getEntries(d,h).next(e=>{(f=e).forEach((e,i)=>{i.isValidDocument()||(_=_.add(e))})}).next(()=>e.localDocuments.getOverlayedDocuments(d,f)).next(o=>{s=o;let h=[];for(let e of i){let i=function(e,i){let s=null;for(let o of e.fieldTransforms){let e=i.data.field(o.field),l=__PRIVATE_computeTransformOperationBaseValue(o.transform,e||null);null!=l&&(null===s&&(s=ObjectValue.empty()),s.set(o.field,l))}return s||null}(e,s.get(e.key).overlayedDocument);null!=i&&h.push(new __PRIVATE_PatchMutation(e.key,i,function __PRIVATE_extractFieldMask(e){let i=[];return forEach(e.fields,(e,s)=>{let o=new FieldPath$1([e]);if(__PRIVATE_isMapValue(s)){let e=__PRIVATE_extractFieldMask(s.mapValue).fields;if(0===e.length)i.push(o);else for(let s of e)i.push(o.child(s))}else i.push(o)}),new FieldMask(i)}(i.value.mapValue),Precondition.exists(!0)))}return e.mutationQueue.addMutationBatch(d,l,h,i)}).next(i=>{o=i;let l=i.applyToLocalDocumentSet(s,_);return e.documentOverlayCache.saveOverlays(d,i.batchId,l)})}).then(()=>({batchId:o.batchId,changes:__PRIVATE_convertOverlayedDocumentMapToDocumentMap(s)}))}(l.localStore,i);l.sharedClientState.addPendingMutation(h.batchId),o=h.batchId,(e=l.Ba[l.currentUser.toKey()])||(e=new SortedMap(__PRIVATE_primitiveComparator)),e=e.insert(o,s),l.Ba[l.currentUser.toKey()]=e,await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(l,h.changes),await __PRIVATE_fillWritePipeline(l.remoteStore)}catch(i){let e=__PRIVATE_wrapInUserErrorIfRecoverable(i,"Failed to persist write");s.reject(e)}}async function __PRIVATE_syncEngineApplyRemoteEvent(e,i){try{let s=await function(e,i){let s=i.snapshotVersion,o=e.os;return e.persistence.runTransaction("Apply remote event","readwrite-primary",l=>{var h;let d,f;let _=e.cs.newChangeBuffer({trackRemovals:!0});o=e.os;let g=[];i.targetChanges.forEach((h,d)=>{var f;let _=o.get(d);if(!_)return;g.push(e.Ur.removeMatchingKeys(l,h.removedDocuments,d).next(()=>e.Ur.addMatchingKeys(l,h.addedDocuments,d)));let b=_.withSequenceNumber(l.currentSequenceNumber);null!==i.targetMismatches.get(d)?b=b.withResumeToken(ByteString.EMPTY_BYTE_STRING,SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()):h.resumeToken.approximateByteSize()>0&&(b=b.withResumeToken(h.resumeToken,s)),o=o.insert(d,b),f=b,(0===_.resumeToken.approximateByteSize()||f.snapshotVersion.toMicroseconds()-_.snapshotVersion.toMicroseconds()>=3e8||h.addedDocuments.size+h.modifiedDocuments.size+h.removedDocuments.size>0)&&g.push(e.Ur.updateTargetData(l,b))});let b=ey,w=__PRIVATE_documentKeySet();if(i.documentUpdates.forEach(s=>{i.resolvedLimboDocuments.has(s)&&g.push(e.persistence.referenceDelegate.updateLimboDocument(l,s))}),g.push((h=i.documentUpdates,d=__PRIVATE_documentKeySet(),f=__PRIVATE_documentKeySet(),h.forEach(e=>d=d.add(e)),_.getEntries(l,d).next(e=>{let i=ey;return h.forEach((s,o)=>{let l=e.get(s);o.isFoundDocument()!==l.isFoundDocument()&&(f=f.add(s)),o.isNoDocument()&&o.version.isEqual(SnapshotVersion.min())?(_.removeEntry(s,o.readTime),i=i.insert(s,o)):!l.isValidDocument()||o.version.compareTo(l.version)>0||0===o.version.compareTo(l.version)&&l.hasPendingWrites?(_.addEntry(o),i=i.insert(s,o)):__PRIVATE_logDebug("LocalStore","Ignoring outdated watch update for ",s,". Current version:",l.version," Watch version:",o.version)}),{Ps:i,Is:f}})).next(e=>{b=e.Ps,w=e.Is})),!s.isEqual(SnapshotVersion.min())){let i=e.Ur.getLastRemoteSnapshotVersion(l).next(i=>e.Ur.setTargetsMetadata(l,l.currentSequenceNumber,s));g.push(i)}return PersistencePromise.waitFor(g).next(()=>_.apply(l)).next(()=>e.localDocuments.getLocalViewOfDocuments(l,b,w)).next(()=>b)}).then(i=>(e.os=o,i))}(e.localStore,i);i.targetChanges.forEach((i,s)=>{let o=e.Na.get(s);o&&(i.addedDocuments.size+i.modifiedDocuments.size+i.removedDocuments.size<=1||fail(),i.addedDocuments.size>0?o.va=!0:i.modifiedDocuments.size>0?o.va||fail():i.removedDocuments.size>0&&(o.va||fail(),o.va=!1))}),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e,s,i)}catch(e){await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}}function __PRIVATE_syncEngineApplyOnlineStateChange(e,i,s){var o;if(e.isPrimaryClient&&0===s||!e.isPrimaryClient&&1===s){let s;let l=[];e.Fa.forEach((e,s)=>{let o=s.view.Z_(i);o.snapshot&&l.push(o.snapshot)}),(o=e.eventManager).onlineState=i,s=!1,o.queries.forEach((e,o)=>{for(let e of o.j_)e.Z_(i)&&(s=!0)}),s&&__PRIVATE_raiseSnapshotsInSyncEvent(o),l.length&&e.Ca.d_(l),e.onlineState=i,e.isPrimaryClient&&e.sharedClientState.setOnlineState(i)}}async function __PRIVATE_syncEngineRejectListen(e,i,s){e.sharedClientState.updateQueryState(i,"rejected",s);let o=e.Na.get(i),l=o&&o.key;if(l){let s=new SortedMap(DocumentKey.comparator);s=s.insert(l,MutableDocument.newNoDocument(l,SnapshotVersion.min()));let o=__PRIVATE_documentKeySet().add(l),h=new RemoteEvent(SnapshotVersion.min(),new Map,new SortedMap(__PRIVATE_primitiveComparator),s,o);await __PRIVATE_syncEngineApplyRemoteEvent(e,h),e.Oa=e.Oa.remove(l),e.Na.delete(i),__PRIVATE_pumpEnqueuedLimboResolutions(e)}else await __PRIVATE_localStoreReleaseTarget(e.localStore,i,!1).then(()=>__PRIVATE_removeAndCleanupTarget(e,i,s)).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)}async function __PRIVATE_syncEngineApplySuccessfulWrite(e,i){var s;let o=i.batch.batchId;try{let l=await (s=e.localStore).persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let o=i.batch.keys(),l=s.cs.newChangeBuffer({trackRemovals:!0});return(function(e,i,s,o){let l=s.batch,h=l.keys(),d=PersistencePromise.resolve();return h.forEach(e=>{d=d.next(()=>o.getEntry(i,e)).next(i=>{let h=s.docVersions.get(e);null!==h||fail(),0>i.version.compareTo(h)&&(l.applyToRemoteDocument(i,s),i.isValidDocument()&&(i.setReadTime(s.commitVersion),o.addEntry(i)))})}),d.next(()=>e.mutationQueue.removeMutationBatch(i,l))})(s,e,i,l).next(()=>l.apply(e)).next(()=>s.mutationQueue.performConsistencyCheck(e)).next(()=>s.documentOverlayCache.removeOverlaysForBatchId(e,o,i.batch.batchId)).next(()=>s.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let i=__PRIVATE_documentKeySet();for(let s=0;s<e.mutationResults.length;++s)e.mutationResults[s].transformResults.length>0&&(i=i.add(e.batch.mutations[s].key));return i}(i))).next(()=>s.localDocuments.getDocuments(e,o))});__PRIVATE_processUserCallback(e,o,null),__PRIVATE_triggerPendingWritesCallbacks(e,o),e.sharedClientState.updateMutationState(o,"acknowledged"),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e,l)}catch(e){await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}}async function __PRIVATE_syncEngineRejectFailedWrite(e,i,s){var o;try{let l=await (o=e.localStore).persistence.runTransaction("Reject batch","readwrite-primary",e=>{let s;return o.mutationQueue.lookupMutationBatch(e,i).next(i=>(null!==i||fail(),s=i.keys(),o.mutationQueue.removeMutationBatch(e,i))).next(()=>o.mutationQueue.performConsistencyCheck(e)).next(()=>o.documentOverlayCache.removeOverlaysForBatchId(e,s,i)).next(()=>o.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,s)).next(()=>o.localDocuments.getDocuments(e,s))});__PRIVATE_processUserCallback(e,i,s),__PRIVATE_triggerPendingWritesCallbacks(e,i),e.sharedClientState.updateMutationState(i,"rejected",s),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e,l)}catch(e){await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}}function __PRIVATE_triggerPendingWritesCallbacks(e,i){(e.ka.get(i)||[]).forEach(e=>{e.resolve()}),e.ka.delete(i)}function __PRIVATE_processUserCallback(e,i,s){let o=e.Ba[e.currentUser.toKey()];if(o){let l=o.get(i);l&&(s?l.reject(s):l.resolve(),o=o.remove(i)),e.Ba[e.currentUser.toKey()]=o}}function __PRIVATE_removeAndCleanupTarget(e,i,s=null){for(let o of(e.sharedClientState.removeLocalQueryTarget(i),e.Ma.get(i)))e.Fa.delete(o),s&&e.Ca.$a(o,s);e.Ma.delete(i),e.isPrimaryClient&&e.La.gr(i).forEach(i=>{e.La.containsKey(i)||__PRIVATE_removeLimboTarget(e,i)})}function __PRIVATE_removeLimboTarget(e,i){e.xa.delete(i.path.canonicalString());let s=e.Oa.get(i);null!==s&&(__PRIVATE_remoteStoreUnlisten(e.remoteStore,s),e.Oa=e.Oa.remove(i),e.Na.delete(s),__PRIVATE_pumpEnqueuedLimboResolutions(e))}function __PRIVATE_updateTrackedLimbos(e,i,s){for(let o of s)o instanceof __PRIVATE_AddedLimboDocument?(e.La.addReference(o.key,i),function(e,i){let s=i.key,o=s.path.canonicalString();e.Oa.get(s)||e.xa.has(o)||(__PRIVATE_logDebug("SyncEngine","New document in limbo: "+s),e.xa.add(o),__PRIVATE_pumpEnqueuedLimboResolutions(e))}(e,o)):o instanceof __PRIVATE_RemovedLimboDocument?(__PRIVATE_logDebug("SyncEngine","Document no longer in limbo: "+o.key),e.La.removeReference(o.key,i),e.La.containsKey(o.key)||__PRIVATE_removeLimboTarget(e,o.key)):fail()}function __PRIVATE_pumpEnqueuedLimboResolutions(e){for(;e.xa.size>0&&e.Oa.size<e.maxConcurrentLimboResolutions;){var i;let s=e.xa.values().next().value;e.xa.delete(s);let o=new DocumentKey(ResourcePath.fromString(s)),l=e.qa.next();e.Na.set(l,new LimboResolution(o)),e.Oa=e.Oa.insert(o,l),__PRIVATE_remoteStoreListen(e.remoteStore,new TargetData(__PRIVATE_queryToTarget((i=o.path,new __PRIVATE_QueryImpl(i))),l,"TargetPurposeLimboResolution",__PRIVATE_ListenSequence.oe))}}async function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e,i,s){let o=[],l=[],h=[];e.Fa.isEmpty()||(e.Fa.forEach((d,f)=>{h.push(e.Ka(f,i,s).then(i=>{var h;if((i||s)&&e.isPrimaryClient){let o=i?!i.fromCache:null===(h=null==s?void 0:s.targetChanges.get(f.targetId))||void 0===h?void 0:h.current;e.sharedClientState.updateQueryState(f.targetId,o?"current":"not-current")}if(i){o.push(i);let e=__PRIVATE_LocalViewChanges.Wi(f.targetId,i);l.push(e)}}))}),await Promise.all(h),e.Ca.d_(o),await async function(e,i){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",s=>PersistencePromise.forEach(i,i=>PersistencePromise.forEach(i.$i,o=>e.persistence.referenceDelegate.addReference(s,i.targetId,o)).next(()=>PersistencePromise.forEach(i.Ui,o=>e.persistence.referenceDelegate.removeReference(s,i.targetId,o)))))}catch(e){if(!__PRIVATE_isIndexedDbTransactionError(e))throw e;__PRIVATE_logDebug("LocalStore","Failed to update sequence numbers: "+e)}for(let s of i){let i=s.targetId;if(!s.fromCache){let s=e.os.get(i),o=s.snapshotVersion,l=s.withLastLimboFreeSnapshotVersion(o);e.os=e.os.insert(i,l)}}}(e.localStore,l))}async function __PRIVATE_syncEngineHandleCredentialChange(e,i){if(!e.currentUser.isEqual(i)){__PRIVATE_logDebug("SyncEngine","User change. New user:",i.toKey());let s=await __PRIVATE_localStoreHandleUserChange(e.localStore,i);e.currentUser=i,e.ka.forEach(e=>{e.forEach(e=>{e.reject(new FirestoreError(e_.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.ka.clear(),e.sharedClientState.handleUserChange(i,s.removedBatchIds,s.addedBatchIds),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e,s.hs)}}function __PRIVATE_syncEngineGetRemoteKeysForTarget(e,i){let s=e.Na.get(i);if(s&&s.va)return __PRIVATE_documentKeySet().add(s.key);{let s=__PRIVATE_documentKeySet(),o=e.Ma.get(i);if(!o)return s;for(let i of o){let o=e.Fa.get(i);s=s.unionWith(o.view.Va)}return s}}function __PRIVATE_ensureWatchCallbacks(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=__PRIVATE_syncEngineApplyRemoteEvent.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=__PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=__PRIVATE_syncEngineRejectListen.bind(null,e),e.Ca.d_=__PRIVATE_eventManagerOnWatchChange.bind(null,e.eventManager),e.Ca.$a=__PRIVATE_eventManagerOnWatchError.bind(null,e.eventManager),e}let __PRIVATE_MemoryOfflineComponentProvider=class __PRIVATE_MemoryOfflineComponentProvider{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=__PRIVATE_newSerializer(e.databaseInfo.databaseId),this.sharedClientState=this.Wa(e),this.persistence=this.Ga(e),await this.persistence.start(),this.localStore=this.za(e),this.gcScheduler=this.ja(e,this.localStore),this.indexBackfillerScheduler=this.Ha(e,this.localStore)}ja(e,i){return null}Ha(e,i){return null}za(e){var i,s,o,l;return i=this.persistence,s=new __PRIVATE_QueryEngine,o=e.initialUser,l=this.serializer,new __PRIVATE_LocalStoreImpl(i,s,o,l)}Ga(e){return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Zr,this.serializer)}Wa(e){return new __PRIVATE_MemorySharedClientState}async terminate(){var e,i;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(i=this.indexBackfillerScheduler)||void 0===i||i.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}};__PRIVATE_MemoryOfflineComponentProvider.provider={build:()=>new __PRIVATE_MemoryOfflineComponentProvider};let OnlineComponentProvider=class OnlineComponentProvider{async initialize(e,i){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(i),this.remoteStore=this.createRemoteStore(i),this.eventManager=this.createEventManager(i),this.syncEngine=this.createSyncEngine(i,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>__PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=__PRIVATE_syncEngineHandleCredentialChange.bind(null,this.syncEngine),await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new __PRIVATE_EventManagerImpl}createDatastore(e){var i,s,o;let l=__PRIVATE_newSerializer(e.databaseInfo.databaseId),h=(i=e.databaseInfo,new __PRIVATE_WebChannelConnection(i));return s=e.authCredentials,o=e.appCheckCredentials,new __PRIVATE_DatastoreImpl(s,o,h,l)}createRemoteStore(e){var i,s,o,l;return i=this.localStore,s=this.datastore,o=e.asyncQueue,l=__PRIVATE_BrowserConnectivityMonitor.D()?new __PRIVATE_BrowserConnectivityMonitor:new __PRIVATE_NoopConnectivityMonitor,new __PRIVATE_RemoteStoreImpl(i,s,o,e=>__PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine,e,0),l)}createSyncEngine(e,i){return function(e,i,s,o,l,h,d){let f=new __PRIVATE_SyncEngineImpl(e,i,s,o,l,h);return d&&(f.Qa=!0),f}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,i)}async terminate(){var e,i;await async function(e){__PRIVATE_logDebug("RemoteStore","RemoteStore shutting down."),e.L_.add(5),await __PRIVATE_disableNetworkInternal(e),e.k_.shutdown(),e.q_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate(),null===(i=this.eventManager)||void 0===i||i.terminate()}};OnlineComponentProvider.provider={build:()=>new OnlineComponentProvider};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *//**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_AsyncObserver=class __PRIVATE_AsyncObserver{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ya(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ya(this.observer.error,e):__PRIVATE_logError("Uncaught Error in snapshot listener:",e.toString()))}Za(){this.muted=!0}Ya(e,i){setTimeout(()=>{this.muted||e(i)},0)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FirestoreClient=class FirestoreClient{constructor(e,i,s,o,l){this.authCredentials=e,this.appCheckCredentials=i,this.asyncQueue=s,this.databaseInfo=o,this.user=User.UNAUTHENTICATED,this.clientId=__PRIVATE_AutoId.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=l,this.authCredentials.start(s,async e=>{__PRIVATE_logDebug("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(s,e=>(__PRIVATE_logDebug("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new __PRIVATE_Deferred;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(s){let i=__PRIVATE_wrapInUserErrorIfRecoverable(s,"Failed to shutdown persistence");e.reject(i)}}),e.promise}};async function __PRIVATE_setOfflineComponentProvider(e,i){e.asyncQueue.verifyOperationInProgress(),__PRIVATE_logDebug("FirestoreClient","Initializing OfflineComponentProvider");let s=e.configuration;await i.initialize(s);let o=s.initialUser;e.setCredentialChangeListener(async e=>{o.isEqual(e)||(await __PRIVATE_localStoreHandleUserChange(i.localStore,e),o=e)}),i.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=i}async function __PRIVATE_setOnlineComponentProvider(e,i){e.asyncQueue.verifyOperationInProgress();let s=await __PRIVATE_ensureOfflineComponents(e);__PRIVATE_logDebug("FirestoreClient","Initializing OnlineComponentProvider"),await i.initialize(s,e.configuration),e.setCredentialChangeListener(e=>__PRIVATE_remoteStoreHandleCredentialChange(i.remoteStore,e)),e.setAppCheckTokenChangeListener((e,s)=>__PRIVATE_remoteStoreHandleCredentialChange(i.remoteStore,s)),e._onlineComponents=i}async function __PRIVATE_ensureOfflineComponents(e){if(!e._offlineComponents){if(e._uninitializedComponentsProvider){__PRIVATE_logDebug("FirestoreClient","Using user provided OfflineComponentProvider");try{await __PRIVATE_setOfflineComponentProvider(e,e._uninitializedComponentsProvider._offline)}catch(i){if(!("FirebaseError"===i.name?i.code===e_.FAILED_PRECONDITION||i.code===e_.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&i instanceof DOMException)||22===i.code||20===i.code||11===i.code))throw i;__PRIVATE_logWarn("Error using user provided cache. Falling back to memory cache: "+i),await __PRIVATE_setOfflineComponentProvider(e,new __PRIVATE_MemoryOfflineComponentProvider)}}else __PRIVATE_logDebug("FirestoreClient","Using default OfflineComponentProvider"),await __PRIVATE_setOfflineComponentProvider(e,new __PRIVATE_MemoryOfflineComponentProvider)}return e._offlineComponents}async function __PRIVATE_ensureOnlineComponents(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(__PRIVATE_logDebug("FirestoreClient","Using user provided OnlineComponentProvider"),await __PRIVATE_setOnlineComponentProvider(e,e._uninitializedComponentsProvider._online)):(__PRIVATE_logDebug("FirestoreClient","Using default OnlineComponentProvider"),await __PRIVATE_setOnlineComponentProvider(e,new OnlineComponentProvider))),e._onlineComponents}async function __PRIVATE_getEventManager(e){let i=await __PRIVATE_ensureOnlineComponents(e),s=i.eventManager;return s.onListen=__PRIVATE_syncEngineListen.bind(null,i.syncEngine),s.onUnlisten=__PRIVATE_syncEngineUnlisten.bind(null,i.syncEngine),s.onFirstRemoteStoreListen=__PRIVATE_triggerRemoteStoreListen.bind(null,i.syncEngine),s.onLastRemoteStoreUnlisten=__PRIVATE_triggerRemoteStoreUnlisten.bind(null,i.syncEngine),s}/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function __PRIVATE_cloneLongPollingOptions(e){let i={};return void 0!==e.timeoutSeconds&&(i.timeoutSeconds=e.timeoutSeconds),i}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let ek=new Map;/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function __PRIVATE_validateNonEmptyArgument(e,i,s){if(!s)throw new FirestoreError(e_.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${i}.`)}function __PRIVATE_validateDocumentPath(e){if(!DocumentKey.isDocumentKey(e))throw new FirestoreError(e_.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_validateCollectionPath(e){if(DocumentKey.isDocumentKey(e))throw new FirestoreError(e_.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_valueDescription(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{var i;let s=(i=e).constructor?i.constructor.name:null;return s?`a custom ${s} object`:"an object"}}return"function"==typeof e?"a function":fail()}function __PRIVATE_cast(e,i){if("_delegate"in e&&(e=e._delegate),!(e instanceof i)){if(i.name===e.constructor.name)throw new FirestoreError(e_.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let s=__PRIVATE_valueDescription(e);throw new FirestoreError(e_.INVALID_ARGUMENT,`Expected type '${i.name}', but it was: ${s}`)}}return e}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FirestoreSettingsImpl=class FirestoreSettingsImpl{constructor(e){var i,s;if(void 0===e.host){if(void 0!==e.ssl)throw new FirestoreError(e_.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(i=e.ssl)||void 0===i||i;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new FirestoreError(e_.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,i,s,o){if(!0===i&&!0===o)throw new FirestoreError(e_.INVALID_ARGUMENT,`${e} and ${s} cannot be used together.`)})("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=__PRIVATE_cloneLongPollingOptions(null!==(s=e.experimentalLongPollingOptions)&&void 0!==s?s:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new FirestoreError(e_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new FirestoreError(e_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new FirestoreError(e_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){var i,s;return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(i=this.experimentalLongPollingOptions,s=e.experimentalLongPollingOptions,i.timeoutSeconds===s.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}};let Firestore$1=class Firestore$1{constructor(e,i,s,o){this._authCredentials=e,this._appCheckCredentials=i,this._databaseId=s,this._app=o,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new FirestoreSettingsImpl({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new FirestoreError(e_.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new FirestoreError(e_.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new FirestoreSettingsImpl(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new __PRIVATE_EmptyAuthCredentialsProvider;switch(e.type){case"firstParty":return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new FirestoreError(e_.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){let i=ek.get(e);i&&(__PRIVATE_logDebug("ComponentProvider","Removing Datastore"),ek.delete(e),i.terminate())}(this),Promise.resolve()}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Query=class Query{constructor(e,i,s){this.converter=i,this._query=s,this.type="query",this.firestore=e}withConverter(e){return new Query(this.firestore,e,this._query)}};let DocumentReference=class DocumentReference{constructor(e,i,s){this.converter=i,this._key=s,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new CollectionReference(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new DocumentReference(this.firestore,e,this._key)}};let CollectionReference=class CollectionReference extends Query{constructor(e,i,s){super(e,i,new __PRIVATE_QueryImpl(s)),this._path=s,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new DocumentReference(this.firestore,null,new DocumentKey(e))}withConverter(e){return new CollectionReference(this.firestore,e,this._path)}};function collection(e,i,...s){if(e=(0,en.m9)(e),__PRIVATE_validateNonEmptyArgument("collection","path",i),e instanceof Firestore$1){let o=ResourcePath.fromString(i,...s);return __PRIVATE_validateCollectionPath(o),new CollectionReference(e,null,o)}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(e_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let o=e._path.child(ResourcePath.fromString(i,...s));return __PRIVATE_validateCollectionPath(o),new CollectionReference(e.firestore,null,o)}}function doc(e,i,...s){if(e=(0,en.m9)(e),1==arguments.length&&(i=__PRIVATE_AutoId.newId()),__PRIVATE_validateNonEmptyArgument("doc","path",i),e instanceof Firestore$1){let o=ResourcePath.fromString(i,...s);return __PRIVATE_validateDocumentPath(o),new DocumentReference(e,null,new DocumentKey(o))}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(e_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let o=e._path.child(ResourcePath.fromString(i,...s));return __PRIVATE_validateDocumentPath(o),new DocumentReference(e.firestore,e instanceof CollectionReference?e.converter:null,new DocumentKey(o))}}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let __PRIVATE_AsyncQueueImpl=class __PRIVATE_AsyncQueueImpl{constructor(e=Promise.resolve()){this.Pu=[],this.Iu=!1,this.Tu=[],this.Eu=null,this.du=!1,this.Au=!1,this.Ru=[],this.t_=new __PRIVATE_ExponentialBackoff(this,"async_queue_retry"),this.Vu=()=>{let e=getDocument();e&&__PRIVATE_logDebug("AsyncQueue","Visibility state changed to "+e.visibilityState),this.t_.jo()},this.mu=e;let i=getDocument();i&&"function"==typeof i.addEventListener&&i.addEventListener("visibilitychange",this.Vu)}get isShuttingDown(){return this.Iu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.fu(),this.gu(e)}enterRestrictedMode(e){if(!this.Iu){this.Iu=!0,this.Au=e||!1;let i=getDocument();i&&"function"==typeof i.removeEventListener&&i.removeEventListener("visibilitychange",this.Vu)}}enqueue(e){if(this.fu(),this.Iu)return new Promise(()=>{});let i=new __PRIVATE_Deferred;return this.gu(()=>this.Iu&&this.Au?Promise.resolve():(e().then(i.resolve,i.reject),i.promise)).then(()=>i.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Pu.push(e),this.pu()))}async pu(){if(0!==this.Pu.length){try{await this.Pu[0](),this.Pu.shift(),this.t_.reset()}catch(e){if(!__PRIVATE_isIndexedDbTransactionError(e))throw e;__PRIVATE_logDebug("AsyncQueue","Operation failed with retryable error: "+e)}this.Pu.length>0&&this.t_.Go(()=>this.pu())}}gu(e){let i=this.mu.then(()=>(this.du=!0,e().catch(e=>{let i;this.Eu=e,this.du=!1;let s=(i=e.message||"",e.stack&&(i=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),i);throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ",s),e}).then(e=>(this.du=!1,e))));return this.mu=i,i}enqueueAfterDelay(e,i,s){this.fu(),this.Ru.indexOf(e)>-1&&(i=0);let o=DelayedOperation.createAndSchedule(this,e,i,s,e=>this.yu(e));return this.Tu.push(o),o}fu(){this.Eu&&fail()}verifyOperationInProgress(){}async wu(){let e;do e=this.mu,await e;while(e!==this.mu)}Su(e){for(let i of this.Tu)if(i.timerId===e)return!0;return!1}bu(e){return this.wu().then(()=>{for(let i of(this.Tu.sort((e,i)=>e.targetTimeMs-i.targetTimeMs),this.Tu))if(i.skipDelay(),"all"!==e&&i.timerId===e)break;return this.wu()})}Du(e){this.Ru.push(e)}yu(e){let i=this.Tu.indexOf(e);this.Tu.splice(i,1)}};let Firestore=class Firestore extends Firestore$1{constructor(e,i,s,o){super(e,i,s,o),this.type="firestore",this._queue=new __PRIVATE_AsyncQueueImpl,this._persistenceKey=(null==o?void 0:o.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new __PRIVATE_AsyncQueueImpl(e),this._firestoreClient=void 0,await e}}};function getFirestore(e,i){let s="object"==typeof e?e:(0,ee.Mq)(),o=(0,ee.qX)(s,"firestore").getImmediate({identifier:"string"==typeof e?e:i||"(default)"});if(!o._initialized){let e=(0,en.P0)("firestore");e&&function(e,i,s,o={}){var l;let h=(e=__PRIVATE_cast(e,Firestore$1))._getSettings(),d=`${i}:${s}`;if("firestore.googleapis.com"!==h.host&&h.host!==d&&__PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},h),{host:d,ssl:!1})),o.mockUserToken){let i,s;if("string"==typeof o.mockUserToken)i=o.mockUserToken,s=User.MOCK_USER;else{i=(0,en.Sg)(o.mockUserToken,null===(l=e._app)||void 0===l?void 0:l.options.projectId);let h=o.mockUserToken.sub||o.mockUserToken.user_id;if(!h)throw new FirestoreError(e_.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");s=new User(h)}e._authCredentials=new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(i,s))}}(o,...e)}return o}function ensureFirestoreConfigured(e){if(e._terminated)throw new FirestoreError(e_.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||function(e){var i,s,o,l,h,d;let f=e._freezeSettings(),_=(l=e._databaseId,h=(null===(i=e._app)||void 0===i?void 0:i.options.appId)||"",d=e._persistenceKey,new DatabaseInfo(l,h,d,f.host,f.ssl,f.experimentalForceLongPolling,f.experimentalAutoDetectLongPolling,__PRIVATE_cloneLongPollingOptions(f.experimentalLongPollingOptions),f.useFetchStreams));e._componentsProvider||(null===(s=f.localCache)||void 0===s?void 0:s._offlineComponentProvider)&&(null===(o=f.localCache)||void 0===o?void 0:o._onlineComponentProvider)&&(e._componentsProvider={_offline:f.localCache._offlineComponentProvider,_online:f.localCache._onlineComponentProvider}),e._firestoreClient=new FirestoreClient(e._authCredentials,e._appCheckCredentials,e._queue,_,e._componentsProvider&&function(e){let i=null==e?void 0:e._online.build();return{_offline:null==e?void 0:e._offline.build(i),_online:i}}(e._componentsProvider))}(e),e._firestoreClient}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Bytes=class Bytes{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Bytes(ByteString.fromBase64String(e))}catch(e){throw new FirestoreError(e_.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Bytes(ByteString.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FieldPath=class FieldPath{constructor(...e){for(let i=0;i<e.length;++i)if(0===e[i].length)throw new FirestoreError(e_.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new FieldPath$1(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FieldValue=class FieldValue{constructor(e){this._methodName=e}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let GeoPoint=class GeoPoint{constructor(e,i){if(!isFinite(e)||e<-90||e>90)throw new FirestoreError(e_.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(i)||i<-180||i>180)throw new FirestoreError(e_.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+i);this._lat=e,this._long=i}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return __PRIVATE_primitiveComparator(this._lat,e._lat)||__PRIVATE_primitiveComparator(this._long,e._long)}};/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let VectorValue=class VectorValue{constructor(e){this._values=(e||[]).map(e=>e)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(e,i){if(e.length!==i.length)return!1;for(let s=0;s<e.length;++s)if(e[s]!==i[s])return!1;return!0}(this._values,e._values)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let eD=/^__.*__$/;let ParsedSetData=class ParsedSetData{constructor(e,i,s){this.data=e,this.fieldMask=i,this.fieldTransforms=s}toMutation(e,i){return null!==this.fieldMask?new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,i,this.fieldTransforms):new __PRIVATE_SetMutation(e,this.data,i,this.fieldTransforms)}};let ParsedUpdateData=class ParsedUpdateData{constructor(e,i,s){this.data=e,this.fieldMask=i,this.fieldTransforms=s}toMutation(e,i){return new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,i,this.fieldTransforms)}};function __PRIVATE_isWrite(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw fail()}}let __PRIVATE_ParseContextImpl=class __PRIVATE_ParseContextImpl{constructor(e,i,s,o,l,h){this.settings=e,this.databaseId=i,this.serializer=s,this.ignoreUndefinedProperties=o,void 0===l&&this.vu(),this.fieldTransforms=l||[],this.fieldMask=h||[]}get path(){return this.settings.path}get Cu(){return this.settings.Cu}Fu(e){return new __PRIVATE_ParseContextImpl(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Mu(e){var i;let s=null===(i=this.path)||void 0===i?void 0:i.child(e),o=this.Fu({path:s,xu:!1});return o.Ou(e),o}Nu(e){var i;let s=null===(i=this.path)||void 0===i?void 0:i.child(e),o=this.Fu({path:s,xu:!1});return o.vu(),o}Lu(e){return this.Fu({path:void 0,xu:!0})}Bu(e){return __PRIVATE_createError(e,this.settings.methodName,this.settings.ku||!1,this.path,this.settings.qu)}contains(e){return void 0!==this.fieldMask.find(i=>e.isPrefixOf(i))||void 0!==this.fieldTransforms.find(i=>e.isPrefixOf(i.field))}vu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Ou(this.path.get(e))}Ou(e){if(0===e.length)throw this.Bu("Document fields must not be empty");if(__PRIVATE_isWrite(this.Cu)&&eD.test(e))throw this.Bu('Document fields cannot begin and end with "__"')}};let __PRIVATE_UserDataReader=class __PRIVATE_UserDataReader{constructor(e,i,s){this.databaseId=e,this.ignoreUndefinedProperties=i,this.serializer=s||__PRIVATE_newSerializer(e)}Qu(e,i,s,o=!1){return new __PRIVATE_ParseContextImpl({Cu:e,methodName:i,qu:s,path:FieldPath$1.emptyPath(),xu:!1,ku:o},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}};function __PRIVATE_newUserDataReader(e){let i=e._freezeSettings(),s=__PRIVATE_newSerializer(e._databaseId);return new __PRIVATE_UserDataReader(e._databaseId,!!i.ignoreUndefinedProperties,s)}function __PRIVATE_parseSetData(e,i,s,o,l,h={}){let d,f;let _=e.Qu(h.merge||h.mergeFields?2:0,i,s,l);__PRIVATE_validatePlainObject("Data must be an object, but it was:",_,o);let g=__PRIVATE_parseObject(o,_);if(h.merge)d=new FieldMask(_.fieldMask),f=_.fieldTransforms;else if(h.mergeFields){let e=[];for(let o of h.mergeFields){let l=__PRIVATE_fieldPathFromArgument$1(i,o,s);if(!_.contains(l))throw new FirestoreError(e_.INVALID_ARGUMENT,`Field '${l}' is specified in your field mask but missing from your input data.`);__PRIVATE_fieldMaskContains(e,l)||e.push(l)}d=new FieldMask(e),f=_.fieldTransforms.filter(e=>d.covers(e.field))}else d=null,f=_.fieldTransforms;return new ParsedSetData(new ObjectValue(g),d,f)}let __PRIVATE_DeleteFieldValueImpl=class __PRIVATE_DeleteFieldValueImpl extends FieldValue{_toFieldTransform(e){if(2!==e.Cu)throw 1===e.Cu?e.Bu(`${this._methodName}() can only appear at the top level of your update data`):e.Bu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof __PRIVATE_DeleteFieldValueImpl}};let __PRIVATE_ServerTimestampFieldValueImpl=class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue{_toFieldTransform(e){return new FieldTransform(e.path,new __PRIVATE_ServerTimestampTransform)}isEqual(e){return e instanceof __PRIVATE_ServerTimestampFieldValueImpl}};function __PRIVATE_parseUpdateData(e,i,s,o){let l=e.Qu(1,i,s);__PRIVATE_validatePlainObject("Data must be an object, but it was:",l,o);let h=[],d=ObjectValue.empty();forEach(o,(e,o)=>{let f=__PRIVATE_fieldPathFromDotSeparatedString(i,e,s);o=(0,en.m9)(o);let _=l.Nu(f);if(o instanceof __PRIVATE_DeleteFieldValueImpl)h.push(f);else{let e=__PRIVATE_parseData(o,_);null!=e&&(h.push(f),d.set(f,e))}});let f=new FieldMask(h);return new ParsedUpdateData(d,f,l.fieldTransforms)}function __PRIVATE_parseUpdateVarargs(e,i,s,o,l,h){let d=e.Qu(1,i,s),f=[__PRIVATE_fieldPathFromArgument$1(i,o,s)],_=[l];if(h.length%2!=0)throw new FirestoreError(e_.INVALID_ARGUMENT,`Function ${i}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<h.length;e+=2)f.push(__PRIVATE_fieldPathFromArgument$1(i,h[e])),_.push(h[e+1]);let g=[],b=ObjectValue.empty();for(let e=f.length-1;e>=0;--e)if(!__PRIVATE_fieldMaskContains(g,f[e])){let i=f[e],s=_[e];s=(0,en.m9)(s);let o=d.Nu(i);if(s instanceof __PRIVATE_DeleteFieldValueImpl)g.push(i);else{let e=__PRIVATE_parseData(s,o);null!=e&&(g.push(i),b.set(i,e))}}let w=new FieldMask(g);return new ParsedUpdateData(b,w,d.fieldTransforms)}function __PRIVATE_parseData(e,i){if(__PRIVATE_looksLikeJsonObject(e=(0,en.m9)(e)))return __PRIVATE_validatePlainObject("Unsupported field value:",i,e),__PRIVATE_parseObject(e,i);if(e instanceof FieldValue)return function(e,i){if(!__PRIVATE_isWrite(i.Cu))throw i.Bu(`${e._methodName}() can only be used with update() and set()`);if(!i.path)throw i.Bu(`${e._methodName}() is not currently supported inside arrays`);let s=e._toFieldTransform(i);s&&i.fieldTransforms.push(s)}(e,i),null;if(void 0===e&&i.ignoreUndefinedProperties)return null;if(i.path&&i.fieldMask.push(i.path),e instanceof Array){if(i.settings.xu&&4!==i.Cu)throw i.Bu("Nested arrays are not supported");return function(e,i){let s=[],o=0;for(let l of e){let e=__PRIVATE_parseData(l,i.Lu(o));null==e&&(e={nullValue:"NULL_VALUE"}),s.push(e),o++}return{arrayValue:{values:s}}}(e,i)}return function(e,i){var s,o,l;if(null===(e=(0,en.m9)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return s=i.serializer,"number"==typeof(l=o=e)&&Number.isInteger(l)&&!__PRIVATE_isNegativeZero(l)&&l<=Number.MAX_SAFE_INTEGER&&l>=Number.MIN_SAFE_INTEGER?__PRIVATE_toInteger(o):__PRIVATE_toDouble(s,o);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){let s=Timestamp.fromDate(e);return{timestampValue:toTimestamp(i.serializer,s)}}if(e instanceof Timestamp){let s=new Timestamp(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:toTimestamp(i.serializer,s)}}if(e instanceof GeoPoint)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Bytes)return{bytesValue:__PRIVATE_toBytes(i.serializer,e._byteString)};if(e instanceof DocumentReference){let s=i.databaseId,o=e.firestore._databaseId;if(!o.isEqual(s))throw i.Bu(`Document reference is for database ${o.projectId}/${o.database} but should be for database ${s.projectId}/${s.database}`);return{referenceValue:__PRIVATE_toResourceName(e.firestore._databaseId||i.databaseId,e._key.path)}}if(e instanceof VectorValue)return{mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw i.Bu("VectorValues must only contain numeric values.");return __PRIVATE_toDouble(i.serializer,e)})}}}}};throw i.Bu(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`)}(e,i)}function __PRIVATE_parseObject(e,i){let s={};return isEmpty(e)?i.path&&i.path.length>0&&i.fieldMask.push(i.path):forEach(e,(e,o)=>{let l=__PRIVATE_parseData(o,i.Mu(e));null!=l&&(s[e]=l)}),{mapValue:{fields:s}}}function __PRIVATE_looksLikeJsonObject(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Timestamp||e instanceof GeoPoint||e instanceof Bytes||e instanceof DocumentReference||e instanceof FieldValue||e instanceof VectorValue)}function __PRIVATE_validatePlainObject(e,i,s){if(!__PRIVATE_looksLikeJsonObject(s)||!("object"==typeof s&&null!==s&&(Object.getPrototypeOf(s)===Object.prototype||null===Object.getPrototypeOf(s)))){let o=__PRIVATE_valueDescription(s);throw"an object"===o?i.Bu(e+" a custom object"):i.Bu(e+" "+o)}}function __PRIVATE_fieldPathFromArgument$1(e,i,s){if((i=(0,en.m9)(i))instanceof FieldPath)return i._internalPath;if("string"==typeof i)return __PRIVATE_fieldPathFromDotSeparatedString(e,i);throw __PRIVATE_createError("Field path arguments must be of type string or ",e,!1,void 0,s)}let ex=RegExp("[~\\*/\\[\\]]");function __PRIVATE_fieldPathFromDotSeparatedString(e,i,s){if(i.search(ex)>=0)throw __PRIVATE_createError(`Invalid field path (${i}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,s);try{return new FieldPath(...i.split("."))._internalPath}catch(o){throw __PRIVATE_createError(`Invalid field path (${i}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,s)}}function __PRIVATE_createError(e,i,s,o,l){let h=o&&!o.isEmpty(),d=void 0!==l,f=`Function ${i}() called with invalid data`;s&&(f+=" (via `toFirestore()`)"),f+=". ";let _="";return(h||d)&&(_+=" (found",h&&(_+=` in field ${o}`),d&&(_+=` in document ${l}`),_+=")"),new FirestoreError(e_.INVALID_ARGUMENT,f+e+_)}function __PRIVATE_fieldMaskContains(e,i){return e.some(e=>e.isEqual(i))}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let DocumentSnapshot$1=class DocumentSnapshot$1{constructor(e,i,s,o,l){this._firestore=e,this._userDataWriter=i,this._key=s,this._document=o,this._converter=l}get id(){return this._key.path.lastSegment()}get ref(){return new DocumentReference(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){let e=new QueryDocumentSnapshot$1(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let i=this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get",e));if(null!==i)return this._userDataWriter.convertValue(i)}}};let QueryDocumentSnapshot$1=class QueryDocumentSnapshot$1 extends DocumentSnapshot$1{data(){return super.data()}};function __PRIVATE_fieldPathFromArgument(e,i){return"string"==typeof i?__PRIVATE_fieldPathFromDotSeparatedString(e,i):i instanceof FieldPath?i._internalPath:i._delegate._internalPath}let AbstractUserDataWriter=class AbstractUserDataWriter{convertValue(e,i="none"){switch(__PRIVATE_typeOrder(e)){case 0:return null;case 1:return e.booleanValue;case 2:return __PRIVATE_normalizeNumber(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,i);case 5:return e.stringValue;case 6:return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,i);case 11:return this.convertObject(e.mapValue,i);case 10:return this.convertVectorValue(e.mapValue);default:throw fail()}}convertObject(e,i){return this.convertObjectMap(e.fields,i)}convertObjectMap(e,i="none"){let s={};return forEach(e,(e,o)=>{s[e]=this.convertValue(o,i)}),s}convertVectorValue(e){var i,s,o;let l=null===(o=null===(s=null===(i=e.fields)||void 0===i?void 0:i.value.arrayValue)||void 0===s?void 0:s.values)||void 0===o?void 0:o.map(e=>__PRIVATE_normalizeNumber(e.doubleValue));return new VectorValue(l)}convertGeoPoint(e){return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(e.longitude))}convertArray(e,i){return(e.values||[]).map(e=>this.convertValue(e,i))}convertServerTimestamp(e,i){switch(i){case"previous":let s=__PRIVATE_getPreviousValue(e);return null==s?null:this.convertValue(s,i);case"estimate":return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));default:return null}}convertTimestamp(e){let i=__PRIVATE_normalizeTimestamp(e);return new Timestamp(i.seconds,i.nanos)}convertDocumentKey(e,i){let s=ResourcePath.fromString(e);__PRIVATE_isValidResourceName(s)||fail();let o=new DatabaseId(s.get(1),s.get(3)),l=new DocumentKey(s.popFirst(5));return o.isEqual(i)||__PRIVATE_logError(`Document ${l} contains a document reference within a different database (${o.projectId}/${o.database}) which is not supported. It will be treated as a reference in the current database (${i.projectId}/${i.database}) instead.`),l}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function __PRIVATE_applyFirestoreDataConverter(e,i,s){return e?s&&(s.merge||s.mergeFields)?e.toFirestore(i,s):e.toFirestore(i):i}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let SnapshotMetadata=class SnapshotMetadata{constructor(e,i){this.hasPendingWrites=e,this.fromCache=i}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}};let DocumentSnapshot=class DocumentSnapshot extends DocumentSnapshot$1{constructor(e,i,s,o,l,h){super(e,i,s,o,h),this._firestore=e,this._firestoreImpl=e,this.metadata=l}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let i=new QueryDocumentSnapshot(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(i,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,i={}){if(this._document){let s=this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get",e));if(null!==s)return this._userDataWriter.convertValue(s,i.serverTimestamps)}}};let QueryDocumentSnapshot=class QueryDocumentSnapshot extends DocumentSnapshot{data(e={}){return super.data(e)}};let QuerySnapshot=class QuerySnapshot{constructor(e,i,s,o){this._firestore=e,this._userDataWriter=i,this._snapshot=o,this.metadata=new SnapshotMetadata(o.hasPendingWrites,o.fromCache),this.query=s}get docs(){let e=[];return this.forEach(i=>e.push(i)),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,i){this._snapshot.docs.forEach(s=>{e.call(i,new QueryDocumentSnapshot(this._firestore,this._userDataWriter,s.key,s,new SnapshotMetadata(this._snapshot.mutatedKeys.has(s.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let i=!!e.includeMetadataChanges;if(i&&this._snapshot.excludesMetadataChanges)throw new FirestoreError(e_.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===i||(this._cachedChanges=function(e,i){if(e._snapshot.oldDocs.isEmpty()){let i=0;return e._snapshot.docChanges.map(s=>{let o=new QueryDocumentSnapshot(e._firestore,e._userDataWriter,s.doc.key,s.doc,new SnapshotMetadata(e._snapshot.mutatedKeys.has(s.doc.key),e._snapshot.fromCache),e.query.converter);return s.doc,{type:"added",doc:o,oldIndex:-1,newIndex:i++}})}{let s=e._snapshot.oldDocs;return e._snapshot.docChanges.filter(e=>i||3!==e.type).map(i=>{let o=new QueryDocumentSnapshot(e._firestore,e._userDataWriter,i.doc.key,i.doc,new SnapshotMetadata(e._snapshot.mutatedKeys.has(i.doc.key),e._snapshot.fromCache),e.query.converter),l=-1,h=-1;return 0!==i.type&&(l=s.indexOf(i.doc.key),s=s.delete(i.doc.key)),1!==i.type&&(h=(s=s.add(i.doc)).indexOf(i.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return fail()}}(i.type),doc:o,oldIndex:l,newIndex:h}})}}(this,i),this._cachedChangesIncludeMetadataChanges=i),this._cachedChanges}};/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function getDoc(e){e=__PRIVATE_cast(e,DocumentReference);let i=__PRIVATE_cast(e.firestore,Firestore);return(function(e,i,s={}){let o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget(async()=>(function(e,i,s,o,l){var h;let d=new __PRIVATE_AsyncObserver({next:h=>{d.Za(),i.enqueueAndForget(()=>__PRIVATE_eventManagerUnlisten(e,f));let _=h.docs.has(s);!_&&h.fromCache?l.reject(new FirestoreError(e_.UNAVAILABLE,"Failed to get document because the client is offline.")):_&&h.fromCache&&o&&"server"===o.source?l.reject(new FirestoreError(e_.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):l.resolve(h)},error:e=>l.reject(e)}),f=new __PRIVATE_QueryListener((h=s.path,new __PRIVATE_QueryImpl(h)),d,{includeMetadataChanges:!0,_a:!0});return __PRIVATE_eventManagerListen(e,f)})(await __PRIVATE_getEventManager(e),e.asyncQueue,i,s,o)),o.promise})(ensureFirestoreConfigured(i),e._key).then(s=>(function(e,i,s){let o=s.docs.get(i._key),l=new __PRIVATE_ExpUserDataWriter(e);return new DocumentSnapshot(e,l,i._key,o,new SnapshotMetadata(s.hasPendingWrites,s.fromCache),i.converter)})(i,e,s))}let __PRIVATE_ExpUserDataWriter=class __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter{constructor(e){super(),this.firestore=e}convertBytes(e){return new Bytes(e)}convertReference(e){let i=this.convertDocumentKey(e,this.firestore._databaseId);return new DocumentReference(this.firestore,null,i)}};function getDocs(e){e=__PRIVATE_cast(e,Query);let i=__PRIVATE_cast(e.firestore,Firestore),s=ensureFirestoreConfigured(i),o=new __PRIVATE_ExpUserDataWriter(i);return(/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new FirestoreError(e_.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}(e._query),(function(e,i,s={}){let o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget(async()=>(function(e,i,s,o,l){let h=new __PRIVATE_AsyncObserver({next:s=>{h.Za(),i.enqueueAndForget(()=>__PRIVATE_eventManagerUnlisten(e,d)),s.fromCache&&"server"===o.source?l.reject(new FirestoreError(e_.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):l.resolve(s)},error:e=>l.reject(e)}),d=new __PRIVATE_QueryListener(s,h,{includeMetadataChanges:!0,_a:!0});return __PRIVATE_eventManagerListen(e,d)})(await __PRIVATE_getEventManager(e),e.asyncQueue,i,s,o)),o.promise})(s,e._query).then(s=>new QuerySnapshot(i,o,e,s)))}function updateDoc(e,i,s,...o){e=__PRIVATE_cast(e,DocumentReference);let l=__PRIVATE_cast(e.firestore,Firestore),h=__PRIVATE_newUserDataReader(l);return executeWrite(l,[("string"==typeof(i=(0,en.m9)(i))||i instanceof FieldPath?__PRIVATE_parseUpdateVarargs(h,"updateDoc",e._key,i,s,o):__PRIVATE_parseUpdateData(h,"updateDoc",e._key,i)).toMutation(e._key,Precondition.exists(!0))])}function deleteDoc(e){return executeWrite(__PRIVATE_cast(e.firestore,Firestore),[new __PRIVATE_DeleteMutation(e._key,Precondition.none())])}function addDoc(e,i){let s=__PRIVATE_cast(e.firestore,Firestore),o=doc(e),l=__PRIVATE_applyFirestoreDataConverter(e.converter,i);return executeWrite(s,[__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore),"addDoc",o._key,l,null!==e.converter,{}).toMutation(o._key,Precondition.exists(!1))]).then(()=>o)}function executeWrite(e,i){return function(e,i){let s=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget(async()=>__PRIVATE_syncEngineWrite(await __PRIVATE_ensureOnlineComponents(e).then(e=>e.syncEngine),i,s)),s.promise}(ensureFirestoreConfigured(e),i)}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let WriteBatch=class WriteBatch{constructor(e,i){this._firestore=e,this._commitHandler=i,this._mutations=[],this._committed=!1,this._dataReader=__PRIVATE_newUserDataReader(e)}set(e,i,s){this._verifyNotCommitted();let o=__PRIVATE_validateReference(e,this._firestore),l=__PRIVATE_applyFirestoreDataConverter(o.converter,i,s),h=__PRIVATE_parseSetData(this._dataReader,"WriteBatch.set",o._key,l,null!==o.converter,s);return this._mutations.push(h.toMutation(o._key,Precondition.none())),this}update(e,i,s,...o){let l;this._verifyNotCommitted();let h=__PRIVATE_validateReference(e,this._firestore);return l="string"==typeof(i=(0,en.m9)(i))||i instanceof FieldPath?__PRIVATE_parseUpdateVarargs(this._dataReader,"WriteBatch.update",h._key,i,s,o):__PRIVATE_parseUpdateData(this._dataReader,"WriteBatch.update",h._key,i),this._mutations.push(l.toMutation(h._key,Precondition.exists(!0))),this}delete(e){this._verifyNotCommitted();let i=__PRIVATE_validateReference(e,this._firestore);return this._mutations=this._mutations.concat(new __PRIVATE_DeleteMutation(i._key,Precondition.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new FirestoreError(e_.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}};function __PRIVATE_validateReference(e,i){if((e=(0,en.m9)(e)).firestore!==i)throw new FirestoreError(e_.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}function serverTimestamp(){return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp")}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function writeBatch(e){return ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)),new WriteBatch(e,i=>executeWrite(e,i))}new WeakMap,function(e=!0){eh=ee.Jn,(0,ee.Xd)(new et.wA("firestore",(i,{instanceIdentifier:s,options:o})=>{let l=i.getProvider("app").getImmediate(),h=new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(i.getProvider("auth-internal")),new __PRIVATE_FirebaseAppCheckTokenProvider(i.getProvider("app-check-internal")),function(e,i){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new FirestoreError(e_.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new DatabaseId(e.options.projectId,i)}(l,s),l);return o=Object.assign({useFetchStreams:e},o),h._setSettings(o),h},"PUBLIC").setMultipleInstances(!0)),(0,ee.KN)(eu,"4.7.3",void 0),(0,ee.KN)(eu,"4.7.3","esm2017")}()},6650:function(e,i,s){"use strict";s.d(i,{oq:function(){return deleteObject},Jt:function(){return getDownloadURL},cF:function(){return getStorage},iH:function(){return ref},B0:function(){return uploadBytesResumable}});var o,l,h,d,f=s(5816),_=s(4444),g=s(8463);/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let b="firebasestorage.googleapis.com",w="storageBucket";/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let StorageError=class StorageError extends _.ZR{constructor(e,i,s=0){super(prependCode(e),`Firebase Storage: ${i} (${prependCode(e)})`),this.status_=s,this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,StorageError.prototype)}get status(){return this.status_}set status(e){this.status_=e}_codeEquals(e){return prependCode(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}
${this.customData.serverResponse}`:this.message=this._baseMessage}};function prependCode(e){return"storage/"+e}function unknown(){return new StorageError(h.UNKNOWN,"An unknown error occurred, please check the error payload for server response.")}function retryLimitExceeded(){return new StorageError(h.RETRY_LIMIT_EXCEEDED,"Max retry time for operation exceeded, please try again.")}function canceled(){return new StorageError(h.CANCELED,"User canceled the upload/download.")}function cannotSliceBlob(){return new StorageError(h.CANNOT_SLICE_BLOB,"Cannot slice blob for upload. Please retry the upload.")}function invalidArgument(e){return new StorageError(h.INVALID_ARGUMENT,e)}function appDeleted(){return new StorageError(h.APP_DELETED,"The Firebase app was deleted.")}function invalidFormat(e,i){return new StorageError(h.INVALID_FORMAT,"String does not match format '"+e+"': "+i)}function internalError(e){throw new StorageError(h.INTERNAL_ERROR,"Internal error: "+e)}(o=h||(h={})).UNKNOWN="unknown",o.OBJECT_NOT_FOUND="object-not-found",o.BUCKET_NOT_FOUND="bucket-not-found",o.PROJECT_NOT_FOUND="project-not-found",o.QUOTA_EXCEEDED="quota-exceeded",o.UNAUTHENTICATED="unauthenticated",o.UNAUTHORIZED="unauthorized",o.UNAUTHORIZED_APP="unauthorized-app",o.RETRY_LIMIT_EXCEEDED="retry-limit-exceeded",o.INVALID_CHECKSUM="invalid-checksum",o.CANCELED="canceled",o.INVALID_EVENT_NAME="invalid-event-name",o.INVALID_URL="invalid-url",o.INVALID_DEFAULT_BUCKET="invalid-default-bucket",o.NO_DEFAULT_BUCKET="no-default-bucket",o.CANNOT_SLICE_BLOB="cannot-slice-blob",o.SERVER_FILE_WRONG_SIZE="server-file-wrong-size",o.NO_DOWNLOAD_URL="no-download-url",o.INVALID_ARGUMENT="invalid-argument",o.INVALID_ARGUMENT_COUNT="invalid-argument-count",o.APP_DELETED="app-deleted",o.INVALID_ROOT_OPERATION="invalid-root-operation",o.INVALID_FORMAT="invalid-format",o.INTERNAL_ERROR="internal-error",o.UNSUPPORTED_ENVIRONMENT="unsupported-environment";/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Location=class Location{constructor(e,i){this.bucket=e,this.path_=i}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){let e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){let e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o"}static makeFromBucketSpec(e,i){let s;try{s=Location.makeFromUrl(e,i)}catch(i){return new Location(e,"")}if(""===s.path)return s;throw new StorageError(h.INVALID_DEFAULT_BUCKET,"Invalid default bucket '"+e+"'.")}static makeFromUrl(e,i){let s=null,o="([A-Za-z0-9.\\-_]+)",l=RegExp("^gs://"+o+"(/(.*))?$","i");function httpModify(e){e.path_=decodeURIComponent(e.path)}let d=i.replace(/[.]/g,"\\."),f=RegExp(`^https?://${d}/v[A-Za-z0-9_]+/b/${o}/o(/([^?#]*).*)?$`,"i"),_=RegExp(`^https?://${i===b?"(?:storage.googleapis.com|storage.cloud.google.com)":i}/${o}/([^?#]*)`,"i"),g=[{regex:l,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:f,indices:{bucket:1,path:3},postModify:httpModify},{regex:_,indices:{bucket:1,path:2},postModify:httpModify}];for(let i=0;i<g.length;i++){let o=g[i],l=o.regex.exec(e);if(l){let e=l[o.indices.bucket],i=l[o.indices.path];i||(i=""),s=new Location(e,i),o.postModify(s);break}}if(null==s)throw new StorageError(h.INVALID_URL,"Invalid URL '"+e+"'.");return s}};let FailRequest=class FailRequest{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=!1){}};function isString(e){return"string"==typeof e||e instanceof String}function isNativeBlob(e){return isNativeBlobDefined()&&e instanceof Blob}function isNativeBlobDefined(){return"undefined"!=typeof Blob}function validateNumber(e,i,s,o){if(o<i)throw invalidArgument(`Invalid value for '${e}'. Expected ${i} or greater.`);if(o>s)throw invalidArgument(`Invalid value for '${e}'. Expected ${s} or less.`)}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function makeUrl(e,i,s){let o=i;return null==s&&(o=`https://${i}`),`${s}://${o}/v0${e}`}function makeQueryString(e){let i=encodeURIComponent,s="?";for(let o in e)if(e.hasOwnProperty(o)){let l=i(o)+"="+i(e[o]);s=s+l+"&"}return s.slice(0,-1)}/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function isRetryStatusCode(e,i){let s=e>=500&&e<600,o=-1!==[408,429].indexOf(e),l=-1!==i.indexOf(e);return s||o||l}(l=d||(d={}))[l.NO_ERROR=0]="NO_ERROR",l[l.NETWORK_ERROR=1]="NETWORK_ERROR",l[l.ABORT=2]="ABORT";/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let NetworkRequest=class NetworkRequest{constructor(e,i,s,o,l,h,d,f,_,g,b,w=!0){this.url_=e,this.method_=i,this.headers_=s,this.body_=o,this.successCodes_=l,this.additionalRetryCodes_=h,this.callback_=d,this.errorCallback_=f,this.timeout_=_,this.progressCallback_=g,this.connectionFactory_=b,this.retry=w,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((e,i)=>{this.resolve_=e,this.reject_=i,this.start_()})}start_(){let backoffDone=(e,i)=>{let s=this.resolve_,o=this.reject_,l=i.connection;if(i.wasSuccessCode)try{let e=this.callback_(l,l.getResponse());void 0!==e?s(e):s()}catch(e){o(e)}else if(null!==l){let e=unknown();e.serverResponse=l.getErrorText(),o(this.errorCallback_?this.errorCallback_(l,e):e)}else if(i.canceled){let e=this.appDelete_?appDeleted():canceled();o(e)}else{let e=retryLimitExceeded();o(e)}};this.canceled_?backoffDone(!1,new RequestEndStatus(!1,null,!0)):this.backoffId_=/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function(e,i,s){let o=1,l=null,h=null,d=!1,f=0,_=!1;function triggerCallback(...e){_||(_=!0,i.apply(null,e))}function callWithDelay(i){l=setTimeout(()=>{l=null,e(responseHandler,2===f)},i)}function clearGlobalTimeout(){h&&clearTimeout(h)}function responseHandler(e,...i){let s;if(_){clearGlobalTimeout();return}if(e){clearGlobalTimeout(),triggerCallback.call(null,e,...i);return}let l=2===f||d;if(l){clearGlobalTimeout(),triggerCallback.call(null,e,...i);return}o<64&&(o*=2),1===f?(f=2,s=0):s=(o+Math.random())*1e3,callWithDelay(s)}let g=!1;function stop(e){!g&&(g=!0,clearGlobalTimeout(),!_&&(null!==l?(e||(f=2),clearTimeout(l),callWithDelay(0)):e||(f=1)))}return callWithDelay(0),h=setTimeout(()=>{d=!0,stop(!0)},s),stop}((e,i)=>{if(i){e(!1,new RequestEndStatus(!1,null,!0));return}let s=this.connectionFactory_();this.pendingConnection_=s;let progressListener=e=>{let i=e.loaded,s=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(i,s)};null!==this.progressCallback_&&s.addUploadProgressListener(progressListener),s.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&s.removeUploadProgressListener(progressListener),this.pendingConnection_=null;let i=s.getErrorCode()===d.NO_ERROR,o=s.getStatus();if(!i||isRetryStatusCode(o,this.additionalRetryCodes_)&&this.retry){let i=s.getErrorCode()===d.ABORT;e(!1,new RequestEndStatus(!1,null,i));return}let l=-1!==this.successCodes_.indexOf(o);e(!0,new RequestEndStatus(l,s))})},backoffDone,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}};let RequestEndStatus=class RequestEndStatus{constructor(e,i,s){this.wasSuccessCode=e,this.connection=i,this.canceled=!!s}};function getBlob$1(...e){let i="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==i){let s=new i;for(let i=0;i<e.length;i++)s.append(e[i]);return s.getBlob()}if(isNativeBlobDefined())return new Blob(e);throw new StorageError(h.UNSUPPORTED_ENVIRONMENT,"This browser doesn't seem to support creating Blobs")}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let k={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};let StringData=class StringData{constructor(e,i){this.data=e,this.contentType=i||null}};function utf8Bytes_(e){let i=[];for(let s=0;s<e.length;s++){let o=e.charCodeAt(s);if(o<=127)i.push(o);else if(o<=2047)i.push(192|o>>6,128|63&o);else if((64512&o)==55296){let l=s<e.length-1&&(64512&e.charCodeAt(s+1))==56320;if(l){let l=o,h=e.charCodeAt(++s);o=65536|(1023&l)<<10|1023&h,i.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|63&o)}else i.push(239,191,189)}else(64512&o)==56320?i.push(239,191,189):i.push(224|o>>12,128|o>>6&63,128|63&o)}return new Uint8Array(i)}function base64Bytes_(e,i){let s;switch(e){case k.BASE64:{let s=-1!==i.indexOf("-"),o=-1!==i.indexOf("_");if(s||o)throw invalidFormat(e,"Invalid character '"+(s?"-":"_")+"' found: is it base64url encoded?");break}case k.BASE64URL:{let s=-1!==i.indexOf("+"),o=-1!==i.indexOf("/");if(s||o)throw invalidFormat(e,"Invalid character '"+(s?"+":"/")+"' found: is it base64 encoded?");i=i.replace(/-/g,"+").replace(/_/g,"/")}}try{s=/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function(e){if("undefined"==typeof atob)throw new StorageError(h.UNSUPPORTED_ENVIRONMENT,"base-64 is missing. Make sure to install the required polyfills. See https://firebase.google.com/docs/web/environments-js-sdk#polyfills for more information.");return atob(e)}(i)}catch(i){if(i.message.includes("polyfill"))throw i;throw invalidFormat(e,"Invalid character found")}let o=new Uint8Array(s.length);for(let e=0;e<s.length;e++)o[e]=s.charCodeAt(e);return o}let DataURLParts=class DataURLParts{constructor(e){this.base64=!1,this.contentType=null;let i=e.match(/^data:([^,]+)?,/);if(null===i)throw invalidFormat(k.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");let s=i[1]||null;null!=s&&(this.base64=function(e,i){let s=e.length>=i.length;return!!s&&e.substring(e.length-i.length)===i}(s,";base64"),this.contentType=this.base64?s.substring(0,s.length-7):s),this.rest=e.substring(e.indexOf(",")+1)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let FbsBlob=class FbsBlob{constructor(e,i){let s=0,o="";isNativeBlob(e)?(this.data_=e,s=e.size,o=e.type):e instanceof ArrayBuffer?(i?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),s=this.data_.length):e instanceof Uint8Array&&(i?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),s=e.length),this.size_=s,this.type_=o}size(){return this.size_}type(){return this.type_}slice(e,i){if(isNativeBlob(this.data_)){let s=this.data_,o=s.webkitSlice?s.webkitSlice(e,i):s.mozSlice?s.mozSlice(e,i):s.slice?s.slice(e,i):null;return null===o?null:new FbsBlob(o)}{let s=new Uint8Array(this.data_.buffer,e,i-e);return new FbsBlob(s,!0)}}static getBlob(...e){if(isNativeBlobDefined()){let i=e.map(e=>e instanceof FbsBlob?e.data_:e);return new FbsBlob(getBlob$1.apply(null,i))}{let i=e.map(e=>isString(e)?function(e,i){switch(e){case k.RAW:return new StringData(utf8Bytes_(i));case k.BASE64:case k.BASE64URL:return new StringData(base64Bytes_(e,i));case k.DATA_URL:return new StringData(function(e){let i=new DataURLParts(e);return i.base64?base64Bytes_(k.BASE64,i.rest):function(e){let i;try{i=decodeURIComponent(e)}catch(e){throw invalidFormat(k.DATA_URL,"Malformed data URL.")}return utf8Bytes_(i)}(i.rest)}(i),function(e){let i=new DataURLParts(e);return i.contentType}(i))}throw unknown()}(k.RAW,e).data:e.data_),s=0;i.forEach(e=>{s+=e.byteLength});let o=new Uint8Array(s),l=0;return i.forEach(e=>{for(let i=0;i<e.length;i++)o[l++]=e[i]}),new FbsBlob(o,!0)}}uploadData(){return this.data_}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function jsonObjectOrNull(e){var i;let s;try{s=JSON.parse(e)}catch(e){return null}return"object"!=typeof(i=s)||Array.isArray(i)?null:s}function lastComponent(e){let i=e.lastIndexOf("/",e.length-2);return -1===i?e:e.slice(i+1)}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function noXform_(e,i){return i}let Mapping=class Mapping{constructor(e,i,s,o){this.server=e,this.local=i||e,this.writable=!!s,this.xform=o||noXform_}};let O=null;function getMappings(){if(O)return O;let e=[];e.push(new Mapping("bucket")),e.push(new Mapping("generation")),e.push(new Mapping("metageneration")),e.push(new Mapping("name","fullPath",!0));let i=new Mapping("name");i.xform=function(e,i){return!isString(i)||i.length<2?i:lastComponent(i)},e.push(i);let s=new Mapping("size");return s.xform=function(e,i){return void 0!==i?Number(i):i},e.push(s),e.push(new Mapping("timeCreated")),e.push(new Mapping("updated")),e.push(new Mapping("md5Hash",null,!0)),e.push(new Mapping("cacheControl",null,!0)),e.push(new Mapping("contentDisposition",null,!0)),e.push(new Mapping("contentEncoding",null,!0)),e.push(new Mapping("contentLanguage",null,!0)),e.push(new Mapping("contentType",null,!0)),e.push(new Mapping("metadata","customMetadata",!0)),O=e}function fromResourceString(e,i,s){let o=jsonObjectOrNull(i);return null===o?null:function(e,i,s){let o={};o.type="file";let l=s.length;for(let e=0;e<l;e++){let l=s[e];o[l.local]=l.xform(o,i[l.server])}return Object.defineProperty(o,"ref",{get:function(){let i=o.bucket,s=o.fullPath,l=new Location(i,s);return e._makeStorageReference(l)}}),o}(e,o,s)}function toResourceString(e,i){let s={},o=i.length;for(let l=0;l<o;l++){let o=i[l];o.writable&&(s[o.server]=e[o.local])}return JSON.stringify(s)}let RequestInfo=class RequestInfo{constructor(e,i,s,o){this.url=e,this.method=i,this.handler=s,this.timeout=o,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function handlerCheck(e){if(!e)throw unknown()}function metadataHandler(e,i){return function(s,o){let l=fromResourceString(e,o,i);return handlerCheck(null!==l),l}}function sharedErrorHandler(e){return function(i,s){var o,l;let d;return 401===i.getStatus()?d=i.getErrorText().includes("Firebase App Check token is invalid")?new StorageError(h.UNAUTHORIZED_APP,"This app does not have permission to access Firebase Storage on this project."):new StorageError(h.UNAUTHENTICATED,"User is not authenticated, please authenticate using Firebase Authentication and try again."):402===i.getStatus()?(o=e.bucket,d=new StorageError(h.QUOTA_EXCEEDED,"Quota for bucket '"+o+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===i.getStatus()?(l=e.path,d=new StorageError(h.UNAUTHORIZED,"User does not have permission to access '"+l+"'.")):d=s,d.status=i.getStatus(),d.serverResponse=s.serverResponse,d}}function objectErrorHandler(e){let i=sharedErrorHandler(e);return function(s,o){let l=i(s,o);if(404===s.getStatus()){var d;d=e.path,l=new StorageError(h.OBJECT_NOT_FOUND,"Object '"+d+"' does not exist.")}return l.serverResponse=o.serverResponse,l}}function metadataForUpload_(e,i,s){let o=Object.assign({},s);return o.fullPath=e.path,o.size=i.size(),!o.contentType&&(o.contentType=i&&i.type()||"application/octet-stream"),o}let ResumableUploadStatus=class ResumableUploadStatus{constructor(e,i,s,o){this.current=e,this.total=i,this.finalized=!!s,this.metadata=o||null}};function checkResumeHeader_(e,i){let s=null;try{s=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){handlerCheck(!1)}return handlerCheck(!!s&&-1!==(i||["active"]).indexOf(s)),s}let j={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function taskStateFromInternalTaskState(e){switch(e){case"running":case"pausing":case"canceling":return j.RUNNING;case"paused":return j.PAUSED;case"success":return j.SUCCESS;case"canceled":return j.CANCELED;default:return j.ERROR}}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Observer=class Observer{constructor(e,i,s){"function"==typeof e||null!=i||null!=s?(this.next=e,this.error=null!=i?i:void 0,this.complete=null!=s?s:void 0):(this.next=e.next,this.error=e.error,this.complete=e.complete)}};/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function index_esm2017_async(e){return(...i)=>{Promise.resolve().then(()=>e(...i))}}let XhrConnection=class XhrConnection{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=d.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=d.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=d.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,i,s,o){if(this.sent_)throw internalError("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(i,e,!0),void 0!==o)for(let e in o)o.hasOwnProperty(e)&&this.xhr_.setRequestHeader(e,o[e].toString());return void 0!==s?this.xhr_.send(s):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw internalError("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw internalError("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return -1}}getResponse(){if(!this.sent_)throw internalError("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw internalError("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}};let XhrTextConnection=class XhrTextConnection extends XhrConnection{initXhr(){this.xhr_.responseType="text"}};function newTextConnection(){return new XhrTextConnection}/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let UploadTask=class UploadTask{constructor(e,i,s=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=i,this._metadata=s,this._mappings=getMappings(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{if(this._request=void 0,this._chunkMultiplier=1,e._codeEquals(h.CANCELED))this._needToFetchStatus=!0,this.completeTransitions_();else{let i=this.isExponentialBackoffExpired();if(isRetryStatusCode(e.status,[])){if(i)e=retryLimitExceeded();else{this.sleepTime=Math.max(2*this.sleepTime,1e3),this._needToFetchStatus=!0,this.completeTransitions_();return}}this._error=e,this._transition("error")}},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals(h.CANCELED)?this.completeTransitions_():(this._error=e,this._transition("error"))},this.sleepTime=0,this.maxSleepTime=this._ref.storage.maxUploadRetryTime,this._promise=new Promise((e,i)=>{this._resolve=e,this._reject=i,this._start()}),this._promise.then(null,()=>{})}isExponentialBackoffExpired(){return this.sleepTime>this.maxSleepTime}_makeProgressCallback(){let e=this._transferred;return i=>this._updateProgress(e+i)}_shouldDoResumable(e){return e.size()>262144}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this.pendingTimeout=setTimeout(()=>{this.pendingTimeout=void 0,this._continueUpload()},this.sleepTime):this._oneShotUpload())}_resolveToken(e){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([i,s])=>{switch(this._state){case"running":e(i,s);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,i)=>{let s=function(e,i,s,o,l){let h=i.bucketOnlyServerUrl(),d=metadataForUpload_(i,o,l),f={name:d.fullPath},_=makeUrl(h,e.host,e._protocol),g={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${o.size()}`,"X-Goog-Upload-Header-Content-Type":d.contentType,"Content-Type":"application/json; charset=utf-8"},b=toResourceString(d,s),w=e.maxUploadRetryTime,k=new RequestInfo(_,"POST",function(e){let i;checkResumeHeader_(e);try{i=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){handlerCheck(!1)}return handlerCheck(isString(i)),i},w);return k.urlParams=f,k.headers=g,k.body=b,k.errorHandler=sharedErrorHandler(i),k}(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),o=this._ref.storage._makeRequest(s,newTextConnection,e,i);this._request=o,o.getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){let e=this._uploadUrl;this._resolveToken((i,s)=>{let o=function(e,i,s,o){let l=e.maxUploadRetryTime,h=new RequestInfo(s,"POST",function(e){let i=checkResumeHeader_(e,["active","final"]),s=null;try{s=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){handlerCheck(!1)}s||handlerCheck(!1);let l=Number(s);return handlerCheck(!isNaN(l)),new ResumableUploadStatus(l,o.size(),"final"===i)},l);return h.headers={"X-Goog-Upload-Command":"query"},h.errorHandler=sharedErrorHandler(i),h}(this._ref.storage,this._ref._location,e,this._blob),l=this._ref.storage._makeRequest(o,newTextConnection,i,s);this._request=l,l.getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){let e=262144*this._chunkMultiplier,i=new ResumableUploadStatus(this._transferred,this._blob.size()),s=this._uploadUrl;this._resolveToken((o,l)=>{let d;try{d=function(e,i,s,o,l,d,f,_){let g=new ResumableUploadStatus(0,0);if(f?(g.current=f.current,g.total=f.total):(g.current=0,g.total=o.size()),o.size()!==g.total)throw new StorageError(h.SERVER_FILE_WRONG_SIZE,"Server recorded incorrect upload file size, please retry the upload.");let b=g.total-g.current,w=b;l>0&&(w=Math.min(w,l));let k=g.current,O=k+w,j="";j=0===w?"finalize":b===w?"upload, finalize":"upload";let q={"X-Goog-Upload-Command":j,"X-Goog-Upload-Offset":`${g.current}`},$=o.slice(k,O);if(null===$)throw cannotSliceBlob();let ee=i.maxUploadRetryTime,et=new RequestInfo(s,"POST",function(e,s){let l;let h=checkResumeHeader_(e,["active","final"]),f=g.current+w,_=o.size();return l="final"===h?metadataHandler(i,d)(e,s):null,new ResumableUploadStatus(f,_,"final"===h,l)},ee);return et.headers=q,et.body=$.uploadData(),et.progressCallback=_||null,et.errorHandler=sharedErrorHandler(e),et}(this._ref._location,this._ref.storage,s,this._blob,e,this._mappings,i,this._makeProgressCallback())}catch(e){this._error=e,this._transition("error");return}let f=this._ref.storage._makeRequest(d,newTextConnection,o,l,!1);this._request=f,f.getPromise().then(e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){let e=262144*this._chunkMultiplier;2*e<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,i)=>{let s=function(e,i,s){let o=i.fullServerUrl(),l=makeUrl(o,e.host,e._protocol),h=e.maxOperationRetryTime,d=new RequestInfo(l,"GET",metadataHandler(e,s),h);return d.errorHandler=objectErrorHandler(i),d}(this._ref.storage,this._ref._location,this._mappings),o=this._ref.storage._makeRequest(s,newTextConnection,e,i);this._request=o,o.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,i)=>{let s=function(e,i,s,o,l){let h=i.bucketOnlyServerUrl(),d={"X-Goog-Upload-Protocol":"multipart"},f=function(){let e="";for(let i=0;i<2;i++)e+=Math.random().toString().slice(2);return e}();d["Content-Type"]="multipart/related; boundary="+f;let _=metadataForUpload_(i,o,l),g=toResourceString(_,s),b="--"+f+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+g+"\r\n--"+f+"\r\nContent-Type: "+_.contentType+"\r\n\r\n",w=FbsBlob.getBlob(b,o,"\r\n--"+f+"--");if(null===w)throw cannotSliceBlob();let k={name:_.fullPath},O=makeUrl(h,e.host,e._protocol),j=e.maxUploadRetryTime,q=new RequestInfo(O,"POST",metadataHandler(e,s),j);return q.urlParams=k,q.headers=d,q.body=w.uploadData(),q.errorHandler=sharedErrorHandler(i),q}(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata),o=this._ref.storage._makeRequest(s,newTextConnection,e,i);this._request=o,o.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){let i=this._transferred;this._transferred=e,this._transferred!==i&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request?this._request.cancel():this.pendingTimeout&&(clearTimeout(this.pendingTimeout),this.pendingTimeout=void 0,this.completeTransitions_());break;case"running":let i="paused"===this._state;this._state=e,i&&(this._notifyObservers(),this._start());break;case"paused":case"error":case"success":this._state=e,this._notifyObservers();break;case"canceled":this._error=canceled(),this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){let e=taskStateFromInternalTaskState(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,i,s,o){let l=new Observer(i||void 0,s||void 0,o||void 0);return this._addObserver(l),()=>{this._removeObserver(l)}}then(e,i){return this._promise.then(e,i)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){let i=this._observers.indexOf(e);-1!==i&&this._observers.splice(i,1)}_notifyObservers(){this._finishPromise();let e=this._observers.slice();e.forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(taskStateFromInternalTaskState(this._state)){case j.SUCCESS:index_esm2017_async(this._resolve.bind(null,this.snapshot))();break;case j.CANCELED:case j.ERROR:let i=this._reject;index_esm2017_async(i.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){let i=taskStateFromInternalTaskState(this._state);switch(i){case j.RUNNING:case j.PAUSED:e.next&&index_esm2017_async(e.next.bind(e,this.snapshot))();break;case j.SUCCESS:e.complete&&index_esm2017_async(e.complete.bind(e))();break;case j.CANCELED:case j.ERROR:default:e.error&&index_esm2017_async(e.error.bind(e,this._error))()}}resume(){let e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){let e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){let e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}};/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */let Reference=class Reference{constructor(e,i){this._service=e,i instanceof Location?this._location=i:this._location=Location.makeFromUrl(i,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,i){return new Reference(e,i)}get root(){let e=new Location(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return lastComponent(this._location.path)}get storage(){return this._service}get parent(){let e=/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */function(e){if(0===e.length)return null;let i=e.lastIndexOf("/");if(-1===i)return"";let s=e.slice(0,i);return s}(this._location.path);if(null===e)return null;let i=new Location(this._location.bucket,e);return new Reference(this._service,i)}_throwIfRoot(e){if(""===this._location.path)throw new StorageError(h.INVALID_ROOT_OPERATION,"The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}};function extractBucket(e,i){let s=null==i?void 0:i[w];return null==s?null:Location.makeFromBucketSpec(s,e)}let FirebaseStorageImpl=class FirebaseStorageImpl{constructor(e,i,s,o,l){this.app=e,this._authProvider=i,this._appCheckProvider=s,this._url=o,this._firebaseVersion=l,this._bucket=null,this._host=b,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,null!=o?this._bucket=Location.makeFromBucketSpec(o,this._host):this._bucket=extractBucket(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=Location.makeFromBucketSpec(this._url,e):this._bucket=extractBucket(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){validateNumber("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;let e=this._authProvider.getImmediate({optional:!0});if(e){let i=await e.getToken();if(null!==i)return i.accessToken}return null}async _getAppCheckToken(){let e=this._appCheckProvider.getImmediate({optional:!0});if(e){let i=await e.getToken();return i.token}return null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new Reference(this,e)}_makeRequest(e,i,s,o,l=!0){if(this._deleted)return new FailRequest(appDeleted());{let h=function(e,i,s,o,l,h,d=!0){let f=makeQueryString(e.urlParams),_=e.url+f,g=Object.assign({},e.headers);return i&&(g["X-Firebase-GMPID"]=i),null!==s&&s.length>0&&(g.Authorization="Firebase "+s),g["X-Firebase-Storage-Version"]="webjs/"+(null!=h?h:"AppManager"),null!==o&&(g["X-Firebase-AppCheck"]=o),new NetworkRequest(_,e.method,g,e.body,e.successCodes,e.additionalRetryCodes,e.handler,e.errorHandler,e.timeout,e.progressCallback,l,d)}(e,this._appId,s,o,i,this._firebaseVersion,l);return this._requests.add(h),h.getPromise().then(()=>this._requests.delete(h),()=>this._requests.delete(h)),h}}async makeRequestWithTokens(e,i){let[s,o]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,i,s,o).getPromise()}};let q="@firebase/storage",$="0.13.2",ee="storage";function uploadBytesResumable(e,i,s){var o;return(o=e=(0,_.m9)(e))._throwIfRoot("uploadBytesResumable"),new UploadTask(o,new FbsBlob(i),s)}function getDownloadURL(e){return function(e){e._throwIfRoot("getDownloadURL");let i=function(e,i,s){let o=i.fullServerUrl(),l=makeUrl(o,e.host,e._protocol),h=e.maxOperationRetryTime,d=new RequestInfo(l,"GET",function(i,o){let l=fromResourceString(e,o,s);return handlerCheck(null!==l),function(e,i,s,o){let l=jsonObjectOrNull(i);if(null===l||!isString(l.downloadTokens))return null;let h=l.downloadTokens;if(0===h.length)return null;let d=encodeURIComponent,f=h.split(","),_=f.map(i=>{let l=e.bucket,h=e.fullPath,f="/b/"+d(l)+"/o/"+d(h),_=makeUrl(f,s,o),g=makeQueryString({alt:"media",token:i});return _+g});return _[0]}(l,o,e.host,e._protocol)},h);return d.errorHandler=objectErrorHandler(i),d}(e.storage,e._location,getMappings());return e.storage.makeRequestWithTokens(i,newTextConnection).then(e=>{if(null===e)throw new StorageError(h.NO_DOWNLOAD_URL,"The given file does not have any download URLs.");return e})}(e=(0,_.m9)(e))}function deleteObject(e){return function(e){e._throwIfRoot("deleteObject");let i=function(e,i){let s=i.fullServerUrl(),o=makeUrl(s,e.host,e._protocol),l=e.maxOperationRetryTime,h=new RequestInfo(o,"DELETE",function(e,i){},l);return h.successCodes=[200,204],h.errorHandler=objectErrorHandler(i),h}(e.storage,e._location);return e.storage.makeRequestWithTokens(i,newTextConnection)}(e=(0,_.m9)(e))}function ref(e,i){return function(e,i){if(!(i&&/^[A-Za-z]+:\/\//.test(i)))return function refFromPath(e,i){if(e instanceof FirebaseStorageImpl){if(null==e._bucket)throw new StorageError(h.NO_DEFAULT_BUCKET,"No default bucket found. Did you set the '"+w+"' property when initializing the app?");let s=new Reference(e,e._bucket);return null!=i?refFromPath(s,i):s}return void 0!==i?function(e,i){let s=function(e,i){let s=i.split("/").filter(e=>e.length>0).join("/");return 0===e.length?s:e+"/"+s}(e._location.path,i),o=new Location(e._location.bucket,s);return new Reference(e.storage,o)}(e,i):e}(e,i);if(e instanceof FirebaseStorageImpl)return new Reference(e,i);throw invalidArgument("To use ref(service, url), the first argument must be a Storage instance.")}(e=(0,_.m9)(e),i)}function getStorage(e=(0,f.Mq)(),i){e=(0,_.m9)(e);let s=(0,f.qX)(e,ee),o=s.getImmediate({identifier:i}),l=(0,_.P0)("storage");return l&&function(e,i,s,o={}){!function(e,i,s,o={}){e.host=`${i}:${s}`,e._protocol="http";let{mockUserToken:l}=o;l&&(e._overrideAuthToken="string"==typeof l?l:(0,_.Sg)(l,e.app.options.projectId))}(e,i,s,o)}(o,...l),o}(0,f.Xd)(new g.wA(ee,function(e,{instanceIdentifier:i}){let s=e.getProvider("app").getImmediate(),o=e.getProvider("auth-internal"),l=e.getProvider("app-check-internal");return new FirebaseStorageImpl(s,o,l,i,f.Jn)},"PUBLIC").setMultipleInstances(!0)),(0,f.KN)(q,$,""),(0,f.KN)(q,$,"esm2017")}},function(e){var __webpack_exec__=function(i){return e(e.s=i)};e.O(0,[774,179],function(){return __webpack_exec__(1118),__webpack_exec__(9974)}),_N_E=e.O()}]);