firebase
Version:
Firebase JavaScript library for web and Node.js
1 lines • 164 kB
JavaScript
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(wo,Co){try{!(function(){function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function r(t){var n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}let q=t(wo),W={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},f=function(e,t){if(!e)throw B(t)},B=function(e){return new Error("Firebase Database ("+W.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},U={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let c=0;c<n.length;c+=3){var s=n[c],o=c+1<n.length,a=o?n[c+1]:0,l=c+2<n.length,h=l?n[c+2]:0;let e=(15&a)<<2|h>>6,t=63&h;l||(t=64,o)||(e=64),i.push(r[s>>2],r[(3&s)<<4|a>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(r(e),t)},decodeString(n,r){if(this.HAS_NATIVE_SUPPORT&&!r)return atob(n);{var i=this.decodeStringToByteArray(n,r);var s=[];let e=0,t=0;for(;e<i.length;){var o,a,l,h=i[e++];h<128?s[t++]=String.fromCharCode(h):191<h&&h<224?(o=i[e++],s[t++]=String.fromCharCode((31&h)<<6|63&o)):239<h&&h<365?(o=((7&h)<<18|(63&i[e++])<<12|(63&i[e++])<<6|63&i[e++])-65536,s[t++]=String.fromCharCode(55296+(o>>10)),s[t++]=String.fromCharCode(56320+(1023&o))):(a=i[e++],l=i[e++],s[t++]=String.fromCharCode((15&h)<<12|(63&a)<<6|63&l))}return s.join("");return}},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let l=0;l<e.length;){var i=n[e.charAt(l++)],s=l<e.length?n[e.charAt(l)]:0,o=++l<e.length?n[e.charAt(l)]:64,a=++l<e.length?n[e.charAt(l)]:64;if(++l,null==i||null==s||null==o||null==a)throw new j;r.push(i<<2|s>>4),64!==o&&(r.push(s<<4&240|o>>2),64!==a)&&r.push(o<<6&192|a)}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class j extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let V=function(e){var t=r(e);return U.encodeByteArray(t,!0)},z=function(e){return V(e).replace(/\./g,"")},H=function(e){try{return U.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function Q(e){return function e(t,n){if(!(n instanceof Object))return n;switch(n.constructor){case Date:let e=n;return new Date(e.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return n}for(var r in n)n.hasOwnProperty(r)&&Y(r)&&(t[r]=e(t[r],n[r]));return t}(void 0,e)}function Y(e){return"__proto__"!==e}class _{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function K(){return"undefined"!=typeof window&&(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test("undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:"")}function G(){return!0===W.NODE_ADMIN}function $(e){return JSON.parse(e)}function a(e){return JSON.stringify(e)}function J(e){let t={},n={},r={},i="";try{var s=e.split(".");t=$(H(s[0])||""),n=$(H(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function p(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function X(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function Z(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function ee(e,t,n){var r,i={};for(r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=t.call(n,e[r],r,e));return i}function te(e){return null!==e&&"object"==typeof e}class ne{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;var i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],o=this.chain_[2],a=this.chain_[3],l=this.chain_[4],h,c;for(let _=0;_<80;_++){c=_<40?_<20?(h=a^s&(o^a),1518500249):(h=s^o^a,1859775393):_<60?(h=s&o|a&(s|o),2400959708):(h=s^o^a,3395469782);var u=(t<<5|t>>>27)+h+l+c+i[_]&4294967295;l=a,a=o,o=4294967295&(s<<30|s>>>2),s=t,t=u}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+l&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;var s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){var t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function l(e,t,n,r){let i;var s;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i)throw s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".",new Error(s)}function h(e,t){return e+` failed: ${t} argument `}function c(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(h(e,t)+"must be a valid function.")}function re(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(h(e,t)+"must be a valid context object.")}let ie=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t};function g(e){return e&&e._delegate?e._delegate:e}class se{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let oe="[DEFAULT]";class ae{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){var n=new _;if(this.instancesDeferred.set(t,n),this.isInitialized(t)||this.shouldAutoInitialize())try{var r=this.getOrInitializeService({instanceIdentifier:t});r&&n.resolve(r)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),n=null!=(n=null==e?void 0:e.optional)&&n;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:oe})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=oe){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){var 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=oe){return this.instances.has(e)}getOptions(e=oe){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(this.name+`(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);let r=null!=(i=this.onInitCallbacks.get(n))?i:new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(var r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===oe?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=oe){return!this.component||this.component.multipleInstances?e:oe}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class le{constructor(e){this.name=e,this.providers=new Map}addComponent(e){var t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with `+this.name);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){var t;return this.providers.has(e)?this.providers.get(e):(t=new ae(e,this),this.providers.set(e,t),t)}getProviders(){return Array.from(this.providers.values())}}var n;(e=n=n||{})[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT";let he={debug:n.DEBUG,verbose:n.VERBOSE,info:n.INFO,warn:n.WARN,error:n.ERROR,silent:n.SILENT},ce=n.INFO,ue={[n.DEBUG]:"log",[n.VERBOSE]:"log",[n.INFO]:"info",[n.WARN]:"warn",[n.ERROR]:"error"},de=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=ue[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class _e{constructor(e){this.name=e,this._logLevel=ce,this._logHandler=de,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in n))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?he[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,n.DEBUG,...e),this._logHandler(this,n.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,n.VERBOSE,...e),this._logHandler(this,n.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,n.INFO,...e),this._logHandler(this,n.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,n.WARN,...e),this._logHandler(this,n.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,n.ERROR,...e),this._logHandler(this,n.ERROR,...e)}}let pe="@firebase/database",fe="";function ge(e){fe=e}class me{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),a(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:$(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class ve{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return p(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}function ye(e){try{var t;if("undefined"!=typeof window&&void 0!==window[e])return(t=window[e]).setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new me(t)}catch(e){}return new ve}var d,we;function Ce(e){var t=(t=>{var n,r,i=[];let s=0;for(let o=0;o<t.length;o++){let e=t.charCodeAt(o);55296<=e&&e<=56319&&(n=e-55296,o++,f(o<t.length,"Surrogate pair missing trail surrogate."),r=t.charCodeAt(o)-56320,e=65536+(n<<10)+r),e<128?i[s++]=e:(e<2048?i[s++]=e>>6|192:(e<65536?i[s++]=e>>12|224:(i[s++]=e>>18|240,i[s++]=e>>12&63|128),i[s++]=e>>6&63|128),i[s++]=63&e|128)}return i})(e),n=new ne,t=(n.update(t),n.digest());return U.encodeByteArray(t)}function be(t){return function(...e){u(t,...e)}}function Te(...e){var t="FIREBASE INTERNAL ERROR: "+De(...e);Re.error(t)}function Ie(e,t){return e===t?0:e<t?-1:1}function Ee(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+a(t))}function Se(e){if("object"!=typeof e||null===e)return a(e);var t,n=[];for(t in e)n.push(t);n.sort();let r="{";for(let i=0;i<n.length;i++)0!==i&&(r+=","),r=(r=r+a(n[i])+":")+Se(e[n[i]]);return r+="}"}function ke(e,t){var n=e.length;if(n<=t)return[e];var r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}let Ne=ye("localStorage"),Pe=ye("sessionStorage"),Re=new _e("@firebase/database"),xe=(()=>{let e=1;return function(){return e++}})(),De=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=De.apply(null,n):t+="object"==typeof n?a(n):n,t+=" "}return t},Ae=null,Oe=!0,Le=function(e,t){f(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(Re.logLevel=n.VERBOSE,Ae=Re.log.bind(Re),t&&Pe.set("logging_enabled",!0)):"function"==typeof e?Ae=e:(Ae=null,Pe.remove("logging_enabled"))},u=function(...e){var t;!0===Oe&&(Oe=!1,null===Ae)&&!0===Pe.get("logging_enabled")&&Le(!0),Ae&&(t=De.apply(null,e),Ae(t))},Me=function(...e){var t="FIREBASE FATAL ERROR: "+De(...e);throw Re.error(t),new Error(t)},m=function(...e){var t="FIREBASE WARNING: "+De(...e);Re.warn(t)},Fe=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&m("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},qe=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},We="[MIN_NAME]",Be="[MAX_NAME]",Ue=function(e,t){var n,r;return e===t?0:e===We||t===Be?-1:t===We||e===Be?1:(n=Ve(e),r=Ve(t),null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1)};function v(e,t){for(var n in e)e.hasOwnProperty(n)&&t(n,e[n])}function je(e){f(!qe(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));var o=[];for(s=52;s;--s)o.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();var a=o.join("");let l="";for(s=0;s<64;s+=8){let e=parseInt(a.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()}function Ve(e){if(He.test(e)){var t=Number(e);if(t>=Qe&&t<=Ye)return t}return null}function ze(e,t){var n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n}let He=new RegExp("^-?(0*)\\d{1,10}$"),Qe=-2147483648,Ye=2147483647,Ke=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw m("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Ge{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,Co._isFirebaseServerApp(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null!=t&&t.get().then(e=>this.appCheck=e)}getToken(n){if(this.serverAppAppCheckToken){if(n)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){var e;null!=(e=this.appCheckProvider)&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){m(`Provided AppCheck credentials for the app named "${this.appName}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class $e{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(u("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',m(e)}}class Je{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Je.OWNER="owner";let Xe=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Ze="websocket",et="long_polling";class tt{constructor(e,t,n,r,i=!1,s="",o=!1,a=!1,l=null){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=Ne.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost())&&Ne.set("host:"+this._host,this.internalHost)}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?"?ns="+this.namespace:"";return e+this.host+"/"+t}}function nt(e,t,n){f("string"==typeof t,"typeof type must == string"),f("object"==typeof n,"typeof params must == object");let r;if(t===Ze)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==et)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);let i=[];return v(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class rt{constructor(){this.counters_={}}incrementCounter(e,t=1){p(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return Q(this.counters_)}}let it={},st={};function ot(e){var t=e.toString();return it[t]||(it[t]=new rt),it[t]}class at{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){let e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&Ke(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class lt{constructor(e,t,n,r,i,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=be(e),this.stats_=ot(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),nt(t,et,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new at(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4));var n=()=>{var e;this.isClosed_||(this.scriptTagHolder=new ht((...e)=>{var[t,n,r,,,]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn),(e={start:"t"}).ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&Xe.test(location.hostname)&&(e.r="f"),e=this.urlFn(e),this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{}))};if("complete"===document.readyState)n();else{let e=!1,t=function(){document.body?e||(e=!0,n()):setTimeout(t,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",t,!1),window.addEventListener("load",t,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&t()}),window.attachEvent("onload",t))}}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){lt.forceAllow_=!0}static forceDisallow(){lt.forceDisallow_=!0}static isAvailable(){return!!lt.forceAllow_||!(lt.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){var t=a(e),t=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),V(t)),n=ke(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");var n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){var t=a(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class ht{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=xe(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=ht.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){u("frame writing exception"),e.stack&&u(e.stack),u(e)}}}static createIFrame_(){var t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||u("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));var e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(0<this.pendingSegs.length?2:1)){this.currentSerial++;var n={},n=(n.id=this.myID,n.pw=this.myPW,n.ser=this.currentSerial,this.urlFn(n));let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);let n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(this.sendNewPolls){let t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{u("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}}catch(e){}},Math.floor(1))}}let ct=null;"undefined"!=typeof MozWebSocket?ct=MozWebSocket:"undefined"!=typeof WebSocket&&(ct=WebSocket);class y{constructor(e,t,n,r,i,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=be(this.connId),this.stats_=ot(t),this.connURL=y.connectionURL_(t,s,o,r,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){var s={v:"5"};return"undefined"!=typeof location&&location.hostname&&Xe.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),r&&(s.ac=r),i&&(s.p=i),nt(e,Ze,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Ne.set("previous_websocket_failure",!0);try{G(),this.mySock=new ct(this.connURL,[],void 0)}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){y.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return!(e="undefined"!=typeof navigator&&navigator.userAgent&&(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4?!0:e)&&null!==ct&&!y.forceDisallow_}static previouslyFailed(){return Ne.isInMemoryStorage||!0===Ne.get("previous_websocket_failure")}markConnectionHealthy(){Ne.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=$(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(f(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=a(e),n=(this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length),ke(t,16384));1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}y.responsesRequiredToBeHealthy=2,y.healthyTimeout=3e4;class ut{static get ALL_TRANSPORTS(){return[lt,y]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){var t=y&&y.isAvailable();let n=t&&!y.previouslyFailed();if(e.webSocketOnly&&(t||m("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[y];else{var r,i=this.transports_=[];for(r of ut.ALL_TRANSPORTS)r&&r.isAvailable()&&i.push(r);ut.globalTransportInitialized_=!0}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}ut.globalTransportInitialized_=!1;class dt{constructor(e,t,n,r,i,s,o,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=be("c:"+this.id+":"),this.transportManager_=new ut(t),this.log_("Connection created"),this.start_()}start_(){var e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));e=e.healthyTimeout||0;0<e&&(this.healthyTimeout_=ze(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(e)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){var t;"t"in e&&("a"===(t=e.t)?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_()))}onSecondaryMessageReceived_(e){var t=Ee("t",e),n=Ee("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){var t=Ee("t",e),n=Ee("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){var t=Ee("t",e);if("d"in e){var n=e.d;if("h"===t){var r=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(r.h=this.repoInfo_.host),this.onHandshake_(r)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?Te("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Te("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&m("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),ze(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(6e4))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):ze(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){var e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(Ne.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_)&&(this.onDisconnect_(),this.onDisconnect_=null)}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class _t{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class pt{constructor(e){this.allowedEvents_=e,this.listeners_={},f(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){var r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);var r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){f(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class ft extends pt{static getInstance(){return new ft}constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||K()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}getInitialEvent(e){return f("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}let gt=32,mt=768;class w{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function C(){return new w("")}function b(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function vt(e){return e.pieces_.length-e.pieceNum_}function T(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new w(e.pieces_,t)}function yt(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function wt(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function Ct(e){if(e.pieceNum_>=e.pieces_.length)return null;var t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new w(t,0)}function I(e,t){var n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof w)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new w(n,0)}function E(e){return e.pieceNum_>=e.pieces_.length}function S(e,t){var n=b(e),r=b(t);if(null===n)return t;if(n===r)return S(T(e),T(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function bt(e,t){var n=wt(e,0),r=wt(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Ue(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function Tt(e,t){if(vt(e)!==vt(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function k(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(vt(e)>vt(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class It{constructor(e,t){this.errorPrefix_=t,this.parts_=wt(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=ie(this.parts_[n]);Et(this)}}function Et(e){if(e.byteLength_>mt)throw new Error(e.errorPrefix_+"has a key path longer than "+mt+" bytes ("+e.byteLength_+").");if(e.parts_.length>gt)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+gt+") or object contains a cycle "+St(e))}function St(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class kt extends pt{static getInstance(){return new kt}constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}getInitialEvent(e){return f("visible"===e,"Unknown event type: "+e),[this.visible_]}}class Nt extends _t{constructor(e,t,n,r,i,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=Nt.nextPersistentConnectionId_++,this.log_=be("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=1e3,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a&&!G())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");kt.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&ft.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(a(i)),f(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();let n=new _;var t={p:e._path.toString(),q:e._queryObject},t=(this.outstandingGets_.push({action:"g",request:t,onComplete:e=>{var t=e.d;"ok"===e.s?n.resolve(t):n.reject(t)}}),this.outstandingGetCount_++,this.outstandingGets_.length-1);return this.connected_&&this.sendGet_(t),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString(),o=(this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),f(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),f(!this.listens.get(s).has(i),"listen() called twice for same path/queryId."),{onComplete:r,hashFn:t,query:e,tag:n});this.listens.get(s).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(t){let n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(i){let s=i.query,o=s._path.toString(),a=s._queryIdentifier;this.log_("Listen on "+o+" for "+a);var e={p:o};i.tag&&(e.q=s._queryObject,e.t=i.tag),e.h=i.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s,r=(Nt.warnOnListenWarnings_(t,s),this.listens.get(o)&&this.listens.get(o).get(a));r===i&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(o,a),i.onComplete)&&i.onComplete(n,t)})}static warnOnListenWarnings_(e,t){var n,r;e&&"object"==typeof e&&p(e,"w")&&(n=X(e,"w"),Array.isArray(n))&&~n.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),m("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+r+" to your security rules for better performance."))}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){var t;(e&&40===e.length||(e=e,"object"==typeof(t=J(e).claims)&&!0===t.admin))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let r=this.authToken_;n=r;var e=!!(e=J(n).claims)&&"object"==typeof e&&e.hasOwnProperty("iat")?"auth":"gauth",t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}var n,e}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier,i=(this.log_("Unlisten called for "+n+" "+r),f(e._quer