2 lines
230 KiB
JavaScript
2 lines
230 KiB
JavaScript
/*! For license information please see 481.8b61055c.iframe.bundle.js.LICENSE.txt */
|
|
"use strict";(self.webpackChunkfibonacci_fold=self.webpackChunkfibonacci_fold||[]).push([[481],{"./node_modules/firebase/database/dist/esm/index.esm.js":(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{Jt:()=>get,Zy:()=>onValue,KR:()=>ref,hZ:()=>set});__webpack_require__("./node_modules/process/browser.js");const CONSTANTS_NODE_CLIENT=!1,CONSTANTS_NODE_ADMIN=!1,CONSTANTS_SDK_VERSION="${JSCORE_VERSION}",index_esm2017_assert=function(assertion,message){if(!assertion)throw assertionError(message)},assertionError=function(message){return new Error("Firebase Database ("+CONSTANTS_SDK_VERSION+") INTERNAL ASSERT FAILED: "+message)},stringToByteArray$1=function(str){const out=[];let p=0;for(let i=0;i<str.length;i++){let c=str.charCodeAt(i);c<128?out[p++]=c:c<2048?(out[p++]=c>>6|192,out[p++]=63&c|128):55296==(64512&c)&&i+1<str.length&&56320==(64512&str.charCodeAt(i+1))?(c=65536+((1023&c)<<10)+(1023&str.charCodeAt(++i)),out[p++]=c>>18|240,out[p++]=c>>12&63|128,out[p++]=c>>6&63|128,out[p++]=63&c|128):(out[p++]=c>>12|224,out[p++]=c>>6&63|128,out[p++]=63&c|128)}return out},base64={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(input,webSafe){if(!Array.isArray(input))throw Error("encodeByteArray takes an array as a parameter");this.init_();const byteToCharMap=webSafe?this.byteToCharMapWebSafe_:this.byteToCharMap_,output=[];for(let i=0;i<input.length;i+=3){const byte1=input[i],haveByte2=i+1<input.length,byte2=haveByte2?input[i+1]:0,haveByte3=i+2<input.length,byte3=haveByte3?input[i+2]:0,outByte1=byte1>>2,outByte2=(3&byte1)<<4|byte2>>4;let outByte3=(15&byte2)<<2|byte3>>6,outByte4=63&byte3;haveByte3||(outByte4=64,haveByte2||(outByte3=64)),output.push(byteToCharMap[outByte1],byteToCharMap[outByte2],byteToCharMap[outByte3],byteToCharMap[outByte4])}return output.join("")},encodeString(input,webSafe){return this.HAS_NATIVE_SUPPORT&&!webSafe?btoa(input):this.encodeByteArray(stringToByteArray$1(input),webSafe)},decodeString(input,webSafe){return this.HAS_NATIVE_SUPPORT&&!webSafe?atob(input):function(bytes){const out=[];let pos=0,c=0;for(;pos<bytes.length;){const c1=bytes[pos++];if(c1<128)out[c++]=String.fromCharCode(c1);else if(c1>191&&c1<224){const c2=bytes[pos++];out[c++]=String.fromCharCode((31&c1)<<6|63&c2)}else if(c1>239&&c1<365){const u=((7&c1)<<18|(63&bytes[pos++])<<12|(63&bytes[pos++])<<6|63&bytes[pos++])-65536;out[c++]=String.fromCharCode(55296+(u>>10)),out[c++]=String.fromCharCode(56320+(1023&u))}else{const c2=bytes[pos++],c3=bytes[pos++];out[c++]=String.fromCharCode((15&c1)<<12|(63&c2)<<6|63&c3)}}return out.join("")}(this.decodeStringToByteArray(input,webSafe))},decodeStringToByteArray(input,webSafe){this.init_();const charToByteMap=webSafe?this.charToByteMapWebSafe_:this.charToByteMap_,output=[];for(let i=0;i<input.length;){const byte1=charToByteMap[input.charAt(i++)],byte2=i<input.length?charToByteMap[input.charAt(i)]:0;++i;const byte3=i<input.length?charToByteMap[input.charAt(i)]:64;++i;const byte4=i<input.length?charToByteMap[input.charAt(i)]:64;if(++i,null==byte1||null==byte2||null==byte3||null==byte4)throw new DecodeBase64StringError;const outByte1=byte1<<2|byte2>>4;if(output.push(outByte1),64!==byte3){const outByte2=byte2<<4&240|byte3>>2;if(output.push(outByte2),64!==byte4){const outByte3=byte3<<6&192|byte4;output.push(outByte3)}}}return output},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let i=0;i<this.ENCODED_VALS.length;i++)this.byteToCharMap_[i]=this.ENCODED_VALS.charAt(i),this.charToByteMap_[this.byteToCharMap_[i]]=i,this.byteToCharMapWebSafe_[i]=this.ENCODED_VALS_WEBSAFE.charAt(i),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]]=i,i>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)]=i,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)]=i)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64Encode=function(str){const utf8Bytes=stringToByteArray$1(str);return base64.encodeByteArray(utf8Bytes,!0)},base64urlEncodeWithoutPadding=function(str){return base64Encode(str).replace(/\./g,"")},base64Decode=function(str){try{return base64.decodeString(str,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function deepCopy(value){return deepExtend(void 0,value)}function deepExtend(target,source){if(!(source instanceof Object))return source;switch(source.constructor){case Date:return new Date(source.getTime());case Object:void 0===target&&(target={});break;case Array:target=[];break;default:return source}for(const prop in source)source.hasOwnProperty(prop)&&"__proto__"!==prop&&(target[prop]=deepExtend(target[prop],source[prop]));return target}class index_esm2017_Deferred{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((resolve,reject)=>{this.resolve=resolve,this.reject=reject}))}wrapCallback(callback){return(error,value)=>{error?this.reject(error):this.resolve(value),"function"==typeof callback&&(this.promise.catch((()=>{})),1===callback.length?callback(error):callback(error,value))}}}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 isNodeSdk(){return!0===CONSTANTS_NODE_CLIENT||!0===CONSTANTS_NODE_ADMIN}class FirebaseError extends Error{constructor(code,message,customData){super(message),this.code=code,this.customData=customData,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(service,serviceName,errors){this.service=service,this.serviceName=serviceName,this.errors=errors}create(code,...data){const customData=data[0]||{},fullCode=`${this.service}/${code}`,template=this.errors[code],message=template?function replaceTemplate(template,data){return template.replace(PATTERN,((_,key)=>{const value=data[key];return null!=value?String(value):`<${key}?>`}))}(template,customData):"Error",fullMessage=`${this.serviceName}: ${message} (${fullCode}).`;return new FirebaseError(fullCode,fullMessage,customData)}}const PATTERN=/\{\$([^}]+)}/g;function jsonEval(str){return JSON.parse(str)}function stringify(data){return JSON.stringify(data)}const decode=function(token){let header={},claims={},data={},signature="";try{const parts=token.split(".");header=jsonEval(base64Decode(parts[0])||""),claims=jsonEval(base64Decode(parts[1])||""),signature=parts[2],data=claims.d||{},delete claims.d}catch(e){}return{header,claims,data,signature}};function index_esm2017_contains(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)}function index_esm2017_safeGet(obj,key){return Object.prototype.hasOwnProperty.call(obj,key)?obj[key]:void 0}function index_esm2017_isEmpty(obj){for(const key in obj)if(Object.prototype.hasOwnProperty.call(obj,key))return!1;return!0}function map(obj,fn,contextObj){const res={};for(const key in obj)Object.prototype.hasOwnProperty.call(obj,key)&&(res[key]=fn.call(contextObj,obj[key],key,obj));return res}class Sha1{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let i=1;i<this.blockSize;++i)this.pad_[i]=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_(buf,offset){offset||(offset=0);const W=this.W_;if("string"==typeof buf)for(let i=0;i<16;i++)W[i]=buf.charCodeAt(offset)<<24|buf.charCodeAt(offset+1)<<16|buf.charCodeAt(offset+2)<<8|buf.charCodeAt(offset+3),offset+=4;else for(let i=0;i<16;i++)W[i]=buf[offset]<<24|buf[offset+1]<<16|buf[offset+2]<<8|buf[offset+3],offset+=4;for(let i=16;i<80;i++){const t=W[i-3]^W[i-8]^W[i-14]^W[i-16];W[i]=4294967295&(t<<1|t>>>31)}let f,k,a=this.chain_[0],b=this.chain_[1],c=this.chain_[2],d=this.chain_[3],e=this.chain_[4];for(let i=0;i<80;i++){i<40?i<20?(f=d^b&(c^d),k=1518500249):(f=b^c^d,k=1859775393):i<60?(f=b&c|d&(b|c),k=2400959708):(f=b^c^d,k=3395469782);const t=(a<<5|a>>>27)+f+e+k+W[i]&4294967295;e=d,d=c,c=4294967295&(b<<30|b>>>2),b=a,a=t}this.chain_[0]=this.chain_[0]+a&4294967295,this.chain_[1]=this.chain_[1]+b&4294967295,this.chain_[2]=this.chain_[2]+c&4294967295,this.chain_[3]=this.chain_[3]+d&4294967295,this.chain_[4]=this.chain_[4]+e&4294967295}update(bytes,length){if(null==bytes)return;void 0===length&&(length=bytes.length);const lengthMinusBlock=length-this.blockSize;let n=0;const buf=this.buf_;let inbuf=this.inbuf_;for(;n<length;){if(0===inbuf)for(;n<=lengthMinusBlock;)this.compress_(bytes,n),n+=this.blockSize;if("string"==typeof bytes){for(;n<length;)if(buf[inbuf]=bytes.charCodeAt(n),++inbuf,++n,inbuf===this.blockSize){this.compress_(buf),inbuf=0;break}}else for(;n<length;)if(buf[inbuf]=bytes[n],++inbuf,++n,inbuf===this.blockSize){this.compress_(buf),inbuf=0;break}}this.inbuf_=inbuf,this.total_+=length}digest(){const digest=[];let totalBits=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let i=this.blockSize-1;i>=56;i--)this.buf_[i]=255&totalBits,totalBits/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let j=24;j>=0;j-=8)digest[n]=this.chain_[i]>>j&255,++n;return digest}}function index_esm2017_errorPrefix(fnName,argName){return`${fnName} failed: ${argName} argument `}const stringLength=function(str){let p=0;for(let i=0;i<str.length;i++){const c=str.charCodeAt(i);c<128?p++:c<2048?p+=2:c>=55296&&c<=56319?(p+=4,i++):p+=3}return p};function index_esm2017_getModularInstance(service){return service&&service._delegate?service._delegate:service}class index_esm2017_Component{constructor(name,instanceFactory,type){this.name=name,this.instanceFactory=instanceFactory,this.type=type,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(mode){return this.instantiationMode=mode,this}setMultipleInstances(multipleInstances){return this.multipleInstances=multipleInstances,this}setServiceProps(props){return this.serviceProps=props,this}setInstanceCreatedCallback(callback){return this.onInstanceCreated=callback,this}}const instances=[];var LogLevel;!function(LogLevel){LogLevel[LogLevel.DEBUG=0]="DEBUG",LogLevel[LogLevel.VERBOSE=1]="VERBOSE",LogLevel[LogLevel.INFO=2]="INFO",LogLevel[LogLevel.WARN=3]="WARN",LogLevel[LogLevel.ERROR=4]="ERROR",LogLevel[LogLevel.SILENT=5]="SILENT"}(LogLevel||(LogLevel={}));const levelStringToEnum={debug:LogLevel.DEBUG,verbose:LogLevel.VERBOSE,info:LogLevel.INFO,warn:LogLevel.WARN,error:LogLevel.ERROR,silent:LogLevel.SILENT},defaultLogLevel=LogLevel.INFO,ConsoleMethod={[LogLevel.DEBUG]:"log",[LogLevel.VERBOSE]:"log",[LogLevel.INFO]:"info",[LogLevel.WARN]:"warn",[LogLevel.ERROR]:"error"},defaultLogHandler=(instance,logType,...args)=>{if(logType<instance.logLevel)return;const now=(new Date).toISOString(),method=ConsoleMethod[logType];if(!method)throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);console[method](`[${now}] ${instance.name}:`,...args)};class Logger{constructor(name){this.name=name,this._logLevel=defaultLogLevel,this._logHandler=defaultLogHandler,this._userLogHandler=null,instances.push(this)}get logLevel(){return this._logLevel}set logLevel(val){if(!(val in LogLevel))throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``);this._logLevel=val}setLogLevel(val){this._logLevel="string"==typeof val?levelStringToEnum[val]:val}get logHandler(){return this._logHandler}set logHandler(val){if("function"!=typeof val)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=val}get userLogHandler(){return this._userLogHandler}set userLogHandler(val){this._userLogHandler=val}debug(...args){this._userLogHandler&&this._userLogHandler(this,LogLevel.DEBUG,...args),this._logHandler(this,LogLevel.DEBUG,...args)}log(...args){this._userLogHandler&&this._userLogHandler(this,LogLevel.VERBOSE,...args),this._logHandler(this,LogLevel.VERBOSE,...args)}info(...args){this._userLogHandler&&this._userLogHandler(this,LogLevel.INFO,...args),this._logHandler(this,LogLevel.INFO,...args)}warn(...args){this._userLogHandler&&this._userLogHandler(this,LogLevel.WARN,...args),this._logHandler(this,LogLevel.WARN,...args)}error(...args){this._userLogHandler&&this._userLogHandler(this,LogLevel.ERROR,...args),this._logHandler(this,LogLevel.ERROR,...args)}}const instanceOfAny=(object,constructors)=>constructors.some((c=>object instanceof c));let idbProxyableTypes,cursorAdvanceMethods;const cursorRequestMap=new WeakMap,transactionDoneMap=new WeakMap,transactionStoreNamesMap=new WeakMap,transformCache=new WeakMap,reverseTransformCache=new WeakMap;let idbProxyTraps={get(target,prop,receiver){if(target instanceof IDBTransaction){if("done"===prop)return transactionDoneMap.get(target);if("objectStoreNames"===prop)return target.objectStoreNames||transactionStoreNamesMap.get(target);if("store"===prop)return receiver.objectStoreNames[1]?void 0:receiver.objectStore(receiver.objectStoreNames[0])}return wrap_idb_value_wrap(target[prop])},set:(target,prop,value)=>(target[prop]=value,!0),has:(target,prop)=>target instanceof IDBTransaction&&("done"===prop||"store"===prop)||prop in target};function wrapFunction(func){return func!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(func)?function(...args){return func.apply(unwrap(this),args),wrap_idb_value_wrap(cursorRequestMap.get(this))}:function(...args){return wrap_idb_value_wrap(func.apply(unwrap(this),args))}:function(storeNames,...args){const tx=func.call(unwrap(this),storeNames,...args);return transactionStoreNamesMap.set(tx,storeNames.sort?storeNames.sort():[storeNames]),wrap_idb_value_wrap(tx)}}function transformCachableValue(value){return"function"==typeof value?wrapFunction(value):(value instanceof IDBTransaction&&function cacheDonePromiseForTransaction(tx){if(transactionDoneMap.has(tx))return;const done=new Promise(((resolve,reject)=>{const unlisten=()=>{tx.removeEventListener("complete",complete),tx.removeEventListener("error",error),tx.removeEventListener("abort",error)},complete=()=>{resolve(),unlisten()},error=()=>{reject(tx.error||new DOMException("AbortError","AbortError")),unlisten()};tx.addEventListener("complete",complete),tx.addEventListener("error",error),tx.addEventListener("abort",error)}));transactionDoneMap.set(tx,done)}(value),instanceOfAny(value,function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}())?new Proxy(value,idbProxyTraps):value)}function wrap_idb_value_wrap(value){if(value instanceof IDBRequest)return function promisifyRequest(request){const promise=new Promise(((resolve,reject)=>{const unlisten=()=>{request.removeEventListener("success",success),request.removeEventListener("error",error)},success=()=>{resolve(wrap_idb_value_wrap(request.result)),unlisten()},error=()=>{reject(request.error),unlisten()};request.addEventListener("success",success),request.addEventListener("error",error)}));return promise.then((value=>{value instanceof IDBCursor&&cursorRequestMap.set(value,request)})).catch((()=>{})),reverseTransformCache.set(promise,request),promise}(value);if(transformCache.has(value))return transformCache.get(value);const newValue=transformCachableValue(value);return newValue!==value&&(transformCache.set(value,newValue),reverseTransformCache.set(newValue,value)),newValue}const unwrap=value=>reverseTransformCache.get(value);const readMethods=["get","getKey","getAll","getAllKeys","count"],writeMethods=["put","add","delete","clear"],cachedMethods=new Map;function getMethod(target,prop){if(!(target instanceof IDBDatabase)||prop in target||"string"!=typeof prop)return;if(cachedMethods.get(prop))return cachedMethods.get(prop);const targetFuncName=prop.replace(/FromIndex$/,""),useIndex=prop!==targetFuncName,isWrite=writeMethods.includes(targetFuncName);if(!(targetFuncName in(useIndex?IDBIndex:IDBObjectStore).prototype)||!isWrite&&!readMethods.includes(targetFuncName))return;const method=async function(storeName,...args){const tx=this.transaction(storeName,isWrite?"readwrite":"readonly");let target=tx.store;return useIndex&&(target=target.index(args.shift())),(await Promise.all([target[targetFuncName](...args),isWrite&&tx.done]))[0]};return cachedMethods.set(prop,method),method}!function replaceTraps(callback){idbProxyTraps=callback(idbProxyTraps)}((oldTraps=>({...oldTraps,get:(target,prop,receiver)=>getMethod(target,prop)||oldTraps.get(target,prop,receiver),has:(target,prop)=>!!getMethod(target,prop)||oldTraps.has(target,prop)})));class PlatformLoggerServiceImpl{constructor(container){this.container=container}getPlatformInfoString(){return this.container.getProviders().map((provider=>{if(function isVersionServiceProvider(provider){const component=provider.getComponent();return"VERSION"===(null==component?void 0:component.type)}(provider)){const service=provider.getImmediate();return`${service.library}/${service.version}`}return null})).filter((logString=>logString)).join(" ")}}const name$p="@firebase/app",logger=new Logger("@firebase/app"),name$o="@firebase/app-compat",name$n="@firebase/analytics-compat",name$m="@firebase/analytics",name$l="@firebase/app-check-compat",name$k="@firebase/app-check",name$j="@firebase/auth",name$i="@firebase/auth-compat",name$h="@firebase/database",name$g="@firebase/database-compat",name$f="@firebase/functions",name$e="@firebase/functions-compat",name$d="@firebase/installations",name$c="@firebase/installations-compat",name$b="@firebase/messaging",name$a="@firebase/messaging-compat",name$9="@firebase/performance",name$8="@firebase/performance-compat",name$7="@firebase/remote-config",name$6="@firebase/remote-config-compat",name$5="@firebase/storage",name$4="@firebase/storage-compat",name$3="@firebase/firestore",name$2="@firebase/vertexai-preview",name$1="@firebase/firestore-compat",index_esm2017_name="firebase",PLATFORM_LOG_STRING={[name$p]:"fire-core",[name$o]:"fire-core-compat",[name$m]:"fire-analytics",[name$n]:"fire-analytics-compat",[name$k]:"fire-app-check",[name$l]:"fire-app-check-compat",[name$j]:"fire-auth",[name$i]:"fire-auth-compat",[name$h]:"fire-rtdb",[name$g]:"fire-rtdb-compat",[name$f]:"fire-fn",[name$e]:"fire-fn-compat",[name$d]:"fire-iid",[name$c]:"fire-iid-compat",[name$b]:"fire-fcm",[name$a]:"fire-fcm-compat",[name$9]:"fire-perf",[name$8]:"fire-perf-compat",[name$7]:"fire-rc",[name$6]:"fire-rc-compat",[name$5]:"fire-gcs",[name$4]:"fire-gcs-compat",[name$3]:"fire-fst",[name$1]:"fire-fst-compat",[name$2]:"fire-vertex","fire-js":"fire-js",[index_esm2017_name]:"fire-js-all"},_apps=new Map,_serverApps=new Map,_components=new Map;function _addComponent(app,component){try{app.container.addComponent(component)}catch(e){logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`,e)}}function _registerComponent(component){const componentName=component.name;if(_components.has(componentName))return logger.debug(`There were multiple attempts to register component ${componentName}.`),!1;_components.set(componentName,component);for(const app of _apps.values())_addComponent(app,component);for(const serverApp of _serverApps.values())_addComponent(serverApp,component);return!0}const ERROR_FACTORY=new ErrorFactory("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."});function registerVersion(libraryKeyOrName,version,variant){var _a;let library=null!==(_a=PLATFORM_LOG_STRING[libraryKeyOrName])&&void 0!==_a?_a:libraryKeyOrName;variant&&(library+=`-${variant}`);const libraryMismatch=library.match(/\s|\//),versionMismatch=version.match(/\s|\//);if(libraryMismatch||versionMismatch){const warning=[`Unable to register library "${library}" with version "${version}":`];return libraryMismatch&&warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`),libraryMismatch&&versionMismatch&&warning.push("and"),versionMismatch&&warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`),void logger.warn(warning.join(" "))}_registerComponent(new index_esm2017_Component(`${library}-version`,(()=>({library,version})),"VERSION"))}const DB_NAME="firebase-heartbeat-database",DB_VERSION=1,STORE_NAME="firebase-heartbeat-store";let dbPromise=null;function getDbPromise(){return dbPromise||(dbPromise=function openDB(name,version,{blocked,upgrade,blocking,terminated}={}){const request=indexedDB.open(name,version),openPromise=wrap_idb_value_wrap(request);return upgrade&&request.addEventListener("upgradeneeded",(event=>{upgrade(wrap_idb_value_wrap(request.result),event.oldVersion,event.newVersion,wrap_idb_value_wrap(request.transaction),event)})),blocked&&request.addEventListener("blocked",(event=>blocked(event.oldVersion,event.newVersion,event))),openPromise.then((db=>{terminated&&db.addEventListener("close",(()=>terminated())),blocking&&db.addEventListener("versionchange",(event=>blocking(event.oldVersion,event.newVersion,event)))})).catch((()=>{})),openPromise}(DB_NAME,DB_VERSION,{upgrade:(db,oldVersion)=>{if(0===oldVersion)try{db.createObjectStore(STORE_NAME)}catch(e){console.warn(e)}}}).catch((e=>{throw ERROR_FACTORY.create("idb-open",{originalErrorMessage:e.message})}))),dbPromise}async function writeHeartbeatsToIndexedDB(app,heartbeatObject){try{const tx=(await getDbPromise()).transaction(STORE_NAME,"readwrite"),objectStore=tx.objectStore(STORE_NAME);await objectStore.put(heartbeatObject,computeKey(app)),await tx.done}catch(e){if(e instanceof FirebaseError)logger.warn(e.message);else{const idbGetError=ERROR_FACTORY.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});logger.warn(idbGetError.message)}}}function computeKey(app){return`${app.name}!${app.options.appId}`}class HeartbeatServiceImpl{constructor(container){this.container=container,this._heartbeatsCache=null;const app=this.container.getProvider("app").getImmediate();this._storage=new HeartbeatStorageImpl(app),this._heartbeatsCachePromise=this._storage.read().then((result=>(this._heartbeatsCache=result,result)))}async triggerHeartbeat(){var _a,_b,_c;try{const agent=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),date=getUTCDateString();if(console.log("heartbeats",null===(_a=this._heartbeatsCache)||void 0===_a?void 0:_a.heartbeats),null==(null===(_b=this._heartbeatsCache)||void 0===_b?void 0:_b.heartbeats)&&(this._heartbeatsCache=await this._heartbeatsCachePromise,null==(null===(_c=this._heartbeatsCache)||void 0===_c?void 0:_c.heartbeats)))return;if(this._heartbeatsCache.lastSentHeartbeatDate===date||this._heartbeatsCache.heartbeats.some((singleDateHeartbeat=>singleDateHeartbeat.date===date)))return;return this._heartbeatsCache.heartbeats.push({date,agent}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((singleDateHeartbeat=>{const hbTimestamp=new Date(singleDateHeartbeat.date).valueOf();return Date.now()-hbTimestamp<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}catch(e){logger.warn(e)}}async getHeartbeatsHeader(){var _a;try{if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(_a=this._heartbeatsCache)||void 0===_a?void 0:_a.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";const date=getUTCDateString(),{heartbeatsToSend,unsentEntries}=function extractHeartbeatsForHeader(heartbeatsCache,maxSize=1024){const heartbeatsToSend=[];let unsentEntries=heartbeatsCache.slice();for(const singleDateHeartbeat of heartbeatsCache){const heartbeatEntry=heartbeatsToSend.find((hb=>hb.agent===singleDateHeartbeat.agent));if(heartbeatEntry){if(heartbeatEntry.dates.push(singleDateHeartbeat.date),countBytes(heartbeatsToSend)>maxSize){heartbeatEntry.dates.pop();break}}else if(heartbeatsToSend.push({agent:singleDateHeartbeat.agent,dates:[singleDateHeartbeat.date]}),countBytes(heartbeatsToSend)>maxSize){heartbeatsToSend.pop();break}unsentEntries=unsentEntries.slice(1)}return{heartbeatsToSend,unsentEntries}}(this._heartbeatsCache.heartbeats),headerString=base64urlEncodeWithoutPadding(JSON.stringify({version:2,heartbeats:heartbeatsToSend}));return this._heartbeatsCache.lastSentHeartbeatDate=date,unsentEntries.length>0?(this._heartbeatsCache.heartbeats=unsentEntries,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),headerString}catch(e){return logger.warn(e),""}}}function getUTCDateString(){return(new Date).toISOString().substring(0,10)}class HeartbeatStorageImpl{constructor(app){this.app=app,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!function isIndexedDBAvailable(){try{return"object"==typeof indexedDB}catch(e){return!1}}()&&function validateIndexedDBOpenable(){return new Promise(((resolve,reject)=>{try{let preExist=!0;const DB_CHECK_NAME="validate-browser-context-for-indexeddb-analytics-module",request=self.indexedDB.open(DB_CHECK_NAME);request.onsuccess=()=>{request.result.close(),preExist||self.indexedDB.deleteDatabase(DB_CHECK_NAME),resolve(!0)},request.onupgradeneeded=()=>{preExist=!1},request.onerror=()=>{var _a;reject((null===(_a=request.error)||void 0===_a?void 0:_a.message)||"")}}catch(error){reject(error)}}))}().then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const idbHeartbeatObject=await async function readHeartbeatsFromIndexedDB(app){try{const tx=(await getDbPromise()).transaction(STORE_NAME),result=await tx.objectStore(STORE_NAME).get(computeKey(app));return await tx.done,result}catch(e){if(e instanceof FirebaseError)logger.warn(e.message);else{const idbGetError=ERROR_FACTORY.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});logger.warn(idbGetError.message)}}}(this.app);return(null==idbHeartbeatObject?void 0:idbHeartbeatObject.heartbeats)?idbHeartbeatObject:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(heartbeatsObject){var _a;if(await this._canUseIndexedDBPromise){const existingHeartbeatsObject=await this.read();return writeHeartbeatsToIndexedDB(this.app,{lastSentHeartbeatDate:null!==(_a=heartbeatsObject.lastSentHeartbeatDate)&&void 0!==_a?_a:existingHeartbeatsObject.lastSentHeartbeatDate,heartbeats:heartbeatsObject.heartbeats})}}async add(heartbeatsObject){var _a;if(await this._canUseIndexedDBPromise){const existingHeartbeatsObject=await this.read();return writeHeartbeatsToIndexedDB(this.app,{lastSentHeartbeatDate:null!==(_a=heartbeatsObject.lastSentHeartbeatDate)&&void 0!==_a?_a:existingHeartbeatsObject.lastSentHeartbeatDate,heartbeats:[...existingHeartbeatsObject.heartbeats,...heartbeatsObject.heartbeats]})}}}function countBytes(heartbeatsCache){return base64urlEncodeWithoutPadding(JSON.stringify({version:2,heartbeats:heartbeatsCache})).length}!function registerCoreComponents(variant){_registerComponent(new index_esm2017_Component("platform-logger",(container=>new PlatformLoggerServiceImpl(container)),"PRIVATE")),_registerComponent(new index_esm2017_Component("heartbeat",(container=>new HeartbeatServiceImpl(container)),"PRIVATE")),registerVersion(name$p,"0.10.9",variant),registerVersion(name$p,"0.10.9","esm2017"),registerVersion("fire-js","")}("");var index_esm2017_process=__webpack_require__("./node_modules/process/browser.js");let index_esm2017_SDK_VERSION="";function setSDKVersion(version){index_esm2017_SDK_VERSION=version}class DOMStorageWrapper{constructor(domStorage_){this.domStorage_=domStorage_,this.prefix_="firebase:"}set(key,value){null==value?this.domStorage_.removeItem(this.prefixedName_(key)):this.domStorage_.setItem(this.prefixedName_(key),stringify(value))}get(key){const storedVal=this.domStorage_.getItem(this.prefixedName_(key));return null==storedVal?null:jsonEval(storedVal)}remove(key){this.domStorage_.removeItem(this.prefixedName_(key))}prefixedName_(name){return this.prefix_+name}toString(){return this.domStorage_.toString()}}class MemoryStorage{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(key,value){null==value?delete this.cache_[key]:this.cache_[key]=value}get(key){return index_esm2017_contains(this.cache_,key)?this.cache_[key]:null}remove(key){delete this.cache_[key]}}const createStoragefor=function(domStorageName){try{if("undefined"!=typeof window&&void 0!==window[domStorageName]){const domStorage=window[domStorageName];return domStorage.setItem("firebase:sentinel","cache"),domStorage.removeItem("firebase:sentinel"),new DOMStorageWrapper(domStorage)}}catch(e){}return new MemoryStorage},PersistentStorage=createStoragefor("localStorage"),SessionStorage=createStoragefor("sessionStorage"),logClient=new Logger("@firebase/database"),LUIDGenerator=function(){let id=1;return function(){return id++}}(),sha1=function(str){const utf8Bytes=function(str){const out=[];let p=0;for(let i=0;i<str.length;i++){let c=str.charCodeAt(i);if(c>=55296&&c<=56319){const high=c-55296;i++,index_esm2017_assert(i<str.length,"Surrogate pair missing trail surrogate."),c=65536+(high<<10)+(str.charCodeAt(i)-56320)}c<128?out[p++]=c:c<2048?(out[p++]=c>>6|192,out[p++]=63&c|128):c<65536?(out[p++]=c>>12|224,out[p++]=c>>6&63|128,out[p++]=63&c|128):(out[p++]=c>>18|240,out[p++]=c>>12&63|128,out[p++]=c>>6&63|128,out[p++]=63&c|128)}return out}(str),sha1=new Sha1;sha1.update(utf8Bytes);const sha1Bytes=sha1.digest();return base64.encodeByteArray(sha1Bytes)},buildLogMessage_=function(...varArgs){let message="";for(let i=0;i<varArgs.length;i++){const arg=varArgs[i];Array.isArray(arg)||arg&&"object"==typeof arg&&"number"==typeof arg.length?message+=buildLogMessage_.apply(null,arg):message+="object"==typeof arg?stringify(arg):arg,message+=" "}return message};let index_esm2017_logger=null,firstLog_=!0;const enableLogging$1=function(logger_,persistent){index_esm2017_assert(!persistent||!0===logger_||!1===logger_,"Can't turn on custom loggers persistently."),!0===logger_?(logClient.logLevel=LogLevel.VERBOSE,index_esm2017_logger=logClient.log.bind(logClient),persistent&&SessionStorage.set("logging_enabled",!0)):"function"==typeof logger_?index_esm2017_logger=logger_:(index_esm2017_logger=null,SessionStorage.remove("logging_enabled"))},log=function(...varArgs){if(!0===firstLog_&&(firstLog_=!1,null===index_esm2017_logger&&!0===SessionStorage.get("logging_enabled")&&enableLogging$1(!0)),index_esm2017_logger){const message=buildLogMessage_.apply(null,varArgs);index_esm2017_logger(message)}},logWrapper=function(prefix){return function(...varArgs){log(prefix,...varArgs)}},error=function(...varArgs){const message="FIREBASE INTERNAL ERROR: "+buildLogMessage_(...varArgs);logClient.error(message)},fatal=function(...varArgs){const message=`FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;throw logClient.error(message),new Error(message)},warn=function(...varArgs){const message="FIREBASE WARNING: "+buildLogMessage_(...varArgs);logClient.warn(message)},isInvalidJSONNumber=function(data){return"number"==typeof data&&(data!=data||data===Number.POSITIVE_INFINITY||data===Number.NEGATIVE_INFINITY)},MIN_NAME="[MIN_NAME]",MAX_NAME="[MAX_NAME]",nameCompare=function(a,b){if(a===b)return 0;if(a===MIN_NAME||b===MAX_NAME)return-1;if(b===MIN_NAME||a===MAX_NAME)return 1;{const aAsInt=tryParseInt(a),bAsInt=tryParseInt(b);return null!==aAsInt?null!==bAsInt?aAsInt-bAsInt==0?a.length-b.length:aAsInt-bAsInt:-1:null!==bAsInt?1:a<b?-1:1}},stringCompare=function(a,b){return a===b?0:a<b?-1:1},requireKey=function(key,obj){if(obj&&key in obj)return obj[key];throw new Error("Missing required key ("+key+") in object: "+stringify(obj))},ObjectToUniqueKey=function(obj){if("object"!=typeof obj||null===obj)return stringify(obj);const keys=[];for(const k in obj)keys.push(k);keys.sort();let key="{";for(let i=0;i<keys.length;i++)0!==i&&(key+=","),key+=stringify(keys[i]),key+=":",key+=ObjectToUniqueKey(obj[keys[i]]);return key+="}",key},splitStringBySize=function(str,segsize){const len=str.length;if(len<=segsize)return[str];const dataSegs=[];for(let c=0;c<len;c+=segsize)c+segsize>len?dataSegs.push(str.substring(c,len)):dataSegs.push(str.substring(c,c+segsize));return dataSegs};function each(obj,fn){for(const key in obj)obj.hasOwnProperty(key)&&fn(key,obj[key])}const doubleToIEEE754String=function(v){index_esm2017_assert(!isInvalidJSONNumber(v),"Invalid JSON number");let s,e,f,ln,i;0===v?(e=0,f=0,s=1/v==-1/0?1:0):(s=v<0,(v=Math.abs(v))>=Math.pow(2,-1022)?(ln=Math.min(Math.floor(Math.log(v)/Math.LN2),1023),e=ln+1023,f=Math.round(v*Math.pow(2,52-ln)-Math.pow(2,52))):(e=0,f=Math.round(v/Math.pow(2,-1074))));const bits=[];for(i=52;i;i-=1)bits.push(f%2?1:0),f=Math.floor(f/2);for(i=11;i;i-=1)bits.push(e%2?1:0),e=Math.floor(e/2);bits.push(s?1:0),bits.reverse();const str=bits.join("");let hexByteString="";for(i=0;i<64;i+=8){let hexByte=parseInt(str.substr(i,8),2).toString(16);1===hexByte.length&&(hexByte="0"+hexByte),hexByteString+=hexByte}return hexByteString.toLowerCase()};const INTEGER_REGEXP_=new RegExp("^-?(0*)\\d{1,10}$"),tryParseInt=function(str){if(INTEGER_REGEXP_.test(str)){const intVal=Number(str);if(intVal>=-2147483648&&intVal<=2147483647)return intVal}return null},exceptionGuard=function(fn){try{fn()}catch(e){setTimeout((()=>{const stack=e.stack||"";throw warn("Exception was thrown by user callback.",stack),e}),Math.floor(0))}},setTimeoutNonBlocking=function(fn,time){const timeout=setTimeout(fn,time);return"number"==typeof timeout&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(timeout):"object"==typeof timeout&&timeout.unref&&timeout.unref(),timeout};class AppCheckTokenProvider{constructor(appName_,appCheckProvider){this.appName_=appName_,this.appCheckProvider=appCheckProvider,this.appCheck=null==appCheckProvider?void 0:appCheckProvider.getImmediate({optional:!0}),this.appCheck||null==appCheckProvider||appCheckProvider.get().then((appCheck=>this.appCheck=appCheck))}getToken(forceRefresh){return this.appCheck?this.appCheck.getToken(forceRefresh):new Promise(((resolve,reject)=>{setTimeout((()=>{this.appCheck?this.getToken(forceRefresh).then(resolve,reject):resolve(null)}),0)}))}addTokenChangeListener(listener){var _a;null===(_a=this.appCheckProvider)||void 0===_a||_a.get().then((appCheck=>appCheck.addTokenListener(listener)))}notifyForInvalidToken(){warn(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}class FirebaseAuthTokenProvider{constructor(appName_,firebaseOptions_,authProvider_){this.appName_=appName_,this.firebaseOptions_=firebaseOptions_,this.authProvider_=authProvider_,this.auth_=null,this.auth_=authProvider_.getImmediate({optional:!0}),this.auth_||authProvider_.onInit((auth=>this.auth_=auth))}getToken(forceRefresh){return this.auth_?this.auth_.getToken(forceRefresh).catch((error=>error&&"auth/token-not-initialized"===error.code?(log("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(error))):new Promise(((resolve,reject)=>{setTimeout((()=>{this.auth_?this.getToken(forceRefresh).then(resolve,reject):resolve(null)}),0)}))}addTokenChangeListener(listener){this.auth_?this.auth_.addAuthTokenListener(listener):this.authProvider_.get().then((auth=>auth.addAuthTokenListener(listener)))}removeTokenChangeListener(listener){this.authProvider_.get().then((auth=>auth.removeAuthTokenListener(listener)))}notifyForInvalidToken(){let errorMessage='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?errorMessage+='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_?errorMessage+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':errorMessage+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',warn(errorMessage)}}class EmulatorTokenProvider{constructor(accessToken){this.accessToken=accessToken}getToken(forceRefresh){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(listener){listener(this.accessToken)}removeTokenChangeListener(listener){}notifyForInvalidToken(){}}EmulatorTokenProvider.OWNER="owner";const FORGE_DOMAIN_RE=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;class RepoInfo{constructor(host,secure,namespace,webSocketOnly,nodeAdmin=!1,persistenceKey="",includeNamespaceInQueryParams=!1,isUsingEmulator=!1){this.secure=secure,this.namespace=namespace,this.webSocketOnly=webSocketOnly,this.nodeAdmin=nodeAdmin,this.persistenceKey=persistenceKey,this.includeNamespaceInQueryParams=includeNamespaceInQueryParams,this.isUsingEmulator=isUsingEmulator,this._host=host.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=PersistentStorage.get("host:"+host)||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(newHost){newHost!==this.internalHost&&(this.internalHost=newHost,this.isCacheableHost()&&PersistentStorage.set("host:"+this._host,this.internalHost))}toString(){let str=this.toURLString();return this.persistenceKey&&(str+="<"+this.persistenceKey+">"),str}toURLString(){const protocol=this.secure?"https://":"http://",query=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${protocol}${this.host}/${query}`}}function repoInfoConnectionURL(repoInfo,type,params){let connURL;if(index_esm2017_assert("string"==typeof type,"typeof type must == string"),index_esm2017_assert("object"==typeof params,"typeof params must == object"),"websocket"===type)connURL=(repoInfo.secure?"wss://":"ws://")+repoInfo.internalHost+"/.ws?";else{if("long_polling"!==type)throw new Error("Unknown connection type: "+type);connURL=(repoInfo.secure?"https://":"http://")+repoInfo.internalHost+"/.lp?"}(function repoInfoNeedsQueryParam(repoInfo){return repoInfo.host!==repoInfo.internalHost||repoInfo.isCustomHost()||repoInfo.includeNamespaceInQueryParams})(repoInfo)&&(params.ns=repoInfo.namespace);const pairs=[];return each(params,((key,value)=>{pairs.push(key+"="+value)})),connURL+pairs.join("&")}class StatsCollection{constructor(){this.counters_={}}incrementCounter(name,amount=1){index_esm2017_contains(this.counters_,name)||(this.counters_[name]=0),this.counters_[name]+=amount}get(){return deepCopy(this.counters_)}}const collections={},reporters={};function statsManagerGetCollection(repoInfo){const hashString=repoInfo.toString();return collections[hashString]||(collections[hashString]=new StatsCollection),collections[hashString]}class PacketReceiver{constructor(onMessage_){this.onMessage_=onMessage_,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(responseNum,callback){this.closeAfterResponse=responseNum,this.onClose=callback,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(requestNum,data){for(this.pendingResponses[requestNum]=data;this.pendingResponses[this.currentResponseNum];){const toProcess=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let i=0;i<toProcess.length;++i)toProcess[i]&&exceptionGuard((()=>{this.onMessage_(toProcess[i])}));if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class BrowserPollConnection{constructor(connId,repoInfo,applicationId,appCheckToken,authToken,transportSessionId,lastSessionId){this.connId=connId,this.repoInfo=repoInfo,this.applicationId=applicationId,this.appCheckToken=appCheckToken,this.authToken=authToken,this.transportSessionId=transportSessionId,this.lastSessionId=lastSessionId,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=logWrapper(connId),this.stats_=statsManagerGetCollection(repoInfo),this.urlFn=params=>(this.appCheckToken&&(params.ac=this.appCheckToken),repoInfoConnectionURL(repoInfo,"long_polling",params))}open(onMessage,onDisconnect){this.curSegmentNum=0,this.onDisconnect_=onDisconnect,this.myPacketOrderer=new PacketReceiver(onMessage),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout((()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null}),Math.floor(3e4)),function(fn){if(isNodeSdk()||"complete"===document.readyState)fn();else{let called=!1;const wrappedFn=function(){document.body?called||(called=!0,fn()):setTimeout(wrappedFn,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",wrappedFn,!1),window.addEventListener("load",wrappedFn,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",(()=>{"complete"===document.readyState&&wrappedFn()})),window.attachEvent("onload",wrappedFn))}}((()=>{if(this.isClosed_)return;this.scriptTagHolder=new FirebaseIFrameScriptHolder(((...args)=>{const[command,arg1,arg2,arg3,arg4]=args;if(this.incrementIncomingBytes_(args),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===command)this.id=arg1,this.password=arg2;else{if("close"!==command)throw new Error("Unrecognized command received: "+command);arg1?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(arg1,(()=>{this.onClosed_()}))):this.onClosed_()}}),((...args)=>{const[pN,data]=args;this.incrementIncomingBytes_(args),this.myPacketOrderer.handleResponse(pN,data)}),(()=>{this.onClosed_()}),this.urlFn);const urlParams={start:"t"};urlParams.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(urlParams.cb=this.scriptTagHolder.uniqueCallbackIdentifier),urlParams.v="5",this.transportSessionId&&(urlParams.s=this.transportSessionId),this.lastSessionId&&(urlParams.ls=this.lastSessionId),this.applicationId&&(urlParams.p=this.applicationId),this.appCheckToken&&(urlParams.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&FORGE_DOMAIN_RE.test(location.hostname)&&(urlParams.r="f");const connectURL=this.urlFn(urlParams);this.log_("Connecting via long-poll to "+connectURL),this.scriptTagHolder.addTag(connectURL,(()=>{}))}))}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){BrowserPollConnection.forceAllow_=!0}static forceDisallow(){BrowserPollConnection.forceDisallow_=!0}static isAvailable(){return!isNodeSdk()&&(!!BrowserPollConnection.forceAllow_||!(BrowserPollConnection.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(data){const dataStr=stringify(data);this.bytesSent+=dataStr.length,this.stats_.incrementCounter("bytes_sent",dataStr.length);const base64data=base64Encode(dataStr),dataSegs=splitStringBySize(base64data,1840);for(let i=0;i<dataSegs.length;i++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,dataSegs.length,dataSegs[i]),this.curSegmentNum++}addDisconnectPingFrame(id,pw){if(isNodeSdk())return;this.myDisconnFrame=document.createElement("iframe");const urlParams={dframe:"t"};urlParams.id=id,urlParams.pw=pw,this.myDisconnFrame.src=this.urlFn(urlParams),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(args){const bytesReceived=stringify(args).length;this.bytesReceived+=bytesReceived,this.stats_.incrementCounter("bytes_received",bytesReceived)}}class FirebaseIFrameScriptHolder{constructor(commandCB,onMessageCB,onDisconnect,urlFn){if(this.onDisconnect=onDisconnect,this.urlFn=urlFn,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0,isNodeSdk())this.commandCB=commandCB,this.onMessageCB=onMessageCB;else{this.uniqueCallbackIdentifier=LUIDGenerator(),window["pLPCommand"+this.uniqueCallbackIdentifier]=commandCB,window["pRTLPCB"+this.uniqueCallbackIdentifier]=onMessageCB,this.myIFrame=FirebaseIFrameScriptHolder.createIFrame_();let script="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)){script='<script>document.domain="'+document.domain+'";<\/script>'}const iframeContents="<html><body>"+script+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(iframeContents),this.myIFrame.doc.close()}catch(e){log("frame writing exception"),e.stack&&log(e.stack),log(e)}}}static createIFrame_(){const iframe=document.createElement("iframe");if(iframe.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(iframe);try{iframe.contentWindow.document||log("No IE domain setting required")}catch(e){const domain=document.domain;iframe.src="javascript:void((function(){document.open();document.domain='"+domain+"';document.close();})())"}return iframe.contentDocument?iframe.doc=iframe.contentDocument:iframe.contentWindow?iframe.doc=iframe.contentWindow.document:iframe.document&&(iframe.doc=iframe.document),iframe}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout((()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)}),Math.floor(0)));const onDisconnect=this.onDisconnect;onDisconnect&&(this.onDisconnect=null,onDisconnect())}startLongPoll(id,pw){for(this.myID=id,this.myPW=pw,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const urlParams={};urlParams.id=this.myID,urlParams.pw=this.myPW,urlParams.ser=this.currentSerial;let theURL=this.urlFn(urlParams),curDataString="",i=0;for(;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+30+curDataString.length<=1870))break;{const theSeg=this.pendingSegs.shift();curDataString=curDataString+"&seg"+i+"="+theSeg.seg+"&ts"+i+"="+theSeg.ts+"&d"+i+"="+theSeg.d,i++}}return theURL+=curDataString,this.addLongPollTag_(theURL,this.currentSerial),!0}return!1}enqueueSegment(segnum,totalsegs,data){this.pendingSegs.push({seg:segnum,ts:totalsegs,d:data}),this.alive&&this.newRequest_()}addLongPollTag_(url,serial){this.outstandingRequests.add(serial);const doNewRequest=()=>{this.outstandingRequests.delete(serial),this.newRequest_()},keepaliveTimeout=setTimeout(doNewRequest,Math.floor(25e3));this.addTag(url,(()=>{clearTimeout(keepaliveTimeout),doNewRequest()}))}addTag(url,loadCB){isNodeSdk()?this.doNodeLongPoll(url,loadCB):setTimeout((()=>{try{if(!this.sendNewPolls)return;const newScript=this.myIFrame.doc.createElement("script");newScript.type="text/javascript",newScript.async=!0,newScript.src=url,newScript.onload=newScript.onreadystatechange=function(){const rstate=newScript.readyState;rstate&&"loaded"!==rstate&&"complete"!==rstate||(newScript.onload=newScript.onreadystatechange=null,newScript.parentNode&&newScript.parentNode.removeChild(newScript),loadCB())},newScript.onerror=()=>{log("Long-poll script failed to load: "+url),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(newScript)}catch(e){}}),Math.floor(1))}}let WebSocketImpl=null;"undefined"!=typeof MozWebSocket?WebSocketImpl=MozWebSocket:"undefined"!=typeof WebSocket&&(WebSocketImpl=WebSocket);class WebSocketConnection{constructor(connId,repoInfo,applicationId,appCheckToken,authToken,transportSessionId,lastSessionId){this.connId=connId,this.applicationId=applicationId,this.appCheckToken=appCheckToken,this.authToken=authToken,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=logWrapper(this.connId),this.stats_=statsManagerGetCollection(repoInfo),this.connURL=WebSocketConnection.connectionURL_(repoInfo,transportSessionId,lastSessionId,appCheckToken,applicationId),this.nodeAdmin=repoInfo.nodeAdmin}static connectionURL_(repoInfo,transportSessionId,lastSessionId,appCheckToken,applicationId){const urlParams={v:"5"};return!isNodeSdk()&&"undefined"!=typeof location&&location.hostname&&FORGE_DOMAIN_RE.test(location.hostname)&&(urlParams.r="f"),transportSessionId&&(urlParams.s=transportSessionId),lastSessionId&&(urlParams.ls=lastSessionId),appCheckToken&&(urlParams.ac=appCheckToken),applicationId&&(urlParams.p=applicationId),repoInfoConnectionURL(repoInfo,"websocket",urlParams)}open(onMessage,onDisconnect){this.onDisconnect=onDisconnect,this.onMessage=onMessage,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,PersistentStorage.set("previous_websocket_failure",!0);try{let options;if(isNodeSdk()){const device=this.nodeAdmin?"AdminNode":"Node";options={headers:{"User-Agent":`Firebase/5/${index_esm2017_SDK_VERSION}/${index_esm2017_process.platform}/${device}`,"X-Firebase-GMPID":this.applicationId||""}},this.authToken&&(options.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(options.headers["X-Firebase-AppCheck"]=this.appCheckToken);const env=index_esm2017_process.env,proxy=0===this.connURL.indexOf("wss://")?env.HTTPS_PROXY||env.https_proxy:env.HTTP_PROXY||env.http_proxy;proxy&&(options.proxy={origin:proxy})}this.mySock=new WebSocketImpl(this.connURL,[],options)}catch(e){this.log_("Error instantiating WebSocket.");const error=e.message||e.data;return error&&this.log_(error),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=m=>{this.handleIncomingFrame(m)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");const error=e.message||e.data;error&&this.log_(error),this.onClosed_()}}start(){}static forceDisallow(){WebSocketConnection.forceDisallow_=!0}static isAvailable(){let isOldAndroid=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const oldAndroidRegex=/Android ([0-9]{0,}\.[0-9]{0,})/,oldAndroidMatch=navigator.userAgent.match(oldAndroidRegex);oldAndroidMatch&&oldAndroidMatch.length>1&&parseFloat(oldAndroidMatch[1])<4.4&&(isOldAndroid=!0)}return!isOldAndroid&&null!==WebSocketImpl&&!WebSocketConnection.forceDisallow_}static previouslyFailed(){return PersistentStorage.isInMemoryStorage||!0===PersistentStorage.get("previous_websocket_failure")}markConnectionHealthy(){PersistentStorage.remove("previous_websocket_failure")}appendFrame_(data){if(this.frames.push(data),this.frames.length===this.totalFrames){const fullMess=this.frames.join("");this.frames=null;const jsonMess=jsonEval(fullMess);this.onMessage(jsonMess)}}handleNewFrameCount_(frameCount){this.totalFrames=frameCount,this.frames=[]}extractFrameCount_(data){if(index_esm2017_assert(null===this.frames,"We already have a frame buffer"),data.length<=6){const frameCount=Number(data);if(!isNaN(frameCount))return this.handleNewFrameCount_(frameCount),null}return this.handleNewFrameCount_(1),data}handleIncomingFrame(mess){if(null===this.mySock)return;const data=mess.data;if(this.bytesReceived+=data.length,this.stats_.incrementCounter("bytes_received",data.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(data);else{const remainingData=this.extractFrameCount_(data);null!==remainingData&&this.appendFrame_(remainingData)}}send(data){this.resetKeepAlive();const dataStr=stringify(data);this.bytesSent+=dataStr.length,this.stats_.incrementCounter("bytes_sent",dataStr.length);const dataSegs=splitStringBySize(dataStr,16384);dataSegs.length>1&&this.sendString_(String(dataSegs.length));for(let i=0;i<dataSegs.length;i++)this.sendString_(dataSegs[i])}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_(str){try{this.mySock.send(str)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}WebSocketConnection.responsesRequiredToBeHealthy=2,WebSocketConnection.healthyTimeout=3e4;class TransportManager{constructor(repoInfo){this.initTransports_(repoInfo)}static get ALL_TRANSPORTS(){return[BrowserPollConnection,WebSocketConnection]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(repoInfo){const isWebSocketsAvailable=WebSocketConnection&&WebSocketConnection.isAvailable();let isSkipPollConnection=isWebSocketsAvailable&&!WebSocketConnection.previouslyFailed();if(repoInfo.webSocketOnly&&(isWebSocketsAvailable||warn("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),isSkipPollConnection=!0),isSkipPollConnection)this.transports_=[WebSocketConnection];else{const transports=this.transports_=[];for(const transport of TransportManager.ALL_TRANSPORTS)transport&&transport.isAvailable()&&transports.push(transport);TransportManager.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}TransportManager.globalTransportInitialized_=!1;class Connection{constructor(id,repoInfo_,applicationId_,appCheckToken_,authToken_,onMessage_,onReady_,onDisconnect_,onKill_,lastSessionId){this.id=id,this.repoInfo_=repoInfo_,this.applicationId_=applicationId_,this.appCheckToken_=appCheckToken_,this.authToken_=authToken_,this.onMessage_=onMessage_,this.onReady_=onReady_,this.onDisconnect_=onDisconnect_,this.onKill_=onKill_,this.lastSessionId=lastSessionId,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=logWrapper("c:"+this.id+":"),this.transportManager_=new TransportManager(repoInfo_),this.log_("Connection created"),this.start_()}start_(){const conn=this.transportManager_.initialTransport();this.conn_=new conn(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=conn.responsesRequiredToBeHealthy||0;const onMessageReceived=this.connReceiver_(this.conn_),onConnectionLost=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout((()=>{this.conn_&&this.conn_.open(onMessageReceived,onConnectionLost)}),Math.floor(0));const healthyTimeoutMS=conn.healthyTimeout||0;healthyTimeoutMS>0&&(this.healthyTimeout_=setTimeoutNonBlocking((()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))}),Math.floor(healthyTimeoutMS)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(conn){return everConnected=>{conn===this.conn_?this.onConnectionLost_(everConnected):conn===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(conn){return message=>{2!==this.state_&&(conn===this.rx_?this.onPrimaryMessageReceived_(message):conn===this.secondaryConn_?this.onSecondaryMessageReceived_(message):this.log_("message on old connection"))}}sendRequest(dataMsg){const msg={t:"d",d:dataMsg};this.sendData_(msg)}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_(controlData){if("t"in controlData){const cmd=controlData.t;"a"===cmd?this.upgradeIfSecondaryHealthy_():"r"===cmd?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===cmd&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(parsedData){const layer=requireKey("t",parsedData),data=requireKey("d",parsedData);if("c"===layer)this.onSecondaryControl_(data);else{if("d"!==layer)throw new Error("Unknown protocol layer: "+layer);this.pendingDataMessages.push(data)}}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_(parsedData){const layer=requireKey("t",parsedData),data=requireKey("d",parsedData);"c"===layer?this.onControl_(data):"d"===layer&&this.onDataMessage_(data)}onDataMessage_(message){this.onPrimaryResponse_(),this.onMessage_(message)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(controlData){const cmd=requireKey("t",controlData);if("d"in controlData){const payload=controlData.d;if("h"===cmd){const handshakePayload=Object.assign({},payload);this.repoInfo_.isUsingEmulator&&(handshakePayload.h=this.repoInfo_.host),this.onHandshake_(handshakePayload)}else if("n"===cmd){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let i=0;i<this.pendingDataMessages.length;++i)this.onDataMessage_(this.pendingDataMessages[i]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===cmd?this.onConnectionShutdown_(payload):"r"===cmd?this.onReset_(payload):"e"===cmd?error("Server Error: "+payload):"o"===cmd?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):error("Unknown control packet command: "+cmd)}}onHandshake_(handshake){const timestamp=handshake.ts,version=handshake.v,host=handshake.h;this.sessionId=handshake.s,this.repoInfo_.host=host,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,timestamp),"5"!==version&&warn("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const conn=this.transportManager_.upgradeTransport();conn&&this.startUpgrade_(conn)}startUpgrade_(conn){this.secondaryConn_=new conn(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=conn.responsesRequiredToBeHealthy||0;const onMessage=this.connReceiver_(this.secondaryConn_),onDisconnect=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(onMessage,onDisconnect),setTimeoutNonBlocking((()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())}),Math.floor(6e4))}onReset_(host){this.log_("Reset packet received. New host: "+host),this.repoInfo_.host=host,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(conn,timestamp){this.log_("Realtime connection established."),this.conn_=conn,this.state_=1,this.onReady_&&(this.onReady_(timestamp,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):setTimeoutNonBlocking((()=>{this.sendPingOnPrimaryIfNecessary_()}),Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){const conn=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==conn&&this.rx_!==conn||this.close()}onConnectionLost_(everConnected){this.conn_=null,everConnected||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(PersistentStorage.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(reason){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(reason),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(data){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(data)}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 ServerActions{put(pathString,data,onComplete,hash){}merge(pathString,data,onComplete,hash){}refreshAuthToken(token){}refreshAppCheckToken(token){}onDisconnectPut(pathString,data,onComplete){}onDisconnectMerge(pathString,data,onComplete){}onDisconnectCancel(pathString,onComplete){}reportStats(stats){}}class EventEmitter{constructor(allowedEvents_){this.allowedEvents_=allowedEvents_,this.listeners_={},index_esm2017_assert(Array.isArray(allowedEvents_)&&allowedEvents_.length>0,"Requires a non-empty array")}trigger(eventType,...varArgs){if(Array.isArray(this.listeners_[eventType])){const listeners=[...this.listeners_[eventType]];for(let i=0;i<listeners.length;i++)listeners[i].callback.apply(listeners[i].context,varArgs)}}on(eventType,callback,context){this.validateEventType_(eventType),this.listeners_[eventType]=this.listeners_[eventType]||[],this.listeners_[eventType].push({callback,context});const eventData=this.getInitialEvent(eventType);eventData&&callback.apply(context,eventData)}off(eventType,callback,context){this.validateEventType_(eventType);const listeners=this.listeners_[eventType]||[];for(let i=0;i<listeners.length;i++)if(listeners[i].callback===callback&&(!context||context===listeners[i].context))return void listeners.splice(i,1)}validateEventType_(eventType){index_esm2017_assert(this.allowedEvents_.find((et=>et===eventType)),"Unknown event: "+eventType)}}class OnlineMonitor extends EventEmitter{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||isMobileCordova()||(window.addEventListener("online",(()=>{this.online_||(this.online_=!0,this.trigger("online",!0))}),!1),window.addEventListener("offline",(()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))}),!1))}static getInstance(){return new OnlineMonitor}getInitialEvent(eventType){return index_esm2017_assert("online"===eventType,"Unknown event type: "+eventType),[this.online_]}currentlyOnline(){return this.online_}}const MAX_PATH_DEPTH=32,MAX_PATH_LENGTH_BYTES=768;class Path{constructor(pathOrString,pieceNum){if(void 0===pieceNum){this.pieces_=pathOrString.split("/");let copyTo=0;for(let i=0;i<this.pieces_.length;i++)this.pieces_[i].length>0&&(this.pieces_[copyTo]=this.pieces_[i],copyTo++);this.pieces_.length=copyTo,this.pieceNum_=0}else this.pieces_=pathOrString,this.pieceNum_=pieceNum}toString(){let pathString="";for(let i=this.pieceNum_;i<this.pieces_.length;i++)""!==this.pieces_[i]&&(pathString+="/"+this.pieces_[i]);return pathString||"/"}}function newEmptyPath(){return new Path("")}function pathGetFront(path){return path.pieceNum_>=path.pieces_.length?null:path.pieces_[path.pieceNum_]}function pathGetLength(path){return path.pieces_.length-path.pieceNum_}function pathPopFront(path){let pieceNum=path.pieceNum_;return pieceNum<path.pieces_.length&&pieceNum++,new Path(path.pieces_,pieceNum)}function pathGetBack(path){return path.pieceNum_<path.pieces_.length?path.pieces_[path.pieces_.length-1]:null}function pathSlice(path,begin=0){return path.pieces_.slice(path.pieceNum_+begin)}function pathParent(path){if(path.pieceNum_>=path.pieces_.length)return null;const pieces=[];for(let i=path.pieceNum_;i<path.pieces_.length-1;i++)pieces.push(path.pieces_[i]);return new Path(pieces,0)}function pathChild(path,childPathObj){const pieces=[];for(let i=path.pieceNum_;i<path.pieces_.length;i++)pieces.push(path.pieces_[i]);if(childPathObj instanceof Path)for(let i=childPathObj.pieceNum_;i<childPathObj.pieces_.length;i++)pieces.push(childPathObj.pieces_[i]);else{const childPieces=childPathObj.split("/");for(let i=0;i<childPieces.length;i++)childPieces[i].length>0&&pieces.push(childPieces[i])}return new Path(pieces,0)}function pathIsEmpty(path){return path.pieceNum_>=path.pieces_.length}function newRelativePath(outerPath,innerPath){const outer=pathGetFront(outerPath),inner=pathGetFront(innerPath);if(null===outer)return innerPath;if(outer===inner)return newRelativePath(pathPopFront(outerPath),pathPopFront(innerPath));throw new Error("INTERNAL ERROR: innerPath ("+innerPath+") is not within outerPath ("+outerPath+")")}function pathEquals(path,other){if(pathGetLength(path)!==pathGetLength(other))return!1;for(let i=path.pieceNum_,j=other.pieceNum_;i<=path.pieces_.length;i++,j++)if(path.pieces_[i]!==other.pieces_[j])return!1;return!0}function pathContains(path,other){let i=path.pieceNum_,j=other.pieceNum_;if(pathGetLength(path)>pathGetLength(other))return!1;for(;i<path.pieces_.length;){if(path.pieces_[i]!==other.pieces_[j])return!1;++i,++j}return!0}class ValidationPath{constructor(path,errorPrefix_){this.errorPrefix_=errorPrefix_,this.parts_=pathSlice(path,0),this.byteLength_=Math.max(1,this.parts_.length);for(let i=0;i<this.parts_.length;i++)this.byteLength_+=stringLength(this.parts_[i]);validationPathCheckValid(this)}}function validationPathCheckValid(validationPath){if(validationPath.byteLength_>MAX_PATH_LENGTH_BYTES)throw new Error(validationPath.errorPrefix_+"has a key path longer than "+MAX_PATH_LENGTH_BYTES+" bytes ("+validationPath.byteLength_+").");if(validationPath.parts_.length>MAX_PATH_DEPTH)throw new Error(validationPath.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+MAX_PATH_DEPTH+") or object contains a cycle "+validationPathToErrorString(validationPath))}function validationPathToErrorString(validationPath){return 0===validationPath.parts_.length?"":"in property '"+validationPath.parts_.join(".")+"'"}class VisibilityMonitor extends EventEmitter{constructor(){let hidden,visibilityChange;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(visibilityChange="visibilitychange",hidden="hidden"):void 0!==document.mozHidden?(visibilityChange="mozvisibilitychange",hidden="mozHidden"):void 0!==document.msHidden?(visibilityChange="msvisibilitychange",hidden="msHidden"):void 0!==document.webkitHidden&&(visibilityChange="webkitvisibilitychange",hidden="webkitHidden")),this.visible_=!0,visibilityChange&&document.addEventListener(visibilityChange,(()=>{const visible=!document[hidden];visible!==this.visible_&&(this.visible_=visible,this.trigger("visible",visible))}),!1)}static getInstance(){return new VisibilityMonitor}getInitialEvent(eventType){return index_esm2017_assert("visible"===eventType,"Unknown event type: "+eventType),[this.visible_]}}class PersistentConnection extends ServerActions{constructor(repoInfo_,applicationId_,onDataUpdate_,onConnectStatus_,onServerInfoUpdate_,authTokenProvider_,appCheckTokenProvider_,authOverride_){if(super(),this.repoInfo_=repoInfo_,this.applicationId_=applicationId_,this.onDataUpdate_=onDataUpdate_,this.onConnectStatus_=onConnectStatus_,this.onServerInfoUpdate_=onServerInfoUpdate_,this.authTokenProvider_=authTokenProvider_,this.appCheckTokenProvider_=appCheckTokenProvider_,this.authOverride_=authOverride_,this.id=PersistentConnection.nextPersistentConnectionId_++,this.log_=logWrapper("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,authOverride_&&!isNodeSdk())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");VisibilityMonitor.getInstance().on("visible",this.onVisible_,this),-1===repoInfo_.host.indexOf("fblocal")&&OnlineMonitor.getInstance().on("online",this.onOnline_,this)}sendRequest(action,body,onResponse){const curReqNum=++this.requestNumber_,msg={r:curReqNum,a:action,b:body};this.log_(stringify(msg)),index_esm2017_assert(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(msg),onResponse&&(this.requestCBHash_[curReqNum]=onResponse)}get(query){this.initConnection_();const deferred=new index_esm2017_Deferred,outstandingGet={action:"g",request:{p:query._path.toString(),q:query._queryObject},onComplete:message=>{const payload=message.d;"ok"===message.s?deferred.resolve(payload):deferred.reject(payload)}};this.outstandingGets_.push(outstandingGet),this.outstandingGetCount_++;const index=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(index),deferred.promise}listen(query,currentHashFn,tag,onComplete){this.initConnection_();const queryId=query._queryIdentifier,pathString=query._path.toString();this.log_("Listen called for "+pathString+" "+queryId),this.listens.has(pathString)||this.listens.set(pathString,new Map),index_esm2017_assert(query._queryParams.isDefault()||!query._queryParams.loadsAllData(),"listen() called for non-default but complete query"),index_esm2017_assert(!this.listens.get(pathString).has(queryId),"listen() called twice for same path/queryId.");const listenSpec={onComplete,hashFn:currentHashFn,query,tag};this.listens.get(pathString).set(queryId,listenSpec),this.connected_&&this.sendListen_(listenSpec)}sendGet_(index){const get=this.outstandingGets_[index];this.sendRequest("g",get.request,(message=>{delete this.outstandingGets_[index],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),get.onComplete&&get.onComplete(message)}))}sendListen_(listenSpec){const query=listenSpec.query,pathString=query._path.toString(),queryId=query._queryIdentifier;this.log_("Listen on "+pathString+" for "+queryId);const req={p:pathString};listenSpec.tag&&(req.q=query._queryObject,req.t=listenSpec.tag),req.h=listenSpec.hashFn(),this.sendRequest("q",req,(message=>{const payload=message.d,status=message.s;PersistentConnection.warnOnListenWarnings_(payload,query);(this.listens.get(pathString)&&this.listens.get(pathString).get(queryId))===listenSpec&&(this.log_("listen response",message),"ok"!==status&&this.removeListen_(pathString,queryId),listenSpec.onComplete&&listenSpec.onComplete(status,payload))}))}static warnOnListenWarnings_(payload,query){if(payload&&"object"==typeof payload&&index_esm2017_contains(payload,"w")){const warnings=index_esm2017_safeGet(payload,"w");if(Array.isArray(warnings)&&~warnings.indexOf("no_index")){const indexSpec='".indexOn": "'+query._queryParams.getIndex().toString()+'"',indexPath=query._path.toString();warn(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${indexSpec} at ${indexPath} to your security rules for better performance.`)}}}refreshAuthToken(token){this.authToken_=token,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},(()=>{})),this.reduceReconnectDelayIfAdminCredential_(token)}reduceReconnectDelayIfAdminCredential_(credential){(credential&&40===credential.length||function(token){const claims=decode(token).claims;return"object"==typeof claims&&!0===claims.admin}(credential))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(token){this.appCheckToken_=token,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},(()=>{}))}tryAuth(){if(this.connected_&&this.authToken_){const token=this.authToken_,authMethod=function(token){const claims=decode(token).claims;return!!claims&&"object"==typeof claims&&claims.hasOwnProperty("iat")}(token)?"auth":"gauth",requestData={cred:token};null===this.authOverride_?requestData.noauth=!0:"object"==typeof this.authOverride_&&(requestData.authvar=this.authOverride_),this.sendRequest(authMethod,requestData,(res=>{const status=res.s,data=res.d||"error";this.authToken_===token&&("ok"===status?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(status,data))}))}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},(res=>{const status=res.s,data=res.d||"error";"ok"===status?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(status,data)}))}unlisten(query,tag){const pathString=query._path.toString(),queryId=query._queryIdentifier;this.log_("Unlisten called for "+pathString+" "+queryId),index_esm2017_assert(query._queryParams.isDefault()||!query._queryParams.loadsAllData(),"unlisten() called for non-default but complete query");this.removeListen_(pathString,queryId)&&this.connected_&&this.sendUnlisten_(pathString,queryId,query._queryObject,tag)}sendUnlisten_(pathString,queryId,queryObj,tag){this.log_("Unlisten on "+pathString+" for "+queryId);const req={p:pathString};tag&&(req.q=queryObj,req.t=tag),this.sendRequest("n",req)}onDisconnectPut(pathString,data,onComplete){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",pathString,data,onComplete):this.onDisconnectRequestQueue_.push({pathString,action:"o",data,onComplete})}onDisconnectMerge(pathString,data,onComplete){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",pathString,data,onComplete):this.onDisconnectRequestQueue_.push({pathString,action:"om",data,onComplete})}onDisconnectCancel(pathString,onComplete){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",pathString,null,onComplete):this.onDisconnectRequestQueue_.push({pathString,action:"oc",data:null,onComplete})}sendOnDisconnect_(action,pathString,data,onComplete){const request={p:pathString,d:data};this.log_("onDisconnect "+action,request),this.sendRequest(action,request,(response=>{onComplete&&setTimeout((()=>{onComplete(response.s,response.d)}),Math.floor(0))}))}put(pathString,data,onComplete,hash){this.putInternal("p",pathString,data,onComplete,hash)}merge(pathString,data,onComplete,hash){this.putInternal("m",pathString,data,onComplete,hash)}putInternal(action,pathString,data,onComplete,hash){this.initConnection_();const request={p:pathString,d:data};void 0!==hash&&(request.h=hash),this.outstandingPuts_.push({action,request,onComplete}),this.outstandingPutCount_++;const index=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(index):this.log_("Buffering put: "+pathString)}sendPut_(index){const action=this.outstandingPuts_[index].action,request=this.outstandingPuts_[index].request,onComplete=this.outstandingPuts_[index].onComplete;this.outstandingPuts_[index].queued=this.connected_,this.sendRequest(action,request,(message=>{this.log_(action+" response",message),delete this.outstandingPuts_[index],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),onComplete&&onComplete(message.s,message.d)}))}reportStats(stats){if(this.connected_){const request={c:stats};this.log_("reportStats",request),this.sendRequest("s",request,(result=>{if("ok"!==result.s){const errorReason=result.d;this.log_("reportStats","Error sending stats: "+errorReason)}}))}}onDataMessage_(message){if("r"in message){this.log_("from server: "+stringify(message));const reqNum=message.r,onResponse=this.requestCBHash_[reqNum];onResponse&&(delete this.requestCBHash_[reqNum],onResponse(message.b))}else{if("error"in message)throw"A server-side error has occurred: "+message.error;"a"in message&&this.onDataPush_(message.a,message.b)}}onDataPush_(action,body){this.log_("handleServerMessage",action,body),"d"===action?this.onDataUpdate_(body.p,body.d,!1,body.t):"m"===action?this.onDataUpdate_(body.p,body.d,!0,body.t):"c"===action?this.onListenRevoked_(body.p,body.q):"ac"===action?this.onAuthRevoked_(body.s,body.d):"apc"===action?this.onAppCheckRevoked_(body.s,body.d):"sd"===action?this.onSecurityDebugPacket_(body):error("Unrecognized action received from server: "+stringify(action)+"\nAre you using the latest client?")}onReady_(timestamp,sessionId){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(timestamp),this.lastSessionId=sessionId,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(timeout){index_esm2017_assert(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout((()=>{this.establishConnectionTimer_=null,this.establishConnection_()}),Math.floor(timeout))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(visible){visible&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=visible}onOnline_(online){online?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline. Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){if(this.visible_){if(this.lastConnectionEstablishedTime_){(new Date).getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();const timeSinceLastConnectAttempt=(new Date).getTime()-this.lastConnectionAttemptTime_;let reconnectDelay=Math.max(0,this.reconnectDelay_-timeSinceLastConnectAttempt);reconnectDelay=Math.random()*reconnectDelay,this.log_("Trying to reconnect in "+reconnectDelay+"ms"),this.scheduleConnect_(reconnectDelay),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;const onDataMessage=this.onDataMessage_.bind(this),onReady=this.onReady_.bind(this),onDisconnect=this.onRealtimeDisconnect_.bind(this),connId=this.id+":"+PersistentConnection.nextConnectionId_++,lastSessionId=this.lastSessionId;let canceled=!1,connection=null;const closeFn=function(){connection?connection.close():(canceled=!0,onDisconnect())},sendRequestFn=function(msg){index_esm2017_assert(connection,"sendRequest call when we're not connected not allowed."),connection.sendRequest(msg)};this.realtime_={close:closeFn,sendRequest:sendRequestFn};const forceRefresh=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[authToken,appCheckToken]=await Promise.all([this.authTokenProvider_.getToken(forceRefresh),this.appCheckTokenProvider_.getToken(forceRefresh)]);canceled?log("getToken() completed but was canceled"):(log("getToken() completed. Creating connection."),this.authToken_=authToken&&authToken.accessToken,this.appCheckToken_=appCheckToken&&appCheckToken.token,connection=new Connection(connId,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,onDataMessage,onReady,onDisconnect,(reason=>{warn(reason+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")}),lastSessionId))}catch(error){this.log_("Failed to get token: "+error),canceled||(this.repoInfo_.nodeAdmin&&warn(error),closeFn())}}}interrupt(reason){log("Interrupting connection for reason: "+reason),this.interruptReasons_[reason]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(reason){log("Resuming connection for reason: "+reason),delete this.interruptReasons_[reason],index_esm2017_isEmpty(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(timestamp){const delta=timestamp-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:delta})}cancelSentTransactions_(){for(let i=0;i<this.outstandingPuts_.length;i++){const put=this.outstandingPuts_[i];put&&"h"in put.request&&put.queued&&(put.onComplete&&put.onComplete("disconnect"),delete this.outstandingPuts_[i],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(pathString,query){let queryId;queryId=query?query.map((q=>ObjectToUniqueKey(q))).join("$"):"default";const listen=this.removeListen_(pathString,queryId);listen&&listen.onComplete&&listen.onComplete("permission_denied")}removeListen_(pathString,queryId){const normalizedPathString=new Path(pathString).toString();let listen;if(this.listens.has(normalizedPathString)){const map=this.listens.get(normalizedPathString);listen=map.get(queryId),map.delete(queryId),0===map.size&&this.listens.delete(normalizedPathString)}else listen=void 0;return listen}onAuthRevoked_(statusCode,explanation){log("Auth token revoked: "+statusCode+"/"+explanation),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==statusCode&&"permission_denied"!==statusCode||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(statusCode,explanation){log("App check token revoked: "+statusCode+"/"+explanation),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==statusCode&&"permission_denied"!==statusCode||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(body){this.securityDebugCallback_?this.securityDebugCallback_(body):"msg"in body&&console.log("FIREBASE: "+body.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const queries of this.listens.values())for(const listenSpec of queries.values())this.sendListen_(listenSpec);for(let i=0;i<this.outstandingPuts_.length;i++)this.outstandingPuts_[i]&&this.sendPut_(i);for(;this.onDisconnectRequestQueue_.length;){const request=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(request.action,request.pathString,request.data,request.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){const stats={};let clientName="js";isNodeSdk()&&(clientName=this.repoInfo_.nodeAdmin?"admin_node":"node"),stats["sdk."+clientName+"."+index_esm2017_SDK_VERSION.replace(/\./g,"-")]=1,isMobileCordova()?stats["framework.cordova"]=1:function isReactNative(){return"object"==typeof navigator&&"ReactNative"===navigator.product}()&&(stats["framework.reactnative"]=1),this.reportStats(stats)}shouldReconnect_(){const online=OnlineMonitor.getInstance().currentlyOnline();return index_esm2017_isEmpty(this.interruptReasons_)&&online}}PersistentConnection.nextPersistentConnectionId_=0,PersistentConnection.nextConnectionId_=0;class NamedNode{constructor(name,node){this.name=name,this.node=node}static Wrap(name,node){return new NamedNode(name,node)}}class Index{getCompare(){return this.compare.bind(this)}indexedValueChanged(oldNode,newNode){const oldWrapped=new NamedNode(MIN_NAME,oldNode),newWrapped=new NamedNode(MIN_NAME,newNode);return 0!==this.compare(oldWrapped,newWrapped)}minPost(){return NamedNode.MIN}}let __EMPTY_NODE;class KeyIndex extends Index{static get __EMPTY_NODE(){return __EMPTY_NODE}static set __EMPTY_NODE(val){__EMPTY_NODE=val}compare(a,b){return nameCompare(a.name,b.name)}isDefinedOn(node){throw assertionError("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(oldNode,newNode){return!1}minPost(){return NamedNode.MIN}maxPost(){return new NamedNode(MAX_NAME,__EMPTY_NODE)}makePost(indexValue,name){return index_esm2017_assert("string"==typeof indexValue,"KeyIndex indexValue must always be a string."),new NamedNode(indexValue,__EMPTY_NODE)}toString(){return".key"}}const KEY_INDEX=new KeyIndex;class SortedMapIterator{constructor(node,startKey,comparator,isReverse_,resultGenerator_=null){this.isReverse_=isReverse_,this.resultGenerator_=resultGenerator_,this.nodeStack_=[];let cmp=1;for(;!node.isEmpty();)if(cmp=startKey?comparator(node.key,startKey):1,isReverse_&&(cmp*=-1),cmp<0)node=this.isReverse_?node.left:node.right;else{if(0===cmp){this.nodeStack_.push(node);break}this.nodeStack_.push(node),node=this.isReverse_?node.right:node.left}}getNext(){if(0===this.nodeStack_.length)return null;let result,node=this.nodeStack_.pop();if(result=this.resultGenerator_?this.resultGenerator_(node.key,node.value):{key:node.key,value:node.value},this.isReverse_)for(node=node.left;!node.isEmpty();)this.nodeStack_.push(node),node=node.right;else for(node=node.right;!node.isEmpty();)this.nodeStack_.push(node),node=node.left;return result}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;const node=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(node.key,node.value):{key:node.key,value:node.value}}}class LLRBNode{constructor(key,value,color,left,right){this.key=key,this.value=value,this.color=null!=color?color:LLRBNode.RED,this.left=null!=left?left:SortedMap.EMPTY_NODE,this.right=null!=right?right:SortedMap.EMPTY_NODE}copy(key,value,color,left,right){return new LLRBNode(null!=key?key:this.key,null!=value?value:this.value,null!=color?color:this.color,null!=left?left:this.left,null!=right?right:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(action){return this.left.inorderTraversal(action)||!!action(this.key,this.value)||this.right.inorderTraversal(action)}reverseTraversal(action){return this.right.reverseTraversal(action)||action(this.key,this.value)||this.left.reverseTraversal(action)}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(key,value,comparator){let n=this;const cmp=comparator(key,n.key);return n=cmp<0?n.copy(null,null,null,n.left.insert(key,value,comparator),null):0===cmp?n.copy(null,value,null,null,null):n.copy(null,null,null,null,n.right.insert(key,value,comparator)),n.fixUp_()}removeMin_(){if(this.left.isEmpty())return SortedMap.EMPTY_NODE;let n=this;return n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.removeMin_(),null),n.fixUp_()}remove(key,comparator){let n,smallest;if(n=this,comparator(key,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(key,comparator),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===comparator(key,n.key)){if(n.right.isEmpty())return SortedMap.EMPTY_NODE;smallest=n.right.min_(),n=n.copy(smallest.key,smallest.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(key,comparator))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let n=this;return n.right.isRed_()&&!n.left.isRed_()&&(n=n.rotateLeft_()),n.left.isRed_()&&n.left.left.isRed_()&&(n=n.rotateRight_()),n.left.isRed_()&&n.right.isRed_()&&(n=n.colorFlip_()),n}moveRedLeft_(){let n=this.colorFlip_();return n.right.left.isRed_()&&(n=n.copy(null,null,null,null,n.right.rotateRight_()),n=n.rotateLeft_(),n=n.colorFlip_()),n}moveRedRight_(){let n=this.colorFlip_();return n.left.left.isRed_()&&(n=n.rotateRight_(),n=n.colorFlip_()),n}rotateLeft_(){const nl=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,nl,null)}rotateRight_(){const nr=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,nr)}colorFlip_(){const left=this.left.copy(null,null,!this.left.color,null,null),right=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,left,right)}checkMaxDepth_(){const blackDepth=this.check_();return Math.pow(2,blackDepth)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const blackDepth=this.left.check_();if(blackDepth!==this.right.check_())throw new Error("Black depths differ");return blackDepth+(this.isRed_()?0:1)}}LLRBNode.RED=!0,LLRBNode.BLACK=!1;class SortedMap{constructor(comparator_,root_=SortedMap.EMPTY_NODE){this.comparator_=comparator_,this.root_=root_}insert(key,value){return new SortedMap(this.comparator_,this.root_.insert(key,value,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))}remove(key){return new SortedMap(this.comparator_,this.root_.remove(key,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))}get(key){let cmp,node=this.root_;for(;!node.isEmpty();){if(cmp=this.comparator_(key,node.key),0===cmp)return node.value;cmp<0?node=node.left:cmp>0&&(node=node.right)}return null}getPredecessorKey(key){let cmp,node=this.root_,rightParent=null;for(;!node.isEmpty();){if(cmp=this.comparator_(key,node.key),0===cmp){if(node.left.isEmpty())return rightParent?rightParent.key:null;for(node=node.left;!node.right.isEmpty();)node=node.right;return node.key}cmp<0?node=node.left:cmp>0&&(rightParent=node,node=node.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(action){return this.root_.inorderTraversal(action)}reverseTraversal(action){return this.root_.reverseTraversal(action)}getIterator(resultGenerator){return new SortedMapIterator(this.root_,null,this.comparator_,!1,resultGenerator)}getIteratorFrom(key,resultGenerator){return new SortedMapIterator(this.root_,key,this.comparator_,!1,resultGenerator)}getReverseIteratorFrom(key,resultGenerator){return new SortedMapIterator(this.root_,key,this.comparator_,!0,resultGenerator)}getReverseIterator(resultGenerator){return new SortedMapIterator(this.root_,null,this.comparator_,!0,resultGenerator)}}function NAME_ONLY_COMPARATOR(left,right){return nameCompare(left.name,right.name)}function NAME_COMPARATOR(left,right){return nameCompare(left,right)}let MAX_NODE$2;SortedMap.EMPTY_NODE=new class LLRBEmptyNode{copy(key,value,color,left,right){return this}insert(key,value,comparator){return new LLRBNode(key,value,null)}remove(key,comparator){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(action){return!1}reverseTraversal(action){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};const priorityHashText=function(priority){return"number"==typeof priority?"number:"+doubleToIEEE754String(priority):"string:"+priority},validatePriorityNode=function(priorityNode){if(priorityNode.isLeafNode()){const val=priorityNode.val();index_esm2017_assert("string"==typeof val||"number"==typeof val||"object"==typeof val&&index_esm2017_contains(val,".sv"),"Priority must be a string or number.")}else index_esm2017_assert(priorityNode===MAX_NODE$2||priorityNode.isEmpty(),"priority of unexpected type.");index_esm2017_assert(priorityNode===MAX_NODE$2||priorityNode.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let __childrenNodeConstructor,nodeFromJSON$1,MAX_NODE$1;class LeafNode{constructor(value_,priorityNode_=LeafNode.__childrenNodeConstructor.EMPTY_NODE){this.value_=value_,this.priorityNode_=priorityNode_,this.lazyHash_=null,index_esm2017_assert(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),validatePriorityNode(this.priorityNode_)}static set __childrenNodeConstructor(val){__childrenNodeConstructor=val}static get __childrenNodeConstructor(){return __childrenNodeConstructor}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(newPriorityNode){return new LeafNode(this.value_,newPriorityNode)}getImmediateChild(childName){return".priority"===childName?this.priorityNode_:LeafNode.__childrenNodeConstructor.EMPTY_NODE}getChild(path){return pathIsEmpty(path)?this:".priority"===pathGetFront(path)?this.priorityNode_:LeafNode.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(childName,childNode){return null}updateImmediateChild(childName,newChildNode){return".priority"===childName?this.updatePriority(newChildNode):newChildNode.isEmpty()&&".priority"!==childName?this:LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName,newChildNode).updatePriority(this.priorityNode_)}updateChild(path,newChildNode){const front=pathGetFront(path);return null===front?newChildNode:newChildNode.isEmpty()&&".priority"!==front?this:(index_esm2017_assert(".priority"!==front||1===pathGetLength(path),".priority must be the last token in a path"),this.updateImmediateChild(front,LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path),newChildNode)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(index,action){return!1}val(exportFormat){return exportFormat&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let toHash="";this.priorityNode_.isEmpty()||(toHash+="priority:"+priorityHashText(this.priorityNode_.val())+":");const type=typeof this.value_;toHash+=type+":",toHash+="number"===type?doubleToIEEE754String(this.value_):this.value_,this.lazyHash_=sha1(toHash)}return this.lazyHash_}getValue(){return this.value_}compareTo(other){return other===LeafNode.__childrenNodeConstructor.EMPTY_NODE?1:other instanceof LeafNode.__childrenNodeConstructor?-1:(index_esm2017_assert(other.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(other))}compareToLeafNode_(otherLeaf){const otherLeafType=typeof otherLeaf.value_,thisLeafType=typeof this.value_,otherIndex=LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType),thisIndex=LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);return index_esm2017_assert(otherIndex>=0,"Unknown leaf type: "+otherLeafType),index_esm2017_assert(thisIndex>=0,"Unknown leaf type: "+thisLeafType),otherIndex===thisIndex?"object"===thisLeafType?0:this.value_<otherLeaf.value_?-1:this.value_===otherLeaf.value_?0:1:thisIndex-otherIndex}withIndex(){return this}isIndexed(){return!0}equals(other){if(other===this)return!0;if(other.isLeafNode()){const otherLeaf=other;return this.value_===otherLeaf.value_&&this.priorityNode_.equals(otherLeaf.priorityNode_)}return!1}}LeafNode.VALUE_TYPE_ORDER=["object","boolean","number","string"];const PRIORITY_INDEX=new class PriorityIndex extends Index{compare(a,b){const aPriority=a.node.getPriority(),bPriority=b.node.getPriority(),indexCmp=aPriority.compareTo(bPriority);return 0===indexCmp?nameCompare(a.name,b.name):indexCmp}isDefinedOn(node){return!node.getPriority().isEmpty()}indexedValueChanged(oldNode,newNode){return!oldNode.getPriority().equals(newNode.getPriority())}minPost(){return NamedNode.MIN}maxPost(){return new NamedNode(MAX_NAME,new LeafNode("[PRIORITY-POST]",MAX_NODE$1))}makePost(indexValue,name){const priorityNode=nodeFromJSON$1(indexValue);return new NamedNode(name,new LeafNode("[PRIORITY-POST]",priorityNode))}toString(){return".priority"}},LOG_2=Math.log(2);class Base12Num{constructor(length){var num;this.count=(num=length+1,parseInt(Math.log(num)/LOG_2,10)),this.current_=this.count-1;const mask=(bits=this.count,parseInt(Array(bits+1).join("1"),2));var bits;this.bits_=length+1&mask}nextBitIsOne(){const result=!(this.bits_&1<<this.current_);return this.current_--,result}}const buildChildSet=function(childList,cmp,keyFn,mapSortFn){childList.sort(cmp);const buildBalancedTree=function(low,high){const length=high-low;let namedNode,key;if(0===length)return null;if(1===length)return namedNode=childList[low],key=keyFn?keyFn(namedNode):namedNode,new LLRBNode(key,namedNode.node,LLRBNode.BLACK,null,null);{const middle=parseInt(length/2,10)+low,left=buildBalancedTree(low,middle),right=buildBalancedTree(middle+1,high);return namedNode=childList[middle],key=keyFn?keyFn(namedNode):namedNode,new LLRBNode(key,namedNode.node,LLRBNode.BLACK,left,right)}},root=function(base12){let node=null,root=null,index=childList.length;const buildPennant=function(chunkSize,color){const low=index-chunkSize,high=index;index-=chunkSize;const childTree=buildBalancedTree(low+1,high),namedNode=childList[low],key=keyFn?keyFn(namedNode):namedNode;attachPennant(new LLRBNode(key,namedNode.node,color,null,childTree))},attachPennant=function(pennant){node?(node.left=pennant,node=pennant):(root=pennant,node=pennant)};for(let i=0;i<base12.count;++i){const isOne=base12.nextBitIsOne(),chunkSize=Math.pow(2,base12.count-(i+1));isOne?buildPennant(chunkSize,LLRBNode.BLACK):(buildPennant(chunkSize,LLRBNode.BLACK),buildPennant(chunkSize,LLRBNode.RED))}return root}(new Base12Num(childList.length));return new SortedMap(mapSortFn||cmp,root)};let _defaultIndexMap;const fallbackObject={};class IndexMap{constructor(indexes_,indexSet_){this.indexes_=indexes_,this.indexSet_=indexSet_}static get Default(){return index_esm2017_assert(fallbackObject&&PRIORITY_INDEX,"ChildrenNode.ts has not been loaded"),_defaultIndexMap=_defaultIndexMap||new IndexMap({".priority":fallbackObject},{".priority":PRIORITY_INDEX}),_defaultIndexMap}get(indexKey){const sortedMap=index_esm2017_safeGet(this.indexes_,indexKey);if(!sortedMap)throw new Error("No index defined for "+indexKey);return sortedMap instanceof SortedMap?sortedMap:null}hasIndex(indexDefinition){return index_esm2017_contains(this.indexSet_,indexDefinition.toString())}addIndex(indexDefinition,existingChildren){index_esm2017_assert(indexDefinition!==KEY_INDEX,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const childList=[];let sawIndexedValue=!1;const iter=existingChildren.getIterator(NamedNode.Wrap);let newIndex,next=iter.getNext();for(;next;)sawIndexedValue=sawIndexedValue||indexDefinition.isDefinedOn(next.node),childList.push(next),next=iter.getNext();newIndex=sawIndexedValue?buildChildSet(childList,indexDefinition.getCompare()):fallbackObject;const indexName=indexDefinition.toString(),newIndexSet=Object.assign({},this.indexSet_);newIndexSet[indexName]=indexDefinition;const newIndexes=Object.assign({},this.indexes_);return newIndexes[indexName]=newIndex,new IndexMap(newIndexes,newIndexSet)}addToIndexes(namedNode,existingChildren){const newIndexes=map(this.indexes_,((indexedChildren,indexName)=>{const index=index_esm2017_safeGet(this.indexSet_,indexName);if(index_esm2017_assert(index,"Missing index implementation for "+indexName),indexedChildren===fallbackObject){if(index.isDefinedOn(namedNode.node)){const childList=[],iter=existingChildren.getIterator(NamedNode.Wrap);let next=iter.getNext();for(;next;)next.name!==namedNode.name&&childList.push(next),next=iter.getNext();return childList.push(namedNode),buildChildSet(childList,index.getCompare())}return fallbackObject}{const existingSnap=existingChildren.get(namedNode.name);let newChildren=indexedChildren;return existingSnap&&(newChildren=newChildren.remove(new NamedNode(namedNode.name,existingSnap))),newChildren.insert(namedNode,namedNode.node)}}));return new IndexMap(newIndexes,this.indexSet_)}removeFromIndexes(namedNode,existingChildren){const newIndexes=map(this.indexes_,(indexedChildren=>{if(indexedChildren===fallbackObject)return indexedChildren;{const existingSnap=existingChildren.get(namedNode.name);return existingSnap?indexedChildren.remove(new NamedNode(namedNode.name,existingSnap)):indexedChildren}}));return new IndexMap(newIndexes,this.indexSet_)}}let EMPTY_NODE;class ChildrenNode{constructor(children_,priorityNode_,indexMap_){this.children_=children_,this.priorityNode_=priorityNode_,this.indexMap_=indexMap_,this.lazyHash_=null,this.priorityNode_&&validatePriorityNode(this.priorityNode_),this.children_.isEmpty()&&index_esm2017_assert(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return EMPTY_NODE||(EMPTY_NODE=new ChildrenNode(new SortedMap(NAME_COMPARATOR),null,IndexMap.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||EMPTY_NODE}updatePriority(newPriorityNode){return this.children_.isEmpty()?this:new ChildrenNode(this.children_,newPriorityNode,this.indexMap_)}getImmediateChild(childName){if(".priority"===childName)return this.getPriority();{const child=this.children_.get(childName);return null===child?EMPTY_NODE:child}}getChild(path){const front=pathGetFront(path);return null===front?this:this.getImmediateChild(front).getChild(pathPopFront(path))}hasChild(childName){return null!==this.children_.get(childName)}updateImmediateChild(childName,newChildNode){if(index_esm2017_assert(newChildNode,"We should always be passing snapshot nodes"),".priority"===childName)return this.updatePriority(newChildNode);{const namedNode=new NamedNode(childName,newChildNode);let newChildren,newIndexMap;newChildNode.isEmpty()?(newChildren=this.children_.remove(childName),newIndexMap=this.indexMap_.removeFromIndexes(namedNode,this.children_)):(newChildren=this.children_.insert(childName,newChildNode),newIndexMap=this.indexMap_.addToIndexes(namedNode,this.children_));const newPriority=newChildren.isEmpty()?EMPTY_NODE:this.priorityNode_;return new ChildrenNode(newChildren,newPriority,newIndexMap)}}updateChild(path,newChildNode){const front=pathGetFront(path);if(null===front)return newChildNode;{index_esm2017_assert(".priority"!==pathGetFront(path)||1===pathGetLength(path),".priority must be the last token in a path");const newImmediateChild=this.getImmediateChild(front).updateChild(pathPopFront(path),newChildNode);return this.updateImmediateChild(front,newImmediateChild)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(exportFormat){if(this.isEmpty())return null;const obj={};let numKeys=0,maxKey=0,allIntegerKeys=!0;if(this.forEachChild(PRIORITY_INDEX,((key,childNode)=>{obj[key]=childNode.val(exportFormat),numKeys++,allIntegerKeys&&ChildrenNode.INTEGER_REGEXP_.test(key)?maxKey=Math.max(maxKey,Number(key)):allIntegerKeys=!1})),!exportFormat&&allIntegerKeys&&maxKey<2*numKeys){const array=[];for(const key in obj)array[key]=obj[key];return array}return exportFormat&&!this.getPriority().isEmpty()&&(obj[".priority"]=this.getPriority().val()),obj}hash(){if(null===this.lazyHash_){let toHash="";this.getPriority().isEmpty()||(toHash+="priority:"+priorityHashText(this.getPriority().val())+":"),this.forEachChild(PRIORITY_INDEX,((key,childNode)=>{const childHash=childNode.hash();""!==childHash&&(toHash+=":"+key+":"+childHash)})),this.lazyHash_=""===toHash?"":sha1(toHash)}return this.lazyHash_}getPredecessorChildName(childName,childNode,index){const idx=this.resolveIndex_(index);if(idx){const predecessor=idx.getPredecessorKey(new NamedNode(childName,childNode));return predecessor?predecessor.name:null}return this.children_.getPredecessorKey(childName)}getFirstChildName(indexDefinition){const idx=this.resolveIndex_(indexDefinition);if(idx){const minKey=idx.minKey();return minKey&&minKey.name}return this.children_.minKey()}getFirstChild(indexDefinition){const minKey=this.getFirstChildName(indexDefinition);return minKey?new NamedNode(minKey,this.children_.get(minKey)):null}getLastChildName(indexDefinition){const idx=this.resolveIndex_(indexDefinition);if(idx){const maxKey=idx.maxKey();return maxKey&&maxKey.name}return this.children_.maxKey()}getLastChild(indexDefinition){const maxKey=this.getLastChildName(indexDefinition);return maxKey?new NamedNode(maxKey,this.children_.get(maxKey)):null}forEachChild(index,action){const idx=this.resolveIndex_(index);return idx?idx.inorderTraversal((wrappedNode=>action(wrappedNode.name,wrappedNode.node))):this.children_.inorderTraversal(action)}getIterator(indexDefinition){return this.getIteratorFrom(indexDefinition.minPost(),indexDefinition)}getIteratorFrom(startPost,indexDefinition){const idx=this.resolveIndex_(indexDefinition);if(idx)return idx.getIteratorFrom(startPost,(key=>key));{const iterator=this.children_.getIteratorFrom(startPost.name,NamedNode.Wrap);let next=iterator.peek();for(;null!=next&&indexDefinition.compare(next,startPost)<0;)iterator.getNext(),next=iterator.peek();return iterator}}getReverseIterator(indexDefinition){return this.getReverseIteratorFrom(indexDefinition.maxPost(),indexDefinition)}getReverseIteratorFrom(endPost,indexDefinition){const idx=this.resolveIndex_(indexDefinition);if(idx)return idx.getReverseIteratorFrom(endPost,(key=>key));{const iterator=this.children_.getReverseIteratorFrom(endPost.name,NamedNode.Wrap);let next=iterator.peek();for(;null!=next&&indexDefinition.compare(next,endPost)>0;)iterator.getNext(),next=iterator.peek();return iterator}}compareTo(other){return this.isEmpty()?other.isEmpty()?0:-1:other.isLeafNode()||other.isEmpty()?1:other===MAX_NODE?-1:0}withIndex(indexDefinition){if(indexDefinition===KEY_INDEX||this.indexMap_.hasIndex(indexDefinition))return this;{const newIndexMap=this.indexMap_.addIndex(indexDefinition,this.children_);return new ChildrenNode(this.children_,this.priorityNode_,newIndexMap)}}isIndexed(index){return index===KEY_INDEX||this.indexMap_.hasIndex(index)}equals(other){if(other===this)return!0;if(other.isLeafNode())return!1;{const otherChildrenNode=other;if(this.getPriority().equals(otherChildrenNode.getPriority())){if(this.children_.count()===otherChildrenNode.children_.count()){const thisIter=this.getIterator(PRIORITY_INDEX),otherIter=otherChildrenNode.getIterator(PRIORITY_INDEX);let thisCurrent=thisIter.getNext(),otherCurrent=otherIter.getNext();for(;thisCurrent&&otherCurrent;){if(thisCurrent.name!==otherCurrent.name||!thisCurrent.node.equals(otherCurrent.node))return!1;thisCurrent=thisIter.getNext(),otherCurrent=otherIter.getNext()}return null===thisCurrent&&null===otherCurrent}return!1}return!1}}resolveIndex_(indexDefinition){return indexDefinition===KEY_INDEX?null:this.indexMap_.get(indexDefinition.toString())}}ChildrenNode.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const MAX_NODE=new class MaxNode extends ChildrenNode{constructor(){super(new SortedMap(NAME_COMPARATOR),ChildrenNode.EMPTY_NODE,IndexMap.Default)}compareTo(other){return other===this?0:1}equals(other){return other===this}getPriority(){return this}getImmediateChild(childName){return ChildrenNode.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(NamedNode,{MIN:{value:new NamedNode(MIN_NAME,ChildrenNode.EMPTY_NODE)},MAX:{value:new NamedNode(MAX_NAME,MAX_NODE)}}),KeyIndex.__EMPTY_NODE=ChildrenNode.EMPTY_NODE,LeafNode.__childrenNodeConstructor=ChildrenNode,function setMaxNode$1(val){MAX_NODE$2=val}(MAX_NODE),function setMaxNode(val){MAX_NODE$1=val}(MAX_NODE);const USE_HINZE=!0;function nodeFromJSON(json,priority=null){if(null===json)return ChildrenNode.EMPTY_NODE;if("object"==typeof json&&".priority"in json&&(priority=json[".priority"]),index_esm2017_assert(null===priority||"string"==typeof priority||"number"==typeof priority||"object"==typeof priority&&".sv"in priority,"Invalid priority type found: "+typeof priority),"object"==typeof json&&".value"in json&&null!==json[".value"]&&(json=json[".value"]),"object"!=typeof json||".sv"in json){return new LeafNode(json,nodeFromJSON(priority))}if(json instanceof Array||!USE_HINZE){let node=ChildrenNode.EMPTY_NODE;return each(json,((key,childData)=>{if(index_esm2017_contains(json,key)&&"."!==key.substring(0,1)){const childNode=nodeFromJSON(childData);!childNode.isLeafNode()&&childNode.isEmpty()||(node=node.updateImmediateChild(key,childNode))}})),node.updatePriority(nodeFromJSON(priority))}{const children=[];let childrenHavePriority=!1;if(each(json,((key,child)=>{if("."!==key.substring(0,1)){const childNode=nodeFromJSON(child);childNode.isEmpty()||(childrenHavePriority=childrenHavePriority||!childNode.getPriority().isEmpty(),children.push(new NamedNode(key,childNode)))}})),0===children.length)return ChildrenNode.EMPTY_NODE;const childSet=buildChildSet(children,NAME_ONLY_COMPARATOR,(namedNode=>namedNode.name),NAME_COMPARATOR);if(childrenHavePriority){const sortedChildSet=buildChildSet(children,PRIORITY_INDEX.getCompare());return new ChildrenNode(childSet,nodeFromJSON(priority),new IndexMap({".priority":sortedChildSet},{".priority":PRIORITY_INDEX}))}return new ChildrenNode(childSet,nodeFromJSON(priority),IndexMap.Default)}}!function setNodeFromJSON(val){nodeFromJSON$1=val}(nodeFromJSON);class PathIndex extends Index{constructor(indexPath_){super(),this.indexPath_=indexPath_,index_esm2017_assert(!pathIsEmpty(indexPath_)&&".priority"!==pathGetFront(indexPath_),"Can't create PathIndex with empty path or .priority key")}extractChild(snap){return snap.getChild(this.indexPath_)}isDefinedOn(node){return!node.getChild(this.indexPath_).isEmpty()}compare(a,b){const aChild=this.extractChild(a.node),bChild=this.extractChild(b.node),indexCmp=aChild.compareTo(bChild);return 0===indexCmp?nameCompare(a.name,b.name):indexCmp}makePost(indexValue,name){const valueNode=nodeFromJSON(indexValue),node=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,valueNode);return new NamedNode(name,node)}maxPost(){const node=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,MAX_NODE);return new NamedNode(MAX_NAME,node)}toString(){return pathSlice(this.indexPath_,0).join("/")}}const VALUE_INDEX=new class ValueIndex extends Index{compare(a,b){const indexCmp=a.node.compareTo(b.node);return 0===indexCmp?nameCompare(a.name,b.name):indexCmp}isDefinedOn(node){return!0}indexedValueChanged(oldNode,newNode){return!oldNode.equals(newNode)}minPost(){return NamedNode.MIN}maxPost(){return NamedNode.MAX}makePost(indexValue,name){const valueNode=nodeFromJSON(indexValue);return new NamedNode(name,valueNode)}toString(){return".value"}};function changeValue(snapshotNode){return{type:"value",snapshotNode}}function changeChildAdded(childName,snapshotNode){return{type:"child_added",snapshotNode,childName}}function changeChildRemoved(childName,snapshotNode){return{type:"child_removed",snapshotNode,childName}}function changeChildChanged(childName,snapshotNode,oldSnap){return{type:"child_changed",snapshotNode,childName,oldSnap}}class IndexedFilter{constructor(index_){this.index_=index_}updateChild(snap,key,newChild,affectedPath,source,optChangeAccumulator){index_esm2017_assert(snap.isIndexed(this.index_),"A node must be indexed if only a child is updated");const oldChild=snap.getImmediateChild(key);return oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))&&oldChild.isEmpty()===newChild.isEmpty()?snap:(null!=optChangeAccumulator&&(newChild.isEmpty()?snap.hasChild(key)?optChangeAccumulator.trackChildChange(changeChildRemoved(key,oldChild)):index_esm2017_assert(snap.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):oldChild.isEmpty()?optChangeAccumulator.trackChildChange(changeChildAdded(key,newChild)):optChangeAccumulator.trackChildChange(changeChildChanged(key,newChild,oldChild))),snap.isLeafNode()&&newChild.isEmpty()?snap:snap.updateImmediateChild(key,newChild).withIndex(this.index_))}updateFullNode(oldSnap,newSnap,optChangeAccumulator){return null!=optChangeAccumulator&&(oldSnap.isLeafNode()||oldSnap.forEachChild(PRIORITY_INDEX,((key,childNode)=>{newSnap.hasChild(key)||optChangeAccumulator.trackChildChange(changeChildRemoved(key,childNode))})),newSnap.isLeafNode()||newSnap.forEachChild(PRIORITY_INDEX,((key,childNode)=>{if(oldSnap.hasChild(key)){const oldChild=oldSnap.getImmediateChild(key);oldChild.equals(childNode)||optChangeAccumulator.trackChildChange(changeChildChanged(key,childNode,oldChild))}else optChangeAccumulator.trackChildChange(changeChildAdded(key,childNode))}))),newSnap.withIndex(this.index_)}updatePriority(oldSnap,newPriority){return oldSnap.isEmpty()?ChildrenNode.EMPTY_NODE:oldSnap.updatePriority(newPriority)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class RangedFilter{constructor(params){this.indexedFilter_=new IndexedFilter(params.getIndex()),this.index_=params.getIndex(),this.startPost_=RangedFilter.getStartPost_(params),this.endPost_=RangedFilter.getEndPost_(params),this.startIsInclusive_=!params.startAfterSet_,this.endIsInclusive_=!params.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(node){const isWithinStart=this.startIsInclusive_?this.index_.compare(this.getStartPost(),node)<=0:this.index_.compare(this.getStartPost(),node)<0,isWithinEnd=this.endIsInclusive_?this.index_.compare(node,this.getEndPost())<=0:this.index_.compare(node,this.getEndPost())<0;return isWithinStart&&isWithinEnd}updateChild(snap,key,newChild,affectedPath,source,optChangeAccumulator){return this.matches(new NamedNode(key,newChild))||(newChild=ChildrenNode.EMPTY_NODE),this.indexedFilter_.updateChild(snap,key,newChild,affectedPath,source,optChangeAccumulator)}updateFullNode(oldSnap,newSnap,optChangeAccumulator){newSnap.isLeafNode()&&(newSnap=ChildrenNode.EMPTY_NODE);let filtered=newSnap.withIndex(this.index_);filtered=filtered.updatePriority(ChildrenNode.EMPTY_NODE);const self=this;return newSnap.forEachChild(PRIORITY_INDEX,((key,childNode)=>{self.matches(new NamedNode(key,childNode))||(filtered=filtered.updateImmediateChild(key,ChildrenNode.EMPTY_NODE))})),this.indexedFilter_.updateFullNode(oldSnap,filtered,optChangeAccumulator)}updatePriority(oldSnap,newPriority){return oldSnap}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(params){if(params.hasStart()){const startName=params.getIndexStartName();return params.getIndex().makePost(params.getIndexStartValue(),startName)}return params.getIndex().minPost()}static getEndPost_(params){if(params.hasEnd()){const endName=params.getIndexEndName();return params.getIndex().makePost(params.getIndexEndValue(),endName)}return params.getIndex().maxPost()}}class LimitedFilter{constructor(params){this.withinDirectionalStart=node=>this.reverse_?this.withinEndPost(node):this.withinStartPost(node),this.withinDirectionalEnd=node=>this.reverse_?this.withinStartPost(node):this.withinEndPost(node),this.withinStartPost=node=>{const compareRes=this.index_.compare(this.rangedFilter_.getStartPost(),node);return this.startIsInclusive_?compareRes<=0:compareRes<0},this.withinEndPost=node=>{const compareRes=this.index_.compare(node,this.rangedFilter_.getEndPost());return this.endIsInclusive_?compareRes<=0:compareRes<0},this.rangedFilter_=new RangedFilter(params),this.index_=params.getIndex(),this.limit_=params.getLimit(),this.reverse_=!params.isViewFromLeft(),this.startIsInclusive_=!params.startAfterSet_,this.endIsInclusive_=!params.endBeforeSet_}updateChild(snap,key,newChild,affectedPath,source,optChangeAccumulator){return this.rangedFilter_.matches(new NamedNode(key,newChild))||(newChild=ChildrenNode.EMPTY_NODE),snap.getImmediateChild(key).equals(newChild)?snap:snap.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(snap,key,newChild,affectedPath,source,optChangeAccumulator):this.fullLimitUpdateChild_(snap,key,newChild,source,optChangeAccumulator)}updateFullNode(oldSnap,newSnap,optChangeAccumulator){let filtered;if(newSnap.isLeafNode()||newSnap.isEmpty())filtered=ChildrenNode.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<newSnap.numChildren()&&newSnap.isIndexed(this.index_)){let iterator;filtered=ChildrenNode.EMPTY_NODE.withIndex(this.index_),iterator=this.reverse_?newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let count=0;for(;iterator.hasNext()&&count<this.limit_;){const next=iterator.getNext();if(this.withinDirectionalStart(next)){if(!this.withinDirectionalEnd(next))break;filtered=filtered.updateImmediateChild(next.name,next.node),count++}}}else{let iterator;filtered=newSnap.withIndex(this.index_),filtered=filtered.updatePriority(ChildrenNode.EMPTY_NODE),iterator=this.reverse_?filtered.getReverseIterator(this.index_):filtered.getIterator(this.index_);let count=0;for(;iterator.hasNext();){const next=iterator.getNext();count<this.limit_&&this.withinDirectionalStart(next)&&this.withinDirectionalEnd(next)?count++:filtered=filtered.updateImmediateChild(next.name,ChildrenNode.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(oldSnap,filtered,optChangeAccumulator)}updatePriority(oldSnap,newPriority){return oldSnap}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(snap,childKey,childSnap,source,changeAccumulator){let cmp;if(this.reverse_){const indexCmp=this.index_.getCompare();cmp=(a,b)=>indexCmp(b,a)}else cmp=this.index_.getCompare();const oldEventCache=snap;index_esm2017_assert(oldEventCache.numChildren()===this.limit_,"");const newChildNamedNode=new NamedNode(childKey,childSnap),windowBoundary=this.reverse_?oldEventCache.getFirstChild(this.index_):oldEventCache.getLastChild(this.index_),inRange=this.rangedFilter_.matches(newChildNamedNode);if(oldEventCache.hasChild(childKey)){const oldChildSnap=oldEventCache.getImmediateChild(childKey);let nextChild=source.getChildAfterChild(this.index_,windowBoundary,this.reverse_);for(;null!=nextChild&&(nextChild.name===childKey||oldEventCache.hasChild(nextChild.name));)nextChild=source.getChildAfterChild(this.index_,nextChild,this.reverse_);const compareNext=null==nextChild?1:cmp(nextChild,newChildNamedNode);if(inRange&&!childSnap.isEmpty()&&compareNext>=0)return null!=changeAccumulator&&changeAccumulator.trackChildChange(changeChildChanged(childKey,childSnap,oldChildSnap)),oldEventCache.updateImmediateChild(childKey,childSnap);{null!=changeAccumulator&&changeAccumulator.trackChildChange(changeChildRemoved(childKey,oldChildSnap));const newEventCache=oldEventCache.updateImmediateChild(childKey,ChildrenNode.EMPTY_NODE);return null!=nextChild&&this.rangedFilter_.matches(nextChild)?(null!=changeAccumulator&&changeAccumulator.trackChildChange(changeChildAdded(nextChild.name,nextChild.node)),newEventCache.updateImmediateChild(nextChild.name,nextChild.node)):newEventCache}}return childSnap.isEmpty()?snap:inRange&&cmp(windowBoundary,newChildNamedNode)>=0?(null!=changeAccumulator&&(changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name,windowBoundary.node)),changeAccumulator.trackChildChange(changeChildAdded(childKey,childSnap))),oldEventCache.updateImmediateChild(childKey,childSnap).updateImmediateChild(windowBoundary.name,ChildrenNode.EMPTY_NODE)):snap}}class QueryParams{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=PRIORITY_INDEX}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return index_esm2017_assert(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return index_esm2017_assert(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:MIN_NAME}hasEnd(){return this.endSet_}getIndexEndValue(){return index_esm2017_assert(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return index_esm2017_assert(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:MAX_NAME}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return index_esm2017_assert(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===PRIORITY_INDEX}copy(){const copy=new QueryParams;return copy.limitSet_=this.limitSet_,copy.limit_=this.limit_,copy.startSet_=this.startSet_,copy.startAfterSet_=this.startAfterSet_,copy.indexStartValue_=this.indexStartValue_,copy.startNameSet_=this.startNameSet_,copy.indexStartName_=this.indexStartName_,copy.endSet_=this.endSet_,copy.endBeforeSet_=this.endBeforeSet_,copy.indexEndValue_=this.indexEndValue_,copy.endNameSet_=this.endNameSet_,copy.indexEndName_=this.indexEndName_,copy.index_=this.index_,copy.viewFrom_=this.viewFrom_,copy}}function queryParamsToRestQueryStringParameters(queryParams){const qs={};if(queryParams.isDefault())return qs;let orderBy;if(queryParams.index_===PRIORITY_INDEX?orderBy="$priority":queryParams.index_===VALUE_INDEX?orderBy="$value":queryParams.index_===KEY_INDEX?orderBy="$key":(index_esm2017_assert(queryParams.index_ instanceof PathIndex,"Unrecognized index type!"),orderBy=queryParams.index_.toString()),qs.orderBy=stringify(orderBy),queryParams.startSet_){const startParam=queryParams.startAfterSet_?"startAfter":"startAt";qs[startParam]=stringify(queryParams.indexStartValue_),queryParams.startNameSet_&&(qs[startParam]+=","+stringify(queryParams.indexStartName_))}if(queryParams.endSet_){const endParam=queryParams.endBeforeSet_?"endBefore":"endAt";qs[endParam]=stringify(queryParams.indexEndValue_),queryParams.endNameSet_&&(qs[endParam]+=","+stringify(queryParams.indexEndName_))}return queryParams.limitSet_&&(queryParams.isViewFromLeft()?qs.limitToFirst=queryParams.limit_:qs.limitToLast=queryParams.limit_),qs}function queryParamsGetQueryObject(queryParams){const obj={};if(queryParams.startSet_&&(obj.sp=queryParams.indexStartValue_,queryParams.startNameSet_&&(obj.sn=queryParams.indexStartName_),obj.sin=!queryParams.startAfterSet_),queryParams.endSet_&&(obj.ep=queryParams.indexEndValue_,queryParams.endNameSet_&&(obj.en=queryParams.indexEndName_),obj.ein=!queryParams.endBeforeSet_),queryParams.limitSet_){obj.l=queryParams.limit_;let viewFrom=queryParams.viewFrom_;""===viewFrom&&(viewFrom=queryParams.isViewFromLeft()?"l":"r"),obj.vf=viewFrom}return queryParams.index_!==PRIORITY_INDEX&&(obj.i=queryParams.index_.toString()),obj}class ReadonlyRestClient extends ServerActions{constructor(repoInfo_,onDataUpdate_,authTokenProvider_,appCheckTokenProvider_){super(),this.repoInfo_=repoInfo_,this.onDataUpdate_=onDataUpdate_,this.authTokenProvider_=authTokenProvider_,this.appCheckTokenProvider_=appCheckTokenProvider_,this.log_=logWrapper("p:rest:"),this.listens_={}}reportStats(stats){throw new Error("Method not implemented.")}static getListenId_(query,tag){return void 0!==tag?"tag$"+tag:(index_esm2017_assert(query._queryParams.isDefault(),"should have a tag if it's not a default query."),query._path.toString())}listen(query,currentHashFn,tag,onComplete){const pathString=query._path.toString();this.log_("Listen called for "+pathString+" "+query._queryIdentifier);const listenId=ReadonlyRestClient.getListenId_(query,tag),thisListen={};this.listens_[listenId]=thisListen;const queryStringParameters=queryParamsToRestQueryStringParameters(query._queryParams);this.restRequest_(pathString+".json",queryStringParameters,((error,result)=>{let data=result;if(404===error&&(data=null,error=null),null===error&&this.onDataUpdate_(pathString,data,!1,tag),index_esm2017_safeGet(this.listens_,listenId)===thisListen){let status;status=error?401===error?"permission_denied":"rest_error:"+error:"ok",onComplete(status,null)}}))}unlisten(query,tag){const listenId=ReadonlyRestClient.getListenId_(query,tag);delete this.listens_[listenId]}get(query){const queryStringParameters=queryParamsToRestQueryStringParameters(query._queryParams),pathString=query._path.toString(),deferred=new index_esm2017_Deferred;return this.restRequest_(pathString+".json",queryStringParameters,((error,result)=>{let data=result;404===error&&(data=null,error=null),null===error?(this.onDataUpdate_(pathString,data,!1,null),deferred.resolve(data)):deferred.reject(new Error(data))})),deferred.promise}refreshAuthToken(token){}restRequest_(pathString,queryStringParameters={},callback){return queryStringParameters.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then((([authToken,appCheckToken])=>{authToken&&authToken.accessToken&&(queryStringParameters.auth=authToken.accessToken),appCheckToken&&appCheckToken.token&&(queryStringParameters.ac=appCheckToken.token);const url=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+pathString+"?ns="+this.repoInfo_.namespace+function querystring(querystringParams){const params=[];for(const[key,value]of Object.entries(querystringParams))Array.isArray(value)?value.forEach((arrayVal=>{params.push(encodeURIComponent(key)+"="+encodeURIComponent(arrayVal))})):params.push(encodeURIComponent(key)+"="+encodeURIComponent(value));return params.length?"&"+params.join("&"):""}(queryStringParameters);this.log_("Sending REST request for "+url);const xhr=new XMLHttpRequest;xhr.onreadystatechange=()=>{if(callback&&4===xhr.readyState){this.log_("REST Response for "+url+" received. status:",xhr.status,"response:",xhr.responseText);let res=null;if(xhr.status>=200&&xhr.status<300){try{res=jsonEval(xhr.responseText)}catch(e){warn("Failed to parse JSON response for "+url+": "+xhr.responseText)}callback(null,res)}else 401!==xhr.status&&404!==xhr.status&&warn("Got unsuccessful REST response for "+url+" Status: "+xhr.status),callback(xhr.status);callback=null}},xhr.open("GET",url,!0),xhr.send()}))}}class SnapshotHolder{constructor(){this.rootNode_=ChildrenNode.EMPTY_NODE}getNode(path){return this.rootNode_.getChild(path)}updateSnapshot(path,newSnapshotNode){this.rootNode_=this.rootNode_.updateChild(path,newSnapshotNode)}}function newSparseSnapshotTree(){return{value:null,children:new Map}}function sparseSnapshotTreeRemember(sparseSnapshotTree,path,data){if(pathIsEmpty(path))sparseSnapshotTree.value=data,sparseSnapshotTree.children.clear();else if(null!==sparseSnapshotTree.value)sparseSnapshotTree.value=sparseSnapshotTree.value.updateChild(path,data);else{const childKey=pathGetFront(path);sparseSnapshotTree.children.has(childKey)||sparseSnapshotTree.children.set(childKey,newSparseSnapshotTree());sparseSnapshotTreeRemember(sparseSnapshotTree.children.get(childKey),path=pathPopFront(path),data)}}function sparseSnapshotTreeForEachTree(sparseSnapshotTree,prefixPath,func){null!==sparseSnapshotTree.value?func(prefixPath,sparseSnapshotTree.value):function sparseSnapshotTreeForEachChild(sparseSnapshotTree,func){sparseSnapshotTree.children.forEach(((tree,key)=>{func(key,tree)}))}(sparseSnapshotTree,((key,tree)=>{sparseSnapshotTreeForEachTree(tree,new Path(prefixPath.toString()+"/"+key),func)}))}class StatsListener{constructor(collection_){this.collection_=collection_,this.last_=null}get(){const newStats=this.collection_.get(),delta=Object.assign({},newStats);return this.last_&&each(this.last_,((stat,value)=>{delta[stat]=delta[stat]-value})),this.last_=newStats,delta}}class StatsReporter{constructor(collection,server_){this.server_=server_,this.statsToReport_={},this.statsListener_=new StatsListener(collection);const timeout=1e4+2e4*Math.random();setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(timeout))}reportStats_(){const stats=this.statsListener_.get(),reportedStats={};let haveStatsToReport=!1;each(stats,((stat,value)=>{value>0&&index_esm2017_contains(this.statsToReport_,stat)&&(reportedStats[stat]=value,haveStatsToReport=!0)})),haveStatsToReport&&this.server_.reportStats(reportedStats),setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}var OperationType;function newOperationSourceServerTaggedQuery(queryId){return{fromUser:!1,fromServer:!0,queryId,tagged:!0}}!function(OperationType){OperationType[OperationType.OVERWRITE=0]="OVERWRITE",OperationType[OperationType.MERGE=1]="MERGE",OperationType[OperationType.ACK_USER_WRITE=2]="ACK_USER_WRITE",OperationType[OperationType.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(OperationType||(OperationType={}));class AckUserWrite{constructor(path,affectedTree,revert){this.path=path,this.affectedTree=affectedTree,this.revert=revert,this.type=OperationType.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(childName){if(pathIsEmpty(this.path)){if(null!=this.affectedTree.value)return index_esm2017_assert(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const childTree=this.affectedTree.subtree(new Path(childName));return new AckUserWrite(newEmptyPath(),childTree,this.revert)}}return index_esm2017_assert(pathGetFront(this.path)===childName,"operationForChild called for unrelated child."),new AckUserWrite(pathPopFront(this.path),this.affectedTree,this.revert)}}class ListenComplete{constructor(source,path){this.source=source,this.path=path,this.type=OperationType.LISTEN_COMPLETE}operationForChild(childName){return pathIsEmpty(this.path)?new ListenComplete(this.source,newEmptyPath()):new ListenComplete(this.source,pathPopFront(this.path))}}class Overwrite{constructor(source,path,snap){this.source=source,this.path=path,this.snap=snap,this.type=OperationType.OVERWRITE}operationForChild(childName){return pathIsEmpty(this.path)?new Overwrite(this.source,newEmptyPath(),this.snap.getImmediateChild(childName)):new Overwrite(this.source,pathPopFront(this.path),this.snap)}}class Merge{constructor(source,path,children){this.source=source,this.path=path,this.children=children,this.type=OperationType.MERGE}operationForChild(childName){if(pathIsEmpty(this.path)){const childTree=this.children.subtree(new Path(childName));return childTree.isEmpty()?null:childTree.value?new Overwrite(this.source,newEmptyPath(),childTree.value):new Merge(this.source,newEmptyPath(),childTree)}return index_esm2017_assert(pathGetFront(this.path)===childName,"Can't get a merge for a child not on the path of the operation"),new Merge(this.source,pathPopFront(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class CacheNode{constructor(node_,fullyInitialized_,filtered_){this.node_=node_,this.fullyInitialized_=fullyInitialized_,this.filtered_=filtered_}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(path){if(pathIsEmpty(path))return this.isFullyInitialized()&&!this.filtered_;const childKey=pathGetFront(path);return this.isCompleteForChild(childKey)}isCompleteForChild(key){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(key)}getNode(){return this.node_}}class EventGenerator{constructor(query_){this.query_=query_,this.index_=this.query_._queryParams.getIndex()}}function eventGeneratorGenerateEventsForType(eventGenerator,events,eventType,changes,registrations,eventCache){const filteredChanges=changes.filter((change=>change.type===eventType));filteredChanges.sort(((a,b)=>function eventGeneratorCompareChanges(eventGenerator,a,b){if(null==a.childName||null==b.childName)throw assertionError("Should only compare child_ events.");const aWrapped=new NamedNode(a.childName,a.snapshotNode),bWrapped=new NamedNode(b.childName,b.snapshotNode);return eventGenerator.index_.compare(aWrapped,bWrapped)}(eventGenerator,a,b))),filteredChanges.forEach((change=>{const materializedChange=function eventGeneratorMaterializeSingleChange(eventGenerator,change,eventCache){return"value"===change.type||"child_removed"===change.type||(change.prevName=eventCache.getPredecessorChildName(change.childName,change.snapshotNode,eventGenerator.index_)),change}(eventGenerator,change,eventCache);registrations.forEach((registration=>{registration.respondsTo(change.type)&&events.push(registration.createEvent(materializedChange,eventGenerator.query_))}))}))}function newViewCache(eventCache,serverCache){return{eventCache,serverCache}}function viewCacheUpdateEventSnap(viewCache,eventSnap,complete,filtered){return newViewCache(new CacheNode(eventSnap,complete,filtered),viewCache.serverCache)}function viewCacheUpdateServerSnap(viewCache,serverSnap,complete,filtered){return newViewCache(viewCache.eventCache,new CacheNode(serverSnap,complete,filtered))}function viewCacheGetCompleteEventSnap(viewCache){return viewCache.eventCache.isFullyInitialized()?viewCache.eventCache.getNode():null}function viewCacheGetCompleteServerSnap(viewCache){return viewCache.serverCache.isFullyInitialized()?viewCache.serverCache.getNode():null}let emptyChildrenSingleton;class ImmutableTree{constructor(value,children=(()=>(emptyChildrenSingleton||(emptyChildrenSingleton=new SortedMap(stringCompare)),emptyChildrenSingleton))()){this.value=value,this.children=children}static fromObject(obj){let tree=new ImmutableTree(null);return each(obj,((childPath,childSnap)=>{tree=tree.set(new Path(childPath),childSnap)})),tree}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(relativePath,predicate){if(null!=this.value&&predicate(this.value))return{path:newEmptyPath(),value:this.value};if(pathIsEmpty(relativePath))return null;{const front=pathGetFront(relativePath),child=this.children.get(front);if(null!==child){const childExistingPathAndValue=child.findRootMostMatchingPathAndValue(pathPopFront(relativePath),predicate);if(null!=childExistingPathAndValue){return{path:pathChild(new Path(front),childExistingPathAndValue.path),value:childExistingPathAndValue.value}}return null}return null}}findRootMostValueAndPath(relativePath){return this.findRootMostMatchingPathAndValue(relativePath,(()=>!0))}subtree(relativePath){if(pathIsEmpty(relativePath))return this;{const front=pathGetFront(relativePath),childTree=this.children.get(front);return null!==childTree?childTree.subtree(pathPopFront(relativePath)):new ImmutableTree(null)}}set(relativePath,toSet){if(pathIsEmpty(relativePath))return new ImmutableTree(toSet,this.children);{const front=pathGetFront(relativePath),newChild=(this.children.get(front)||new ImmutableTree(null)).set(pathPopFront(relativePath),toSet),newChildren=this.children.insert(front,newChild);return new ImmutableTree(this.value,newChildren)}}remove(relativePath){if(pathIsEmpty(relativePath))return this.children.isEmpty()?new ImmutableTree(null):new ImmutableTree(null,this.children);{const front=pathGetFront(relativePath),child=this.children.get(front);if(child){const newChild=child.remove(pathPopFront(relativePath));let newChildren;return newChildren=newChild.isEmpty()?this.children.remove(front):this.children.insert(front,newChild),null===this.value&&newChildren.isEmpty()?new ImmutableTree(null):new ImmutableTree(this.value,newChildren)}return this}}get(relativePath){if(pathIsEmpty(relativePath))return this.value;{const front=pathGetFront(relativePath),child=this.children.get(front);return child?child.get(pathPopFront(relativePath)):null}}setTree(relativePath,newTree){if(pathIsEmpty(relativePath))return newTree;{const front=pathGetFront(relativePath),newChild=(this.children.get(front)||new ImmutableTree(null)).setTree(pathPopFront(relativePath),newTree);let newChildren;return newChildren=newChild.isEmpty()?this.children.remove(front):this.children.insert(front,newChild),new ImmutableTree(this.value,newChildren)}}fold(fn){return this.fold_(newEmptyPath(),fn)}fold_(pathSoFar,fn){const accum={};return this.children.inorderTraversal(((childKey,childTree)=>{accum[childKey]=childTree.fold_(pathChild(pathSoFar,childKey),fn)})),fn(pathSoFar,this.value,accum)}findOnPath(path,f){return this.findOnPath_(path,newEmptyPath(),f)}findOnPath_(pathToFollow,pathSoFar,f){const result=!!this.value&&f(pathSoFar,this.value);if(result)return result;if(pathIsEmpty(pathToFollow))return null;{const front=pathGetFront(pathToFollow),nextChild=this.children.get(front);return nextChild?nextChild.findOnPath_(pathPopFront(pathToFollow),pathChild(pathSoFar,front),f):null}}foreachOnPath(path,f){return this.foreachOnPath_(path,newEmptyPath(),f)}foreachOnPath_(pathToFollow,currentRelativePath,f){if(pathIsEmpty(pathToFollow))return this;{this.value&&f(currentRelativePath,this.value);const front=pathGetFront(pathToFollow),nextChild=this.children.get(front);return nextChild?nextChild.foreachOnPath_(pathPopFront(pathToFollow),pathChild(currentRelativePath,front),f):new ImmutableTree(null)}}foreach(f){this.foreach_(newEmptyPath(),f)}foreach_(currentRelativePath,f){this.children.inorderTraversal(((childName,childTree)=>{childTree.foreach_(pathChild(currentRelativePath,childName),f)})),this.value&&f(currentRelativePath,this.value)}foreachChild(f){this.children.inorderTraversal(((childName,childTree)=>{childTree.value&&f(childName,childTree.value)}))}}class CompoundWrite{constructor(writeTree_){this.writeTree_=writeTree_}static empty(){return new CompoundWrite(new ImmutableTree(null))}}function compoundWriteAddWrite(compoundWrite,path,node){if(pathIsEmpty(path))return new CompoundWrite(new ImmutableTree(node));{const rootmost=compoundWrite.writeTree_.findRootMostValueAndPath(path);if(null!=rootmost){const rootMostPath=rootmost.path;let value=rootmost.value;const relativePath=newRelativePath(rootMostPath,path);return value=value.updateChild(relativePath,node),new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath,value))}{const subtree=new ImmutableTree(node),newWriteTree=compoundWrite.writeTree_.setTree(path,subtree);return new CompoundWrite(newWriteTree)}}}function compoundWriteAddWrites(compoundWrite,path,updates){let newWrite=compoundWrite;return each(updates,((childKey,node)=>{newWrite=compoundWriteAddWrite(newWrite,pathChild(path,childKey),node)})),newWrite}function compoundWriteRemoveWrite(compoundWrite,path){if(pathIsEmpty(path))return CompoundWrite.empty();{const newWriteTree=compoundWrite.writeTree_.setTree(path,new ImmutableTree(null));return new CompoundWrite(newWriteTree)}}function compoundWriteHasCompleteWrite(compoundWrite,path){return null!=compoundWriteGetCompleteNode(compoundWrite,path)}function compoundWriteGetCompleteNode(compoundWrite,path){const rootmost=compoundWrite.writeTree_.findRootMostValueAndPath(path);return null!=rootmost?compoundWrite.writeTree_.get(rootmost.path).getChild(newRelativePath(rootmost.path,path)):null}function compoundWriteGetCompleteChildren(compoundWrite){const children=[],node=compoundWrite.writeTree_.value;return null!=node?node.isLeafNode()||node.forEachChild(PRIORITY_INDEX,((childName,childNode)=>{children.push(new NamedNode(childName,childNode))})):compoundWrite.writeTree_.children.inorderTraversal(((childName,childTree)=>{null!=childTree.value&&children.push(new NamedNode(childName,childTree.value))})),children}function compoundWriteChildCompoundWrite(compoundWrite,path){if(pathIsEmpty(path))return compoundWrite;{const shadowingNode=compoundWriteGetCompleteNode(compoundWrite,path);return new CompoundWrite(null!=shadowingNode?new ImmutableTree(shadowingNode):compoundWrite.writeTree_.subtree(path))}}function compoundWriteIsEmpty(compoundWrite){return compoundWrite.writeTree_.isEmpty()}function compoundWriteApply(compoundWrite,node){return applySubtreeWrite(newEmptyPath(),compoundWrite.writeTree_,node)}function applySubtreeWrite(relativePath,writeTree,node){if(null!=writeTree.value)return node.updateChild(relativePath,writeTree.value);{let priorityWrite=null;return writeTree.children.inorderTraversal(((childKey,childTree)=>{".priority"===childKey?(index_esm2017_assert(null!==childTree.value,"Priority writes must always be leaf nodes"),priorityWrite=childTree.value):node=applySubtreeWrite(pathChild(relativePath,childKey),childTree,node)})),node.getChild(relativePath).isEmpty()||null===priorityWrite||(node=node.updateChild(pathChild(relativePath,".priority"),priorityWrite)),node}}function writeTreeChildWrites(writeTree,path){return newWriteTreeRef(path,writeTree)}function writeTreeRemoveWrite(writeTree,writeId){const idx=writeTree.allWrites.findIndex((s=>s.writeId===writeId));index_esm2017_assert(idx>=0,"removeWrite called with nonexistent writeId.");const writeToRemove=writeTree.allWrites[idx];writeTree.allWrites.splice(idx,1);let removedWriteWasVisible=writeToRemove.visible,removedWriteOverlapsWithOtherWrites=!1,i=writeTree.allWrites.length-1;for(;removedWriteWasVisible&&i>=0;){const currentWrite=writeTree.allWrites[i];currentWrite.visible&&(i>=idx&&writeTreeRecordContainsPath_(currentWrite,writeToRemove.path)?removedWriteWasVisible=!1:pathContains(writeToRemove.path,currentWrite.path)&&(removedWriteOverlapsWithOtherWrites=!0)),i--}if(removedWriteWasVisible){if(removedWriteOverlapsWithOtherWrites)return function writeTreeResetTree_(writeTree){writeTree.visibleWrites=writeTreeLayerTree_(writeTree.allWrites,writeTreeDefaultFilter_,newEmptyPath()),writeTree.allWrites.length>0?writeTree.lastWriteId=writeTree.allWrites[writeTree.allWrites.length-1].writeId:writeTree.lastWriteId=-1}(writeTree),!0;if(writeToRemove.snap)writeTree.visibleWrites=compoundWriteRemoveWrite(writeTree.visibleWrites,writeToRemove.path);else{each(writeToRemove.children,(childName=>{writeTree.visibleWrites=compoundWriteRemoveWrite(writeTree.visibleWrites,pathChild(writeToRemove.path,childName))}))}return!0}return!1}function writeTreeRecordContainsPath_(writeRecord,path){if(writeRecord.snap)return pathContains(writeRecord.path,path);for(const childName in writeRecord.children)if(writeRecord.children.hasOwnProperty(childName)&&pathContains(pathChild(writeRecord.path,childName),path))return!0;return!1}function writeTreeDefaultFilter_(write){return write.visible}function writeTreeLayerTree_(writes,filter,treeRoot){let compoundWrite=CompoundWrite.empty();for(let i=0;i<writes.length;++i){const write=writes[i];if(filter(write)){const writePath=write.path;let relativePath;if(write.snap)pathContains(treeRoot,writePath)?(relativePath=newRelativePath(treeRoot,writePath),compoundWrite=compoundWriteAddWrite(compoundWrite,relativePath,write.snap)):pathContains(writePath,treeRoot)&&(relativePath=newRelativePath(writePath,treeRoot),compoundWrite=compoundWriteAddWrite(compoundWrite,newEmptyPath(),write.snap.getChild(relativePath)));else{if(!write.children)throw assertionError("WriteRecord should have .snap or .children");if(pathContains(treeRoot,writePath))relativePath=newRelativePath(treeRoot,writePath),compoundWrite=compoundWriteAddWrites(compoundWrite,relativePath,write.children);else if(pathContains(writePath,treeRoot))if(relativePath=newRelativePath(writePath,treeRoot),pathIsEmpty(relativePath))compoundWrite=compoundWriteAddWrites(compoundWrite,newEmptyPath(),write.children);else{const child=index_esm2017_safeGet(write.children,pathGetFront(relativePath));if(child){const deepNode=child.getChild(pathPopFront(relativePath));compoundWrite=compoundWriteAddWrite(compoundWrite,newEmptyPath(),deepNode)}}}}}return compoundWrite}function writeTreeCalcCompleteEventCache(writeTree,treePath,completeServerCache,writeIdsToExclude,includeHiddenWrites){if(writeIdsToExclude||includeHiddenWrites){const merge=compoundWriteChildCompoundWrite(writeTree.visibleWrites,treePath);if(!includeHiddenWrites&&compoundWriteIsEmpty(merge))return completeServerCache;if(includeHiddenWrites||null!=completeServerCache||compoundWriteHasCompleteWrite(merge,newEmptyPath())){const filter=function(write){return(write.visible||includeHiddenWrites)&&(!writeIdsToExclude||!~writeIdsToExclude.indexOf(write.writeId))&&(pathContains(write.path,treePath)||pathContains(treePath,write.path))};return compoundWriteApply(writeTreeLayerTree_(writeTree.allWrites,filter,treePath),completeServerCache||ChildrenNode.EMPTY_NODE)}return null}{const shadowingNode=compoundWriteGetCompleteNode(writeTree.visibleWrites,treePath);if(null!=shadowingNode)return shadowingNode;{const subMerge=compoundWriteChildCompoundWrite(writeTree.visibleWrites,treePath);if(compoundWriteIsEmpty(subMerge))return completeServerCache;if(null!=completeServerCache||compoundWriteHasCompleteWrite(subMerge,newEmptyPath())){return compoundWriteApply(subMerge,completeServerCache||ChildrenNode.EMPTY_NODE)}return null}}}function writeTreeRefCalcCompleteEventCache(writeTreeRef,completeServerCache,writeIdsToExclude,includeHiddenWrites){return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree,writeTreeRef.treePath,completeServerCache,writeIdsToExclude,includeHiddenWrites)}function writeTreeRefCalcCompleteEventChildren(writeTreeRef,completeServerChildren){return function writeTreeCalcCompleteEventChildren(writeTree,treePath,completeServerChildren){let completeChildren=ChildrenNode.EMPTY_NODE;const topLevelSet=compoundWriteGetCompleteNode(writeTree.visibleWrites,treePath);if(topLevelSet)return topLevelSet.isLeafNode()||topLevelSet.forEachChild(PRIORITY_INDEX,((childName,childSnap)=>{completeChildren=completeChildren.updateImmediateChild(childName,childSnap)})),completeChildren;if(completeServerChildren){const merge=compoundWriteChildCompoundWrite(writeTree.visibleWrites,treePath);return completeServerChildren.forEachChild(PRIORITY_INDEX,((childName,childNode)=>{const node=compoundWriteApply(compoundWriteChildCompoundWrite(merge,new Path(childName)),childNode);completeChildren=completeChildren.updateImmediateChild(childName,node)})),compoundWriteGetCompleteChildren(merge).forEach((namedNode=>{completeChildren=completeChildren.updateImmediateChild(namedNode.name,namedNode.node)})),completeChildren}return compoundWriteGetCompleteChildren(compoundWriteChildCompoundWrite(writeTree.visibleWrites,treePath)).forEach((namedNode=>{completeChildren=completeChildren.updateImmediateChild(namedNode.name,namedNode.node)})),completeChildren}(writeTreeRef.writeTree,writeTreeRef.treePath,completeServerChildren)}function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef,path,existingEventSnap,existingServerSnap){return function writeTreeCalcEventCacheAfterServerOverwrite(writeTree,treePath,childPath,existingEventSnap,existingServerSnap){index_esm2017_assert(existingEventSnap||existingServerSnap,"Either existingEventSnap or existingServerSnap must exist");const path=pathChild(treePath,childPath);if(compoundWriteHasCompleteWrite(writeTree.visibleWrites,path))return null;{const childMerge=compoundWriteChildCompoundWrite(writeTree.visibleWrites,path);return compoundWriteIsEmpty(childMerge)?existingServerSnap.getChild(childPath):compoundWriteApply(childMerge,existingServerSnap.getChild(childPath))}}(writeTreeRef.writeTree,writeTreeRef.treePath,path,existingEventSnap,existingServerSnap)}function writeTreeRefShadowingWrite(writeTreeRef,path){return function writeTreeShadowingWrite(writeTree,path){return compoundWriteGetCompleteNode(writeTree.visibleWrites,path)}(writeTreeRef.writeTree,pathChild(writeTreeRef.treePath,path))}function writeTreeRefCalcIndexedSlice(writeTreeRef,completeServerData,startPost,count,reverse,index){return function writeTreeCalcIndexedSlice(writeTree,treePath,completeServerData,startPost,count,reverse,index){let toIterate;const merge=compoundWriteChildCompoundWrite(writeTree.visibleWrites,treePath),shadowingNode=compoundWriteGetCompleteNode(merge,newEmptyPath());if(null!=shadowingNode)toIterate=shadowingNode;else{if(null==completeServerData)return[];toIterate=compoundWriteApply(merge,completeServerData)}if(toIterate=toIterate.withIndex(index),toIterate.isEmpty()||toIterate.isLeafNode())return[];{const nodes=[],cmp=index.getCompare(),iter=reverse?toIterate.getReverseIteratorFrom(startPost,index):toIterate.getIteratorFrom(startPost,index);let next=iter.getNext();for(;next&&nodes.length<count;)0!==cmp(next,startPost)&&nodes.push(next),next=iter.getNext();return nodes}}(writeTreeRef.writeTree,writeTreeRef.treePath,completeServerData,startPost,count,reverse,index)}function writeTreeRefCalcCompleteChild(writeTreeRef,childKey,existingServerCache){return function writeTreeCalcCompleteChild(writeTree,treePath,childKey,existingServerSnap){const path=pathChild(treePath,childKey),shadowingNode=compoundWriteGetCompleteNode(writeTree.visibleWrites,path);if(null!=shadowingNode)return shadowingNode;if(existingServerSnap.isCompleteForChild(childKey))return compoundWriteApply(compoundWriteChildCompoundWrite(writeTree.visibleWrites,path),existingServerSnap.getNode().getImmediateChild(childKey));return null}(writeTreeRef.writeTree,writeTreeRef.treePath,childKey,existingServerCache)}function writeTreeRefChild(writeTreeRef,childName){return newWriteTreeRef(pathChild(writeTreeRef.treePath,childName),writeTreeRef.writeTree)}function newWriteTreeRef(path,writeTree){return{treePath:path,writeTree}}class ChildChangeAccumulator{constructor(){this.changeMap=new Map}trackChildChange(change){const type=change.type,childKey=change.childName;index_esm2017_assert("child_added"===type||"child_changed"===type||"child_removed"===type,"Only child changes supported for tracking"),index_esm2017_assert(".priority"!==childKey,"Only non-priority child changes can be tracked.");const oldChange=this.changeMap.get(childKey);if(oldChange){const oldType=oldChange.type;if("child_added"===type&&"child_removed"===oldType)this.changeMap.set(childKey,changeChildChanged(childKey,change.snapshotNode,oldChange.snapshotNode));else if("child_removed"===type&&"child_added"===oldType)this.changeMap.delete(childKey);else if("child_removed"===type&&"child_changed"===oldType)this.changeMap.set(childKey,changeChildRemoved(childKey,oldChange.oldSnap));else if("child_changed"===type&&"child_added"===oldType)this.changeMap.set(childKey,changeChildAdded(childKey,change.snapshotNode));else{if("child_changed"!==type||"child_changed"!==oldType)throw assertionError("Illegal combination of changes: "+change+" occurred after "+oldChange);this.changeMap.set(childKey,changeChildChanged(childKey,change.snapshotNode,oldChange.oldSnap))}}else this.changeMap.set(childKey,change)}getChanges(){return Array.from(this.changeMap.values())}}const NO_COMPLETE_CHILD_SOURCE=new class NoCompleteChildSource_{getCompleteChild(childKey){return null}getChildAfterChild(index,child,reverse){return null}};class WriteTreeCompleteChildSource{constructor(writes_,viewCache_,optCompleteServerCache_=null){this.writes_=writes_,this.viewCache_=viewCache_,this.optCompleteServerCache_=optCompleteServerCache_}getCompleteChild(childKey){const node=this.viewCache_.eventCache;if(node.isCompleteForChild(childKey))return node.getNode().getImmediateChild(childKey);{const serverNode=null!=this.optCompleteServerCache_?new CacheNode(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return writeTreeRefCalcCompleteChild(this.writes_,childKey,serverNode)}}getChildAfterChild(index,child,reverse){const completeServerData=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:viewCacheGetCompleteServerSnap(this.viewCache_),nodes=writeTreeRefCalcIndexedSlice(this.writes_,completeServerData,child,1,reverse,index);return 0===nodes.length?null:nodes[0]}}function viewProcessorApplyOperation(viewProcessor,oldViewCache,operation,writesCache,completeCache){const accumulator=new ChildChangeAccumulator;let newViewCache,filterServerNode;if(operation.type===OperationType.OVERWRITE){const overwrite=operation;overwrite.source.fromUser?newViewCache=viewProcessorApplyUserOverwrite(viewProcessor,oldViewCache,overwrite.path,overwrite.snap,writesCache,completeCache,accumulator):(index_esm2017_assert(overwrite.source.fromServer,"Unknown source."),filterServerNode=overwrite.source.tagged||oldViewCache.serverCache.isFiltered()&&!pathIsEmpty(overwrite.path),newViewCache=viewProcessorApplyServerOverwrite(viewProcessor,oldViewCache,overwrite.path,overwrite.snap,writesCache,completeCache,filterServerNode,accumulator))}else if(operation.type===OperationType.MERGE){const merge=operation;merge.source.fromUser?newViewCache=function viewProcessorApplyUserMerge(viewProcessor,viewCache,path,changedChildren,writesCache,serverCache,accumulator){let curViewCache=viewCache;return changedChildren.foreach(((relativePath,childNode)=>{const writePath=pathChild(path,relativePath);viewProcessorCacheHasChild(viewCache,pathGetFront(writePath))&&(curViewCache=viewProcessorApplyUserOverwrite(viewProcessor,curViewCache,writePath,childNode,writesCache,serverCache,accumulator))})),changedChildren.foreach(((relativePath,childNode)=>{const writePath=pathChild(path,relativePath);viewProcessorCacheHasChild(viewCache,pathGetFront(writePath))||(curViewCache=viewProcessorApplyUserOverwrite(viewProcessor,curViewCache,writePath,childNode,writesCache,serverCache,accumulator))})),curViewCache}(viewProcessor,oldViewCache,merge.path,merge.children,writesCache,completeCache,accumulator):(index_esm2017_assert(merge.source.fromServer,"Unknown source."),filterServerNode=merge.source.tagged||oldViewCache.serverCache.isFiltered(),newViewCache=viewProcessorApplyServerMerge(viewProcessor,oldViewCache,merge.path,merge.children,writesCache,completeCache,filterServerNode,accumulator))}else if(operation.type===OperationType.ACK_USER_WRITE){const ackUserWrite=operation;newViewCache=ackUserWrite.revert?function viewProcessorRevertUserWrite(viewProcessor,viewCache,path,writesCache,completeServerCache,accumulator){let complete;if(null!=writeTreeRefShadowingWrite(writesCache,path))return viewCache;{const source=new WriteTreeCompleteChildSource(writesCache,viewCache,completeServerCache),oldEventCache=viewCache.eventCache.getNode();let newEventCache;if(pathIsEmpty(path)||".priority"===pathGetFront(path)){let newNode;if(viewCache.serverCache.isFullyInitialized())newNode=writeTreeRefCalcCompleteEventCache(writesCache,viewCacheGetCompleteServerSnap(viewCache));else{const serverChildren=viewCache.serverCache.getNode();index_esm2017_assert(serverChildren instanceof ChildrenNode,"serverChildren would be complete if leaf node"),newNode=writeTreeRefCalcCompleteEventChildren(writesCache,serverChildren)}newEventCache=viewProcessor.filter.updateFullNode(oldEventCache,newNode,accumulator)}else{const childKey=pathGetFront(path);let newChild=writeTreeRefCalcCompleteChild(writesCache,childKey,viewCache.serverCache);null==newChild&&viewCache.serverCache.isCompleteForChild(childKey)&&(newChild=oldEventCache.getImmediateChild(childKey)),newEventCache=null!=newChild?viewProcessor.filter.updateChild(oldEventCache,childKey,newChild,pathPopFront(path),source,accumulator):viewCache.eventCache.getNode().hasChild(childKey)?viewProcessor.filter.updateChild(oldEventCache,childKey,ChildrenNode.EMPTY_NODE,pathPopFront(path),source,accumulator):oldEventCache,newEventCache.isEmpty()&&viewCache.serverCache.isFullyInitialized()&&(complete=writeTreeRefCalcCompleteEventCache(writesCache,viewCacheGetCompleteServerSnap(viewCache)),complete.isLeafNode()&&(newEventCache=viewProcessor.filter.updateFullNode(newEventCache,complete,accumulator)))}return complete=viewCache.serverCache.isFullyInitialized()||null!=writeTreeRefShadowingWrite(writesCache,newEmptyPath()),viewCacheUpdateEventSnap(viewCache,newEventCache,complete,viewProcessor.filter.filtersNodes())}}(viewProcessor,oldViewCache,ackUserWrite.path,writesCache,completeCache,accumulator):function viewProcessorAckUserWrite(viewProcessor,viewCache,ackPath,affectedTree,writesCache,completeCache,accumulator){if(null!=writeTreeRefShadowingWrite(writesCache,ackPath))return viewCache;const filterServerNode=viewCache.serverCache.isFiltered(),serverCache=viewCache.serverCache;if(null!=affectedTree.value){if(pathIsEmpty(ackPath)&&serverCache.isFullyInitialized()||serverCache.isCompleteForPath(ackPath))return viewProcessorApplyServerOverwrite(viewProcessor,viewCache,ackPath,serverCache.getNode().getChild(ackPath),writesCache,completeCache,filterServerNode,accumulator);if(pathIsEmpty(ackPath)){let changedChildren=new ImmutableTree(null);return serverCache.getNode().forEachChild(KEY_INDEX,((name,node)=>{changedChildren=changedChildren.set(new Path(name),node)})),viewProcessorApplyServerMerge(viewProcessor,viewCache,ackPath,changedChildren,writesCache,completeCache,filterServerNode,accumulator)}return viewCache}{let changedChildren=new ImmutableTree(null);return affectedTree.foreach(((mergePath,value)=>{const serverCachePath=pathChild(ackPath,mergePath);serverCache.isCompleteForPath(serverCachePath)&&(changedChildren=changedChildren.set(mergePath,serverCache.getNode().getChild(serverCachePath)))})),viewProcessorApplyServerMerge(viewProcessor,viewCache,ackPath,changedChildren,writesCache,completeCache,filterServerNode,accumulator)}}(viewProcessor,oldViewCache,ackUserWrite.path,ackUserWrite.affectedTree,writesCache,completeCache,accumulator)}else{if(operation.type!==OperationType.LISTEN_COMPLETE)throw assertionError("Unknown operation type: "+operation.type);newViewCache=function viewProcessorListenComplete(viewProcessor,viewCache,path,writesCache,accumulator){const oldServerNode=viewCache.serverCache,newViewCache=viewCacheUpdateServerSnap(viewCache,oldServerNode.getNode(),oldServerNode.isFullyInitialized()||pathIsEmpty(path),oldServerNode.isFiltered());return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor,newViewCache,path,writesCache,NO_COMPLETE_CHILD_SOURCE,accumulator)}(viewProcessor,oldViewCache,operation.path,writesCache,accumulator)}const changes=accumulator.getChanges();return function viewProcessorMaybeAddValueEvent(oldViewCache,newViewCache,accumulator){const eventSnap=newViewCache.eventCache;if(eventSnap.isFullyInitialized()){const isLeafOrEmpty=eventSnap.getNode().isLeafNode()||eventSnap.getNode().isEmpty(),oldCompleteSnap=viewCacheGetCompleteEventSnap(oldViewCache);(accumulator.length>0||!oldViewCache.eventCache.isFullyInitialized()||isLeafOrEmpty&&!eventSnap.getNode().equals(oldCompleteSnap)||!eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority()))&&accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)))}}(oldViewCache,newViewCache,changes),{viewCache:newViewCache,changes}}function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor,viewCache,changePath,writesCache,source,accumulator){const oldEventSnap=viewCache.eventCache;if(null!=writeTreeRefShadowingWrite(writesCache,changePath))return viewCache;{let newEventCache,serverNode;if(pathIsEmpty(changePath))if(index_esm2017_assert(viewCache.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),viewCache.serverCache.isFiltered()){const serverCache=viewCacheGetCompleteServerSnap(viewCache),completeEventChildren=writeTreeRefCalcCompleteEventChildren(writesCache,serverCache instanceof ChildrenNode?serverCache:ChildrenNode.EMPTY_NODE);newEventCache=viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(),completeEventChildren,accumulator)}else{const completeNode=writeTreeRefCalcCompleteEventCache(writesCache,viewCacheGetCompleteServerSnap(viewCache));newEventCache=viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(),completeNode,accumulator)}else{const childKey=pathGetFront(changePath);if(".priority"===childKey){index_esm2017_assert(1===pathGetLength(changePath),"Can't have a priority with additional path components");const oldEventNode=oldEventSnap.getNode();serverNode=viewCache.serverCache.getNode();const updatedPriority=writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache,changePath,oldEventNode,serverNode);newEventCache=null!=updatedPriority?viewProcessor.filter.updatePriority(oldEventNode,updatedPriority):oldEventSnap.getNode()}else{const childChangePath=pathPopFront(changePath);let newEventChild;if(oldEventSnap.isCompleteForChild(childKey)){serverNode=viewCache.serverCache.getNode();const eventChildUpdate=writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache,changePath,oldEventSnap.getNode(),serverNode);newEventChild=null!=eventChildUpdate?oldEventSnap.getNode().getImmediateChild(childKey).updateChild(childChangePath,eventChildUpdate):oldEventSnap.getNode().getImmediateChild(childKey)}else newEventChild=writeTreeRefCalcCompleteChild(writesCache,childKey,viewCache.serverCache);newEventCache=null!=newEventChild?viewProcessor.filter.updateChild(oldEventSnap.getNode(),childKey,newEventChild,childChangePath,source,accumulator):oldEventSnap.getNode()}}return viewCacheUpdateEventSnap(viewCache,newEventCache,oldEventSnap.isFullyInitialized()||pathIsEmpty(changePath),viewProcessor.filter.filtersNodes())}}function viewProcessorApplyServerOverwrite(viewProcessor,oldViewCache,changePath,changedSnap,writesCache,completeCache,filterServerNode,accumulator){const oldServerSnap=oldViewCache.serverCache;let newServerCache;const serverFilter=filterServerNode?viewProcessor.filter:viewProcessor.filter.getIndexedFilter();if(pathIsEmpty(changePath))newServerCache=serverFilter.updateFullNode(oldServerSnap.getNode(),changedSnap,null);else if(serverFilter.filtersNodes()&&!oldServerSnap.isFiltered()){const newServerNode=oldServerSnap.getNode().updateChild(changePath,changedSnap);newServerCache=serverFilter.updateFullNode(oldServerSnap.getNode(),newServerNode,null)}else{const childKey=pathGetFront(changePath);if(!oldServerSnap.isCompleteForPath(changePath)&&pathGetLength(changePath)>1)return oldViewCache;const childChangePath=pathPopFront(changePath),newChildNode=oldServerSnap.getNode().getImmediateChild(childKey).updateChild(childChangePath,changedSnap);newServerCache=".priority"===childKey?serverFilter.updatePriority(oldServerSnap.getNode(),newChildNode):serverFilter.updateChild(oldServerSnap.getNode(),childKey,newChildNode,childChangePath,NO_COMPLETE_CHILD_SOURCE,null)}const newViewCache=viewCacheUpdateServerSnap(oldViewCache,newServerCache,oldServerSnap.isFullyInitialized()||pathIsEmpty(changePath),serverFilter.filtersNodes());return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor,newViewCache,changePath,writesCache,new WriteTreeCompleteChildSource(writesCache,newViewCache,completeCache),accumulator)}function viewProcessorApplyUserOverwrite(viewProcessor,oldViewCache,changePath,changedSnap,writesCache,completeCache,accumulator){const oldEventSnap=oldViewCache.eventCache;let newViewCache,newEventCache;const source=new WriteTreeCompleteChildSource(writesCache,oldViewCache,completeCache);if(pathIsEmpty(changePath))newEventCache=viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(),changedSnap,accumulator),newViewCache=viewCacheUpdateEventSnap(oldViewCache,newEventCache,!0,viewProcessor.filter.filtersNodes());else{const childKey=pathGetFront(changePath);if(".priority"===childKey)newEventCache=viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(),changedSnap),newViewCache=viewCacheUpdateEventSnap(oldViewCache,newEventCache,oldEventSnap.isFullyInitialized(),oldEventSnap.isFiltered());else{const childChangePath=pathPopFront(changePath),oldChild=oldEventSnap.getNode().getImmediateChild(childKey);let newChild;if(pathIsEmpty(childChangePath))newChild=changedSnap;else{const childNode=source.getCompleteChild(childKey);newChild=null!=childNode?".priority"===pathGetBack(childChangePath)&&childNode.getChild(pathParent(childChangePath)).isEmpty()?childNode:childNode.updateChild(childChangePath,changedSnap):ChildrenNode.EMPTY_NODE}if(oldChild.equals(newChild))newViewCache=oldViewCache;else{newViewCache=viewCacheUpdateEventSnap(oldViewCache,viewProcessor.filter.updateChild(oldEventSnap.getNode(),childKey,newChild,childChangePath,source,accumulator),oldEventSnap.isFullyInitialized(),viewProcessor.filter.filtersNodes())}}}return newViewCache}function viewProcessorCacheHasChild(viewCache,childKey){return viewCache.eventCache.isCompleteForChild(childKey)}function viewProcessorApplyMerge(viewProcessor,node,merge){return merge.foreach(((relativePath,childNode)=>{node=node.updateChild(relativePath,childNode)})),node}function viewProcessorApplyServerMerge(viewProcessor,viewCache,path,changedChildren,writesCache,serverCache,filterServerNode,accumulator){if(viewCache.serverCache.getNode().isEmpty()&&!viewCache.serverCache.isFullyInitialized())return viewCache;let viewMergeTree,curViewCache=viewCache;viewMergeTree=pathIsEmpty(path)?changedChildren:new ImmutableTree(null).setTree(path,changedChildren);const serverNode=viewCache.serverCache.getNode();return viewMergeTree.children.inorderTraversal(((childKey,childTree)=>{if(serverNode.hasChild(childKey)){const newChild=viewProcessorApplyMerge(0,viewCache.serverCache.getNode().getImmediateChild(childKey),childTree);curViewCache=viewProcessorApplyServerOverwrite(viewProcessor,curViewCache,new Path(childKey),newChild,writesCache,serverCache,filterServerNode,accumulator)}})),viewMergeTree.children.inorderTraversal(((childKey,childMergeTree)=>{const isUnknownDeepMerge=!viewCache.serverCache.isCompleteForChild(childKey)&&null===childMergeTree.value;if(!serverNode.hasChild(childKey)&&!isUnknownDeepMerge){const newChild=viewProcessorApplyMerge(0,viewCache.serverCache.getNode().getImmediateChild(childKey),childMergeTree);curViewCache=viewProcessorApplyServerOverwrite(viewProcessor,curViewCache,new Path(childKey),newChild,writesCache,serverCache,filterServerNode,accumulator)}})),curViewCache}class View{constructor(query_,initialViewCache){this.query_=query_,this.eventRegistrations_=[];const params=this.query_._queryParams,indexFilter=new IndexedFilter(params.getIndex()),filter=function queryParamsGetNodeFilter(queryParams){return queryParams.loadsAllData()?new IndexedFilter(queryParams.getIndex()):queryParams.hasLimit()?new LimitedFilter(queryParams):new RangedFilter(queryParams)}(params);this.processor_=function newViewProcessor(filter){return{filter}}(filter);const initialServerCache=initialViewCache.serverCache,initialEventCache=initialViewCache.eventCache,serverSnap=indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE,initialServerCache.getNode(),null),eventSnap=filter.updateFullNode(ChildrenNode.EMPTY_NODE,initialEventCache.getNode(),null),newServerCache=new CacheNode(serverSnap,initialServerCache.isFullyInitialized(),indexFilter.filtersNodes()),newEventCache=new CacheNode(eventSnap,initialEventCache.isFullyInitialized(),filter.filtersNodes());this.viewCache_=newViewCache(newEventCache,newServerCache),this.eventGenerator_=new EventGenerator(this.query_)}get query(){return this.query_}}function viewGetCompleteServerCache(view,path){const cache=viewCacheGetCompleteServerSnap(view.viewCache_);return cache&&(view.query._queryParams.loadsAllData()||!pathIsEmpty(path)&&!cache.getImmediateChild(pathGetFront(path)).isEmpty())?cache.getChild(path):null}function viewIsEmpty(view){return 0===view.eventRegistrations_.length}function viewRemoveEventRegistration(view,eventRegistration,cancelError){const cancelEvents=[];if(cancelError){index_esm2017_assert(null==eventRegistration,"A cancel should cancel all event registrations.");const path=view.query._path;view.eventRegistrations_.forEach((registration=>{const maybeEvent=registration.createCancelEvent(cancelError,path);maybeEvent&&cancelEvents.push(maybeEvent)}))}if(eventRegistration){let remaining=[];for(let i=0;i<view.eventRegistrations_.length;++i){const existing=view.eventRegistrations_[i];if(existing.matches(eventRegistration)){if(eventRegistration.hasAnyCallback()){remaining=remaining.concat(view.eventRegistrations_.slice(i+1));break}}else remaining.push(existing)}view.eventRegistrations_=remaining}else view.eventRegistrations_=[];return cancelEvents}function viewApplyOperation(view,operation,writesCache,completeServerCache){operation.type===OperationType.MERGE&&null!==operation.source.queryId&&(index_esm2017_assert(viewCacheGetCompleteServerSnap(view.viewCache_),"We should always have a full cache before handling merges"),index_esm2017_assert(viewCacheGetCompleteEventSnap(view.viewCache_),"Missing event cache, even though we have a server cache"));const oldViewCache=view.viewCache_,result=viewProcessorApplyOperation(view.processor_,oldViewCache,operation,writesCache,completeServerCache);return function viewProcessorAssertIndexed(viewProcessor,viewCache){index_esm2017_assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()),"Event snap not indexed"),index_esm2017_assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()),"Server snap not indexed")}(view.processor_,result.viewCache),index_esm2017_assert(result.viewCache.serverCache.isFullyInitialized()||!oldViewCache.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),view.viewCache_=result.viewCache,viewGenerateEventsForChanges_(view,result.changes,result.viewCache.eventCache.getNode(),null)}function viewGenerateEventsForChanges_(view,changes,eventCache,eventRegistration){const registrations=eventRegistration?[eventRegistration]:view.eventRegistrations_;return function eventGeneratorGenerateEventsForChanges(eventGenerator,changes,eventCache,eventRegistrations){const events=[],moves=[];return changes.forEach((change=>{"child_changed"===change.type&&eventGenerator.index_.indexedValueChanged(change.oldSnap,change.snapshotNode)&&moves.push(function changeChildMoved(childName,snapshotNode){return{type:"child_moved",snapshotNode,childName}}(change.childName,change.snapshotNode))})),eventGeneratorGenerateEventsForType(eventGenerator,events,"child_removed",changes,eventRegistrations,eventCache),eventGeneratorGenerateEventsForType(eventGenerator,events,"child_added",changes,eventRegistrations,eventCache),eventGeneratorGenerateEventsForType(eventGenerator,events,"child_moved",moves,eventRegistrations,eventCache),eventGeneratorGenerateEventsForType(eventGenerator,events,"child_changed",changes,eventRegistrations,eventCache),eventGeneratorGenerateEventsForType(eventGenerator,events,"value",changes,eventRegistrations,eventCache),events}(view.eventGenerator_,changes,eventCache,registrations)}let referenceConstructor$1,referenceConstructor;class SyncPoint{constructor(){this.views=new Map}}function syncPointApplyOperation(syncPoint,operation,writesCache,optCompleteServerCache){const queryId=operation.source.queryId;if(null!==queryId){const view=syncPoint.views.get(queryId);return index_esm2017_assert(null!=view,"SyncTree gave us an op for an invalid query."),viewApplyOperation(view,operation,writesCache,optCompleteServerCache)}{let events=[];for(const view of syncPoint.views.values())events=events.concat(viewApplyOperation(view,operation,writesCache,optCompleteServerCache));return events}}function syncPointGetView(syncPoint,query,writesCache,serverCache,serverCacheComplete){const queryId=query._queryIdentifier,view=syncPoint.views.get(queryId);if(!view){let eventCache=writeTreeRefCalcCompleteEventCache(writesCache,serverCacheComplete?serverCache:null),eventCacheComplete=!1;eventCache?eventCacheComplete=!0:serverCache instanceof ChildrenNode?(eventCache=writeTreeRefCalcCompleteEventChildren(writesCache,serverCache),eventCacheComplete=!1):(eventCache=ChildrenNode.EMPTY_NODE,eventCacheComplete=!1);const viewCache=newViewCache(new CacheNode(eventCache,eventCacheComplete,!1),new CacheNode(serverCache,serverCacheComplete,!1));return new View(query,viewCache)}return view}function syncPointAddEventRegistration(syncPoint,query,eventRegistration,writesCache,serverCache,serverCacheComplete){const view=syncPointGetView(syncPoint,query,writesCache,serverCache,serverCacheComplete);return syncPoint.views.has(query._queryIdentifier)||syncPoint.views.set(query._queryIdentifier,view),function viewAddEventRegistration(view,eventRegistration){view.eventRegistrations_.push(eventRegistration)}(view,eventRegistration),function viewGetInitialEvents(view,registration){const eventSnap=view.viewCache_.eventCache,initialChanges=[];eventSnap.getNode().isLeafNode()||eventSnap.getNode().forEachChild(PRIORITY_INDEX,((key,childNode)=>{initialChanges.push(changeChildAdded(key,childNode))}));return eventSnap.isFullyInitialized()&&initialChanges.push(changeValue(eventSnap.getNode())),viewGenerateEventsForChanges_(view,initialChanges,eventSnap.getNode(),registration)}(view,eventRegistration)}function syncPointRemoveEventRegistration(syncPoint,query,eventRegistration,cancelError){const queryId=query._queryIdentifier,removed=[];let cancelEvents=[];const hadCompleteView=syncPointHasCompleteView(syncPoint);if("default"===queryId)for(const[viewQueryId,view]of syncPoint.views.entries())cancelEvents=cancelEvents.concat(viewRemoveEventRegistration(view,eventRegistration,cancelError)),viewIsEmpty(view)&&(syncPoint.views.delete(viewQueryId),view.query._queryParams.loadsAllData()||removed.push(view.query));else{const view=syncPoint.views.get(queryId);view&&(cancelEvents=cancelEvents.concat(viewRemoveEventRegistration(view,eventRegistration,cancelError)),viewIsEmpty(view)&&(syncPoint.views.delete(queryId),view.query._queryParams.loadsAllData()||removed.push(view.query)))}return hadCompleteView&&!syncPointHasCompleteView(syncPoint)&&removed.push(new(function syncPointGetReferenceConstructor(){return index_esm2017_assert(referenceConstructor$1,"Reference.ts has not been loaded"),referenceConstructor$1}())(query._repo,query._path)),{removed,events:cancelEvents}}function syncPointGetQueryViews(syncPoint){const result=[];for(const view of syncPoint.views.values())view.query._queryParams.loadsAllData()||result.push(view);return result}function syncPointGetCompleteServerCache(syncPoint,path){let serverCache=null;for(const view of syncPoint.views.values())serverCache=serverCache||viewGetCompleteServerCache(view,path);return serverCache}function syncPointViewForQuery(syncPoint,query){if(query._queryParams.loadsAllData())return syncPointGetCompleteView(syncPoint);{const queryId=query._queryIdentifier;return syncPoint.views.get(queryId)}}function syncPointViewExistsForQuery(syncPoint,query){return null!=syncPointViewForQuery(syncPoint,query)}function syncPointHasCompleteView(syncPoint){return null!=syncPointGetCompleteView(syncPoint)}function syncPointGetCompleteView(syncPoint){for(const view of syncPoint.views.values())if(view.query._queryParams.loadsAllData())return view;return null}let syncTreeNextQueryTag_=1;class SyncTree{constructor(listenProvider_){this.listenProvider_=listenProvider_,this.syncPointTree_=new ImmutableTree(null),this.pendingWriteTree_=function newWriteTree(){return{visibleWrites:CompoundWrite.empty(),allWrites:[],lastWriteId:-1}}(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function syncTreeApplyUserOverwrite(syncTree,path,newData,writeId,visible){return function writeTreeAddOverwrite(writeTree,path,snap,writeId,visible){index_esm2017_assert(writeId>writeTree.lastWriteId,"Stacking an older write on top of newer ones"),void 0===visible&&(visible=!0),writeTree.allWrites.push({path,snap,writeId,visible}),visible&&(writeTree.visibleWrites=compoundWriteAddWrite(writeTree.visibleWrites,path,snap)),writeTree.lastWriteId=writeId}(syncTree.pendingWriteTree_,path,newData,writeId,visible),visible?syncTreeApplyOperationToSyncPoints_(syncTree,new Overwrite({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},path,newData)):[]}function syncTreeAckUserWrite(syncTree,writeId,revert=!1){const write=function writeTreeGetWrite(writeTree,writeId){for(let i=0;i<writeTree.allWrites.length;i++){const record=writeTree.allWrites[i];if(record.writeId===writeId)return record}return null}(syncTree.pendingWriteTree_,writeId);if(writeTreeRemoveWrite(syncTree.pendingWriteTree_,writeId)){let affectedTree=new ImmutableTree(null);return null!=write.snap?affectedTree=affectedTree.set(newEmptyPath(),!0):each(write.children,(pathString=>{affectedTree=affectedTree.set(new Path(pathString),!0)})),syncTreeApplyOperationToSyncPoints_(syncTree,new AckUserWrite(write.path,affectedTree,revert))}return[]}function syncTreeApplyServerOverwrite(syncTree,path,newData){return syncTreeApplyOperationToSyncPoints_(syncTree,new Overwrite({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},path,newData))}function syncTreeRemoveEventRegistration(syncTree,query,eventRegistration,cancelError,skipListenerDedup=!1){const path=query._path,maybeSyncPoint=syncTree.syncPointTree_.get(path);let cancelEvents=[];if(maybeSyncPoint&&("default"===query._queryIdentifier||syncPointViewExistsForQuery(maybeSyncPoint,query))){const removedAndEvents=syncPointRemoveEventRegistration(maybeSyncPoint,query,eventRegistration,cancelError);(function syncPointIsEmpty(syncPoint){return 0===syncPoint.views.size})(maybeSyncPoint)&&(syncTree.syncPointTree_=syncTree.syncPointTree_.remove(path));const removed=removedAndEvents.removed;if(cancelEvents=removedAndEvents.events,!skipListenerDedup){const removingDefault=-1!==removed.findIndex((query=>query._queryParams.loadsAllData())),covered=syncTree.syncPointTree_.findOnPath(path,((relativePath,parentSyncPoint)=>syncPointHasCompleteView(parentSyncPoint)));if(removingDefault&&!covered){const subtree=syncTree.syncPointTree_.subtree(path);if(!subtree.isEmpty()){const newViews=function syncTreeCollectDistinctViewsForSubTree_(subtree){return subtree.fold(((relativePath,maybeChildSyncPoint,childMap)=>{if(maybeChildSyncPoint&&syncPointHasCompleteView(maybeChildSyncPoint)){return[syncPointGetCompleteView(maybeChildSyncPoint)]}{let views=[];return maybeChildSyncPoint&&(views=syncPointGetQueryViews(maybeChildSyncPoint)),each(childMap,((_key,childViews)=>{views=views.concat(childViews)})),views}}))}(subtree);for(let i=0;i<newViews.length;++i){const view=newViews[i],newQuery=view.query,listener=syncTreeCreateListenerForView_(syncTree,view);syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery),syncTreeTagForQuery(syncTree,newQuery),listener.hashFn,listener.onComplete)}}}if(!covered&&removed.length>0&&!cancelError)if(removingDefault){const defaultTag=null;syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query),defaultTag)}else removed.forEach((queryToRemove=>{const tagToRemove=syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove),tagToRemove)}))}!function syncTreeRemoveTags_(syncTree,queries){for(let j=0;j<queries.length;++j){const removedQuery=queries[j];if(!removedQuery._queryParams.loadsAllData()){const removedQueryKey=syncTreeMakeQueryKey_(removedQuery),removedQueryTag=syncTree.queryToTagMap.get(removedQueryKey);syncTree.queryToTagMap.delete(removedQueryKey),syncTree.tagToQueryMap.delete(removedQueryTag)}}}(syncTree,removed)}return cancelEvents}function syncTreeApplyTaggedQueryOverwrite(syncTree,path,snap,tag){const queryKey=syncTreeQueryKeyForTag_(syncTree,tag);if(null!=queryKey){const r=syncTreeParseQueryKey_(queryKey),queryPath=r.path,queryId=r.queryId,relativePath=newRelativePath(queryPath,path);return syncTreeApplyTaggedOperation_(syncTree,queryPath,new Overwrite(newOperationSourceServerTaggedQuery(queryId),relativePath,snap))}return[]}function syncTreeAddEventRegistration(syncTree,query,eventRegistration,skipSetupListener=!1){const path=query._path;let serverCache=null,foundAncestorDefaultView=!1;syncTree.syncPointTree_.foreachOnPath(path,((pathToSyncPoint,sp)=>{const relativePath=newRelativePath(pathToSyncPoint,path);serverCache=serverCache||syncPointGetCompleteServerCache(sp,relativePath),foundAncestorDefaultView=foundAncestorDefaultView||syncPointHasCompleteView(sp)}));let serverCacheComplete,syncPoint=syncTree.syncPointTree_.get(path);if(syncPoint?(foundAncestorDefaultView=foundAncestorDefaultView||syncPointHasCompleteView(syncPoint),serverCache=serverCache||syncPointGetCompleteServerCache(syncPoint,newEmptyPath())):(syncPoint=new SyncPoint,syncTree.syncPointTree_=syncTree.syncPointTree_.set(path,syncPoint)),null!=serverCache)serverCacheComplete=!0;else{serverCacheComplete=!1,serverCache=ChildrenNode.EMPTY_NODE;syncTree.syncPointTree_.subtree(path).foreachChild(((childName,childSyncPoint)=>{const completeCache=syncPointGetCompleteServerCache(childSyncPoint,newEmptyPath());completeCache&&(serverCache=serverCache.updateImmediateChild(childName,completeCache))}))}const viewAlreadyExists=syncPointViewExistsForQuery(syncPoint,query);if(!viewAlreadyExists&&!query._queryParams.loadsAllData()){const queryKey=syncTreeMakeQueryKey_(query);index_esm2017_assert(!syncTree.queryToTagMap.has(queryKey),"View does not exist, but we have a tag");const tag=function syncTreeGetNextQueryTag_(){return syncTreeNextQueryTag_++}();syncTree.queryToTagMap.set(queryKey,tag),syncTree.tagToQueryMap.set(tag,queryKey)}let events=syncPointAddEventRegistration(syncPoint,query,eventRegistration,writeTreeChildWrites(syncTree.pendingWriteTree_,path),serverCache,serverCacheComplete);if(!viewAlreadyExists&&!foundAncestorDefaultView&&!skipSetupListener){const view=syncPointViewForQuery(syncPoint,query);events=events.concat(function syncTreeSetupListener_(syncTree,query,view){const path=query._path,tag=syncTreeTagForQuery(syncTree,query),listener=syncTreeCreateListenerForView_(syncTree,view),events=syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query),tag,listener.hashFn,listener.onComplete),subtree=syncTree.syncPointTree_.subtree(path);if(tag)index_esm2017_assert(!syncPointHasCompleteView(subtree.value),"If we're adding a query, it shouldn't be shadowed");else{const queriesToStop=subtree.fold(((relativePath,maybeChildSyncPoint,childMap)=>{if(!pathIsEmpty(relativePath)&&maybeChildSyncPoint&&syncPointHasCompleteView(maybeChildSyncPoint))return[syncPointGetCompleteView(maybeChildSyncPoint).query];{let queries=[];return maybeChildSyncPoint&&(queries=queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map((view=>view.query)))),each(childMap,((_key,childQueries)=>{queries=queries.concat(childQueries)})),queries}}));for(let i=0;i<queriesToStop.length;++i){const queryToStop=queriesToStop[i];syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop),syncTreeTagForQuery(syncTree,queryToStop))}}return events}(syncTree,query,view))}return events}function syncTreeCalcCompleteEventCache(syncTree,path,writeIdsToExclude){const writeTree=syncTree.pendingWriteTree_,serverCache=syncTree.syncPointTree_.findOnPath(path,((pathSoFar,syncPoint)=>{const serverCache=syncPointGetCompleteServerCache(syncPoint,newRelativePath(pathSoFar,path));if(serverCache)return serverCache}));return writeTreeCalcCompleteEventCache(writeTree,path,serverCache,writeIdsToExclude,!0)}function syncTreeGetServerValue(syncTree,query){const path=query._path;let serverCache=null;syncTree.syncPointTree_.foreachOnPath(path,((pathToSyncPoint,sp)=>{const relativePath=newRelativePath(pathToSyncPoint,path);serverCache=serverCache||syncPointGetCompleteServerCache(sp,relativePath)}));let syncPoint=syncTree.syncPointTree_.get(path);syncPoint?serverCache=serverCache||syncPointGetCompleteServerCache(syncPoint,newEmptyPath()):(syncPoint=new SyncPoint,syncTree.syncPointTree_=syncTree.syncPointTree_.set(path,syncPoint));const serverCacheComplete=null!=serverCache,serverCacheNode=serverCacheComplete?new CacheNode(serverCache,!0,!1):null;return function viewGetCompleteNode(view){return viewCacheGetCompleteEventSnap(view.viewCache_)}(syncPointGetView(syncPoint,query,writeTreeChildWrites(syncTree.pendingWriteTree_,query._path),serverCacheComplete?serverCacheNode.getNode():ChildrenNode.EMPTY_NODE,serverCacheComplete))}function syncTreeApplyOperationToSyncPoints_(syncTree,operation){return syncTreeApplyOperationHelper_(operation,syncTree.syncPointTree_,null,writeTreeChildWrites(syncTree.pendingWriteTree_,newEmptyPath()))}function syncTreeApplyOperationHelper_(operation,syncPointTree,serverCache,writesCache){if(pathIsEmpty(operation.path))return syncTreeApplyOperationDescendantsHelper_(operation,syncPointTree,serverCache,writesCache);{const syncPoint=syncPointTree.get(newEmptyPath());null==serverCache&&null!=syncPoint&&(serverCache=syncPointGetCompleteServerCache(syncPoint,newEmptyPath()));let events=[];const childName=pathGetFront(operation.path),childOperation=operation.operationForChild(childName),childTree=syncPointTree.children.get(childName);if(childTree&&childOperation){const childServerCache=serverCache?serverCache.getImmediateChild(childName):null,childWritesCache=writeTreeRefChild(writesCache,childName);events=events.concat(syncTreeApplyOperationHelper_(childOperation,childTree,childServerCache,childWritesCache))}return syncPoint&&(events=events.concat(syncPointApplyOperation(syncPoint,operation,writesCache,serverCache))),events}}function syncTreeApplyOperationDescendantsHelper_(operation,syncPointTree,serverCache,writesCache){const syncPoint=syncPointTree.get(newEmptyPath());null==serverCache&&null!=syncPoint&&(serverCache=syncPointGetCompleteServerCache(syncPoint,newEmptyPath()));let events=[];return syncPointTree.children.inorderTraversal(((childName,childTree)=>{const childServerCache=serverCache?serverCache.getImmediateChild(childName):null,childWritesCache=writeTreeRefChild(writesCache,childName),childOperation=operation.operationForChild(childName);childOperation&&(events=events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation,childTree,childServerCache,childWritesCache)))})),syncPoint&&(events=events.concat(syncPointApplyOperation(syncPoint,operation,writesCache,serverCache))),events}function syncTreeCreateListenerForView_(syncTree,view){const query=view.query,tag=syncTreeTagForQuery(syncTree,query);return{hashFn:()=>{const cache=function viewGetServerCache(view){return view.viewCache_.serverCache.getNode()}(view)||ChildrenNode.EMPTY_NODE;return cache.hash()},onComplete:status=>{if("ok"===status)return tag?function syncTreeApplyTaggedListenComplete(syncTree,path,tag){const queryKey=syncTreeQueryKeyForTag_(syncTree,tag);if(queryKey){const r=syncTreeParseQueryKey_(queryKey),queryPath=r.path,queryId=r.queryId,relativePath=newRelativePath(queryPath,path);return syncTreeApplyTaggedOperation_(syncTree,queryPath,new ListenComplete(newOperationSourceServerTaggedQuery(queryId),relativePath))}return[]}(syncTree,query._path,tag):function syncTreeApplyListenComplete(syncTree,path){return syncTreeApplyOperationToSyncPoints_(syncTree,new ListenComplete({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},path))}(syncTree,query._path);{const error=function errorForServerCode(code,query){let reason="Unknown Error";"too_big"===code?reason="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===code?reason="Client doesn't have permission to access the desired data.":"unavailable"===code&&(reason="The service is unavailable");const error=new Error(code+" at "+query._path.toString()+": "+reason);return error.code=code.toUpperCase(),error}(status,query);return syncTreeRemoveEventRegistration(syncTree,query,null,error)}}}}function syncTreeTagForQuery(syncTree,query){const queryKey=syncTreeMakeQueryKey_(query);return syncTree.queryToTagMap.get(queryKey)}function syncTreeMakeQueryKey_(query){return query._path.toString()+"$"+query._queryIdentifier}function syncTreeQueryKeyForTag_(syncTree,tag){return syncTree.tagToQueryMap.get(tag)}function syncTreeParseQueryKey_(queryKey){const splitIndex=queryKey.indexOf("$");return index_esm2017_assert(-1!==splitIndex&&splitIndex<queryKey.length-1,"Bad queryKey."),{queryId:queryKey.substr(splitIndex+1),path:new Path(queryKey.substr(0,splitIndex))}}function syncTreeApplyTaggedOperation_(syncTree,queryPath,operation){const syncPoint=syncTree.syncPointTree_.get(queryPath);index_esm2017_assert(syncPoint,"Missing sync point for query tag that we're tracking");return syncPointApplyOperation(syncPoint,operation,writeTreeChildWrites(syncTree.pendingWriteTree_,queryPath),null)}function syncTreeQueryForListening_(query){return query._queryParams.loadsAllData()&&!query._queryParams.isDefault()?new(function syncTreeGetReferenceConstructor(){return index_esm2017_assert(referenceConstructor,"Reference.ts has not been loaded"),referenceConstructor}())(query._repo,query._path):query}class ExistingValueProvider{constructor(node_){this.node_=node_}getImmediateChild(childName){const child=this.node_.getImmediateChild(childName);return new ExistingValueProvider(child)}node(){return this.node_}}class DeferredValueProvider{constructor(syncTree,path){this.syncTree_=syncTree,this.path_=path}getImmediateChild(childName){const childPath=pathChild(this.path_,childName);return new DeferredValueProvider(this.syncTree_,childPath)}node(){return syncTreeCalcCompleteEventCache(this.syncTree_,this.path_)}}const generateWithValues=function(values){return(values=values||{}).timestamp=values.timestamp||(new Date).getTime(),values},resolveDeferredLeafValue=function(value,existingVal,serverValues){return value&&"object"==typeof value?(index_esm2017_assert(".sv"in value,"Unexpected leaf node or priority contents"),"string"==typeof value[".sv"]?resolveScalarDeferredValue(value[".sv"],existingVal,serverValues):"object"==typeof value[".sv"]?resolveComplexDeferredValue(value[".sv"],existingVal):void index_esm2017_assert(!1,"Unexpected server value: "+JSON.stringify(value,null,2))):value},resolveScalarDeferredValue=function(op,existing,serverValues){if("timestamp"===op)return serverValues.timestamp;index_esm2017_assert(!1,"Unexpected server value: "+op)},resolveComplexDeferredValue=function(op,existing,unused){op.hasOwnProperty("increment")||index_esm2017_assert(!1,"Unexpected server value: "+JSON.stringify(op,null,2));const delta=op.increment;"number"!=typeof delta&&index_esm2017_assert(!1,"Unexpected increment value: "+delta);const existingNode=existing.node();if(index_esm2017_assert(null!=existingNode,"Expected ChildrenNode.EMPTY_NODE for nulls"),!existingNode.isLeafNode())return delta;const existingVal=existingNode.getValue();return"number"!=typeof existingVal?delta:existingVal+delta},resolveDeferredValueTree=function(path,node,syncTree,serverValues){return resolveDeferredValue(node,new DeferredValueProvider(syncTree,path),serverValues)},resolveDeferredValueSnapshot=function(node,existing,serverValues){return resolveDeferredValue(node,new ExistingValueProvider(existing),serverValues)};function resolveDeferredValue(node,existingVal,serverValues){const rawPri=node.getPriority().val(),priority=resolveDeferredLeafValue(rawPri,existingVal.getImmediateChild(".priority"),serverValues);let newNode;if(node.isLeafNode()){const leafNode=node,value=resolveDeferredLeafValue(leafNode.getValue(),existingVal,serverValues);return value!==leafNode.getValue()||priority!==leafNode.getPriority().val()?new LeafNode(value,nodeFromJSON(priority)):node}{const childrenNode=node;return newNode=childrenNode,priority!==childrenNode.getPriority().val()&&(newNode=newNode.updatePriority(new LeafNode(priority))),childrenNode.forEachChild(PRIORITY_INDEX,((childName,childNode)=>{const newChildNode=resolveDeferredValue(childNode,existingVal.getImmediateChild(childName),serverValues);newChildNode!==childNode&&(newNode=newNode.updateImmediateChild(childName,newChildNode))})),newNode}}class Tree{constructor(name="",parent=null,node={children:{},childCount:0}){this.name=name,this.parent=parent,this.node=node}}function treeSubTree(tree,pathObj){let path=pathObj instanceof Path?pathObj:new Path(pathObj),child=tree,next=pathGetFront(path);for(;null!==next;){const childNode=index_esm2017_safeGet(child.node.children,next)||{children:{},childCount:0};child=new Tree(next,child,childNode),path=pathPopFront(path),next=pathGetFront(path)}return child}function treeGetValue(tree){return tree.node.value}function treeSetValue(tree,value){tree.node.value=value,treeUpdateParents(tree)}function treeHasChildren(tree){return tree.node.childCount>0}function treeForEachChild(tree,action){each(tree.node.children,((child,childTree)=>{action(new Tree(child,tree,childTree))}))}function treeForEachDescendant(tree,action,includeSelf,childrenFirst){includeSelf&&!childrenFirst&&action(tree),treeForEachChild(tree,(child=>{treeForEachDescendant(child,action,!0,childrenFirst)})),includeSelf&&childrenFirst&&action(tree)}function treeGetPath(tree){return new Path(null===tree.parent?tree.name:treeGetPath(tree.parent)+"/"+tree.name)}function treeUpdateParents(tree){null!==tree.parent&&function treeUpdateChild(tree,childName,child){const childEmpty=function treeIsEmpty(tree){return void 0===treeGetValue(tree)&&!treeHasChildren(tree)}(child),childExists=index_esm2017_contains(tree.node.children,childName);childEmpty&&childExists?(delete tree.node.children[childName],tree.node.childCount--,treeUpdateParents(tree)):childEmpty||childExists||(tree.node.children[childName]=child.node,tree.node.childCount++,treeUpdateParents(tree))}(tree.parent,tree.name,tree)}const INVALID_KEY_REGEX_=/[\[\].#$\/\u0000-\u001F\u007F]/,INVALID_PATH_REGEX_=/[\[\].#$\u0000-\u001F\u007F]/,index_esm2017_isValidKey=function(key){return"string"==typeof key&&0!==key.length&&!INVALID_KEY_REGEX_.test(key)},isValidPathString=function(pathString){return"string"==typeof pathString&&0!==pathString.length&&!INVALID_PATH_REGEX_.test(pathString)},validateFirebaseDataArg=function(fnName,value,path,optional){optional&&void 0===value||validateFirebaseData(index_esm2017_errorPrefix(fnName,"value"),value,path)},validateFirebaseData=function(errorPrefix,data,path_){const path=path_ instanceof Path?new ValidationPath(path_,errorPrefix):path_;if(void 0===data)throw new Error(errorPrefix+"contains undefined "+validationPathToErrorString(path));if("function"==typeof data)throw new Error(errorPrefix+"contains a function "+validationPathToErrorString(path)+" with contents = "+data.toString());if(isInvalidJSONNumber(data))throw new Error(errorPrefix+"contains "+data.toString()+" "+validationPathToErrorString(path));if("string"==typeof data&&data.length>10485760/3&&stringLength(data)>10485760)throw new Error(errorPrefix+"contains a string greater than 10485760 utf8 bytes "+validationPathToErrorString(path)+" ('"+data.substring(0,50)+"...')");if(data&&"object"==typeof data){let hasDotValue=!1,hasActualChild=!1;if(each(data,((key,value)=>{if(".value"===key)hasDotValue=!0;else if(".priority"!==key&&".sv"!==key&&(hasActualChild=!0,!index_esm2017_isValidKey(key)))throw new Error(errorPrefix+" contains an invalid key ("+key+") "+validationPathToErrorString(path)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');!function validationPathPush(validationPath,child){validationPath.parts_.length>0&&(validationPath.byteLength_+=1),validationPath.parts_.push(child),validationPath.byteLength_+=stringLength(child),validationPathCheckValid(validationPath)}(path,key),validateFirebaseData(errorPrefix,value,path),function validationPathPop(validationPath){const last=validationPath.parts_.pop();validationPath.byteLength_-=stringLength(last),validationPath.parts_.length>0&&(validationPath.byteLength_-=1)}(path)})),hasDotValue&&hasActualChild)throw new Error(errorPrefix+' contains ".value" child '+validationPathToErrorString(path)+" in addition to actual children.")}},validatePathString=function(fnName,argumentName,pathString,optional){if(!(optional&&void 0===pathString||isValidPathString(pathString)))throw new Error(index_esm2017_errorPrefix(fnName,argumentName)+'was an invalid path = "'+pathString+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},validateRootPathString=function(fnName,argumentName,pathString,optional){pathString&&(pathString=pathString.replace(/^\/*\.info(\/|$)/,"/")),validatePathString(fnName,argumentName,pathString,optional)},validateWritablePath=function(fnName,path){if(".info"===pathGetFront(path))throw new Error(fnName+" failed = Can't modify data under /.info/")},validateUrl=function(fnName,parsedUrl){const pathString=parsedUrl.path.toString();if("string"!=typeof parsedUrl.repoInfo.host||0===parsedUrl.repoInfo.host.length||!index_esm2017_isValidKey(parsedUrl.repoInfo.namespace)&&"localhost"!==parsedUrl.repoInfo.host.split(":")[0]||0!==pathString.length&&!function(pathString){return pathString&&(pathString=pathString.replace(/^\/*\.info(\/|$)/,"/")),isValidPathString(pathString)}(pathString))throw new Error(index_esm2017_errorPrefix(fnName,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class EventQueue{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function eventQueueQueueEvents(eventQueue,eventDataList){let currList=null;for(let i=0;i<eventDataList.length;i++){const data=eventDataList[i],path=data.getPath();null===currList||pathEquals(path,currList.path)||(eventQueue.eventLists_.push(currList),currList=null),null===currList&&(currList={events:[],path}),currList.events.push(data)}currList&&eventQueue.eventLists_.push(currList)}function eventQueueRaiseEventsAtPath(eventQueue,path,eventDataList){eventQueueQueueEvents(eventQueue,eventDataList),eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue,(eventPath=>pathEquals(eventPath,path)))}function eventQueueRaiseEventsForChangedPath(eventQueue,changedPath,eventDataList){eventQueueQueueEvents(eventQueue,eventDataList),eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue,(eventPath=>pathContains(eventPath,changedPath)||pathContains(changedPath,eventPath)))}function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue,predicate){eventQueue.recursionDepth_++;let sentAll=!0;for(let i=0;i<eventQueue.eventLists_.length;i++){const eventList=eventQueue.eventLists_[i];if(eventList){predicate(eventList.path)?(eventListRaise(eventQueue.eventLists_[i]),eventQueue.eventLists_[i]=null):sentAll=!1}}sentAll&&(eventQueue.eventLists_=[]),eventQueue.recursionDepth_--}function eventListRaise(eventList){for(let i=0;i<eventList.events.length;i++){const eventData=eventList.events[i];if(null!==eventData){eventList.events[i]=null;const eventFn=eventData.getEventRunner();index_esm2017_logger&&log("event: "+eventData.toString()),exceptionGuard(eventFn)}}}const INTERRUPT_REASON="repo_interrupt",MAX_TRANSACTION_RETRIES=25;class Repo{constructor(repoInfo_,forceRestClient_,authTokenProvider_,appCheckProvider_){this.repoInfo_=repoInfo_,this.forceRestClient_=forceRestClient_,this.authTokenProvider_=authTokenProvider_,this.appCheckProvider_=appCheckProvider_,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new EventQueue,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=newSparseSnapshotTree(),this.transactionQueueTree_=new Tree,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function repoStart(repo,appId,authOverride){if(repo.stats_=statsManagerGetCollection(repo.repoInfo_),repo.forceRestClient_||("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0)repo.server_=new ReadonlyRestClient(repo.repoInfo_,((pathString,data,isMerge,tag)=>{repoOnDataUpdate(repo,pathString,data,isMerge,tag)}),repo.authTokenProvider_,repo.appCheckProvider_),setTimeout((()=>repoOnConnectStatus(repo,!0)),0);else{if(null!=authOverride){if("object"!=typeof authOverride)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{stringify(authOverride)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}repo.persistentConnection_=new PersistentConnection(repo.repoInfo_,appId,((pathString,data,isMerge,tag)=>{repoOnDataUpdate(repo,pathString,data,isMerge,tag)}),(connectStatus=>{repoOnConnectStatus(repo,connectStatus)}),(updates=>{!function repoOnServerInfoUpdate(repo,updates){each(updates,((key,value)=>{repoUpdateInfo(repo,key,value)}))}(repo,updates)}),repo.authTokenProvider_,repo.appCheckProvider_,authOverride),repo.server_=repo.persistentConnection_}repo.authTokenProvider_.addTokenChangeListener((token=>{repo.server_.refreshAuthToken(token)})),repo.appCheckProvider_.addTokenChangeListener((result=>{repo.server_.refreshAppCheckToken(result.token)})),repo.statsReporter_=function statsManagerGetOrCreateReporter(repoInfo,creatorFunction){const hashString=repoInfo.toString();return reporters[hashString]||(reporters[hashString]=creatorFunction()),reporters[hashString]}(repo.repoInfo_,(()=>new StatsReporter(repo.stats_,repo.server_))),repo.infoData_=new SnapshotHolder,repo.infoSyncTree_=new SyncTree({startListening:(query,tag,currentHashFn,onComplete)=>{let infoEvents=[];const node=repo.infoData_.getNode(query._path);return node.isEmpty()||(infoEvents=syncTreeApplyServerOverwrite(repo.infoSyncTree_,query._path,node),setTimeout((()=>{onComplete("ok")}),0)),infoEvents},stopListening:()=>{}}),repoUpdateInfo(repo,"connected",!1),repo.serverSyncTree_=new SyncTree({startListening:(query,tag,currentHashFn,onComplete)=>(repo.server_.listen(query,currentHashFn,tag,((status,data)=>{const events=onComplete(status,data);eventQueueRaiseEventsForChangedPath(repo.eventQueue_,query._path,events)})),[]),stopListening:(query,tag)=>{repo.server_.unlisten(query,tag)}})}function repoServerTime(repo){const offset=repo.infoData_.getNode(new Path(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+offset}function repoGenerateServerValues(repo){return generateWithValues({timestamp:repoServerTime(repo)})}function repoOnDataUpdate(repo,pathString,data,isMerge,tag){repo.dataUpdateCount++;const path=new Path(pathString);data=repo.interceptServerDataCallback_?repo.interceptServerDataCallback_(pathString,data):data;let events=[];if(tag)if(isMerge){const taggedChildren=map(data,(raw=>nodeFromJSON(raw)));events=function syncTreeApplyTaggedQueryMerge(syncTree,path,changedChildren,tag){const queryKey=syncTreeQueryKeyForTag_(syncTree,tag);if(queryKey){const r=syncTreeParseQueryKey_(queryKey),queryPath=r.path,queryId=r.queryId,relativePath=newRelativePath(queryPath,path),changeTree=ImmutableTree.fromObject(changedChildren);return syncTreeApplyTaggedOperation_(syncTree,queryPath,new Merge(newOperationSourceServerTaggedQuery(queryId),relativePath,changeTree))}return[]}(repo.serverSyncTree_,path,taggedChildren,tag)}else{const taggedSnap=nodeFromJSON(data);events=syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_,path,taggedSnap,tag)}else if(isMerge){const changedChildren=map(data,(raw=>nodeFromJSON(raw)));events=function syncTreeApplyServerMerge(syncTree,path,changedChildren){const changeTree=ImmutableTree.fromObject(changedChildren);return syncTreeApplyOperationToSyncPoints_(syncTree,new Merge({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},path,changeTree))}(repo.serverSyncTree_,path,changedChildren)}else{const snap=nodeFromJSON(data);events=syncTreeApplyServerOverwrite(repo.serverSyncTree_,path,snap)}let affectedPath=path;events.length>0&&(affectedPath=repoRerunTransactions(repo,path)),eventQueueRaiseEventsForChangedPath(repo.eventQueue_,affectedPath,events)}function repoOnConnectStatus(repo,connectStatus){repoUpdateInfo(repo,"connected",connectStatus),!1===connectStatus&&function repoRunOnDisconnectEvents(repo){repoLog(repo,"onDisconnectEvents");const serverValues=repoGenerateServerValues(repo),resolvedOnDisconnectTree=newSparseSnapshotTree();sparseSnapshotTreeForEachTree(repo.onDisconnect_,newEmptyPath(),((path,node)=>{const resolved=resolveDeferredValueTree(path,node,repo.serverSyncTree_,serverValues);sparseSnapshotTreeRemember(resolvedOnDisconnectTree,path,resolved)}));let events=[];sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree,newEmptyPath(),((path,snap)=>{events=events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_,path,snap));const affectedPath=repoAbortTransactions(repo,path);repoRerunTransactions(repo,affectedPath)})),repo.onDisconnect_=newSparseSnapshotTree(),eventQueueRaiseEventsForChangedPath(repo.eventQueue_,newEmptyPath(),events)}(repo)}function repoUpdateInfo(repo,pathString,value){const path=new Path("/.info/"+pathString),newNode=nodeFromJSON(value);repo.infoData_.updateSnapshot(path,newNode);const events=syncTreeApplyServerOverwrite(repo.infoSyncTree_,path,newNode);eventQueueRaiseEventsForChangedPath(repo.eventQueue_,path,events)}function repoGetNextWriteId(repo){return repo.nextWriteId_++}function repoSetWithPriority(repo,path,newVal,newPriority,onComplete){repoLog(repo,"set",{path:path.toString(),value:newVal,priority:newPriority});const serverValues=repoGenerateServerValues(repo),newNodeUnresolved=nodeFromJSON(newVal,newPriority),existing=syncTreeCalcCompleteEventCache(repo.serverSyncTree_,path),newNode=resolveDeferredValueSnapshot(newNodeUnresolved,existing,serverValues),writeId=repoGetNextWriteId(repo),events=syncTreeApplyUserOverwrite(repo.serverSyncTree_,path,newNode,writeId,!0);eventQueueQueueEvents(repo.eventQueue_,events),repo.server_.put(path.toString(),newNodeUnresolved.val(!0),((status,errorReason)=>{const success="ok"===status;success||warn("set at "+path+" failed: "+status);const clearEvents=syncTreeAckUserWrite(repo.serverSyncTree_,writeId,!success);eventQueueRaiseEventsForChangedPath(repo.eventQueue_,path,clearEvents),repoCallOnCompleteCallback(repo,onComplete,status,errorReason)}));const affectedPath=repoAbortTransactions(repo,path);repoRerunTransactions(repo,affectedPath),eventQueueRaiseEventsForChangedPath(repo.eventQueue_,affectedPath,[])}function repoRemoveEventCallbackForQuery(repo,query,eventRegistration){let events;events=".info"===pathGetFront(query._path)?syncTreeRemoveEventRegistration(repo.infoSyncTree_,query,eventRegistration):syncTreeRemoveEventRegistration(repo.serverSyncTree_,query,eventRegistration),eventQueueRaiseEventsAtPath(repo.eventQueue_,query._path,events)}function repoInterrupt(repo){repo.persistentConnection_&&repo.persistentConnection_.interrupt(INTERRUPT_REASON)}function repoLog(repo,...varArgs){let prefix="";repo.persistentConnection_&&(prefix=repo.persistentConnection_.id+":"),log(prefix,...varArgs)}function repoCallOnCompleteCallback(repo,callback,status,errorReason){callback&&exceptionGuard((()=>{if("ok"===status)callback(null);else{const code=(status||"error").toUpperCase();let message=code;errorReason&&(message+=": "+errorReason);const error=new Error(message);error.code=code,callback(error)}}))}function repoGetLatestState(repo,path,excludeSets){return syncTreeCalcCompleteEventCache(repo.serverSyncTree_,path,excludeSets)||ChildrenNode.EMPTY_NODE}function repoSendReadyTransactions(repo,node=repo.transactionQueueTree_){if(node||repoPruneCompletedTransactionsBelowNode(repo,node),treeGetValue(node)){const queue=repoBuildTransactionQueue(repo,node);index_esm2017_assert(queue.length>0,"Sending zero length transaction queue");queue.every((transaction=>0===transaction.status))&&function repoSendTransactionQueue(repo,path,queue){const setsToIgnore=queue.map((txn=>txn.currentWriteId)),latestState=repoGetLatestState(repo,path,setsToIgnore);let snapToSend=latestState;const latestHash=latestState.hash();for(let i=0;i<queue.length;i++){const txn=queue[i];index_esm2017_assert(0===txn.status,"tryToSendTransactionQueue_: items in queue should all be run."),txn.status=1,txn.retryCount++;const relativePath=newRelativePath(path,txn.path);snapToSend=snapToSend.updateChild(relativePath,txn.currentOutputSnapshotRaw)}const dataToSend=snapToSend.val(!0),pathToSend=path;repo.server_.put(pathToSend.toString(),dataToSend,(status=>{repoLog(repo,"transaction put response",{path:pathToSend.toString(),status});let events=[];if("ok"===status){const callbacks=[];for(let i=0;i<queue.length;i++)queue[i].status=2,events=events.concat(syncTreeAckUserWrite(repo.serverSyncTree_,queue[i].currentWriteId)),queue[i].onComplete&&callbacks.push((()=>queue[i].onComplete(null,!0,queue[i].currentOutputSnapshotResolved))),queue[i].unwatcher();repoPruneCompletedTransactionsBelowNode(repo,treeSubTree(repo.transactionQueueTree_,path)),repoSendReadyTransactions(repo,repo.transactionQueueTree_),eventQueueRaiseEventsForChangedPath(repo.eventQueue_,path,events);for(let i=0;i<callbacks.length;i++)exceptionGuard(callbacks[i])}else{if("datastale"===status)for(let i=0;i<queue.length;i++)3===queue[i].status?queue[i].status=4:queue[i].status=0;else{warn("transaction at "+pathToSend.toString()+" failed: "+status);for(let i=0;i<queue.length;i++)queue[i].status=4,queue[i].abortReason=status}repoRerunTransactions(repo,path)}}),latestHash)}(repo,treeGetPath(node),queue)}else treeHasChildren(node)&&treeForEachChild(node,(childNode=>{repoSendReadyTransactions(repo,childNode)}))}function repoRerunTransactions(repo,changedPath){const rootMostTransactionNode=repoGetAncestorTransactionNode(repo,changedPath),path=treeGetPath(rootMostTransactionNode);return function repoRerunTransactionQueue(repo,queue,path){if(0===queue.length)return;const callbacks=[];let events=[];const txnsToRerun=queue.filter((q=>0===q.status)),setsToIgnore=txnsToRerun.map((q=>q.currentWriteId));for(let i=0;i<queue.length;i++){const transaction=queue[i],relativePath=newRelativePath(path,transaction.path);let abortReason,abortTransaction=!1;if(index_esm2017_assert(null!==relativePath,"rerunTransactionsUnderNode_: relativePath should not be null."),4===transaction.status)abortTransaction=!0,abortReason=transaction.abortReason,events=events.concat(syncTreeAckUserWrite(repo.serverSyncTree_,transaction.currentWriteId,!0));else if(0===transaction.status)if(transaction.retryCount>=MAX_TRANSACTION_RETRIES)abortTransaction=!0,abortReason="maxretry",events=events.concat(syncTreeAckUserWrite(repo.serverSyncTree_,transaction.currentWriteId,!0));else{const currentNode=repoGetLatestState(repo,transaction.path,setsToIgnore);transaction.currentInputSnapshot=currentNode;const newData=queue[i].update(currentNode.val());if(void 0!==newData){validateFirebaseData("transaction failed: Data returned ",newData,transaction.path);let newDataNode=nodeFromJSON(newData);"object"==typeof newData&&null!=newData&&index_esm2017_contains(newData,".priority")||(newDataNode=newDataNode.updatePriority(currentNode.getPriority()));const oldWriteId=transaction.currentWriteId,serverValues=repoGenerateServerValues(repo),newNodeResolved=resolveDeferredValueSnapshot(newDataNode,currentNode,serverValues);transaction.currentOutputSnapshotRaw=newDataNode,transaction.currentOutputSnapshotResolved=newNodeResolved,transaction.currentWriteId=repoGetNextWriteId(repo),setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId),1),events=events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_,transaction.path,newNodeResolved,transaction.currentWriteId,transaction.applyLocally)),events=events.concat(syncTreeAckUserWrite(repo.serverSyncTree_,oldWriteId,!0))}else abortTransaction=!0,abortReason="nodata",events=events.concat(syncTreeAckUserWrite(repo.serverSyncTree_,transaction.currentWriteId,!0))}eventQueueRaiseEventsForChangedPath(repo.eventQueue_,path,events),events=[],abortTransaction&&(queue[i].status=2,unwatcher=queue[i].unwatcher,setTimeout(unwatcher,Math.floor(0)),queue[i].onComplete&&("nodata"===abortReason?callbacks.push((()=>queue[i].onComplete(null,!1,queue[i].currentInputSnapshot))):callbacks.push((()=>queue[i].onComplete(new Error(abortReason),!1,null)))))}var unwatcher;repoPruneCompletedTransactionsBelowNode(repo,repo.transactionQueueTree_);for(let i=0;i<callbacks.length;i++)exceptionGuard(callbacks[i]);repoSendReadyTransactions(repo,repo.transactionQueueTree_)}(repo,repoBuildTransactionQueue(repo,rootMostTransactionNode),path),path}function repoGetAncestorTransactionNode(repo,path){let front,transactionNode=repo.transactionQueueTree_;for(front=pathGetFront(path);null!==front&&void 0===treeGetValue(transactionNode);)transactionNode=treeSubTree(transactionNode,front),front=pathGetFront(path=pathPopFront(path));return transactionNode}function repoBuildTransactionQueue(repo,transactionNode){const transactionQueue=[];return repoAggregateTransactionQueuesForNode(repo,transactionNode,transactionQueue),transactionQueue.sort(((a,b)=>a.order-b.order)),transactionQueue}function repoAggregateTransactionQueuesForNode(repo,node,queue){const nodeQueue=treeGetValue(node);if(nodeQueue)for(let i=0;i<nodeQueue.length;i++)queue.push(nodeQueue[i]);treeForEachChild(node,(child=>{repoAggregateTransactionQueuesForNode(repo,child,queue)}))}function repoPruneCompletedTransactionsBelowNode(repo,node){const queue=treeGetValue(node);if(queue){let to=0;for(let from=0;from<queue.length;from++)2!==queue[from].status&&(queue[to]=queue[from],to++);queue.length=to,treeSetValue(node,queue.length>0?queue:void 0)}treeForEachChild(node,(childNode=>{repoPruneCompletedTransactionsBelowNode(repo,childNode)}))}function repoAbortTransactions(repo,path){const affectedPath=treeGetPath(repoGetAncestorTransactionNode(repo,path)),transactionNode=treeSubTree(repo.transactionQueueTree_,path);return function treeForEachAncestor(tree,action,includeSelf){let node=includeSelf?tree:tree.parent;for(;null!==node;){if(action(node))return!0;node=node.parent}return!1}(transactionNode,(node=>{repoAbortTransactionsOnNode(repo,node)})),repoAbortTransactionsOnNode(repo,transactionNode),treeForEachDescendant(transactionNode,(node=>{repoAbortTransactionsOnNode(repo,node)})),affectedPath}function repoAbortTransactionsOnNode(repo,node){const queue=treeGetValue(node);if(queue){const callbacks=[];let events=[],lastSent=-1;for(let i=0;i<queue.length;i++)3===queue[i].status||(1===queue[i].status?(index_esm2017_assert(lastSent===i-1,"All SENT items should be at beginning of queue."),lastSent=i,queue[i].status=3,queue[i].abortReason="set"):(index_esm2017_assert(0===queue[i].status,"Unexpected transaction status in abort"),queue[i].unwatcher(),events=events.concat(syncTreeAckUserWrite(repo.serverSyncTree_,queue[i].currentWriteId,!0)),queue[i].onComplete&&callbacks.push(queue[i].onComplete.bind(null,new Error("set"),!1,null))));-1===lastSent?treeSetValue(node,void 0):queue.length=lastSent+1,eventQueueRaiseEventsForChangedPath(repo.eventQueue_,treeGetPath(node),events);for(let i=0;i<callbacks.length;i++)exceptionGuard(callbacks[i])}}const parseRepoInfo=function(dataURL,nodeAdmin){const parsedUrl=parseDatabaseURL(dataURL),namespace=parsedUrl.namespace;"firebase.com"===parsedUrl.domain&&fatal(parsedUrl.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),namespace&&"undefined"!==namespace||"localhost"===parsedUrl.domain||fatal("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),parsedUrl.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&warn("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const webSocketOnly="ws"===parsedUrl.scheme||"wss"===parsedUrl.scheme;return{repoInfo:new RepoInfo(parsedUrl.host,parsedUrl.secure,namespace,webSocketOnly,nodeAdmin,"",namespace!==parsedUrl.subdomain),path:new Path(parsedUrl.pathString)}},parseDatabaseURL=function(dataURL){let host="",domain="",subdomain="",pathString="",namespace="",secure=!0,scheme="https",port=443;if("string"==typeof dataURL){let colonInd=dataURL.indexOf("//");colonInd>=0&&(scheme=dataURL.substring(0,colonInd-1),dataURL=dataURL.substring(colonInd+2));let slashInd=dataURL.indexOf("/");-1===slashInd&&(slashInd=dataURL.length);let questionMarkInd=dataURL.indexOf("?");-1===questionMarkInd&&(questionMarkInd=dataURL.length),host=dataURL.substring(0,Math.min(slashInd,questionMarkInd)),slashInd<questionMarkInd&&(pathString=function decodePath(pathString){let pathStringDecoded="";const pieces=pathString.split("/");for(let i=0;i<pieces.length;i++)if(pieces[i].length>0){let piece=pieces[i];try{piece=decodeURIComponent(piece.replace(/\+/g," "))}catch(e){}pathStringDecoded+="/"+piece}return pathStringDecoded}(dataURL.substring(slashInd,questionMarkInd)));const queryParams=function decodeQuery(queryString){const results={};"?"===queryString.charAt(0)&&(queryString=queryString.substring(1));for(const segment of queryString.split("&")){if(0===segment.length)continue;const kv=segment.split("=");2===kv.length?results[decodeURIComponent(kv[0])]=decodeURIComponent(kv[1]):warn(`Invalid query segment '${segment}' in query '${queryString}'`)}return results}(dataURL.substring(Math.min(dataURL.length,questionMarkInd)));colonInd=host.indexOf(":"),colonInd>=0?(secure="https"===scheme||"wss"===scheme,port=parseInt(host.substring(colonInd+1),10)):colonInd=host.length;const hostWithoutPort=host.slice(0,colonInd);if("localhost"===hostWithoutPort.toLowerCase())domain="localhost";else if(hostWithoutPort.split(".").length<=2)domain=hostWithoutPort;else{const dotInd=host.indexOf(".");subdomain=host.substring(0,dotInd).toLowerCase(),domain=host.substring(dotInd+1),namespace=subdomain}"ns"in queryParams&&(namespace=queryParams.ns)}return{host,port,domain,subdomain,secure,scheme,pathString,namespace}},PUSH_CHARS="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";!function(){let lastPushTime=0;const lastRandChars=[]}();class DataEvent{constructor(eventType,eventRegistration,snapshot,prevName){this.eventType=eventType,this.eventRegistration=eventRegistration,this.snapshot=snapshot,this.prevName=prevName}getPath(){const ref=this.snapshot.ref;return"value"===this.eventType?ref._path:ref.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+stringify(this.snapshot.exportVal())}}class CancelEvent{constructor(eventRegistration,error,path){this.eventRegistration=eventRegistration,this.error=error,this.path=path}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class CallbackContext{constructor(snapshotCallback,cancelCallback){this.snapshotCallback=snapshotCallback,this.cancelCallback=cancelCallback}onValue(expDataSnapshot,previousChildName){this.snapshotCallback.call(null,expDataSnapshot,previousChildName)}onCancel(error){return index_esm2017_assert(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,error)}get hasCancelCallback(){return!!this.cancelCallback}matches(other){return this.snapshotCallback===other.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===other.snapshotCallback.userCallback&&this.snapshotCallback.context===other.snapshotCallback.context}}class QueryImpl{constructor(_repo,_path,_queryParams,_orderByCalled){this._repo=_repo,this._path=_path,this._queryParams=_queryParams,this._orderByCalled=_orderByCalled}get key(){return pathIsEmpty(this._path)?null:pathGetBack(this._path)}get ref(){return new ReferenceImpl(this._repo,this._path)}get _queryIdentifier(){const obj=queryParamsGetQueryObject(this._queryParams),id=ObjectToUniqueKey(obj);return"{}"===id?"default":id}get _queryObject(){return queryParamsGetQueryObject(this._queryParams)}isEqual(other){if(!((other=index_esm2017_getModularInstance(other))instanceof QueryImpl))return!1;const sameRepo=this._repo===other._repo,samePath=pathEquals(this._path,other._path),sameQueryIdentifier=this._queryIdentifier===other._queryIdentifier;return sameRepo&&samePath&&sameQueryIdentifier}toJSON(){return this.toString()}toString(){return this._repo.toString()+function pathToUrlEncodedString(path){let pathString="";for(let i=path.pieceNum_;i<path.pieces_.length;i++)""!==path.pieces_[i]&&(pathString+="/"+encodeURIComponent(String(path.pieces_[i])));return pathString||"/"}(this._path)}}class ReferenceImpl extends QueryImpl{constructor(repo,path){super(repo,path,new QueryParams,!1)}get parent(){const parentPath=pathParent(this._path);return null===parentPath?null:new ReferenceImpl(this._repo,parentPath)}get root(){let ref=this;for(;null!==ref.parent;)ref=ref.parent;return ref}}class DataSnapshot{constructor(_node,ref,_index){this._node=_node,this.ref=ref,this._index=_index}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(path){const childPath=new Path(path),childRef=child(this.ref,path);return new DataSnapshot(this._node.getChild(childPath),childRef,PRIORITY_INDEX)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(action){if(this._node.isLeafNode())return!1;return!!this._node.forEachChild(this._index,((key,node)=>action(new DataSnapshot(node,child(this.ref,key),PRIORITY_INDEX))))}hasChild(path){const childPath=new Path(path);return!this._node.getChild(childPath).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function ref(db,path){return(db=index_esm2017_getModularInstance(db))._checkNotDeleted("ref"),void 0!==path?child(db._root,path):db._root}function child(parent,path){return null===pathGetFront((parent=index_esm2017_getModularInstance(parent))._path)?validateRootPathString("child","path",path,!1):validatePathString("child","path",path,!1),new ReferenceImpl(parent._repo,pathChild(parent._path,path))}function set(ref,value){ref=index_esm2017_getModularInstance(ref),validateWritablePath("set",ref._path),validateFirebaseDataArg("set",value,ref._path,!1);const deferred=new index_esm2017_Deferred;return repoSetWithPriority(ref._repo,ref._path,value,null,deferred.wrapCallback((()=>{}))),deferred.promise}function get(query){query=index_esm2017_getModularInstance(query);const callbackContext=new CallbackContext((()=>{})),container=new ValueEventRegistration(callbackContext);return function repoGetValue(repo,query,eventRegistration){const cached=syncTreeGetServerValue(repo.serverSyncTree_,query);return null!=cached?Promise.resolve(cached):repo.server_.get(query).then((payload=>{const node=nodeFromJSON(payload).withIndex(query._queryParams.getIndex());let events;if(syncTreeAddEventRegistration(repo.serverSyncTree_,query,eventRegistration,!0),query._queryParams.loadsAllData())events=syncTreeApplyServerOverwrite(repo.serverSyncTree_,query._path,node);else{const tag=syncTreeTagForQuery(repo.serverSyncTree_,query);events=syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_,query._path,node,tag)}return eventQueueRaiseEventsForChangedPath(repo.eventQueue_,query._path,events),syncTreeRemoveEventRegistration(repo.serverSyncTree_,query,eventRegistration,null,!0),node}),(err=>(repoLog(repo,"get for query "+stringify(query)+" failed: "+err),Promise.reject(new Error(err)))))}(query._repo,query,container).then((node=>new DataSnapshot(node,new ReferenceImpl(query._repo,query._path),query._queryParams.getIndex())))}class ValueEventRegistration{constructor(callbackContext){this.callbackContext=callbackContext}respondsTo(eventType){return"value"===eventType}createEvent(change,query){const index=query._queryParams.getIndex();return new DataEvent("value",this,new DataSnapshot(change.snapshotNode,new ReferenceImpl(query._repo,query._path),index))}getEventRunner(eventData){return"cancel"===eventData.getEventType()?()=>this.callbackContext.onCancel(eventData.error):()=>this.callbackContext.onValue(eventData.snapshot,null)}createCancelEvent(error,path){return this.callbackContext.hasCancelCallback?new CancelEvent(this,error,path):null}matches(other){return other instanceof ValueEventRegistration&&(!other.callbackContext||!this.callbackContext||other.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class ChildEventRegistration{constructor(eventType,callbackContext){this.eventType=eventType,this.callbackContext=callbackContext}respondsTo(eventType){let eventToCheck="children_added"===eventType?"child_added":eventType;return eventToCheck="children_removed"===eventToCheck?"child_removed":eventToCheck,this.eventType===eventToCheck}createCancelEvent(error,path){return this.callbackContext.hasCancelCallback?new CancelEvent(this,error,path):null}createEvent(change,query){index_esm2017_assert(null!=change.childName,"Child events should have a childName.");const childRef=child(new ReferenceImpl(query._repo,query._path),change.childName),index=query._queryParams.getIndex();return new DataEvent(change.type,this,new DataSnapshot(change.snapshotNode,childRef,index),change.prevName)}getEventRunner(eventData){return"cancel"===eventData.getEventType()?()=>this.callbackContext.onCancel(eventData.error):()=>this.callbackContext.onValue(eventData.snapshot,eventData.prevName)}matches(other){return other instanceof ChildEventRegistration&&(this.eventType===other.eventType&&(!this.callbackContext||!other.callbackContext||this.callbackContext.matches(other.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function addEventListener(query,eventType,callback,cancelCallbackOrListenOptions,options){let cancelCallback;if("object"==typeof cancelCallbackOrListenOptions&&(cancelCallback=void 0,options=cancelCallbackOrListenOptions),"function"==typeof cancelCallbackOrListenOptions&&(cancelCallback=cancelCallbackOrListenOptions),options&&options.onlyOnce){const userCallback=callback,onceCallback=(dataSnapshot,previousChildName)=>{repoRemoveEventCallbackForQuery(query._repo,query,container),userCallback(dataSnapshot,previousChildName)};onceCallback.userCallback=callback.userCallback,onceCallback.context=callback.context,callback=onceCallback}const callbackContext=new CallbackContext(callback,cancelCallback||void 0),container="value"===eventType?new ValueEventRegistration(callbackContext):new ChildEventRegistration(eventType,callbackContext);return function repoAddEventCallbackForQuery(repo,query,eventRegistration){let events;events=".info"===pathGetFront(query._path)?syncTreeAddEventRegistration(repo.infoSyncTree_,query,eventRegistration):syncTreeAddEventRegistration(repo.serverSyncTree_,query,eventRegistration),eventQueueRaiseEventsAtPath(repo.eventQueue_,query._path,events)}(query._repo,query,container),()=>repoRemoveEventCallbackForQuery(query._repo,query,container)}function onValue(query,callback,cancelCallbackOrListenOptions,options){return addEventListener(query,"value",callback,cancelCallbackOrListenOptions,options)}!function syncPointSetReferenceConstructor(val){index_esm2017_assert(!referenceConstructor$1,"__referenceConstructor has already been defined"),referenceConstructor$1=val}(ReferenceImpl),function syncTreeSetReferenceConstructor(val){index_esm2017_assert(!referenceConstructor,"__referenceConstructor has already been defined"),referenceConstructor=val}(ReferenceImpl);const FIREBASE_DATABASE_EMULATOR_HOST_VAR="FIREBASE_DATABASE_EMULATOR_HOST",repos={};let useRestClient=!1;function repoManagerDatabaseFromApp(app,authProvider,appCheckProvider,url,nodeAdmin){let dbUrl=url||app.options.databaseURL;void 0===dbUrl&&(app.options.projectId||fatal("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),log("Using default host for project ",app.options.projectId),dbUrl=`${app.options.projectId}-default-rtdb.firebaseio.com`);let isEmulator,dbEmulatorHost,parsedUrl=parseRepoInfo(dbUrl,nodeAdmin),repoInfo=parsedUrl.repoInfo;void 0!==index_esm2017_process&&index_esm2017_process.env&&(dbEmulatorHost=index_esm2017_process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR]),dbEmulatorHost?(isEmulator=!0,dbUrl=`http://${dbEmulatorHost}?ns=${repoInfo.namespace}`,parsedUrl=parseRepoInfo(dbUrl,nodeAdmin),repoInfo=parsedUrl.repoInfo):isEmulator=!parsedUrl.repoInfo.secure;const authTokenProvider=nodeAdmin&&isEmulator?new EmulatorTokenProvider(EmulatorTokenProvider.OWNER):new FirebaseAuthTokenProvider(app.name,app.options,authProvider);validateUrl("Invalid Firebase Database URL",parsedUrl),pathIsEmpty(parsedUrl.path)||fatal("Database URL must point to the root of a Firebase Database (not including a child path).");const repo=function repoManagerCreateRepo(repoInfo,app,authTokenProvider,appCheckProvider){let appRepos=repos[app.name];appRepos||(appRepos={},repos[app.name]=appRepos);let repo=appRepos[repoInfo.toURLString()];repo&&fatal("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return repo=new Repo(repoInfo,useRestClient,authTokenProvider,appCheckProvider),appRepos[repoInfo.toURLString()]=repo,repo}(repoInfo,app,authTokenProvider,new AppCheckTokenProvider(app.name,appCheckProvider));return new Database(repo,app)}class Database{constructor(_repoInternal,app){this._repoInternal=_repoInternal,this.app=app,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(repoStart(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new ReferenceImpl(this._repo,newEmptyPath())),this._rootInternal}_delete(){return null!==this._rootInternal&&(!function repoManagerDeleteRepo(repo,appName){const appRepos=repos[appName];appRepos&&appRepos[repo.key]===repo||fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`),repoInterrupt(repo),delete appRepos[repo.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(apiName){null===this._rootInternal&&fatal("Cannot call "+apiName+" on a deleted database.")}}PersistentConnection.prototype.simpleListen=function(pathString,onComplete){this.sendRequest("q",{p:pathString},onComplete)},PersistentConnection.prototype.echo=function(data,onEcho){this.sendRequest("echo",{d:data},onEcho)};!function registerDatabase(variant){setSDKVersion("10.13.0"),_registerComponent(new index_esm2017_Component("database",((container,{instanceIdentifier:url})=>repoManagerDatabaseFromApp(container.getProvider("app").getImmediate(),container.getProvider("auth-internal"),container.getProvider("app-check-internal"),url)),"PUBLIC").setMultipleInstances(!0)),registerVersion("@firebase/database","1.0.7",variant),registerVersion("@firebase/database","1.0.7","esm2017")}()},"./node_modules/react/cjs/react-jsx-runtime.production.min.js":(__unused_webpack_module,exports,__webpack_require__)=>{var f=__webpack_require__("./node_modules/react/index.js"),k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};function q(c,a,g){var b,d={},e=null,h=null;for(b in void 0!==g&&(e=""+g),void 0!==a.key&&(e=""+a.key),void 0!==a.ref&&(h=a.ref),a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps)void 0===d[b]&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}exports.Fragment=l,exports.jsx=q,exports.jsxs=q},"./node_modules/react/jsx-runtime.js":(module,__unused_webpack_exports,__webpack_require__)=>{module.exports=__webpack_require__("./node_modules/react/cjs/react-jsx-runtime.production.min.js")}}]); |