-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.bundle.js
More file actions
2 lines (2 loc) · 221 KB
/
Copy pathmain.bundle.js
File metadata and controls
2 lines (2 loc) · 221 KB
1
2
/*! For license information please see main.bundle.js.LICENSE.txt */
(()=>{var e={"./node_modules/@firebase/database/dist/index.esm2017.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{DataSnapshot:()=>Ws,Database:()=>Mr,OnDisconnect:()=>Os,QueryConstraint:()=>lr,TransactionResult:()=>Kr,_QueryImpl:()=>Ms,_QueryParams:()=>yt,_ReferenceImpl:()=>js,_TEST_ACCESS_forceRestClient:()=>Xr,_TEST_ACCESS_hijackHash:()=>Qr,_initStandalone:()=>Jr,_repoManagerDatabaseFromApp:()=>Or,_setSDKVersion:()=>h,_validatePathString:()=>$i,_validateWritablePath:()=>Ki,child:()=>Vs,connectDatabaseEmulator:()=>Wr,enableLogging:()=>Vr,endAt:()=>hr,endBefore:()=>dr,equalTo:()=>Pr,forceLongPolling:()=>Br,forceWebSockets:()=>qr,get:()=>Js,getDatabase:()=>jr,goOffline:()=>Ur,goOnline:()=>zr,increment:()=>Yr,limitToFirst:()=>vr,limitToLast:()=>wr,off:()=>ar,onChildAdded:()=>ir,onChildChanged:()=>sr,onChildMoved:()=>rr,onChildRemoved:()=>or,onDisconnect:()=>Hs,onValue:()=>nr,orderByChild:()=>Cr,orderByKey:()=>Er,orderByPriority:()=>Ir,orderByValue:()=>xr,push:()=>$s,query:()=>Dr,ref:()=>Us,refFromURL:()=>zs,remove:()=>Ys,runTransaction:()=>Gr,serverTimestamp:()=>$r,set:()=>Ks,setPriority:()=>Gs,setWithPriority:()=>Qs,startAfter:()=>_r,startAt:()=>fr,update:()=>Xs});var i=n("./node_modules/@firebase/app/dist/esm/index.esm2017.js"),s=n("./node_modules/@firebase/component/dist/esm/index.esm2017.js"),r=n("./node_modules/@firebase/util/dist/index.esm2017.js"),o=n("./node_modules/@firebase/logger/dist/esm/index.esm2017.js");const a="@firebase/database",l="1.0.3";let c="";function h(e){c=e}class u{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),(0,r.stringify)(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:(0,r.jsonEval)(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class d{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return(0,r.contains)(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}const p=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new u(t)}}catch(e){}return new d},f=p("localStorage"),m=p("sessionStorage"),_=new o.Logger("@firebase/database"),g=function(){let e=1;return function(){return e++}}(),v=function(e){const t=(0,r.stringToByteArray)(e),n=new r.Sha1;n.update(t);const i=n.digest();return r.base64.encodeByteArray(i)},y=function(...e){let t="";for(let n=0;n<e.length;n++){const i=e[n];Array.isArray(i)||i&&"object"==typeof i&&"number"==typeof i.length?t+=y.apply(null,i):t+="object"==typeof i?(0,r.stringify)(i):i,t+=" "}return t};let w=null,b=!0;const C=function(e,t){(0,r.assert)(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(_.logLevel=o.LogLevel.VERBOSE,w=_.log.bind(_),t&&m.set("logging_enabled",!0)):"function"==typeof e?w=e:(w=null,m.remove("logging_enabled"))},S=function(...e){if(!0===b&&(b=!1,null===w&&!0===m.get("logging_enabled")&&C(!0)),w){const t=y.apply(null,e);w(t)}},E=function(e){return function(...t){S(e,...t)}},T=function(...e){const t="FIREBASE INTERNAL ERROR: "+y(...e);_.error(t)},I=function(...e){const t=`FIREBASE FATAL ERROR: ${y(...e)}`;throw _.error(t),new Error(t)},k=function(...e){const t="FIREBASE WARNING: "+y(...e);_.warn(t)},x=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},N="[MIN_NAME]",P="[MAX_NAME]",D=function(e,t){if(e===t)return 0;if(e===N||t===P)return-1;if(t===N||e===P)return 1;{const n=B(e),i=B(t);return null!==n?null!==i?n-i==0?e.length-t.length:n-i:-1:null!==i?1:e<t?-1:1}},R=function(e,t){return e===t?0:e<t?-1:1},A=function(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+(0,r.stringify)(t))},L=function(e){if("object"!=typeof e||null===e)return(0,r.stringify)(e);const t=[];for(const n in e)t.push(n);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=(0,r.stringify)(t[i]),n+=":",n+=L(e[t[i]]);return n+="}",n},O=function(e,t){const n=e.length;if(n<=t)return[e];const i=[];for(let s=0;s<n;s+=t)s+t>n?i.push(e.substring(s,n)):i.push(e.substring(s,s+t));return i};function M(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}const F=function(e){(0,r.assert)(!x(e),"Invalid JSON number");const t=1023;let n,i,s,o,a;0===e?(i=0,s=0,n=1/e==-1/0?1:0):(n=e<0,(e=Math.abs(e))>=Math.pow(2,-1022)?(o=Math.min(Math.floor(Math.log(e)/Math.LN2),t),i=o+t,s=Math.round(e*Math.pow(2,52-o)-Math.pow(2,52))):(i=0,s=Math.round(e/Math.pow(2,-1074))));const l=[];for(a=52;a;a-=1)l.push(s%2?1:0),s=Math.floor(s/2);for(a=11;a;a-=1)l.push(i%2?1:0),i=Math.floor(i/2);l.push(n?1:0),l.reverse();const c=l.join("");let h="";for(a=0;a<64;a+=8){let e=parseInt(c.substr(a,8),2).toString(16);1===e.length&&(e="0"+e),h+=e}return h.toLowerCase()};const q=new RegExp("^-?(0*)\\d{1,10}$"),B=function(e){if(q.test(e)){const t=Number(e);if(t>=-2147483648&&t<=2147483647)return t}return null},j=function(e){try{e()}catch(e){setTimeout((()=>{const t=e.stack||"";throw k("Exception was thrown by user callback.",t),e}),Math.floor(0))}},W=function(e,t){const n=setTimeout(e,t);return"number"==typeof n&&"undefined"!=typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};class U{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then((e=>this.appCheck=e))}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise(((t,n)=>{setTimeout((()=>{this.appCheck?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){var t;null===(t=this.appCheckProvider)||void 0===t||t.get().then((t=>t.addTokenListener(e)))}notifyForInvalidToken(){k(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}class z{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit((e=>this.auth_=e))}getToken(e){return this.auth_?this.auth_.getToken(e).catch((e=>e&&"auth/token-not-initialized"===e.code?(S("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(e))):new Promise(((t,n)=>{setTimeout((()=>{this.auth_?this.getToken(e).then(t,n):t(null)}),0)}))}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):this.authProvider_.get().then((t=>t.addAuthTokenListener(e)))}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',k(e)}}class V{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}V.OWNER="owner";const H="5",$=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Y="ac",K="websocket",G="long_polling";class Q{constructor(e,t,n,i,s=!1,r="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=i,this.nodeAdmin=s,this.persistenceKey=r,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=f.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&f.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){const e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function X(e,t,n){let i;if((0,r.assert)("string"==typeof t,"typeof type must == string"),(0,r.assert)("object"==typeof n,"typeof params must == object"),t===K)i=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==G)throw new Error("Unknown connection type: "+t);i=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}(function(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams})(e)&&(n.ns=e.namespace);const s=[];return M(n,((e,t)=>{s.push(e+"="+t)})),i+s.join("&")}class J{constructor(){this.counters_={}}incrementCounter(e,t=1){(0,r.contains)(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return(0,r.deepCopy)(this.counters_)}}const Z={},ee={};function te(e){const t=e.toString();return Z[t]||(Z[t]=new J),Z[t]}class ne{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&j((()=>{this.onMessage_(e[t])}));if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}const ie="start";class se{constructor(e,t,n,i,s,r,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.transportSessionId=r,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=E(e),this.stats_=te(t),this.urlFn=e=>(this.appCheckToken&&(e[Y]=this.appCheckToken),X(t,G,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new ne(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout((()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null}),Math.floor(3e4)),function(e){if((0,r.isNodeSdk)()||"complete"===document.readyState)e();else{let t=!1;const n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",(()=>{"complete"===document.readyState&&n()})),window.attachEvent("onload",n))}}((()=>{if(this.isClosed_)return;this.scriptTagHolder=new re(((...e)=>{const[t,n,i,s,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===ie)this.id=n,this.password=i;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,(()=>{this.onClosed_()}))):this.onClosed_()}}),((...e)=>{const[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)}),(()=>{this.onClosed_()}),this.urlFn);const e={};e[ie]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v=H,this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e[Y]=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&$.test(location.hostname)&&(e.r="f");const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t),this.scriptTagHolder.addTag(t,(()=>{}))}))}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){se.forceAllow_=!0}static forceDisallow(){se.forceDisallow_=!0}static isAvailable(){return!(0,r.isNodeSdk)()&&(!!se.forceAllow_||!(se.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI))}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){const t=(0,r.stringify)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=(0,r.base64Encode)(t),i=O(n,1840);for(let e=0;e<i.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[e]),this.curSegmentNum++}addDisconnectPingFrame(e,t){if((0,r.isNodeSdk)())return;this.myDisconnFrame=document.createElement("iframe");const n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const t=(0,r.stringify)(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class re{constructor(e,t,n,i){if(this.onDisconnect=n,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0,(0,r.isNodeSdk)())this.commandCB=e,this.onMessageCB=t;else{this.uniqueCallbackIdentifier=g(),window["pLPCommand"+this.uniqueCallbackIdentifier]=e,window["pRTLPCB"+this.uniqueCallbackIdentifier]=t,this.myIFrame=re.createIFrame_();let n="";if(this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)){n='<script>document.domain="'+document.domain+'";<\/script>'}const i="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){S("frame writing exception"),e.stack&&S(e.stack),S(e)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(e);try{e.contentWindow.document||S("No IE domain setting required")}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout((()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)}),Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",i=0;for(;this.pendingSegs.length>0;){if(!(this.pendingSegs[0].d.length+30+n.length<=1870))break;{const e=this.pendingSegs.shift();n=n+"&seg"+i+"="+e.seg+"&ts"+i+"="+e.ts+"&d"+i+"="+e.d,i++}}return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},i=setTimeout(n,Math.floor(25e3));this.addTag(e,(()=>{clearTimeout(i),n()}))}addTag(e,t){(0,r.isNodeSdk)()?this.doNodeLongPoll(e,t):setTimeout((()=>{try{if(!this.sendNewPolls)return;const n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){const e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{S("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}}),Math.floor(1))}}let oe=null;"undefined"!=typeof MozWebSocket?oe=MozWebSocket:"undefined"!=typeof WebSocket&&(oe=WebSocket);class ae{constructor(e,t,n,i,s,r,o){this.connId=e,this.applicationId=n,this.appCheckToken=i,this.authToken=s,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=E(this.connId),this.stats_=te(t),this.connURL=ae.connectionURL_(t,r,o,i,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,i,s){const o={};return o.v=H,!(0,r.isNodeSdk)()&&"undefined"!=typeof location&&location.hostname&&$.test(location.hostname)&&(o.r="f"),t&&(o.s=t),n&&(o.ls=n),i&&(o[Y]=i),s&&(o.p=s),X(e,K,o)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,f.set("previous_websocket_failure",!0);try{let e;if((0,r.isNodeSdk)()){const t=this.nodeAdmin?"AdminNode":"Node";e={headers:{"User-Agent":`Firebase/${H}/${c}/${process.platform}/${t}`,"X-Firebase-GMPID":this.applicationId||""}},this.authToken&&(e.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(e.headers["X-Firebase-AppCheck"]=this.appCheckToken);const n="MISSING_ENV_VAR",i=0===this.connURL.indexOf("wss://")?n.HTTPS_PROXY||n.https_proxy:n.HTTP_PROXY||n.http_proxy;i&&(e.proxy={origin:i})}this.mySock=new oe(this.connURL,[],e)}catch(e){this.log_("Error instantiating WebSocket.");const t=e.message||e.data;return t&&this.log_(t),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error. Closing connection.");const t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){ae.forceDisallow_=!0}static isAvailable(){let e=!1;if("undefined"!=typeof navigator&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,n=navigator.userAgent.match(t);n&&n.length>1&&parseFloat(n[1])<4.4&&(e=!0)}return!e&&null!==oe&&!ae.forceDisallow_}static previouslyFailed(){return f.isInMemoryStorage||!0===f.get("previous_websocket_failure")}markConnectionHealthy(){f.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=(0,r.jsonEval)(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if((0,r.assert)(null===this.frames,"We already have a frame buffer"),e.length<=6){const t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{const e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();const t=(0,r.stringify)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const n=O(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e<n.length;e++)this.sendString_(n[e])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval((()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()}),Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}ae.responsesRequiredToBeHealthy=2,ae.healthyTimeout=3e4;class le{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[se,ae]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){const t=ae&&ae.isAvailable();let n=t&&!ae.previouslyFailed();if(e.webSocketOnly&&(t||k("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[ae];else{const e=this.transports_=[];for(const t of le.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);le.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}}le.globalTransportInitialized_=!1;class ce{constructor(e,t,n,i,s,r,o,a,l,c){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=s,this.onMessage_=r,this.onReady_=o,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=c,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=E("c:"+this.id+":"),this.transportManager_=new le(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout((()=>{this.conn_&&this.conn_.open(t,n)}),Math.floor(0));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=W((()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes. Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes. Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))}),Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){if("t"in e){const t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=A("t",e),n=A("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=A("t",e),n=A("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){const t=A("t",e);if("d"in e){const n=e.d;if("h"===t){const e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?T("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):T("Unknown control packet command: "+t)}}onHandshake_(e){const t=e.ts,n=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),H!==n&&k("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),W((()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())}),Math.floor(6e4))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):W((()=>{this.sendPingOnPrimaryIfNecessary_()}),Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(f.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class he{put(e,t,n,i){}merge(e,t,n,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class ue{constructor(e){this.allowedEvents_=e,this.listeners_={},(0,r.assert)(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++)n[e].callback.apply(n[e].context,t)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});const i=this.getInitialEvent(e);i&&t.apply(n,i)}off(e,t,n){this.validateEventType_(e);const i=this.listeners_[e]||[];for(let e=0;e<i.length;e++)if(i[e].callback===t&&(!n||n===i[e].context))return void i.splice(e,1)}validateEventType_(e){(0,r.assert)(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class de extends ue{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||(0,r.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 de}getInitialEvent(e){return(0,r.assert)("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}const pe=32,fe=768;class me{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)this.pieces_[e].length>0&&(this.pieces_[t]=this.pieces_[e],t++);this.pieces_.length=t,this.pieceNum_=0}else this.pieces_=e,this.pieceNum_=t}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function _e(){return new me("")}function ge(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function ve(e){return e.pieces_.length-e.pieceNum_}function ye(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new me(e.pieces_,t)}function we(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function be(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function Ce(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new me(t,0)}function Se(e,t){const n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof me)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{const e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new me(n,0)}function Ee(e){return e.pieceNum_>=e.pieces_.length}function Te(e,t){const n=ge(e),i=ge(t);if(null===n)return t;if(n===i)return Te(ye(e),ye(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function Ie(e,t){const n=be(e,0),i=be(t,0);for(let e=0;e<n.length&&e<i.length;e++){const t=D(n[e],i[e]);if(0!==t)return t}return n.length===i.length?0:n.length<i.length?-1:1}function ke(e,t){if(ve(e)!==ve(t))return!1;for(let n=e.pieceNum_,i=t.pieceNum_;n<=e.pieces_.length;n++,i++)if(e.pieces_[n]!==t.pieces_[i])return!1;return!0}function xe(e,t){let n=e.pieceNum_,i=t.pieceNum_;if(ve(e)>ve(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[i])return!1;++n,++i}return!0}class Ne{constructor(e,t){this.errorPrefix_=t,this.parts_=be(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=(0,r.stringLength)(this.parts_[e]);Pe(this)}}function Pe(e){if(e.byteLength_>fe)throw new Error(e.errorPrefix_+"has a key path longer than "+fe+" bytes ("+e.byteLength_+").");if(e.parts_.length>pe)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+pe+") or object contains a cycle "+De(e))}function De(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class Re extends ue{constructor(){let e,t;super(["visible"]),"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,(()=>{const t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))}),!1)}static getInstance(){return new Re}getInitialEvent(e){return(0,r.assert)("visible"===e,"Unknown event type: "+e),[this.visible_]}}const Ae=1e3;class Le extends he{constructor(e,t,n,i,s,o,a,l){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=i,this.onServerInfoUpdate_=s,this.authTokenProvider_=o,this.appCheckTokenProvider_=a,this.authOverride_=l,this.id=Le.nextPersistentConnectionId_++,this.log_=E("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_=Ae,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,l&&!(0,r.isNodeSdk)())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");Re.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&de.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){const i=++this.requestNumber_,s={r:i,a:e,b:t};this.log_((0,r.stringify)(s)),(0,r.assert)(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(s),n&&(this.requestCBHash_[i]=n)}get(e){this.initConnection_();const t=new r.Deferred,n={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{const n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;const i=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(i),t.promise}listen(e,t,n,i){this.initConnection_();const s=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+s),this.listens.has(o)||this.listens.set(o,new Map),(0,r.assert)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),(0,r.assert)(!this.listens.get(o).has(s),"listen() called twice for same path/queryId.");const a={onComplete:i,hashFn:t,query:e,tag:n};this.listens.get(o).set(s,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,(n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)}))}sendListen_(e){const t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);const s={p:n};e.tag&&(s.q=t._queryObject,s.t=e.tag),s.h=e.hashFn(),this.sendRequest("q",s,(s=>{const r=s.d,o=s.s;Le.warnOnListenWarnings_(r,t);(this.listens.get(n)&&this.listens.get(n).get(i))===e&&(this.log_("listen response",s),"ok"!==o&&this.removeListen_(n,i),e.onComplete&&e.onComplete(o,r))}))}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&(0,r.contains)(e,"w")){const n=(0,r.safeGet)(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();k(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${e} at ${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},(()=>{})),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||(0,r.isAdmin)(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},(()=>{}))}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_,t=(0,r.isValidFormat)(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,(t=>{const n=t.s,i=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,i))}))}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},(e=>{const t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)}))}unlisten(e,t){const n=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+i),(0,r.assert)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query");this.removeListen_(n,i)&&this.connected_&&this.sendUnlisten_(n,i,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);const s={p:e};i&&(s.q=n,s.t=i),this.sendRequest("n",s)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,i){const s={p:t,d:n};this.log_("onDisconnect "+e,s),this.sendRequest(e,s,(e=>{i&&setTimeout((()=>{i(e.s,e.d)}),Math.floor(0))}))}put(e,t,n,i){this.putInternal("p",e,t,n,i)}merge(e,t,n,i){this.putInternal("m",e,t,n,i)}putInternal(e,t,n,i,s){this.initConnection_();const r={p:t,d:n};void 0!==s&&(r.h=s),this.outstandingPuts_.push({action:e,request:r,onComplete:i}),this.outstandingPutCount_++;const o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,n,(n=>{this.log_(t+" response",n),delete this.outstandingPuts_[e],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),i&&i(n.s,n.d)}))}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,(e=>{if("ok"!==e.s){const t=e.d;this.log_("reportStats","Error sending stats: "+t)}}))}}onDataMessage_(e){if("r"in e){this.log_("from server: "+(0,r.stringify)(e));const t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):T("Unrecognized action received from server: "+(0,r.stringify)(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){(0,r.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(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible. Reducing delay."),this.reconnectDelay_=Ae,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=Ae,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_=Ae),this.lastConnectionEstablishedTime_=null}}else this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime();const e=(new Date).getTime()-this.lastConnectionAttemptTime_;let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t,this.log_("Trying to reconnect in "+t+"ms"),this.scheduleConnect_(t),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+Le.nextConnectionId_++,s=this.lastSessionId;let o=!1,a=null;const l=function(){a?a.close():(o=!0,n())},c=function(e){(0,r.assert)(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(e)};this.realtime_={close:l,sendRequest:c};const h=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[r,l]=await Promise.all([this.authTokenProvider_.getToken(h),this.appCheckTokenProvider_.getToken(h)]);o?S("getToken() completed but was canceled"):(S("getToken() completed. Creating connection."),this.authToken_=r&&r.accessToken,this.appCheckToken_=l&&l.token,a=new ce(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,(e=>{k(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")}),s))}catch(e){this.log_("Failed to get token: "+e),o||(this.repoInfo_.nodeAdmin&&k(e),l())}}}interrupt(e){S("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){S("Resuming connection for reason: "+e),delete this.interruptReasons_[e],(0,r.isEmpty)(this.interruptReasons_)&&(this.reconnectDelay_=Ae,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map((e=>L(e))).join("$"):"default";const i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){const n=new me(e).toString();let i;if(this.listens.has(n)){const e=this.listens.get(n);i=e.get(t),e.delete(t),0===e.size&&this.listens.delete(n)}else i=void 0;return i}onAuthRevoked_(e,t){S("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){S("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const e of this.listens.values())for(const t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){const e={};let t="js";(0,r.isNodeSdk)()&&(t=this.repoInfo_.nodeAdmin?"admin_node":"node"),e["sdk."+t+"."+c.replace(/\./g,"-")]=1,(0,r.isMobileCordova)()?e["framework.cordova"]=1:(0,r.isReactNative)()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=de.getInstance().currentlyOnline();return(0,r.isEmpty)(this.interruptReasons_)&&e}}Le.nextPersistentConnectionId_=0,Le.nextConnectionId_=0;class Oe{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new Oe(e,t)}}class Me{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const n=new Oe(N,e),i=new Oe(N,t);return 0!==this.compare(n,i)}minPost(){return Oe.MIN}}let Fe;class qe extends Me{static get __EMPTY_NODE(){return Fe}static set __EMPTY_NODE(e){Fe=e}compare(e,t){return D(e.name,t.name)}isDefinedOn(e){throw(0,r.assertionError)("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return Oe.MIN}maxPost(){return new Oe(P,Fe)}makePost(e,t){return(0,r.assert)("string"==typeof e,"KeyIndex indexValue must always be a string."),new Oe(e,Fe)}toString(){return".key"}}const Be=new qe;class je{constructor(e,t,n,i,s=null){this.isReverse_=i,this.resultGenerator_=s,this.nodeStack_=[];let r=1;for(;!e.isEmpty();)if(r=t?n(e.key,t):1,i&&(r*=-1),r<0)e=this.isReverse_?e.left:e.right;else{if(0===r){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e,t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;const e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class We{constructor(e,t,n,i,s){this.key=e,this.value=t,this.color=null!=n?n:We.RED,this.left=null!=i?i:Ue.EMPTY_NODE,this.right=null!=s?s:Ue.EMPTY_NODE}copy(e,t,n,i,s){return new We(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=i?i:this.left,null!=s?s:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let i=this;const s=n(e,i.key);return i=s<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===s?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return Ue.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,i;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return Ue.EMPTY_NODE;i=n.right.min_(),n=n.copy(i.key,i.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){const e=this.copy(null,null,We.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,We.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");const e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}We.RED=!0,We.BLACK=!1;class Ue{constructor(e,t=Ue.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new Ue(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,We.BLACK,null,null))}remove(e){return new Ue(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,We.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,i=null;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),0===t){if(n.left.isEmpty())return i?i.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(i=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key. What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new je(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new je(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new je(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new je(this.root_,null,this.comparator_,!0,e)}}function ze(e,t){return D(e.name,t.name)}function Ve(e,t){return D(e,t)}let He;Ue.EMPTY_NODE=new class{copy(e,t,n,i,s){return this}insert(e,t,n){return new We(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};const $e=function(e){return"number"==typeof e?"number:"+F(e):"string:"+e},Ye=function(e){if(e.isLeafNode()){const t=e.val();(0,r.assert)("string"==typeof t||"number"==typeof t||"object"==typeof t&&(0,r.contains)(t,".sv"),"Priority must be a string or number.")}else(0,r.assert)(e===He||e.isEmpty(),"priority of unexpected type.");(0,r.assert)(e===He||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let Ke,Ge,Qe;class Xe{constructor(e,t=Xe.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,(0,r.assert)(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),Ye(this.priorityNode_)}static set __childrenNodeConstructor(e){Ke=e}static get __childrenNodeConstructor(){return Ke}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new Xe(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:Xe.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return Ee(e)?this:".priority"===ge(e)?this.priorityNode_:Xe.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:Xe.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const n=ge(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:((0,r.assert)(".priority"!==n||1===ve(e),".priority must be the last token in a path"),this.updateImmediateChild(n,Xe.__childrenNodeConstructor.EMPTY_NODE.updateChild(ye(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+$e(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",e+="number"===t?F(this.value_):this.value_,this.lazyHash_=v(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===Xe.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof Xe.__childrenNodeConstructor?-1:((0,r.assert)(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,n=typeof this.value_,i=Xe.VALUE_TYPE_ORDER.indexOf(t),s=Xe.VALUE_TYPE_ORDER.indexOf(n);return(0,r.assert)(i>=0,"Unknown leaf type: "+t),(0,r.assert)(s>=0,"Unknown leaf type: "+n),i===s?"object"===n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:s-i}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1}}Xe.VALUE_TYPE_ORDER=["object","boolean","number","string"];const Je=new class extends Me{compare(e,t){const n=e.node.getPriority(),i=t.node.getPriority(),s=n.compareTo(i);return 0===s?D(e.name,t.name):s}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return Oe.MIN}maxPost(){return new Oe(P,new Xe("[PRIORITY-POST]",Qe))}makePost(e,t){const n=Ge(e);return new Oe(t,new Xe("[PRIORITY-POST]",n))}toString(){return".priority"}},Ze=Math.log(2);class et{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/Ze,10)),this.current_=this.count-1;const n=(i=this.count,parseInt(Array(i+1).join("1"),2));var i;this.bits_=e+1&n}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const tt=function(e,t,n,i){e.sort(t);const s=function(t,i){const r=i-t;let o,a;if(0===r)return null;if(1===r)return o=e[t],a=n?n(o):o,new We(a,o.node,We.BLACK,null,null);{const l=parseInt(r/2,10)+t,c=s(t,l),h=s(l+1,i);return o=e[l],a=n?n(o):o,new We(a,o.node,We.BLACK,c,h)}},r=function(t){let i=null,r=null,o=e.length;const a=function(t,i){const r=o-t,a=o;o-=t;const c=s(r+1,a),h=e[r],u=n?n(h):h;l(new We(u,h.node,i,null,c))},l=function(e){i?(i.left=e,i=e):(r=e,i=e)};for(let e=0;e<t.count;++e){const n=t.nextBitIsOne(),i=Math.pow(2,t.count-(e+1));n?a(i,We.BLACK):(a(i,We.BLACK),a(i,We.RED))}return r}(new et(e.length));return new Ue(i||t,r)};let nt;const it={};class st{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return(0,r.assert)(it&&Je,"ChildrenNode.ts has not been loaded"),nt=nt||new st({".priority":it},{".priority":Je}),nt}get(e){const t=(0,r.safeGet)(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof Ue?t:null}hasIndex(e){return(0,r.contains)(this.indexSet_,e.toString())}addIndex(e,t){(0,r.assert)(e!==Be,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let i=!1;const s=t.getIterator(Oe.Wrap);let o,a=s.getNext();for(;a;)i=i||e.isDefinedOn(a.node),n.push(a),a=s.getNext();o=i?tt(n,e.getCompare()):it;const l=e.toString(),c=Object.assign({},this.indexSet_);c[l]=e;const h=Object.assign({},this.indexes_);return h[l]=o,new st(h,c)}addToIndexes(e,t){const n=(0,r.map)(this.indexes_,((n,i)=>{const s=(0,r.safeGet)(this.indexSet_,i);if((0,r.assert)(s,"Missing index implementation for "+i),n===it){if(s.isDefinedOn(e.node)){const n=[],i=t.getIterator(Oe.Wrap);let r=i.getNext();for(;r;)r.name!==e.name&&n.push(r),r=i.getNext();return n.push(e),tt(n,s.getCompare())}return it}{const i=t.get(e.name);let s=n;return i&&(s=s.remove(new Oe(e.name,i))),s.insert(e,e.node)}}));return new st(n,this.indexSet_)}removeFromIndexes(e,t){const n=(0,r.map)(this.indexes_,(n=>{if(n===it)return n;{const i=t.get(e.name);return i?n.remove(new Oe(e.name,i)):n}}));return new st(n,this.indexSet_)}}let rt;class ot{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Ye(this.priorityNode_),this.children_.isEmpty()&&(0,r.assert)(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return rt||(rt=new ot(new Ue(Ve),null,st.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||rt}updatePriority(e){return this.children_.isEmpty()?this:new ot(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{const t=this.children_.get(e);return null===t?rt:t}}getChild(e){const t=ge(e);return null===t?this:this.getImmediateChild(t).getChild(ye(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if((0,r.assert)(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{const n=new Oe(e,t);let i,s;t.isEmpty()?(i=this.children_.remove(e),s=this.indexMap_.removeFromIndexes(n,this.children_)):(i=this.children_.insert(e,t),s=this.indexMap_.addToIndexes(n,this.children_));const r=i.isEmpty()?rt:this.priorityNode_;return new ot(i,r,s)}}updateChild(e,t){const n=ge(e);if(null===n)return t;{(0,r.assert)(".priority"!==ge(e)||1===ve(e),".priority must be the last token in a path");const i=this.getImmediateChild(n).updateChild(ye(e),t);return this.updateImmediateChild(n,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let n=0,i=0,s=!0;if(this.forEachChild(Je,((r,o)=>{t[r]=o.val(e),n++,s&&ot.INTEGER_REGEXP_.test(r)?i=Math.max(i,Number(r)):s=!1})),!e&&s&&i<2*n){const e=[];for(const n in t)e[n]=t[n];return e}return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+$e(this.getPriority().val())+":"),this.forEachChild(Je,((t,n)=>{const i=n.hash();""!==i&&(e+=":"+t+":"+i)})),this.lazyHash_=""===e?"":v(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const i=this.resolveIndex_(n);if(i){const n=i.getPredecessorKey(new Oe(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){const t=this.getFirstChildName(e);return t?new Oe(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){const t=this.getLastChildName(e);return t?new Oe(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal((e=>t(e.name,e.node))):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,(e=>e));{const n=this.children_.getIteratorFrom(e.name,Oe.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)<0;)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,(e=>e));{const n=this.children_.getReverseIteratorFrom(e.name,Oe.Wrap);let i=n.peek();for(;null!=i&&t.compare(i,e)>0;)n.getNext(),i=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===at?-1:0}withIndex(e){if(e===Be||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new ot(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===Be||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const t=e;if(this.getPriority().equals(t.getPriority())){if(this.children_.count()===t.children_.count()){const e=this.getIterator(Je),n=t.getIterator(Je);let i=e.getNext(),s=n.getNext();for(;i&&s;){if(i.name!==s.name||!i.node.equals(s.node))return!1;i=e.getNext(),s=n.getNext()}return null===i&&null===s}return!1}return!1}}resolveIndex_(e){return e===Be?null:this.indexMap_.get(e.toString())}}ot.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;const at=new class extends ot{constructor(){super(new Ue(Ve),ot.EMPTY_NODE,st.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ot.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(Oe,{MIN:{value:new Oe(N,ot.EMPTY_NODE)},MAX:{value:new Oe(P,at)}}),qe.__EMPTY_NODE=ot.EMPTY_NODE,Xe.__childrenNodeConstructor=ot,He=at,function(e){Qe=e}(at);const lt=!0;function ct(e,t=null){if(null===e)return ot.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),(0,r.assert)(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e){return new Xe(e,ct(t))}if(e instanceof Array||!lt){let n=ot.EMPTY_NODE;return M(e,((t,i)=>{if((0,r.contains)(e,t)&&"."!==t.substring(0,1)){const e=ct(i);!e.isLeafNode()&&e.isEmpty()||(n=n.updateImmediateChild(t,e))}})),n.updatePriority(ct(t))}{const n=[];let i=!1;if(M(e,((e,t)=>{if("."!==e.substring(0,1)){const s=ct(t);s.isEmpty()||(i=i||!s.getPriority().isEmpty(),n.push(new Oe(e,s)))}})),0===n.length)return ot.EMPTY_NODE;const s=tt(n,ze,(e=>e.name),Ve);if(i){const e=tt(n,Je.getCompare());return new ot(s,ct(t),new st({".priority":e},{".priority":Je}))}return new ot(s,ct(t),st.Default)}}!function(e){Ge=e}(ct);class ht extends Me{constructor(e){super(),this.indexPath_=e,(0,r.assert)(!Ee(e)&&".priority"!==ge(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node),i=this.extractChild(t.node),s=n.compareTo(i);return 0===s?D(e.name,t.name):s}makePost(e,t){const n=ct(e),i=ot.EMPTY_NODE.updateChild(this.indexPath_,n);return new Oe(t,i)}maxPost(){const e=ot.EMPTY_NODE.updateChild(this.indexPath_,at);return new Oe(P,e)}toString(){return be(this.indexPath_,0).join("/")}}const ut=new class extends Me{compare(e,t){const n=e.node.compareTo(t.node);return 0===n?D(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return Oe.MIN}maxPost(){return Oe.MAX}makePost(e,t){const n=ct(e);return new Oe(t,n)}toString(){return".value"}};function dt(e){return{type:"value",snapshotNode:e}}function pt(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function ft(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function mt(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class _t{constructor(e){this.index_=e}updateChild(e,t,n,i,s,o){(0,r.assert)(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(i).equals(n.getChild(i))&&a.isEmpty()===n.isEmpty()?e:(null!=o&&(n.isEmpty()?e.hasChild(t)?o.trackChildChange(ft(t,a)):(0,r.assert)(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(pt(t,n)):o.trackChildChange(mt(t,n,a))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(Je,((e,i)=>{t.hasChild(e)||n.trackChildChange(ft(e,i))})),t.isLeafNode()||t.forEachChild(Je,((t,i)=>{if(e.hasChild(t)){const s=e.getImmediateChild(t);s.equals(i)||n.trackChildChange(mt(t,i,s))}else n.trackChildChange(pt(t,i))}))),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?ot.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class gt{constructor(e){this.indexedFilter_=new _t(e.getIndex()),this.index_=e.getIndex(),this.startPost_=gt.getStartPost_(e),this.endPost_=gt.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0,n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,i,s,r){return this.matches(new Oe(t,n))||(n=ot.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,i,s,r)}updateFullNode(e,t,n){t.isLeafNode()&&(t=ot.EMPTY_NODE);let i=t.withIndex(this.index_);i=i.updatePriority(ot.EMPTY_NODE);const s=this;return t.forEachChild(Je,((e,t)=>{s.matches(new Oe(e,t))||(i=i.updateImmediateChild(e,ot.EMPTY_NODE))})),this.indexedFilter_.updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class vt{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e),this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e),this.withinStartPost=e=>{const t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{const t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new gt(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,i,s,r){return this.rangedFilter_.matches(new Oe(t,n))||(n=ot.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,i,s,r):this.fullLimitUpdateChild_(e,t,n,s,r)}updateFullNode(e,t,n){let i;if(t.isLeafNode()||t.isEmpty())i=ot.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;i=ot.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){const t=e.getNext();if(this.withinDirectionalStart(t)){if(!this.withinDirectionalEnd(t))break;i=i.updateImmediateChild(t.name,t.node),n++}}}else{let e;i=t.withIndex(this.index_),i=i.updatePriority(ot.EMPTY_NODE),e=this.reverse_?i.getReverseIterator(this.index_):i.getIterator(this.index_);let n=0;for(;e.hasNext();){const t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:i=i.updateImmediateChild(t.name,ot.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,i,s){let o;if(this.reverse_){const e=this.index_.getCompare();o=(t,n)=>e(n,t)}else o=this.index_.getCompare();const a=e;(0,r.assert)(a.numChildren()===this.limit_,"");const l=new Oe(t,n),c=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),h=this.rangedFilter_.matches(l);if(a.hasChild(t)){const e=a.getImmediateChild(t);let r=i.getChildAfterChild(this.index_,c,this.reverse_);for(;null!=r&&(r.name===t||a.hasChild(r.name));)r=i.getChildAfterChild(this.index_,r,this.reverse_);const u=null==r?1:o(r,l);if(h&&!n.isEmpty()&&u>=0)return null!=s&&s.trackChildChange(mt(t,n,e)),a.updateImmediateChild(t,n);{null!=s&&s.trackChildChange(ft(t,e));const n=a.updateImmediateChild(t,ot.EMPTY_NODE);return null!=r&&this.rangedFilter_.matches(r)?(null!=s&&s.trackChildChange(pt(r.name,r.node)),n.updateImmediateChild(r.name,r.node)):n}}return n.isEmpty()?e:h&&o(c,l)>=0?(null!=s&&(s.trackChildChange(ft(c.name,c.node)),s.trackChildChange(pt(t,n))),a.updateImmediateChild(t,n).updateImmediateChild(c.name,ot.EMPTY_NODE)):e}}class yt{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_=Je}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return(0,r.assert)(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return(0,r.assert)(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:N}hasEnd(){return this.endSet_}getIndexEndValue(){return(0,r.assert)(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return(0,r.assert)(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:P}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return(0,r.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_===Je}copy(){const e=new yt;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.startAfterSet_=this.startAfterSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.endBeforeSet_=this.endBeforeSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function wt(e,t,n){const i=e.copy();return i.startSet_=!0,void 0===t&&(t=null),i.indexStartValue_=t,null!=n?(i.startNameSet_=!0,i.indexStartName_=n):(i.startNameSet_=!1,i.indexStartName_=""),i}function bt(e,t,n){const i=e.copy();return i.endSet_=!0,void 0===t&&(t=null),i.indexEndValue_=t,void 0!==n?(i.endNameSet_=!0,i.indexEndName_=n):(i.endNameSet_=!1,i.indexEndName_=""),i}function Ct(e,t){const n=e.copy();return n.index_=t,n}function St(e){const t={};if(e.isDefault())return t;let n;if(e.index_===Je?n="$priority":e.index_===ut?n="$value":e.index_===Be?n="$key":((0,r.assert)(e.index_ instanceof ht,"Unrecognized index type!"),n=e.index_.toString()),t.orderBy=(0,r.stringify)(n),e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=(0,r.stringify)(e.indexStartValue_),e.startNameSet_&&(t[n]+=","+(0,r.stringify)(e.indexStartName_))}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=(0,r.stringify)(e.indexEndValue_),e.endNameSet_&&(t[n]+=","+(0,r.stringify)(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function Et(e){const t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==Je&&(t.i=e.index_.toString()),t}class Tt extends he{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=E("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:((0,r.assert)(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const o=Tt.getListenId_(e,n),a={};this.listens_[o]=a;const l=St(e._queryParams);this.restRequest_(s+".json",l,((e,t)=>{let l=t;if(404===e&&(l=null,e=null),null===e&&this.onDataUpdate_(s,l,!1,n),(0,r.safeGet)(this.listens_,o)===a){let t;t=e?401===e?"permission_denied":"rest_error:"+e:"ok",i(t,null)}}))}unlisten(e,t){const n=Tt.getListenId_(e,t);delete this.listens_[n]}get(e){const t=St(e._queryParams),n=e._path.toString(),i=new r.Deferred;return this.restRequest_(n+".json",t,((e,t)=>{let s=t;404===e&&(s=null,e=null),null===e?(this.onDataUpdate_(n,s,!1,null),i.resolve(s)):i.reject(new Error(s))})),i.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then((([i,s])=>{i&&i.accessToken&&(t.auth=i.accessToken),s&&s.token&&(t.ac=s.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+(0,r.querystring)(t);this.log_("Sending REST request for "+o);const a=new XMLHttpRequest;a.onreadystatechange=()=>{if(n&&4===a.readyState){this.log_("REST Response for "+o+" received. status:",a.status,"response:",a.responseText);let e=null;if(a.status>=200&&a.status<300){try{e=(0,r.jsonEval)(a.responseText)}catch(e){k("Failed to parse JSON response for "+o+": "+a.responseText)}n(null,e)}else 401!==a.status&&404!==a.status&&k("Got unsuccessful REST response for "+o+" Status: "+a.status),n(a.status);n=null}},a.open("GET",o,!0),a.send()}))}}class It{constructor(){this.rootNode_=ot.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function kt(){return{value:null,children:new Map}}function xt(e,t,n){if(Ee(t))e.value=n,e.children.clear();else if(null!==e.value)e.value=e.value.updateChild(t,n);else{const i=ge(t);e.children.has(i)||e.children.set(i,kt());xt(e.children.get(i),t=ye(t),n)}}function Nt(e,t){if(Ee(t))return e.value=null,e.children.clear(),!0;if(null!==e.value){if(e.value.isLeafNode())return!1;{const n=e.value;return e.value=null,n.forEachChild(Je,((t,n)=>{xt(e,new me(t),n)})),Nt(e,t)}}if(e.children.size>0){const n=ge(t);if(t=ye(t),e.children.has(n)){Nt(e.children.get(n),t)&&e.children.delete(n)}return 0===e.children.size}return!0}function Pt(e,t,n){null!==e.value?n(t,e.value):function(e,t){e.children.forEach(((e,n)=>{t(n,e)}))}(e,((e,i)=>{Pt(i,new me(t.toString()+"/"+e),n)}))}class Dt{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&M(this.last_,((e,n)=>{t[e]=t[e]-n})),this.last_=e,t}}class Rt{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Dt(e);const n=1e4+2e4*Math.random();W(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get(),t={};let n=!1;M(e,((e,i)=>{i>0&&(0,r.contains)(this.statsToReport_,e)&&(t[e]=i,n=!0)})),n&&this.server_.reportStats(t),W(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}var At;function Lt(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}!function(e){e[e.OVERWRITE=0]="OVERWRITE",e[e.MERGE=1]="MERGE",e[e.ACK_USER_WRITE=2]="ACK_USER_WRITE",e[e.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"}(At||(At={}));class Ot{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=At.ACK_USER_WRITE,this.source={fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}operationForChild(e){if(Ee(this.path)){if(null!=this.affectedTree.value)return(0,r.assert)(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new me(e));return new Ot(_e(),t,this.revert)}}return(0,r.assert)(ge(this.path)===e,"operationForChild called for unrelated child."),new Ot(ye(this.path),this.affectedTree,this.revert)}}class Mt{constructor(e,t){this.source=e,this.path=t,this.type=At.LISTEN_COMPLETE}operationForChild(e){return Ee(this.path)?new Mt(this.source,_e()):new Mt(this.source,ye(this.path))}}class Ft{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=At.OVERWRITE}operationForChild(e){return Ee(this.path)?new Ft(this.source,_e(),this.snap.getImmediateChild(e)):new Ft(this.source,ye(this.path),this.snap)}}class qt{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=At.MERGE}operationForChild(e){if(Ee(this.path)){const t=this.children.subtree(new me(e));return t.isEmpty()?null:t.value?new Ft(this.source,_e(),t.value):new qt(this.source,_e(),t)}return(0,r.assert)(ge(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new qt(this.source,ye(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class Bt{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(Ee(e))return this.isFullyInitialized()&&!this.filtered_;const t=ge(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class jt{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function Wt(e,t,n,i,s,o){const a=i.filter((e=>e.type===n));a.sort(((t,n)=>function(e,t,n){if(null==t.childName||null==n.childName)throw(0,r.assertionError)("Should only compare child_ events.");const i=new Oe(t.childName,t.snapshotNode),s=new Oe(n.childName,n.snapshotNode);return e.index_.compare(i,s)}(e,t,n))),a.forEach((n=>{const i=function(e,t,n){return"value"===t.type||"child_removed"===t.type||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}(e,n,o);s.forEach((s=>{s.respondsTo(n.type)&&t.push(s.createEvent(i,e.query_))}))}))}function Ut(e,t){return{eventCache:e,serverCache:t}}function zt(e,t,n,i){return Ut(new Bt(t,n,i),e.serverCache)}function Vt(e,t,n,i){return Ut(e.eventCache,new Bt(t,n,i))}function Ht(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function $t(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Yt;class Kt{constructor(e,t=(()=>(Yt||(Yt=new Ue(R)),Yt))()){this.value=e,this.children=t}static fromObject(e){let t=new Kt(null);return M(e,((e,n)=>{t=t.set(new me(e),n)})),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:_e(),value:this.value};if(Ee(e))return null;{const n=ge(e),i=this.children.get(n);if(null!==i){const s=i.findRootMostMatchingPathAndValue(ye(e),t);if(null!=s){return{path:Se(new me(n),s.path),value:s.value}}return null}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,(()=>!0))}subtree(e){if(Ee(e))return this;{const t=ge(e),n=this.children.get(t);return null!==n?n.subtree(ye(e)):new Kt(null)}}set(e,t){if(Ee(e))return new Kt(t,this.children);{const n=ge(e),i=(this.children.get(n)||new Kt(null)).set(ye(e),t),s=this.children.insert(n,i);return new Kt(this.value,s)}}remove(e){if(Ee(e))return this.children.isEmpty()?new Kt(null):new Kt(null,this.children);{const t=ge(e),n=this.children.get(t);if(n){const i=n.remove(ye(e));let s;return s=i.isEmpty()?this.children.remove(t):this.children.insert(t,i),null===this.value&&s.isEmpty()?new Kt(null):new Kt(this.value,s)}return this}}get(e){if(Ee(e))return this.value;{const t=ge(e),n=this.children.get(t);return n?n.get(ye(e)):null}}setTree(e,t){if(Ee(e))return t;{const n=ge(e),i=(this.children.get(n)||new Kt(null)).setTree(ye(e),t);let s;return s=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),new Kt(this.value,s)}}fold(e){return this.fold_(_e(),e)}fold_(e,t){const n={};return this.children.inorderTraversal(((i,s)=>{n[i]=s.fold_(Se(e,i),t)})),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,_e(),t)}findOnPath_(e,t,n){const i=!!this.value&&n(t,this.value);if(i)return i;if(Ee(e))return null;{const i=ge(e),s=this.children.get(i);return s?s.findOnPath_(ye(e),Se(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,_e(),t)}foreachOnPath_(e,t,n){if(Ee(e))return this;{this.value&&n(t,this.value);const i=ge(e),s=this.children.get(i);return s?s.foreachOnPath_(ye(e),Se(t,i),n):new Kt(null)}}foreach(e){this.foreach_(_e(),e)}foreach_(e,t){this.children.inorderTraversal(((n,i)=>{i.foreach_(Se(e,n),t)})),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal(((t,n)=>{n.value&&e(t,n.value)}))}}class Gt{constructor(e){this.writeTree_=e}static empty(){return new Gt(new Kt(null))}}function Qt(e,t,n){if(Ee(t))return new Gt(new Kt(n));{const i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){const s=i.path;let r=i.value;const o=Te(s,t);return r=r.updateChild(o,n),new Gt(e.writeTree_.set(s,r))}{const i=new Kt(n),s=e.writeTree_.setTree(t,i);return new Gt(s)}}}function Xt(e,t,n){let i=e;return M(n,((e,n)=>{i=Qt(i,Se(t,e),n)})),i}function Jt(e,t){if(Ee(t))return Gt.empty();{const n=e.writeTree_.setTree(t,new Kt(null));return new Gt(n)}}function Zt(e,t){return null!=en(e,t)}function en(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(Te(n.path,t)):null}function tn(e){const t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(Je,((e,n)=>{t.push(new Oe(e,n))})):e.writeTree_.children.inorderTraversal(((e,n)=>{null!=n.value&&t.push(new Oe(e,n.value))})),t}function nn(e,t){if(Ee(t))return e;{const n=en(e,t);return new Gt(null!=n?new Kt(n):e.writeTree_.subtree(t))}}function sn(e){return e.writeTree_.isEmpty()}function rn(e,t){return on(_e(),e.writeTree_,t)}function on(e,t,n){if(null!=t.value)return n.updateChild(e,t.value);{let i=null;return t.children.inorderTraversal(((t,s)=>{".priority"===t?((0,r.assert)(null!==s.value,"Priority writes must always be leaf nodes"),i=s.value):n=on(Se(e,t),s,n)})),n.getChild(e).isEmpty()||null===i||(n=n.updateChild(Se(e,".priority"),i)),n}}function an(e,t){return wn(t,e)}function ln(e,t){const n=e.allWrites.findIndex((e=>e.writeId===t));(0,r.assert)(n>=0,"removeWrite called with nonexistent writeId.");const i=e.allWrites[n];e.allWrites.splice(n,1);let s=i.visible,o=!1,a=e.allWrites.length-1;for(;s&&a>=0;){const t=e.allWrites[a];t.visible&&(a>=n&&cn(t,i.path)?s=!1:xe(i.path,t.path)&&(o=!0)),a--}if(s){if(o)return function(e){e.visibleWrites=un(e.allWrites,hn,_e()),e.allWrites.length>0?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1}(e),!0;if(i.snap)e.visibleWrites=Jt(e.visibleWrites,i.path);else{M(i.children,(t=>{e.visibleWrites=Jt(e.visibleWrites,Se(i.path,t))}))}return!0}return!1}function cn(e,t){if(e.snap)return xe(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&xe(Se(e.path,n),t))return!0;return!1}function hn(e){return e.visible}function un(e,t,n){let i=Gt.empty();for(let s=0;s<e.length;++s){const o=e[s];if(t(o)){const e=o.path;let t;if(o.snap)xe(n,e)?(t=Te(n,e),i=Qt(i,t,o.snap)):xe(e,n)&&(t=Te(e,n),i=Qt(i,_e(),o.snap.getChild(t)));else{if(!o.children)throw(0,r.assertionError)("WriteRecord should have .snap or .children");if(xe(n,e))t=Te(n,e),i=Xt(i,t,o.children);else if(xe(e,n))if(t=Te(e,n),Ee(t))i=Xt(i,_e(),o.children);else{const e=(0,r.safeGet)(o.children,ge(t));if(e){const n=e.getChild(ye(t));i=Qt(i,_e(),n)}}}}}return i}function dn(e,t,n,i,s){if(i||s){const r=nn(e.visibleWrites,t);if(!s&&sn(r))return n;if(s||null!=n||Zt(r,_e())){const r=function(e){return(e.visible||s)&&(!i||!~i.indexOf(e.writeId))&&(xe(e.path,t)||xe(t,e.path))};return rn(un(e.allWrites,r,t),n||ot.EMPTY_NODE)}return null}{const i=en(e.visibleWrites,t);if(null!=i)return i;{const i=nn(e.visibleWrites,t);if(sn(i))return n;if(null!=n||Zt(i,_e())){return rn(i,n||ot.EMPTY_NODE)}return null}}}function pn(e,t,n,i){return dn(e.writeTree,e.treePath,t,n,i)}function fn(e,t){return function(e,t,n){let i=ot.EMPTY_NODE;const s=en(e.visibleWrites,t);if(s)return s.isLeafNode()||s.forEachChild(Je,((e,t)=>{i=i.updateImmediateChild(e,t)})),i;if(n){const s=nn(e.visibleWrites,t);return n.forEachChild(Je,((e,t)=>{const n=rn(nn(s,new me(e)),t);i=i.updateImmediateChild(e,n)})),tn(s).forEach((e=>{i=i.updateImmediateChild(e.name,e.node)})),i}return tn(nn(e.visibleWrites,t)).forEach((e=>{i=i.updateImmediateChild(e.name,e.node)})),i}(e.writeTree,e.treePath,t)}function mn(e,t,n,i){return function(e,t,n,i,s){(0,r.assert)(i||s,"Either existingEventSnap or existingServerSnap must exist");const o=Se(t,n);if(Zt(e.visibleWrites,o))return null;{const t=nn(e.visibleWrites,o);return sn(t)?s.getChild(n):rn(t,s.getChild(n))}}(e.writeTree,e.treePath,t,n,i)}function _n(e,t){return function(e,t){return en(e.visibleWrites,t)}(e.writeTree,Se(e.treePath,t))}function gn(e,t,n,i,s,r){return function(e,t,n,i,s,r,o){let a;const l=nn(e.visibleWrites,t),c=en(l,_e());if(null!=c)a=c;else{if(null==n)return[];a=rn(l,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const e=[],t=o.getCompare(),n=r?a.getReverseIteratorFrom(i,o):a.getIteratorFrom(i,o);let l=n.getNext();for(;l&&e.length<s;)0!==t(l,i)&&e.push(l),l=n.getNext();return e}}(e.writeTree,e.treePath,t,n,i,s,r)}function vn(e,t,n){return function(e,t,n,i){const s=Se(t,n),r=en(e.visibleWrites,s);if(null!=r)return r;if(i.isCompleteForChild(n))return rn(nn(e.visibleWrites,s),i.getNode().getImmediateChild(n));return null}(e.writeTree,e.treePath,t,n)}function yn(e,t){return wn(Se(e.treePath,t),e.writeTree)}function wn(e,t){return{treePath:e,writeTree:t}}class bn{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,n=e.childName;(0,r.assert)("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),(0,r.assert)(".priority"!==n,"Only non-priority child changes can be tracked.");const i=this.changeMap.get(n);if(i){const s=i.type;if("child_added"===t&&"child_removed"===s)this.changeMap.set(n,mt(n,e.snapshotNode,i.snapshotNode));else if("child_removed"===t&&"child_added"===s)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===s)this.changeMap.set(n,ft(n,i.oldSnap));else if("child_changed"===t&&"child_added"===s)this.changeMap.set(n,pt(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==s)throw(0,r.assertionError)("Illegal combination of changes: "+e+" occurred after "+i);this.changeMap.set(n,mt(n,e.snapshotNode,i.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const Cn=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class Sn{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const t=null!=this.optCompleteServerCache_?new Bt(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return vn(this.writes_,e,t)}}getChildAfterChild(e,t,n){const i=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:$t(this.viewCache_),s=gn(this.writes_,i,t,1,n,e);return 0===s.length?null:s[0]}}function En(e,t,n,i,s){const o=new bn;let a,l;if(n.type===At.OVERWRITE){const c=n;c.source.fromUser?a=kn(e,t,c.path,c.snap,i,s,o):((0,r.assert)(c.source.fromServer,"Unknown source."),l=c.source.tagged||t.serverCache.isFiltered()&&!Ee(c.path),a=In(e,t,c.path,c.snap,i,s,l,o))}else if(n.type===At.MERGE){const c=n;c.source.fromUser?a=function(e,t,n,i,s,r,o){let a=t;return i.foreach(((i,l)=>{const c=Se(n,i);xn(t,ge(c))&&(a=kn(e,a,c,l,s,r,o))})),i.foreach(((i,l)=>{const c=Se(n,i);xn(t,ge(c))||(a=kn(e,a,c,l,s,r,o))})),a}(e,t,c.path,c.children,i,s,o):((0,r.assert)(c.source.fromServer,"Unknown source."),l=c.source.tagged||t.serverCache.isFiltered(),a=Pn(e,t,c.path,c.children,i,s,l,o))}else if(n.type===At.ACK_USER_WRITE){const l=n;a=l.revert?function(e,t,n,i,s,o){let a;if(null!=_n(i,n))return t;{const l=new Sn(i,t,s),c=t.eventCache.getNode();let h;if(Ee(n)||".priority"===ge(n)){let n;if(t.serverCache.isFullyInitialized())n=pn(i,$t(t));else{const e=t.serverCache.getNode();(0,r.assert)(e instanceof ot,"serverChildren would be complete if leaf node"),n=fn(i,e)}h=e.filter.updateFullNode(c,n,o)}else{const s=ge(n);let r=vn(i,s,t.serverCache);null==r&&t.serverCache.isCompleteForChild(s)&&(r=c.getImmediateChild(s)),h=null!=r?e.filter.updateChild(c,s,r,ye(n),l,o):t.eventCache.getNode().hasChild(s)?e.filter.updateChild(c,s,ot.EMPTY_NODE,ye(n),l,o):c,h.isEmpty()&&t.serverCache.isFullyInitialized()&&(a=pn(i,$t(t)),a.isLeafNode()&&(h=e.filter.updateFullNode(h,a,o)))}return a=t.serverCache.isFullyInitialized()||null!=_n(i,_e()),zt(t,h,a,e.filter.filtersNodes())}}(e,t,l.path,i,s,o):function(e,t,n,i,s,r,o){if(null!=_n(s,n))return t;const a=t.serverCache.isFiltered(),l=t.serverCache;if(null!=i.value){if(Ee(n)&&l.isFullyInitialized()||l.isCompleteForPath(n))return In(e,t,n,l.getNode().getChild(n),s,r,a,o);if(Ee(n)){let i=new Kt(null);return l.getNode().forEachChild(Be,((e,t)=>{i=i.set(new me(e),t)})),Pn(e,t,n,i,s,r,a,o)}return t}{let c=new Kt(null);return i.foreach(((e,t)=>{const i=Se(n,e);l.isCompleteForPath(i)&&(c=c.set(e,l.getNode().getChild(i)))})),Pn(e,t,n,c,s,r,a,o)}}(e,t,l.path,l.affectedTree,i,s,o)}else{if(n.type!==At.LISTEN_COMPLETE)throw(0,r.assertionError)("Unknown operation type: "+n.type);a=function(e,t,n,i,s){const r=t.serverCache,o=Vt(t,r.getNode(),r.isFullyInitialized()||Ee(n),r.isFiltered());return Tn(e,o,n,i,Cn,s)}(e,t,n.path,i,o)}const c=o.getChanges();return function(e,t,n){const i=t.eventCache;if(i.isFullyInitialized()){const s=i.getNode().isLeafNode()||i.getNode().isEmpty(),r=Ht(e);(n.length>0||!e.eventCache.isFullyInitialized()||s&&!i.getNode().equals(r)||!i.getNode().getPriority().equals(r.getPriority()))&&n.push(dt(Ht(t)))}}(t,a,c),{viewCache:a,changes:c}}function Tn(e,t,n,i,s,o){const a=t.eventCache;if(null!=_n(i,n))return t;{let l,c;if(Ee(n))if((0,r.assert)(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){const n=$t(t),s=fn(i,n instanceof ot?n:ot.EMPTY_NODE);l=e.filter.updateFullNode(t.eventCache.getNode(),s,o)}else{const n=pn(i,$t(t));l=e.filter.updateFullNode(t.eventCache.getNode(),n,o)}else{const h=ge(n);if(".priority"===h){(0,r.assert)(1===ve(n),"Can't have a priority with additional path components");const s=a.getNode();c=t.serverCache.getNode();const o=mn(i,n,s,c);l=null!=o?e.filter.updatePriority(s,o):a.getNode()}else{const r=ye(n);let u;if(a.isCompleteForChild(h)){c=t.serverCache.getNode();const e=mn(i,n,a.getNode(),c);u=null!=e?a.getNode().getImmediateChild(h).updateChild(r,e):a.getNode().getImmediateChild(h)}else u=vn(i,h,t.serverCache);l=null!=u?e.filter.updateChild(a.getNode(),h,u,r,s,o):a.getNode()}}return zt(t,l,a.isFullyInitialized()||Ee(n),e.filter.filtersNodes())}}function In(e,t,n,i,s,r,o,a){const l=t.serverCache;let c;const h=o?e.filter:e.filter.getIndexedFilter();if(Ee(n))c=h.updateFullNode(l.getNode(),i,null);else if(h.filtersNodes()&&!l.isFiltered()){const e=l.getNode().updateChild(n,i);c=h.updateFullNode(l.getNode(),e,null)}else{const e=ge(n);if(!l.isCompleteForPath(n)&&ve(n)>1)return t;const s=ye(n),r=l.getNode().getImmediateChild(e).updateChild(s,i);c=".priority"===e?h.updatePriority(l.getNode(),r):h.updateChild(l.getNode(),e,r,s,Cn,null)}const u=Vt(t,c,l.isFullyInitialized()||Ee(n),h.filtersNodes());return Tn(e,u,n,s,new Sn(s,u,r),a)}function kn(e,t,n,i,s,r,o){const a=t.eventCache;let l,c;const h=new Sn(s,t,r);if(Ee(n))c=e.filter.updateFullNode(t.eventCache.getNode(),i,o),l=zt(t,c,!0,e.filter.filtersNodes());else{const s=ge(n);if(".priority"===s)c=e.filter.updatePriority(t.eventCache.getNode(),i),l=zt(t,c,a.isFullyInitialized(),a.isFiltered());else{const r=ye(n),c=a.getNode().getImmediateChild(s);let u;if(Ee(r))u=i;else{const e=h.getCompleteChild(s);u=null!=e?".priority"===we(r)&&e.getChild(Ce(r)).isEmpty()?e:e.updateChild(r,i):ot.EMPTY_NODE}if(c.equals(u))l=t;else{l=zt(t,e.filter.updateChild(a.getNode(),s,u,r,h,o),a.isFullyInitialized(),e.filter.filtersNodes())}}}return l}function xn(e,t){return e.eventCache.isCompleteForChild(t)}function Nn(e,t,n){return n.foreach(((e,n)=>{t=t.updateChild(e,n)})),t}function Pn(e,t,n,i,s,r,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let l,c=t;l=Ee(n)?i:new Kt(null).setTree(n,i);const h=t.serverCache.getNode();return l.children.inorderTraversal(((n,i)=>{if(h.hasChild(n)){const l=Nn(0,t.serverCache.getNode().getImmediateChild(n),i);c=In(e,c,new me(n),l,s,r,o,a)}})),l.children.inorderTraversal(((n,i)=>{const l=!t.serverCache.isCompleteForChild(n)&&null===i.value;if(!h.hasChild(n)&&!l){const l=Nn(0,t.serverCache.getNode().getImmediateChild(n),i);c=In(e,c,new me(n),l,s,r,o,a)}})),c}class Dn{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,i=new _t(n.getIndex()),s=(r=n).loadsAllData()?new _t(r.getIndex()):r.hasLimit()?new vt(r):new gt(r);var r;this.processor_=function(e){return{filter:e}}(s);const o=t.serverCache,a=t.eventCache,l=i.updateFullNode(ot.EMPTY_NODE,o.getNode(),null),c=s.updateFullNode(ot.EMPTY_NODE,a.getNode(),null),h=new Bt(l,o.isFullyInitialized(),i.filtersNodes()),u=new Bt(c,a.isFullyInitialized(),s.filtersNodes());this.viewCache_=Ut(u,h),this.eventGenerator_=new jt(this.query_)}get query(){return this.query_}}function Rn(e,t){const n=$t(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!Ee(t)&&!n.getImmediateChild(ge(t)).isEmpty())?n.getChild(t):null}function An(e){return 0===e.eventRegistrations_.length}function Ln(e,t,n){const i=[];if(n){(0,r.assert)(null==t,"A cancel should cancel all event registrations.");const s=e.query._path;e.eventRegistrations_.forEach((e=>{const t=e.createCancelEvent(n,s);t&&i.push(t)}))}if(t){let n=[];for(let i=0;i<e.eventRegistrations_.length;++i){const s=e.eventRegistrations_[i];if(s.matches(t)){if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(i+1));break}}else n.push(s)}e.eventRegistrations_=n}else e.eventRegistrations_=[];return i}function On(e,t,n,i){t.type===At.MERGE&&null!==t.source.queryId&&((0,r.assert)($t(e.viewCache_),"We should always have a full cache before handling merges"),(0,r.assert)(Ht(e.viewCache_),"Missing event cache, even though we have a server cache"));const s=e.viewCache_,o=En(e.processor_,s,t,n,i);var a,l;return a=e.processor_,l=o.viewCache,(0,r.assert)(l.eventCache.getNode().isIndexed(a.filter.getIndex()),"Event snap not indexed"),(0,r.assert)(l.serverCache.getNode().isIndexed(a.filter.getIndex()),"Server snap not indexed"),(0,r.assert)(o.viewCache.serverCache.isFullyInitialized()||!s.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=o.viewCache,Mn(e,o.changes,o.viewCache.eventCache.getNode(),null)}function Mn(e,t,n,i){const s=i?[i]:e.eventRegistrations_;return function(e,t,n,i){const s=[],r=[];return t.forEach((t=>{var n;"child_changed"===t.type&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&r.push((n=t.childName,{type:"child_moved",snapshotNode:t.snapshotNode,childName:n}))})),Wt(e,s,"child_removed",t,i,n),Wt(e,s,"child_added",t,i,n),Wt(e,s,"child_moved",r,i,n),Wt(e,s,"child_changed",t,i,n),Wt(e,s,"value",t,i,n),s}(e.eventGenerator_,t,n,s)}let Fn,qn;class Bn{constructor(){this.views=new Map}}function jn(e,t,n,i){const s=t.source.queryId;if(null!==s){const o=e.views.get(s);return(0,r.assert)(null!=o,"SyncTree gave us an op for an invalid query."),On(o,t,n,i)}{let s=[];for(const r of e.views.values())s=s.concat(On(r,t,n,i));return s}}function Wn(e,t,n,i,s){const r=t._queryIdentifier,o=e.views.get(r);if(!o){let e=pn(n,s?i:null),r=!1;e?r=!0:i instanceof ot?(e=fn(n,i),r=!1):(e=ot.EMPTY_NODE,r=!1);const o=Ut(new Bt(e,r,!1),new Bt(i,s,!1));return new Dn(t,o)}return o}function Un(e,t,n,i,s,r){const o=Wn(e,t,i,s,r);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),function(e,t){e.eventRegistrations_.push(t)}(o,n),function(e,t){const n=e.viewCache_.eventCache,i=[];n.getNode().isLeafNode()||n.getNode().forEachChild(Je,((e,t)=>{i.push(pt(e,t))}));return n.isFullyInitialized()&&i.push(dt(n.getNode())),Mn(e,i,n.getNode(),t)}(o,n)}function zn(e,t,n,i){const s=t._queryIdentifier,o=[];let a=[];const l=Kn(e);if("default"===s)for(const[t,s]of e.views.entries())a=a.concat(Ln(s,n,i)),An(s)&&(e.views.delete(t),s.query._queryParams.loadsAllData()||o.push(s.query));else{const t=e.views.get(s);t&&(a=a.concat(Ln(t,n,i)),An(t)&&(e.views.delete(s),t.query._queryParams.loadsAllData()||o.push(t.query)))}return l&&!Kn(e)&&o.push(new((0,r.assert)(Fn,"Reference.ts has not been loaded"),Fn)(t._repo,t._path)),{removed:o,events:a}}function Vn(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function Hn(e,t){let n=null;for(const i of e.views.values())n=n||Rn(i,t);return n}function $n(e,t){if(t._queryParams.loadsAllData())return Gn(e);{const n=t._queryIdentifier;return e.views.get(n)}}function Yn(e,t){return null!=$n(e,t)}function Kn(e){return null!=Gn(e)}function Gn(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let Qn=1;class Xn{constructor(e){this.listenProvider_=e,this.syncPointTree_=new Kt(null),this.pendingWriteTree_={visibleWrites:Gt.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Jn(e,t,n,i,s){return function(e,t,n,i,s){(0,r.assert)(i>e.lastWriteId,"Stacking an older write on top of newer ones"),void 0===s&&(s=!0),e.allWrites.push({path:t,snap:n,writeId:i,visible:s}),s&&(e.visibleWrites=Qt(e.visibleWrites,t,n)),e.lastWriteId=i}(e.pendingWriteTree_,t,n,i,s),s?ai(e,new Ft({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,n)):[]}function Zn(e,t,n,i){!function(e,t,n,i){(0,r.assert)(i>e.lastWriteId,"Stacking an older merge on top of newer ones"),e.allWrites.push({path:t,children:n,writeId:i,visible:!0}),e.visibleWrites=Xt(e.visibleWrites,t,n),e.lastWriteId=i}(e.pendingWriteTree_,t,n,i);const s=Kt.fromObject(n);return ai(e,new qt({fromUser:!0,fromServer:!1,queryId:null,tagged:!1},t,s))}function ei(e,t,n=!1){const i=function(e,t){for(let n=0;n<e.allWrites.length;n++){const i=e.allWrites[n];if(i.writeId===t)return i}return null}(e.pendingWriteTree_,t);if(ln(e.pendingWriteTree_,t)){let t=new Kt(null);return null!=i.snap?t=t.set(_e(),!0):M(i.children,(e=>{t=t.set(new me(e),!0)})),ai(e,new Ot(i.path,t,n))}return[]}function ti(e,t,n){return ai(e,new Ft({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,n))}function ni(e,t,n,i,s=!1){const r=t._path,o=e.syncPointTree_.get(r);let a=[];if(o&&("default"===t._queryIdentifier||Yn(o,t))){const l=zn(o,t,n,i);0===o.views.size&&(e.syncPointTree_=e.syncPointTree_.remove(r));const c=l.removed;if(a=l.events,!s){const n=-1!==c.findIndex((e=>e._queryParams.loadsAllData())),s=e.syncPointTree_.findOnPath(r,((e,t)=>Kn(t)));if(n&&!s){const t=e.syncPointTree_.subtree(r);if(!t.isEmpty()){const n=function(e){return e.fold(((e,t,n)=>{if(t&&Kn(t)){return[Gn(t)]}{let e=[];return t&&(e=Vn(t)),M(n,((t,n)=>{e=e.concat(n)})),e}}))}(t);for(let t=0;t<n.length;++t){const i=n[t],s=i.query,r=hi(e,i);e.listenProvider_.startListening(_i(s),ui(e,s),r.hashFn,r.onComplete)}}}if(!s&&c.length>0&&!i)if(n){const n=null;e.listenProvider_.stopListening(_i(t),n)}else c.forEach((t=>{const n=e.queryToTagMap.get(di(t));e.listenProvider_.stopListening(_i(t),n)}))}!function(e,t){for(let n=0;n<t.length;++n){const i=t[n];if(!i._queryParams.loadsAllData()){const t=di(i),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}(e,c)}return a}function ii(e,t,n,i){const s=pi(e,i);if(null!=s){const i=fi(s),r=i.path,o=i.queryId,a=Te(r,t);return mi(e,r,new Ft(Lt(o),a,n))}return[]}function si(e,t,n,i=!1){const s=t._path;let o=null,a=!1;e.syncPointTree_.foreachOnPath(s,((e,t)=>{const n=Te(e,s);o=o||Hn(t,n),a=a||Kn(t)}));let l,c=e.syncPointTree_.get(s);if(c?(a=a||Kn(c),o=o||Hn(c,_e())):(c=new Bn,e.syncPointTree_=e.syncPointTree_.set(s,c)),null!=o)l=!0;else{l=!1,o=ot.EMPTY_NODE;e.syncPointTree_.subtree(s).foreachChild(((e,t)=>{const n=Hn(t,_e());n&&(o=o.updateImmediateChild(e,n))}))}const h=Yn(c,t);if(!h&&!t._queryParams.loadsAllData()){const n=di(t);(0,r.assert)(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");const i=Qn++;e.queryToTagMap.set(n,i),e.tagToQueryMap.set(i,n)}let u=Un(c,t,n,an(e.pendingWriteTree_,s),o,l);if(!h&&!a&&!i){const n=$n(c,t);u=u.concat(function(e,t,n){const i=t._path,s=ui(e,t),o=hi(e,n),a=e.listenProvider_.startListening(_i(t),s,o.hashFn,o.onComplete),l=e.syncPointTree_.subtree(i);if(s)(0,r.assert)(!Kn(l.value),"If we're adding a query, it shouldn't be shadowed");else{const t=l.fold(((e,t,n)=>{if(!Ee(e)&&t&&Kn(t))return[Gn(t).query];{let e=[];return t&&(e=e.concat(Vn(t).map((e=>e.query)))),M(n,((t,n)=>{e=e.concat(n)})),e}}));for(let n=0;n<t.length;++n){const i=t[n];e.listenProvider_.stopListening(_i(i),ui(e,i))}}return a}(e,t,n))}return u}function ri(e,t,n){const i=e.pendingWriteTree_,s=e.syncPointTree_.findOnPath(t,((e,n)=>{const i=Hn(n,Te(e,t));if(i)return i}));return dn(i,t,s,n,!0)}function oi(e,t){const n=t._path;let i=null;e.syncPointTree_.foreachOnPath(n,((e,t)=>{const s=Te(e,n);i=i||Hn(t,s)}));let s=e.syncPointTree_.get(n);s?i=i||Hn(s,_e()):(s=new Bn,e.syncPointTree_=e.syncPointTree_.set(n,s));const r=null!=i,o=r?new Bt(i,!0,!1):null;return function(e){return Ht(e.viewCache_)}(Wn(s,t,an(e.pendingWriteTree_,t._path),r?o.getNode():ot.EMPTY_NODE,r))}function ai(e,t){return li(t,e.syncPointTree_,null,an(e.pendingWriteTree_,_e()))}function li(e,t,n,i){if(Ee(e.path))return ci(e,t,n,i);{const s=t.get(_e());null==n&&null!=s&&(n=Hn(s,_e()));let r=[];const o=ge(e.path),a=e.operationForChild(o),l=t.children.get(o);if(l&&a){const e=n?n.getImmediateChild(o):null,t=yn(i,o);r=r.concat(li(a,l,e,t))}return s&&(r=r.concat(jn(s,e,i,n))),r}}function ci(e,t,n,i){const s=t.get(_e());null==n&&null!=s&&(n=Hn(s,_e()));let r=[];return t.children.inorderTraversal(((t,s)=>{const o=n?n.getImmediateChild(t):null,a=yn(i,t),l=e.operationForChild(t);l&&(r=r.concat(ci(l,s,o,a)))})),s&&(r=r.concat(jn(s,e,i,n))),r}function hi(e,t){const n=t.query,i=ui(e,n);return{hashFn:()=>{const e=function(e){return e.viewCache_.serverCache.getNode()}(t)||ot.EMPTY_NODE;return e.hash()},onComplete:t=>{if("ok"===t)return i?function(e,t,n){const i=pi(e,n);if(i){const n=fi(i),s=n.path,r=n.queryId,o=Te(s,t);return mi(e,s,new Mt(Lt(r),o))}return[]}(e,n._path,i):function(e,t){return ai(e,new Mt({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t))}(e,n._path);{const i=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const i=new Error(e+" at "+t._path.toString()+": "+n);return i.code=e.toUpperCase(),i}(t,n);return ni(e,n,null,i)}}}}function ui(e,t){const n=di(t);return e.queryToTagMap.get(n)}function di(e){return e._path.toString()+"$"+e._queryIdentifier}function pi(e,t){return e.tagToQueryMap.get(t)}function fi(e){const t=e.indexOf("$");return(0,r.assert)(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new me(e.substr(0,t))}}function mi(e,t,n){const i=e.syncPointTree_.get(t);(0,r.assert)(i,"Missing sync point for query tag that we're tracking");return jn(i,n,an(e.pendingWriteTree_,t),null)}function _i(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new((0,r.assert)(qn,"Reference.ts has not been loaded"),qn)(e._repo,e._path):e}class gi{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new gi(t)}node(){return this.node_}}class vi{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=Se(this.path_,e);return new vi(this.syncTree_,t)}node(){return ri(this.syncTree_,this.path_)}}const yi=function(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e},wi=function(e,t,n){return e&&"object"==typeof e?((0,r.assert)(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?bi(e[".sv"],t,n):"object"==typeof e[".sv"]?Ci(e[".sv"],t):void(0,r.assert)(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e},bi=function(e,t,n){if("timestamp"===e)return n.timestamp;(0,r.assert)(!1,"Unexpected server value: "+e)},Ci=function(e,t,n){e.hasOwnProperty("increment")||(0,r.assert)(!1,"Unexpected server value: "+JSON.stringify(e,null,2));const i=e.increment;"number"!=typeof i&&(0,r.assert)(!1,"Unexpected increment value: "+i);const s=t.node();if((0,r.assert)(null!=s,"Expected ChildrenNode.EMPTY_NODE for nulls"),!s.isLeafNode())return i;const o=s.getValue();return"number"!=typeof o?i:o+i},Si=function(e,t,n,i){return Ti(t,new vi(n,e),i)},Ei=function(e,t,n){return Ti(e,new gi(t),n)};function Ti(e,t,n){const i=e.getPriority().val(),s=wi(i,t.getImmediateChild(".priority"),n);let r;if(e.isLeafNode()){const i=e,r=wi(i.getValue(),t,n);return r!==i.getValue()||s!==i.getPriority().val()?new Xe(r,ct(s)):e}{const i=e;return r=i,s!==i.getPriority().val()&&(r=r.updatePriority(new Xe(s))),i.forEachChild(Je,((e,i)=>{const s=Ti(i,t.getImmediateChild(e),n);s!==i&&(r=r.updateImmediateChild(e,s))})),r}}class Ii{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function ki(e,t){let n=t instanceof me?t:new me(t),i=e,s=ge(n);for(;null!==s;){const e=(0,r.safeGet)(i.node.children,s)||{children:{},childCount:0};i=new Ii(s,i,e),n=ye(n),s=ge(n)}return i}function xi(e){return e.node.value}function Ni(e,t){e.node.value=t,Li(e)}function Pi(e){return e.node.childCount>0}function Di(e,t){M(e.node.children,((n,i)=>{t(new Ii(n,e,i))}))}function Ri(e,t,n,i){n&&!i&&t(e),Di(e,(e=>{Ri(e,t,!0,i)})),n&&i&&t(e)}function Ai(e){return new me(null===e.parent?e.name:Ai(e.parent)+"/"+e.name)}function Li(e){null!==e.parent&&function(e,t,n){const i=function(e){return void 0===xi(e)&&!Pi(e)}(n),s=(0,r.contains)(e.node.children,t);i&&s?(delete e.node.children[t],e.node.childCount--,Li(e)):i||s||(e.node.children[t]=n.node,e.node.childCount++,Li(e))}(e.parent,e.name,e)}const Oi=/[\[\].#$\/\u0000-\u001F\u007F]/,Mi=/[\[\].#$\u0000-\u001F\u007F]/,Fi=10485760,qi=function(e){return"string"==typeof e&&0!==e.length&&!Oi.test(e)},Bi=function(e){return"string"==typeof e&&0!==e.length&&!Mi.test(e)},ji=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!x(e)||e&&"object"==typeof e&&(0,r.contains)(e,".sv")},Wi=function(e,t,n,i){i&&void 0===t||Ui((0,r.errorPrefix)(e,"value"),t,n)},Ui=function(e,t,n){const i=n instanceof me?new Ne(n,e):n;if(void 0===t)throw new Error(e+"contains undefined "+De(i));if("function"==typeof t)throw new Error(e+"contains a function "+De(i)+" with contents = "+t.toString());if(x(t))throw new Error(e+"contains "+t.toString()+" "+De(i));if("string"==typeof t&&t.length>Fi/3&&(0,r.stringLength)(t)>Fi)throw new Error(e+"contains a string greater than "+Fi+" utf8 bytes "+De(i)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,s=!1;if(M(t,((t,o)=>{if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(s=!0,!qi(t)))throw new Error(e+" contains an invalid key ("+t+") "+De(i)+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');!function(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=(0,r.stringLength)(t),Pe(e)}(i,t),Ui(e,o,i),function(e){const t=e.parts_.pop();e.byteLength_-=(0,r.stringLength)(t),e.parts_.length>0&&(e.byteLength_-=1)}(i)})),n&&s)throw new Error(e+' contains ".value" child '+De(i)+" in addition to actual children.")}},zi=function(e,t,n,i){if(i&&void 0===t)return;const s=(0,r.errorPrefix)(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(s+" must be an object containing the children to replace.");const o=[];M(t,((e,t)=>{const i=new me(e);if(Ui(s,t,Se(n,i)),".priority"===we(i)&&!ji(t))throw new Error(s+"contains an invalid value for '"+i.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");o.push(i)})),function(e,t){let n,i;for(n=0;n<t.length;n++){i=t[n];const s=be(i);for(let t=0;t<s.length;t++)if(".priority"===s[t]&&t===s.length-1);else if(!qi(s[t]))throw new Error(e+"contains an invalid key ("+s[t]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}t.sort(Ie);let s=null;for(n=0;n<t.length;n++){if(i=t[n],null!==s&&xe(s,i))throw new Error(e+"contains a path "+s.toString()+" that is ancestor of another path "+i.toString());s=i}}(s,o)},Vi=function(e,t,n){if(!n||void 0!==t){if(x(t))throw new Error((0,r.errorPrefix)(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!ji(t))throw new Error((0,r.errorPrefix)(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}},Hi=function(e,t,n,i){if(!(i&&void 0===n||qi(n)))throw new Error((0,r.errorPrefix)(e,t)+'was an invalid key = "'+n+'". Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},$i=function(e,t,n,i){if(!(i&&void 0===n||Bi(n)))throw new Error((0,r.errorPrefix)(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},Yi=function(e,t,n,i){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),$i(e,t,n,i)},Ki=function(e,t){if(".info"===ge(t))throw new Error(e+" failed = Can't modify data under /.info/")},Gi=function(e,t){const n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!qi(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!function(e){return e&&(e=e.replace(/^\/*\.info(\/|$)/,"/")),Bi(e)}(n))throw new Error((0,r.errorPrefix)(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class Qi{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Xi(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i],r=s.getPath();null===n||ke(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function Ji(e,t,n){Xi(e,n),es(e,(e=>ke(e,t)))}function Zi(e,t,n){Xi(e,n),es(e,(e=>xe(e,t)||xe(t,e)))}function es(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){const s=e.eventLists_[i];if(s){t(s.path)?(ts(e.eventLists_[i]),e.eventLists_[i]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}function ts(e){for(let t=0;t<e.events.length;t++){const n=e.events[t];if(null!==n){e.events[t]=null;const i=n.getEventRunner();w&&S("event: "+n.toString()),j(i)}}}const ns="repo_interrupt",is=25;class ss{constructor(e,t,n,i){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Qi,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=kt(),this.transactionQueueTree_=new Ii,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function rs(e,t,n){if(e.stats_=te(e.repoInfo_),e.forceRestClient_||("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0)e.server_=new Tt(e.repoInfo_,((t,n,i,s)=>{ls(e,t,n,i,s)}),e.authTokenProvider_,e.appCheckProvider_),setTimeout((()=>cs(e,!0)),0);else{if(null!=n){if("object"!=typeof n)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{(0,r.stringify)(n)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new Le(e.repoInfo_,t,((t,n,i,s)=>{ls(e,t,n,i,s)}),(t=>{cs(e,t)}),(t=>{!function(e,t){M(t,((t,n)=>{hs(e,t,n)}))}(e,t)}),e.authTokenProvider_,e.appCheckProvider_,n),e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener((t=>{e.server_.refreshAuthToken(t)})),e.appCheckProvider_.addTokenChangeListener((t=>{e.server_.refreshAppCheckToken(t.token)})),e.statsReporter_=function(e,t){const n=e.toString();return ee[n]||(ee[n]=t()),ee[n]}(e.repoInfo_,(()=>new Rt(e.stats_,e.server_))),e.infoData_=new It,e.infoSyncTree_=new Xn({startListening:(t,n,i,s)=>{let r=[];const o=e.infoData_.getNode(t._path);return o.isEmpty()||(r=ti(e.infoSyncTree_,t._path,o),setTimeout((()=>{s("ok")}),0)),r},stopListening:()=>{}}),hs(e,"connected",!1),e.serverSyncTree_=new Xn({startListening:(t,n,i,s)=>(e.server_.listen(t,i,n,((n,i)=>{const r=s(n,i);Zi(e.eventQueue_,t._path,r)})),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function os(e){const t=e.infoData_.getNode(new me(".info/serverTimeOffset")).val()||0;return(new Date).getTime()+t}function as(e){return yi({timestamp:os(e)})}function ls(e,t,n,i,s){e.dataUpdateCount++;const o=new me(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let a=[];if(s)if(i){const t=(0,r.map)(n,(e=>ct(e)));a=function(e,t,n,i){const s=pi(e,i);if(s){const i=fi(s),r=i.path,o=i.queryId,a=Te(r,t),l=Kt.fromObject(n);return mi(e,r,new qt(Lt(o),a,l))}return[]}(e.serverSyncTree_,o,t,s)}else{const t=ct(n);a=ii(e.serverSyncTree_,o,t,s)}else if(i){const t=(0,r.map)(n,(e=>ct(e)));a=function(e,t,n){const i=Kt.fromObject(n);return ai(e,new qt({fromUser:!1,fromServer:!0,queryId:null,tagged:!1},t,i))}(e.serverSyncTree_,o,t)}else{const t=ct(n);a=ti(e.serverSyncTree_,o,t)}let l=o;a.length>0&&(l=bs(e,o)),Zi(e.eventQueue_,l,a)}function cs(e,t){hs(e,"connected",t),!1===t&&function(e){gs(e,"onDisconnectEvents");const t=as(e),n=kt();Pt(e.onDisconnect_,_e(),((i,s)=>{const r=Si(i,s,e.serverSyncTree_,t);xt(n,i,r)}));let i=[];Pt(n,_e(),((t,n)=>{i=i.concat(ti(e.serverSyncTree_,t,n));const s=Is(e,t);bs(e,s)})),e.onDisconnect_=kt(),Zi(e.eventQueue_,_e(),i)}(e)}function hs(e,t,n){const i=new me("/.info/"+t),s=ct(n);e.infoData_.updateSnapshot(i,s);const r=ti(e.infoSyncTree_,i,s);Zi(e.eventQueue_,i,r)}function us(e){return e.nextWriteId_++}function ds(e,t,n,i,s){gs(e,"set",{path:t.toString(),value:n,priority:i});const r=as(e),o=ct(n,i),a=ri(e.serverSyncTree_,t),l=Ei(o,a,r),c=us(e),h=Jn(e.serverSyncTree_,t,l,c,!0);Xi(e.eventQueue_,h),e.server_.put(t.toString(),o.val(!0),((n,i)=>{const r="ok"===n;r||k("set at "+t+" failed: "+n);const o=ei(e.serverSyncTree_,c,!r);Zi(e.eventQueue_,t,o),vs(e,s,n,i)}));const u=Is(e,t);bs(e,u),Zi(e.eventQueue_,u,[])}function ps(e,t,n){e.server_.onDisconnectCancel(t.toString(),((i,s)=>{"ok"===i&&Nt(e.onDisconnect_,t),vs(e,n,i,s)}))}function fs(e,t,n,i){const s=ct(n);e.server_.onDisconnectPut(t.toString(),s.val(!0),((n,r)=>{"ok"===n&&xt(e.onDisconnect_,t,s),vs(e,i,n,r)}))}function ms(e,t,n){let i;i=".info"===ge(t._path)?ni(e.infoSyncTree_,t,n):ni(e.serverSyncTree_,t,n),Ji(e.eventQueue_,t._path,i)}function _s(e){e.persistentConnection_&&e.persistentConnection_.interrupt(ns)}function gs(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),S(n,...t)}function vs(e,t,n,i){t&&j((()=>{if("ok"===n)t(null);else{const e=(n||"error").toUpperCase();let s=e;i&&(s+=": "+i);const r=new Error(s);r.code=e,t(r)}}))}function ys(e,t,n){return ri(e.serverSyncTree_,t,n)||ot.EMPTY_NODE}function ws(e,t=e.transactionQueueTree_){if(t||Ts(e,t),xi(t)){const n=Ss(e,t);(0,r.assert)(n.length>0,"Sending zero length transaction queue");n.every((e=>0===e.status))&&function(e,t,n){const i=n.map((e=>e.currentWriteId)),s=ys(e,t,i);let o=s;const a=s.hash();for(let e=0;e<n.length;e++){const i=n[e];(0,r.assert)(0===i.status,"tryToSendTransactionQueue_: items in queue should all be run."),i.status=1,i.retryCount++;const s=Te(t,i.path);o=o.updateChild(s,i.currentOutputSnapshotRaw)}const l=o.val(!0),c=t;e.server_.put(c.toString(),l,(i=>{gs(e,"transaction put response",{path:c.toString(),status:i});let s=[];if("ok"===i){const i=[];for(let t=0;t<n.length;t++)n[t].status=2,s=s.concat(ei(e.serverSyncTree_,n[t].currentWriteId)),n[t].onComplete&&i.push((()=>n[t].onComplete(null,!0,n[t].currentOutputSnapshotResolved))),n[t].unwatcher();Ts(e,ki(e.transactionQueueTree_,t)),ws(e,e.transactionQueueTree_),Zi(e.eventQueue_,t,s);for(let e=0;e<i.length;e++)j(i[e])}else{if("datastale"===i)for(let e=0;e<n.length;e++)3===n[e].status?n[e].status=4:n[e].status=0;else{k("transaction at "+c.toString()+" failed: "+i);for(let e=0;e<n.length;e++)n[e].status=4,n[e].abortReason=i}bs(e,t)}}),a)}(e,Ai(t),n)}else Pi(t)&&Di(t,(t=>{ws(e,t)}))}function bs(e,t){const n=Cs(e,t),i=Ai(n);return function(e,t,n){if(0===t.length)return;const i=[];let s=[];const o=t.filter((e=>0===e.status)),a=o.map((e=>e.currentWriteId));for(let o=0;o<t.length;o++){const c=t[o],h=Te(n,c.path);let u,d=!1;if((0,r.assert)(null!==h,"rerunTransactionsUnderNode_: relativePath should not be null."),4===c.status)d=!0,u=c.abortReason,s=s.concat(ei(e.serverSyncTree_,c.currentWriteId,!0));else if(0===c.status)if(c.retryCount>=is)d=!0,u="maxretry",s=s.concat(ei(e.serverSyncTree_,c.currentWriteId,!0));else{const n=ys(e,c.path,a);c.currentInputSnapshot=n;const i=t[o].update(n.val());if(void 0!==i){Ui("transaction failed: Data returned ",i,c.path);let t=ct(i);"object"==typeof i&&null!=i&&(0,r.contains)(i,".priority")||(t=t.updatePriority(n.getPriority()));const o=c.currentWriteId,l=as(e),h=Ei(t,n,l);c.currentOutputSnapshotRaw=t,c.currentOutputSnapshotResolved=h,c.currentWriteId=us(e),a.splice(a.indexOf(o),1),s=s.concat(Jn(e.serverSyncTree_,c.path,h,c.currentWriteId,c.applyLocally)),s=s.concat(ei(e.serverSyncTree_,o,!0))}else d=!0,u="nodata",s=s.concat(ei(e.serverSyncTree_,c.currentWriteId,!0))}Zi(e.eventQueue_,n,s),s=[],d&&(t[o].status=2,l=t[o].unwatcher,setTimeout(l,Math.floor(0)),t[o].onComplete&&("nodata"===u?i.push((()=>t[o].onComplete(null,!1,t[o].currentInputSnapshot))):i.push((()=>t[o].onComplete(new Error(u),!1,null)))))}var l;Ts(e,e.transactionQueueTree_);for(let e=0;e<i.length;e++)j(i[e]);ws(e,e.transactionQueueTree_)}(e,Ss(e,n),i),i}function Cs(e,t){let n,i=e.transactionQueueTree_;for(n=ge(t);null!==n&&void 0===xi(i);)i=ki(i,n),n=ge(t=ye(t));return i}function Ss(e,t){const n=[];return Es(e,t,n),n.sort(((e,t)=>e.order-t.order)),n}function Es(e,t,n){const i=xi(t);if(i)for(let e=0;e<i.length;e++)n.push(i[e]);Di(t,(t=>{Es(e,t,n)}))}function Ts(e,t){const n=xi(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,Ni(t,n.length>0?n:void 0)}Di(t,(t=>{Ts(e,t)}))}function Is(e,t){const n=Ai(Cs(e,t)),i=ki(e.transactionQueueTree_,t);return function(e,t,n){let i=n?e:e.parent;for(;null!==i;){if(t(i))return!0;i=i.parent}}(i,(t=>{ks(e,t)})),ks(e,i),Ri(i,(t=>{ks(e,t)})),n}function ks(e,t){const n=xi(t);if(n){const i=[];let s=[],o=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?((0,r.assert)(o===t-1,"All SENT items should be at beginning of queue."),o=t,n[t].status=3,n[t].abortReason="set"):((0,r.assert)(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),s=s.concat(ei(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&i.push(n[t].onComplete.bind(null,new Error("set"),!1,null))));-1===o?Ni(t,void 0):n.length=o+1,Zi(e.eventQueue_,Ai(t),s);for(let e=0;e<i.length;e++)j(i[e])}}const xs=function(e,t){const n=Ns(e),i=n.namespace;"firebase.com"===n.domain&&I(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||I("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&k("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");const s="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new Q(n.host,n.secure,i,s,t,"",i!==n.subdomain),path:new me(n.pathString)}},Ns=function(e){let t="",n="",i="",s="",r="",o=!0,a="https",l=443;if("string"==typeof e){let c=e.indexOf("//");c>=0&&(a=e.substring(0,c-1),e=e.substring(c+2));let h=e.indexOf("/");-1===h&&(h=e.length);let u=e.indexOf("?");-1===u&&(u=e.length),t=e.substring(0,Math.min(h,u)),h<u&&(s=function(e){let t="";const n=e.split("/");for(let e=0;e<n.length;e++)if(n[e].length>0){let i=n[e];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}(e.substring(h,u)));const d=function(e){const t={};"?"===e.charAt(0)&&(e=e.substring(1));for(const n of e.split("&")){if(0===n.length)continue;const i=n.split("=");2===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):k(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,u)));c=t.indexOf(":"),c>=0?(o="https"===a||"wss"===a,l=parseInt(t.substring(c+1),10)):c=t.length;const p=t.slice(0,c);if("localhost"===p.toLowerCase())n="localhost";else if(p.split(".").length<=2)n=p;else{const e=t.indexOf(".");i=t.substring(0,e).toLowerCase(),n=t.substring(e+1),r=i}"ns"in d&&(r=d.ns)}return{host:t,port:l,domain:n,subdomain:i,secure:o,scheme:a,pathString:s,namespace:r}},Ps="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",Ds=function(){let e=0;const t=[];return function(n){const i=n===e;let s;e=n;const o=new Array(8);for(s=7;s>=0;s--)o[s]=Ps.charAt(n%64),n=Math.floor(n/64);(0,r.assert)(0===n,"Cannot push at time == 0");let a=o.join("");if(i){for(s=11;s>=0&&63===t[s];s--)t[s]=0;t[s]++}else for(s=0;s<12;s++)t[s]=Math.floor(64*Math.random());for(s=0;s<12;s++)a+=Ps.charAt(t[s]);return(0,r.assert)(20===a.length,"nextPushId: Length should be 20."),a}}();class Rs{constructor(e,t,n,i){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=i}getPath(){const e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+(0,r.stringify)(this.snapshot.exportVal())}}class As{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class Ls{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return(0,r.assert)(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class Os{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new r.Deferred;return ps(this._repo,this._path,e.wrapCallback((()=>{}))),e.promise}remove(){Ki("OnDisconnect.remove",this._path);const e=new r.Deferred;return fs(this._repo,this._path,null,e.wrapCallback((()=>{}))),e.promise}set(e){Ki("OnDisconnect.set",this._path),Wi("OnDisconnect.set",e,this._path,!1);const t=new r.Deferred;return fs(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}setWithPriority(e,t){Ki("OnDisconnect.setWithPriority",this._path),Wi("OnDisconnect.setWithPriority",e,this._path,!1),Vi("OnDisconnect.setWithPriority",t,!1);const n=new r.Deferred;return function(e,t,n,i,s){const r=ct(n,i);e.server_.onDisconnectPut(t.toString(),r.val(!0),((n,i)=>{"ok"===n&&xt(e.onDisconnect_,t,r),vs(0,s,n,i)}))}(this._repo,this._path,e,t,n.wrapCallback((()=>{}))),n.promise}update(e){Ki("OnDisconnect.update",this._path),zi("OnDisconnect.update",e,this._path,!1);const t=new r.Deferred;return function(e,t,n,i){if((0,r.isEmpty)(n))return S("onDisconnect().update() called with empty data. Don't do anything."),void vs(0,i,"ok",void 0);e.server_.onDisconnectMerge(t.toString(),n,((s,r)=>{"ok"===s&&M(n,((n,i)=>{const s=ct(i);xt(e.onDisconnect_,Se(t,n),s)})),vs(0,i,s,r)}))}(this._repo,this._path,e,t.wrapCallback((()=>{}))),t.promise}}class Ms{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return Ee(this._path)?null:we(this._path)}get ref(){return new js(this._repo,this._path)}get _queryIdentifier(){const e=Et(this._queryParams),t=L(e);return"{}"===t?"default":t}get _queryObject(){return Et(this._queryParams)}isEqual(e){if(!((e=(0,r.getModularInstance)(e))instanceof Ms))return!1;const t=this._repo===e._repo,n=ke(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return t&&n&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function Fs(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function qs(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===Be){const i="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",s="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==N)throw new Error(i);if("string"!=typeof t)throw new Error(s)}if(e.hasEnd()){if(e.getIndexEndName()!==P)throw new Error(i);if("string"!=typeof n)throw new Error(s)}}else if(e.getIndex()===Je){if(null!=t&&!ji(t)||null!=n&&!ji(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if((0,r.assert)(e.getIndex()instanceof ht||e.getIndex()===ut,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function Bs(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class js extends Ms{constructor(e,t){super(e,t,new yt,!1)}get parent(){const e=Ce(this._path);return null===e?null:new js(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class Ws{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const t=new me(e),n=Vs(this.ref,e);return new Ws(this._node.getChild(t),n,Je)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){if(this._node.isLeafNode())return!1;return!!this._node.forEachChild(this._index,((t,n)=>e(new Ws(n,Vs(this.ref,t),Je))))}hasChild(e){const t=new me(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function Us(e,t){return(e=(0,r.getModularInstance)(e))._checkNotDeleted("ref"),void 0!==t?Vs(e._root,t):e._root}function zs(e,t){(e=(0,r.getModularInstance)(e))._checkNotDeleted("refFromURL");const n=xs(t,e._repo.repoInfo_.nodeAdmin);Gi("refFromURL",n);const i=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||i.host===e._repo.repoInfo_.host||I("refFromURL: Host name does not match the current database: (found "+i.host+" but expected "+e._repo.repoInfo_.host+")"),Us(e,n.path.toString())}function Vs(e,t){return null===ge((e=(0,r.getModularInstance)(e))._path)?Yi("child","path",t,!1):$i("child","path",t,!1),new js(e._repo,Se(e._path,t))}function Hs(e){return e=(0,r.getModularInstance)(e),new Os(e._repo,e._path)}function $s(e,t){e=(0,r.getModularInstance)(e),Ki("push",e._path),Wi("push",t,e._path,!0);const n=os(e._repo),i=Ds(n),s=Vs(e,i),o=Vs(e,i);let a;return a=null!=t?Ks(o,t).then((()=>o)):Promise.resolve(o),s.then=a.then.bind(a),s.catch=a.then.bind(a,void 0),s}function Ys(e){return Ki("remove",e._path),Ks(e,null)}function Ks(e,t){e=(0,r.getModularInstance)(e),Ki("set",e._path),Wi("set",t,e._path,!1);const n=new r.Deferred;return ds(e._repo,e._path,t,null,n.wrapCallback((()=>{}))),n.promise}function Gs(e,t){e=(0,r.getModularInstance)(e),Ki("setPriority",e._path),Vi("setPriority",t,!1);const n=new r.Deferred;return ds(e._repo,Se(e._path,".priority"),t,null,n.wrapCallback((()=>{}))),n.promise}function Qs(e,t,n){if(Ki("setWithPriority",e._path),Wi("setWithPriority",t,e._path,!1),Vi("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const i=new r.Deferred;return ds(e._repo,e._path,t,n,i.wrapCallback((()=>{}))),i.promise}function Xs(e,t){zi("update",t,e._path,!1);const n=new r.Deferred;return function(e,t,n,i){gs(e,"update",{path:t.toString(),value:n});let s=!0;const r=as(e),o={};if(M(n,((n,i)=>{s=!1,o[n]=Si(Se(t,n),ct(i),e.serverSyncTree_,r)})),s)S("update() called with empty data. Don't do anything."),vs(0,i,"ok",void 0);else{const s=us(e),r=Zn(e.serverSyncTree_,t,o,s);Xi(e.eventQueue_,r),e.server_.merge(t.toString(),n,((n,r)=>{const o="ok"===n;o||k("update at "+t+" failed: "+n);const a=ei(e.serverSyncTree_,s,!o),l=a.length>0?bs(e,t):t;Zi(e.eventQueue_,l,a),vs(0,i,n,r)})),M(n,(n=>{const i=Is(e,Se(t,n));bs(e,i)})),Zi(e.eventQueue_,t,[])}}(e._repo,e._path,t,n.wrapCallback((()=>{}))),n.promise}function Js(e){e=(0,r.getModularInstance)(e);const t=new Ls((()=>{})),n=new Zs(t);return function(e,t,n){const i=oi(e.serverSyncTree_,t);return null!=i?Promise.resolve(i):e.server_.get(t).then((i=>{const s=ct(i).withIndex(t._queryParams.getIndex());let r;if(si(e.serverSyncTree_,t,n,!0),t._queryParams.loadsAllData())r=ti(e.serverSyncTree_,t._path,s);else{const n=ui(e.serverSyncTree_,t);r=ii(e.serverSyncTree_,t._path,s,n)}return Zi(e.eventQueue_,t._path,r),ni(e.serverSyncTree_,t,n,null,!0),s}),(n=>(gs(e,"get for query "+(0,r.stringify)(t)+" failed: "+n),Promise.reject(new Error(n)))))}(e._repo,e,n).then((t=>new Ws(t,new js(e._repo,e._path),e._queryParams.getIndex())))}class Zs{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){const n=t._queryParams.getIndex();return new Rs("value",this,new Ws(e.snapshotNode,new js(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new As(this,e,t):null}matches(e){return e instanceof Zs&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class er{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new As(this,e,t):null}createEvent(e,t){(0,r.assert)(null!=e.childName,"Child events should have a childName.");const n=Vs(new js(t._repo,t._path),e.childName),i=t._queryParams.getIndex();return new Rs(e.type,this,new Ws(e.snapshotNode,n,i),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof er&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function tr(e,t,n,i,s){let r;if("object"==typeof i&&(r=void 0,s=i),"function"==typeof i&&(r=i),s&&s.onlyOnce){const t=n,i=(n,i)=>{ms(e._repo,e,a),t(n,i)};i.userCallback=n.userCallback,i.context=n.context,n=i}const o=new Ls(n,r||void 0),a="value"===t?new Zs(o):new er(t,o);return function(e,t,n){let i;i=".info"===ge(t._path)?si(e.infoSyncTree_,t,n):si(e.serverSyncTree_,t,n),Ji(e.eventQueue_,t._path,i)}(e._repo,e,a),()=>ms(e._repo,e,a)}function nr(e,t,n,i){return tr(e,"value",t,n,i)}function ir(e,t,n,i){return tr(e,"child_added",t,n,i)}function sr(e,t,n,i){return tr(e,"child_changed",t,n,i)}function rr(e,t,n,i){return tr(e,"child_moved",t,n,i)}function or(e,t,n,i){return tr(e,"child_removed",t,n,i)}function ar(e,t,n){let i=null;const s=n?new Ls(n):null;"value"===t?i=new Zs(s):t&&(i=new er(t,s)),ms(e._repo,e,i)}class lr{}class cr extends lr{constructor(e,t){super(),this._value=e,this._key=t,this.type="endAt"}_apply(e){Wi("endAt",this._value,e._path,!0);const t=bt(e._queryParams,this._value,this._key);if(Bs(t),qs(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new Ms(e._repo,e._path,t,e._orderByCalled)}}function hr(e,t){return Hi("endAt","key",t,!0),new cr(e,t)}class ur extends lr{constructor(e,t){super(),this._value=e,this._key=t,this.type="endBefore"}_apply(e){Wi("endBefore",this._value,e._path,!1);const t=function(e,t,n){let i;return i=e.index_===Be||n?bt(e,t,n):bt(e,t,N),i.endBeforeSet_=!0,i}(e._queryParams,this._value,this._key);if(Bs(t),qs(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new Ms(e._repo,e._path,t,e._orderByCalled)}}function dr(e,t){return Hi("endBefore","key",t,!0),new ur(e,t)}class pr extends lr{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAt"}_apply(e){Wi("startAt",this._value,e._path,!0);const t=wt(e._queryParams,this._value,this._key);if(Bs(t),qs(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new Ms(e._repo,e._path,t,e._orderByCalled)}}function fr(e=null,t){return Hi("startAt","key",t,!0),new pr(e,t)}class mr extends lr{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){Wi("startAfter",this._value,e._path,!1);const t=function(e,t,n){let i;return i=e.index_===Be||n?wt(e,t,n):wt(e,t,P),i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(Bs(t),qs(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new Ms(e._repo,e._path,t,e._orderByCalled)}}function _r(e,t){return Hi("startAfter","key",t,!0),new mr(e,t)}class gr extends lr{constructor(e){super(),this._limit=e,this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new Ms(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}function vr(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new gr(e)}class yr extends lr{constructor(e){super(),this._limit=e,this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new Ms(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}function wr(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new yr(e)}class br extends lr{constructor(e){super(),this._path=e,this.type="orderByChild"}_apply(e){Fs(e,"orderByChild");const t=new me(this._path);if(Ee(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");const n=new ht(t),i=Ct(e._queryParams,n);return qs(i),new Ms(e._repo,e._path,i,!0)}}function Cr(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid. Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid. Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid. Use orderByValue() instead.');return $i("orderByChild","path",e,!1),new br(e)}class Sr extends lr{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){Fs(e,"orderByKey");const t=Ct(e._queryParams,Be);return qs(t),new Ms(e._repo,e._path,t,!0)}}function Er(){return new Sr}class Tr extends lr{constructor(){super(...arguments),this.type="orderByPriority"}_apply(e){Fs(e,"orderByPriority");const t=Ct(e._queryParams,Je);return qs(t),new Ms(e._repo,e._path,t,!0)}}function Ir(){return new Tr}class kr extends lr{constructor(){super(...arguments),this.type="orderByValue"}_apply(e){Fs(e,"orderByValue");const t=Ct(e._queryParams,ut);return qs(t),new Ms(e._repo,e._path,t,!0)}}function xr(){return new kr}class Nr extends lr{constructor(e,t){super(),this._value=e,this._key=t,this.type="equalTo"}_apply(e){if(Wi("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new cr(this._value,this._key)._apply(new pr(this._value,this._key)._apply(e))}}function Pr(e,t){return Hi("equalTo","key",t,!0),new Nr(e,t)}function Dr(e,...t){let n=(0,r.getModularInstance)(e);for(const e of t)n=e._apply(n);return n}!function(e){(0,r.assert)(!Fn,"__referenceConstructor has already been defined"),Fn=e}(js),function(e){(0,r.assert)(!qn,"__referenceConstructor has already been defined"),qn=e}(js);const Rr="FIREBASE_DATABASE_EMULATOR_HOST",Ar={};let Lr=!1;function Or(e,t,n,i,s){let r=i||e.options.databaseURL;void 0===r&&(e.options.projectId||I("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),S("Using default host for project ",e.options.projectId),r=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o,a,l=xs(r,s),c=l.repoInfo;"undefined"!=typeof process&&(a="MISSING_ENV_VAR"[Rr]),a?(o=!0,r=`http://${a}?ns=${c.namespace}`,l=xs(r,s),c=l.repoInfo):o=!l.repoInfo.secure;const h=s&&o?new V(V.OWNER):new z(e.name,e.options,t);Gi("Invalid Firebase Database URL",l),Ee(l.path)||I("Database URL must point to the root of a Firebase Database (not including a child path).");const u=function(e,t,n,i){let s=Ar[t.name];s||(s={},Ar[t.name]=s);let r=s[e.toURLString()];r&&I("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return r=new ss(e,Lr,n,i),s[e.toURLString()]=r,r}(c,e,h,new U(e.name,n));return new Mr(u,e)}class Mr{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(rs(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new js(this._repo,_e())),this._rootInternal}_delete(){return null!==this._rootInternal&&(!function(e,t){const n=Ar[t];n&&n[e.key]===e||I(`Database ${t}(${e.repoInfo_}) has already been deleted.`),_s(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&I("Cannot call "+e+" on a deleted database.")}}function Fr(){le.IS_TRANSPORT_INITIALIZED&&k("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}function qr(){Fr(),se.forceDisallow()}function Br(){Fr(),ae.forceDisallow(),se.forceAllow()}function jr(e=(0,i.getApp)(),t){const n=(0,i._getProvider)(e,"database").getImmediate({identifier:t});if(!n._instanceStarted){const e=(0,r.getDefaultEmulatorHostnameAndPort)("database");e&&Wr(n,...e)}return n}function Wr(e,t,n,i={}){(e=(0,r.getModularInstance)(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&I("Cannot call useEmulator() after instance has already been initialized.");const s=e._repoInternal;let o;if(s.repoInfo_.nodeAdmin)i.mockUserToken&&I('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new V(V.OWNER);else if(i.mockUserToken){const t="string"==typeof i.mockUserToken?i.mockUserToken:(0,r.createMockUserToken)(i.mockUserToken,e.app.options.projectId);o=new V(t)}!function(e,t,n,i){e.repoInfo_=new Q(`${t}:${n}`,!1,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0),i&&(e.authTokenProvider_=i)}(s,t,n,o)}function Ur(e){(e=(0,r.getModularInstance)(e))._checkNotDeleted("goOffline"),_s(e._repo)}function zr(e){var t;(e=(0,r.getModularInstance)(e))._checkNotDeleted("goOnline"),(t=e._repo).persistentConnection_&&t.persistentConnection_.resume(ns)}function Vr(e,t){C(e,t)}const Hr={".sv":"timestamp"};function $r(){return Hr}function Yr(e){return{".sv":{increment:e}}}class Kr{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function Gr(e,t,n){var i;if(e=(0,r.getModularInstance)(e),Ki("Reference.transaction",e._path),".length"===e.key||".keys"===e.key)throw"Reference.transaction failed: "+e.key+" is a read-only object.";const s=null===(i=null==n?void 0:n.applyLocally)||void 0===i||i,o=new r.Deferred,a=nr(e,(()=>{}));return function(e,t,n,i,s,o){gs(e,"transaction on "+t);const a={path:t,update:n,onComplete:i,status:null,order:g(),applyLocally:o,retryCount:0,unwatcher:s,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},l=ys(e,t,void 0);a.currentInputSnapshot=l;const c=a.update(l.val());if(void 0===c)a.unwatcher(),a.currentOutputSnapshotRaw=null,a.currentOutputSnapshotResolved=null,a.onComplete&&a.onComplete(null,!1,a.currentInputSnapshot);else{Ui("transaction failed: Data returned ",c,a.path),a.status=0;const n=ki(e.transactionQueueTree_,t),i=xi(n)||[];let s;i.push(a),Ni(n,i),"object"==typeof c&&null!==c&&(0,r.contains)(c,".priority")?(s=(0,r.safeGet)(c,".priority"),(0,r.assert)(ji(s),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.")):s=(ri(e.serverSyncTree_,t)||ot.EMPTY_NODE).getPriority().val();const o=as(e),h=ct(c,s),u=Ei(h,l,o);a.currentOutputSnapshotRaw=h,a.currentOutputSnapshotResolved=u,a.currentWriteId=us(e);const d=Jn(e.serverSyncTree_,t,u,a.currentWriteId,a.applyLocally);Zi(e.eventQueue_,t,d),ws(e,e.transactionQueueTree_)}}(e._repo,e._path,t,((t,n,i)=>{let s=null;t?o.reject(t):(s=new Ws(i,new js(e._repo,e._path),Je),o.resolve(new Kr(n,s)))}),a,s),o.promise}Le.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},Le.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)};const Qr=function(e){const t=Le.prototype.put;return Le.prototype.put=function(n,i,s,r){void 0!==r&&(r=e()),t.call(this,n,i,s,r)},function(){Le.prototype.put=t}},Xr=function(e){!function(e){Lr=e}(e)};function Jr({app:e,url:t,version:n,customAuthImpl:i,customAppCheckImpl:r,nodeAdmin:o=!1}){h(n);const a=new s.ComponentContainer("database-standalone"),l=new s.Provider("auth-internal",a);let c;return r&&(c=new s.Provider("app-check-internal",a),c.setComponent(new s.Component("app-check-internal",(()=>r),"PRIVATE"))),l.setComponent(new s.Component("auth-internal",(()=>i),"PRIVATE")),Or(e,l,c,t,o)}var Zr;h(i.SDK_VERSION),(0,i._registerComponent)(new s.Component("database",((e,{instanceIdentifier:t})=>Or(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)),"PUBLIC").setMultipleInstances(!0)),(0,i.registerVersion)(a,l,Zr),(0,i.registerVersion)(a,l,"esm2017")},"./node_modules/@firebase/util/dist/index.esm2017.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{CONSTANTS:()=>i,DecodeBase64StringError:()=>l,Deferred:()=>w,ErrorFactory:()=>F,FirebaseError:()=>M,MAX_VALUE_MILLIS:()=>ge,RANDOM_FACTOR:()=>ve,Sha1:()=>ne,areCookiesEnabled:()=>O,assert:()=>s,assertionError:()=>r,async:()=>re,base64:()=>a,base64Decode:()=>u,base64Encode:()=>c,base64urlEncodeWithoutPadding:()=>h,calculateBackoffMillis:()=>ye,contains:()=>$,createMockUserToken:()=>b,createSubscribe:()=>ie,decode:()=>W,deepCopy:()=>d,deepEqual:()=>Q,deepExtend:()=>p,errorPrefix:()=>le,extractQuerystring:()=>te,getDefaultAppConfig:()=>v,getDefaultEmulatorHost:()=>_,getDefaultEmulatorHostnameAndPort:()=>g,getDefaults:()=>m,getExperimentalSetting:()=>y,getGlobal:()=>f,getModularInstance:()=>be,getUA:()=>C,isAdmin:()=>H,isBrowser:()=>T,isBrowserExtension:()=>I,isElectron:()=>x,isEmpty:()=>K,isIE:()=>N,isIndexedDBAvailable:()=>A,isMobileCordova:()=>S,isNode:()=>E,isNodeSdk:()=>D,isReactNative:()=>k,isSafari:()=>R,isUWP:()=>P,isValidFormat:()=>V,isValidTimestamp:()=>U,issuedAtTime:()=>z,jsonEval:()=>B,map:()=>G,ordinal:()=>we,promiseWithTimeout:()=>J,querystring:()=>Z,querystringDecode:()=>ee,safeGet:()=>Y,stringLength:()=>pe,stringToByteArray:()=>de,stringify:()=>j,uuidv4:()=>fe,validateArgCount:()=>ae,validateCallback:()=>he,validateContextObject:()=>ue,validateIndexedDBOpenable:()=>L,validateNamespace:()=>ce});const i={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},s=function(e,t){if(!e)throw r(t)},r=function(e){return new Error("Firebase Database ("+i.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},o=function(e){const t=[];let n=0;for(let i=0;i<e.length;i++){let s=e.charCodeAt(i);s<128?t[n++]=s:s<2048?(t[n++]=s>>6|192,t[n++]=63&s|128):55296==(64512&s)&&i+1<e.length&&56320==(64512&e.charCodeAt(i+1))?(s=65536+((1023&s)<<10)+(1023&e.charCodeAt(++i)),t[n++]=s>>18|240,t[n++]=s>>12&63|128,t[n++]=s>>6&63|128,t[n++]=63&s|128):(t[n++]=s>>12|224,t[n++]=s>>6&63|128,t[n++]=63&s|128)}return t},a={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let t=0;t<e.length;t+=3){const s=e[t],r=t+1<e.length,o=r?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,c=s>>2,h=(3&s)<<4|o>>4;let u=(15&o)<<2|l>>6,d=63&l;a||(d=64,r||(u=64)),i.push(n[c],n[h],n[u],n[d])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(o(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,i=0;for(;n<e.length;){const s=e[n++];if(s<128)t[i++]=String.fromCharCode(s);else if(s>191&&s<224){const r=e[n++];t[i++]=String.fromCharCode((31&s)<<6|63&r)}else if(s>239&&s<365){const r=((7&s)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[i++]=String.fromCharCode(55296+(r>>10)),t[i++]=String.fromCharCode(56320+(1023&r))}else{const r=e[n++],o=e[n++];t[i++]=String.fromCharCode((15&s)<<12|(63&r)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,i=[];for(let t=0;t<e.length;){const s=n[e.charAt(t++)],r=t<e.length?n[e.charAt(t)]:0;++t;const o=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==s||null==r||null==o||null==a)throw new l;const c=s<<2|r>>4;if(i.push(c),64!==o){const e=r<<4&240|o>>2;if(i.push(e),64!==a){const e=o<<6&192|a;i.push(e)}}}return i},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class l extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const c=function(e){const t=o(e);return a.encodeByteArray(t,!0)},h=function(e){return c(e).replace(/\./g,"")},u=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function d(e){return p(void 0,e)}function p(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=p(e[n],t[n]));return e}function f(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("Unable to locate global object.")}const m=()=>{try{return f().__FIREBASE_DEFAULTS__||(()=>{if("undefined"==typeof process)return;const e="MISSING_ENV_VAR".__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&u(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},_=e=>{var t,n;return null===(n=null===(t=m())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]},g=e=>{const t=_(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const i=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),i]:[t.substring(0,n),i]},v=()=>{var e;return null===(e=m())||void 0===e?void 0:e.config},y=e=>{var t;return null===(t=m())||void 0===t?void 0:t[`_${e}`]};class w{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function b(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",i=e.iat||0,s=e.sub||e.user_id;if(!s)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const r=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:i,exp:i+3600,auth_time:i,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}}},e);return[h(JSON.stringify({alg:"none",type:"JWT"})),h(JSON.stringify(r)),""].join(".")}function C(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function S(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(C())}function E(){var e;const t=null===(e=m())||void 0===e?void 0:e.forceEnvironment;if("node"===t)return!0;if("browser"===t)return!1;try{return"[object process]"===Object.prototype.toString.call(n.g.process)}catch(e){return!1}}function T(){return"object"==typeof self&&self.self===self}function I(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function k(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function x(){return C().indexOf("Electron/")>=0}function N(){const e=C();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}function P(){return C().indexOf("MSAppHost/")>=0}function D(){return!0===i.NODE_CLIENT||!0===i.NODE_ADMIN}function R(){return!E()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function A(){try{return"object"==typeof indexedDB}catch(e){return!1}}function L(){return new Promise(((e,t)=>{try{let n=!0;const i="validate-browser-context-for-indexeddb-analytics-module",s=self.indexedDB.open(i);s.onsuccess=()=>{s.result.close(),n||self.indexedDB.deleteDatabase(i),e(!0)},s.onupgradeneeded=()=>{n=!1},s.onerror=()=>{var e;t((null===(e=s.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))}function O(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class M extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,M.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,F.prototype.create)}}class F{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],r=s?function(e,t){return e.replace(q,((e,n)=>{const i=t[n];return null!=i?String(i):`<${n}?>`}))}(s,n):"Error",o=`${this.serviceName}: ${r} (${i}).`;return new M(i,o,n)}}const q=/\{\$([^}]+)}/g;function B(e){return JSON.parse(e)}function j(e){return JSON.stringify(e)}const W=function(e){let t={},n={},i={},s="";try{const r=e.split(".");t=B(u(r[0])||""),n=B(u(r[1])||""),s=r[2],i=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:i,signature:s}},U=function(e){const t=W(e).claims,n=Math.floor((new Date).getTime()/1e3);let i=0,s=0;return"object"==typeof t&&(t.hasOwnProperty("nbf")?i=t.nbf:t.hasOwnProperty("iat")&&(i=t.iat),s=t.hasOwnProperty("exp")?t.exp:i+86400),!!n&&!!i&&!!s&&n>=i&&n<=s},z=function(e){const t=W(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null},V=function(e){const t=W(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")},H=function(e){const t=W(e).claims;return"object"==typeof t&&!0===t.admin};function $(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Y(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function K(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function G(e,t,n){const i={};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=t.call(n,e[s],s,e));return i}function Q(e,t){if(e===t)return!0;const n=Object.keys(e),i=Object.keys(t);for(const s of n){if(!i.includes(s))return!1;const n=e[s],r=t[s];if(X(n)&&X(r)){if(!Q(n,r))return!1}else if(n!==r)return!1}for(const e of i)if(!n.includes(e))return!1;return!0}function X(e){return null!==e&&"object"==typeof e}function J(e,t=2e3){const n=new w;return setTimeout((()=>n.reject("timeout!")),t),e.then(n.resolve,n.reject),n.promise}function Z(e){const t=[];for(const[n,i]of Object.entries(e))Array.isArray(i)?i.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(i));return t.length?"&"+t.join("&"):""}function ee(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,i]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(i)}})),t}function te(e){const t=e.indexOf("?");if(!t)return"";const n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)}class ne{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(e,t){t||(t=0);const n=this.W_;if("string"==typeof e)for(let i=0;i<16;i++)n[i]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let i=0;i<16;i++)n[i]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let e=16;e<80;e++){const t=n[e-3]^n[e-8]^n[e-14]^n[e-16];n[e]=4294967295&(t<<1|t>>>31)}let i,s,r=this.chain_[0],o=this.chain_[1],a=this.chain_[2],l=this.chain_[3],c=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(i=l^o&(a^l),s=1518500249):(i=o^a^l,s=1859775393):e<60?(i=o&a|l&(o|a),s=2400959708):(i=o^a^l,s=3395469782);const t=(r<<5|r>>>27)+i+c+s+n[e]&4294967295;c=l,l=a,a=4294967295&(o<<30|o>>>2),o=r,r=t}this.chain_[0]=this.chain_[0]+r&4294967295,this.chain_[1]=this.chain_[1]+o&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let i=0;const s=this.buf_;let r=this.inbuf_;for(;i<t;){if(0===r)for(;i<=n;)this.compress_(e,i),i+=this.blockSize;if("string"==typeof e){for(;i<t;)if(s[r]=e.charCodeAt(i),++r,++i,r===this.blockSize){this.compress_(s),r=0;break}}else for(;i<t;)if(s[r]=e[i],++r,++i,r===this.blockSize){this.compress_(s),r=0;break}}this.inbuf_=r,this.total_+=t}digest(){const e=[];let t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let e=this.blockSize-1;e>=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let i=24;i>=0;i-=8)e[n]=this.chain_[t]>>i&255,++n;return e}}function ie(e,t){const n=new se(e,t);return n.subscribe.bind(n)}class se{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,n){let i;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");i=function(e,t){if("object"!=typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===i.next&&(i.next=oe),void 0===i.error&&(i.error=oe),void 0===i.complete&&(i.complete=oe);const s=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch(e){}})),this.observers.push(i),s}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then((()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function re(e,t){return(...n)=>{Promise.resolve(!0).then((()=>{e(...n)})).catch((e=>{t&&t(e)}))}}function oe(){}const ae=function(e,t,n,i){let s;if(i<t?s="at least "+t:i>n&&(s=0===n?"none":"no more than "+n),s){throw new Error(e+" failed: Was called with "+i+(1===i?" argument.":" arguments.")+" Expects "+s+".")}};function le(e,t){return`${e} failed: ${t} argument `}function ce(e,t,n){if((!n||t)&&"string"!=typeof t)throw new Error(le(e,"namespace")+"must be a valid firebase namespace.")}function he(e,t,n,i){if((!i||n)&&"function"!=typeof n)throw new Error(le(e,t)+"must be a valid function.")}function ue(e,t,n,i){if((!i||n)&&("object"!=typeof n||null===n))throw new Error(le(e,t)+"must be a valid context object.")}const de=function(e){const t=[];let n=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if(r>=55296&&r<=56319){const t=r-55296;i++,s(i<e.length,"Surrogate pair missing trail surrogate.");r=65536+(t<<10)+(e.charCodeAt(i)-56320)}r<128?t[n++]=r:r<2048?(t[n++]=r>>6|192,t[n++]=63&r|128):r<65536?(t[n++]=r>>12|224,t[n++]=r>>6&63|128,t[n++]=63&r|128):(t[n++]=r>>18|240,t[n++]=r>>12&63|128,t[n++]=r>>6&63|128,t[n++]=63&r|128)}return t},pe=function(e){let t=0;for(let n=0;n<e.length;n++){const i=e.charCodeAt(n);i<128?t++:i<2048?t+=2:i>=55296&&i<=56319?(t+=4,n++):t+=3}return t},fe=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))},me=1e3,_e=2,ge=144e5,ve=.5;function ye(e,t=me,n=_e){const i=t*Math.pow(n,e),s=Math.round(ve*i*(Math.random()-.5)*2);return Math.min(ge,i+s)}function we(e){return Number.isFinite(e)?e+function(e){e=Math.abs(e);const t=e%100;if(t>=10&&t<=20)return"th";const n=e%10;if(1===n)return"st";if(2===n)return"nd";if(3===n)return"rd";return"th"}(e):`${e}`}function be(e){return e&&e._delegate?e._delegate:e}},"./js/main/code-anime/item.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{Item:()=>c});var i=n("./js/main/code-anime/utils.js");function s(e){return s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s(e)}function r(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,a(i.key),i)}}function o(e,t,n){return(t=a(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e){var t=function(e,t){if("object"!=s(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t||"default");if("object"!=s(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==s(t)?t:String(t)}var l={x:0,y:0};window.addEventListener("mousemove",(function(e){l=(0,i.getMousePos)(e)}));var c=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),o(this,"DOM",{el:null,deco:null}),o(this,"renderedStyles",{x:{previous:0,current:0,amt:.1},y:{previous:0,current:0,amt:.1}}),o(this,"randomString",(0,i.getRandomString)(2e3)),o(this,"scrollVal",void 0),o(this,"rect",void 0),this.DOM.el=t,this.DOM.deco=this.DOM.el.querySelector(".grid__item-img-decox"),this.calculateSizePosition(),this.initEvents()}var t,n,s;return t=e,n=[{key:"calculateSizePosition",value:function(){this.scrollVal={x:window.scrollX,y:window.scrollY},this.rect=this.DOM.el.getBoundingClientRect()}},{key:"initEvents",value:function(){var e=this;window.addEventListener("resize",(function(){return e.calculateSizePosition()})),this.DOM.el.addEventListener("mousemove",(function(){e.randomString=(0,i.getRandomString)(2e3)})),this.DOM.el.addEventListener("mouseenter",(function(){gsap.to(e.DOM.deco,{duration:.5,ease:"power3",opacity:1}),e.loopRender(!0)})),this.DOM.el.addEventListener("mouseleave",(function(){e.stopRendering(),gsap.to(e.DOM.deco,{duration:.5,ease:"power3",opacity:0})}))}},{key:"loopRender",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.requestId||(this.requestId=requestAnimationFrame((function(){return e.render(t)})))}},{key:"stopRendering",value:function(){this.requestId&&(window.cancelAnimationFrame(this.requestId),this.requestId=void 0)}},{key:"render",value:function(e){this.requestId=void 0;var t=this.scrollVal.x-window.scrollX,n=this.scrollVal.y-window.scrollY;for(var s in this.renderedStyles.x.current=l.x-(t+this.rect.left),this.renderedStyles.y.current=l.y-(n+this.rect.top),e&&(this.renderedStyles.x.previous=this.renderedStyles.x.current,this.renderedStyles.y.previous=this.renderedStyles.y.current),this.renderedStyles)this.renderedStyles[s].previous=(0,i.lerp)(this.renderedStyles[s].previous,this.renderedStyles[s].current,this.renderedStyles[s].amt);gsap.set(this.DOM.el,{"--x":this.renderedStyles.x.previous,"--y":this.renderedStyles.y.previous}),this.DOM.deco.innerHTML=this.randomString,this.loopRender()}}],n&&r(t.prototype,n),s&&r(t,s),Object.defineProperty(t,"prototype",{writable:!1}),e}()},"./js/main/code-anime/utils.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{getMousePos:()=>s,getRandomString:()=>r,lerp:()=>i});var i=function(e,t,n){return(1-n)*e+n*t},s=function(e){return{x:e.clientX,y:e.clientY}},r=function(e){for(var t="",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=0;i<e;i++)t+=n.charAt(Math.floor(62*Math.random()));return t}},"./node_modules/lozad/dist/lozad.min.js":function(e){e.exports=function(){"use strict";var e="undefined"!=typeof document&&document.documentMode,t={rootMargin:"0px",threshold:0,load:function(t){if("picture"===t.nodeName.toLowerCase()){var n=t.querySelector("img"),i=!1;null===n&&(n=document.createElement("img"),i=!0),e&&t.getAttribute("data-iesrc")&&(n.src=t.getAttribute("data-iesrc")),t.getAttribute("data-alt")&&(n.alt=t.getAttribute("data-alt")),i&&t.append(n)}if("video"===t.nodeName.toLowerCase()&&!t.getAttribute("data-src")&&t.children){for(var s=t.children,r=void 0,o=0;o<=s.length-1;o++)(r=s[o].getAttribute("data-src"))&&(s[o].src=r);t.load()}t.getAttribute("data-poster")&&(t.poster=t.getAttribute("data-poster")),t.getAttribute("data-src")&&(t.src=t.getAttribute("data-src")),t.getAttribute("data-srcset")&&t.setAttribute("srcset",t.getAttribute("data-srcset"));var a=",";if(t.getAttribute("data-background-delimiter")&&(a=t.getAttribute("data-background-delimiter")),t.getAttribute("data-background-image"))t.style.backgroundImage="url('"+t.getAttribute("data-background-image").split(a).join("'),url('")+"')";else if(t.getAttribute("data-background-image-set")){var l=t.getAttribute("data-background-image-set").split(a),c=l[0].substr(0,l[0].indexOf(" "))||l[0];c=-1===c.indexOf("url(")?"url("+c+")":c,1===l.length?t.style.backgroundImage=c:t.setAttribute("style",(t.getAttribute("style")||"")+"background-image: "+c+"; background-image: -webkit-image-set("+l+"); background-image: image-set("+l+")")}t.getAttribute("data-toggle-class")&&t.classList.toggle(t.getAttribute("data-toggle-class"))},loaded:function(){}};function n(e){e.setAttribute("data-loaded",!0)}var i=function(e){return"true"===e.getAttribute("data-loaded")},s=function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:document;return e instanceof Element?[e]:e instanceof NodeList?e:t.querySelectorAll(e)};return function(){var e,r,o=0<arguments.length&&void 0!==arguments[0]?arguments[0]:".lozad",a=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},l=Object.assign({},t,a),c=l.root,h=l.rootMargin,u=l.threshold,d=l.load,p=l.loaded,f=void 0;"undefined"!=typeof window&&window.IntersectionObserver&&(f=new IntersectionObserver((e=d,r=p,function(t,s){t.forEach((function(t){(0<t.intersectionRatio||t.isIntersecting)&&(s.unobserve(t.target),i(t.target)||(e(t.target),n(t.target),r(t.target)))}))}),{root:c,rootMargin:h,threshold:u}));for(var m,_=s(o,c),g=0;g<_.length;g++)(m=_[g]).getAttribute("data-placeholder-background")&&(m.style.background=m.getAttribute("data-placeholder-background"));return{observe:function(){for(var e=s(o,c),t=0;t<e.length;t++)i(e[t])||(f?f.observe(e[t]):(d(e[t]),n(e[t]),p(e[t])))},triggerLoad:function(e){i(e)||(d(e),n(e),p(e))},observer:f}}}()},"./node_modules/mouse-follower/dist/index.module.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>i});var i=function(){function e(t){void 0===t&&(t={}),this.options=Object.assign({},{el:null,container:document.body,className:"mf-cursor",innerClassName:"mf-cursor-inner",textClassName:"mf-cursor-text",mediaClassName:"mf-cursor-media",mediaBoxClassName:"mf-cursor-media-box",iconSvgClassName:"mf-svgsprite",iconSvgNamePrefix:"-",iconSvgSrc:"",dataAttr:"cursor",hiddenState:"-hidden",textState:"-text",iconState:"-icon",activeState:"-active",mediaState:"-media",stateDetection:{"-pointer":"a,button"},visible:!0,visibleOnState:!1,speed:.55,ease:"expo.out",overwrite:!0,skewing:0,skewingText:2,skewingIcon:2,skewingMedia:2,skewingDelta:.001,skewingDeltaMax:.15,stickDelta:.15,showTimeout:0,hideOnLeave:!0,hideTimeout:300,hideMediaTimeout:300,initialPos:[-window.innerWidth,-window.innerHeight]},t),this.options.visible&&null==t.stateDetection&&(this.options.stateDetection["-hidden"]="iframe"),this.gsap=e.gsap||window.gsap,this.el="string"==typeof this.options.el?document.querySelector(this.options.el):this.options.el,this.container="string"==typeof this.options.container?document.querySelector(this.options.container):this.options.container,this.skewing=this.options.skewing,this.pos={x:this.options.initialPos[0],y:this.options.initialPos[1]},this.vel={x:0,y:0},this.event={},this.events=[],this.init()}e.registerGSAP=function(t){e.gsap=t};var t=e.prototype;return t.init=function(){this.el||this.create(),this.createSetter(),this.bind(),this.render(!0),this.ticker=this.render.bind(this,!1),this.gsap.ticker.add(this.ticker)},t.create=function(){this.el=document.createElement("div"),this.el.className=this.options.className,this.el.classList.add(this.options.hiddenState),this.inner=document.createElement("div"),this.inner.className=this.options.innerClassName,this.text=document.createElement("div"),this.text.className=this.options.textClassName,this.media=document.createElement("div"),this.media.className=this.options.mediaClassName,this.mediaBox=document.createElement("div"),this.mediaBox.className=this.options.mediaBoxClassName,this.media.appendChild(this.mediaBox),this.inner.appendChild(this.media),this.inner.appendChild(this.text),this.el.appendChild(this.inner),this.container.appendChild(this.el)},t.createSetter=function(){this.setter={x:this.gsap.quickSetter(this.el,"x","px"),y:this.gsap.quickSetter(this.el,"y","px"),rotation:this.gsap.quickSetter(this.el,"rotation","deg"),scaleX:this.gsap.quickSetter(this.el,"scaleX"),scaleY:this.gsap.quickSetter(this.el,"scaleY"),wc:this.gsap.quickSetter(this.el,"willChange"),inner:{rotation:this.gsap.quickSetter(this.inner,"rotation","deg")}}},t.bind=function(){var e=this;this.event.mouseleave=function(){return e.hide()},this.event.mouseenter=function(){return e.show()},this.event.mousedown=function(){return e.addState(e.options.activeState)},this.event.mouseup=function(){return e.removeState(e.options.activeState)},this.event.mousemoveOnce=function(){return e.show()},this.event.mousemove=function(t){e.gsap.to(e.pos,{x:e.stick?e.stick.x-(e.stick.x-t.clientX)*e.options.stickDelta:t.clientX,y:e.stick?e.stick.y-(e.stick.y-t.clientY)*e.options.stickDelta:t.clientY,overwrite:e.options.overwrite,ease:e.options.ease,duration:e.visible?e.options.speed:0,onUpdate:function(){return e.vel={x:t.clientX-e.pos.x,y:t.clientY-e.pos.y}}})},this.event.mouseover=function(t){for(var n=t.target;n&&n!==e.container&&(!t.relatedTarget||!n.contains(t.relatedTarget));n=n.parentNode){for(var i in e.options.stateDetection)n.matches(e.options.stateDetection[i])&&e.addState(i);if(e.options.dataAttr){var s=e.getFromDataset(n);s.state&&e.addState(s.state),s.text&&e.setText(s.text),s.icon&&e.setIcon(s.icon),s.img&&e.setImg(s.img),s.video&&e.setVideo(s.video),void 0!==s.show&&e.show(),void 0!==s.stick&&e.setStick(s.stick||n)}}},this.event.mouseout=function(t){for(var n=t.target;n&&n!==e.container&&(!t.relatedTarget||!n.contains(t.relatedTarget));n=n.parentNode){for(var i in e.options.stateDetection)n.matches(e.options.stateDetection[i])&&e.removeState(i);if(e.options.dataAttr){var s=e.getFromDataset(n);s.state&&e.removeState(s.state),s.text&&e.removeText(),s.icon&&e.removeIcon(),s.img&&e.removeImg(),s.video&&e.removeVideo(),void 0!==s.show&&e.hide(),void 0!==s.stick&&e.removeStick()}}},this.options.hideOnLeave&&this.container.addEventListener("mouseleave",this.event.mouseleave,{passive:!0}),this.options.visible&&this.container.addEventListener("mouseenter",this.event.mouseenter,{passive:!0}),this.options.activeState&&(this.container.addEventListener("mousedown",this.event.mousedown,{passive:!0}),this.container.addEventListener("mouseup",this.event.mouseup,{passive:!0})),this.container.addEventListener("mousemove",this.event.mousemove,{passive:!0}),this.options.visible&&this.container.addEventListener("mousemove",this.event.mousemoveOnce,{passive:!0,once:!0}),(this.options.stateDetection||this.options.dataAttr)&&(this.container.addEventListener("mouseover",this.event.mouseover,{passive:!0}),this.container.addEventListener("mouseout",this.event.mouseout,{passive:!0}))},t.render=function(e){if(!0===e||0!==this.vel.y&&0!==this.vel.x){if(this.trigger("render"),this.setter.wc("transform"),this.setter.x(this.pos.x),this.setter.y(this.pos.y),this.skewing){var t=Math.sqrt(Math.pow(this.vel.x,2)+Math.pow(this.vel.y,2)),n=Math.min(t*this.options.skewingDelta,this.options.skewingDeltaMax)*this.skewing,i=180*Math.atan2(this.vel.y,this.vel.x)/Math.PI;this.setter.rotation(i),this.setter.scaleX(1+n),this.setter.scaleY(1-n),this.setter.inner.rotation(-i)}}else this.setter.wc("auto")},t.show=function(){var e=this;this.trigger("show"),clearInterval(this.visibleInt),this.visibleInt=setTimeout((function(){e.el.classList.remove(e.options.hiddenState),e.visible=!0,e.render(!0)}),this.options.showTimeout)},t.hide=function(){var e=this;this.trigger("hide"),clearInterval(this.visibleInt),this.el.classList.add(this.options.hiddenState),this.visibleInt=setTimeout((function(){return e.visible=!1}),this.options.hideTimeout)},t.toggle=function(e){!0===e||!1!==e&&!this.visible?this.show():this.hide()},t.addState=function(e){var t;if(this.trigger("addState",e),e===this.options.hiddenState)return this.hide();(t=this.el.classList).add.apply(t,e.split(" ")),this.options.visibleOnState&&this.show()},t.removeState=function(e){var t;if(this.trigger("removeState",e),e===this.options.hiddenState)return this.show();(t=this.el.classList).remove.apply(t,e.split(" ")),this.options.visibleOnState&&this.el.className===this.options.className&&this.hide()},t.toggleState=function(e,t){!0===t||!1!==t&&!this.el.classList.contains(e)?this.addState(e):this.removeState(e)},t.setSkewing=function(e){this.gsap.to(this,{skewing:e})},t.removeSkewing=function(){this.gsap.to(this,{skewing:this.options.skewing})},t.setStick=function(e){var t=("string"==typeof e?document.querySelector(e):e).getBoundingClientRect();this.stick={y:t.top+t.height/2,x:t.left+t.width/2}},t.removeStick=function(){this.stick=!1},t.setText=function(e){this.text.innerHTML=e,this.addState(this.options.textState),this.setSkewing(this.options.skewingText)},t.removeText=function(){this.removeState(this.options.textState),this.removeSkewing()},t.setIcon=function(e,t){void 0===t&&(t=""),this.text.innerHTML="<svg class='"+this.options.iconSvgClassName+" "+this.options.iconSvgNamePrefix+e+"' style='"+t+"'><use xlink:href='"+this.options.iconSvgSrc+"#"+e+"'></use></svg>",this.addState(this.options.iconState),this.setSkewing(this.options.skewingIcon)},t.removeIcon=function(){this.removeState(this.options.iconState),this.removeSkewing()},t.setMedia=function(e){var t=this;clearTimeout(this.mediaInt),e&&(this.mediaBox.innerHTML="",this.mediaBox.appendChild(e)),this.mediaInt=setTimeout((function(){return t.addState(t.options.mediaState)}),20),this.setSkewing(this.options.skewingMedia)},t.removeMedia=function(){var e=this;clearTimeout(this.mediaInt),this.removeState(this.options.mediaState),this.mediaInt=setTimeout((function(){return e.mediaBox.innerHTML=""}),this.options.hideMediaTimeout),this.removeSkewing()},t.setImg=function(e){this.mediaImg||(this.mediaImg=new Image),this.mediaImg.src!==e&&(this.mediaImg.src=e),this.setMedia(this.mediaImg)},t.removeImg=function(){this.removeMedia()},t.setVideo=function(e){this.mediaVideo||(this.mediaVideo=document.createElement("video"),this.mediaVideo.muted=!0,this.mediaVideo.loop=!0,this.mediaVideo.autoplay=!0),this.mediaVideo.src!==e&&(this.mediaVideo.src=e,this.mediaVideo.load()),this.mediaVideo.play(),this.setMedia(this.mediaVideo)},t.removeVideo=function(){this.mediaVideo&&this.mediaVideo.readyState>2&&this.mediaVideo.pause(),this.removeMedia()},t.on=function(e,t){this.events[e]instanceof Array||this.off(e),this.events[e].push(t)},t.off=function(e,t){this.events[e]=t?this.events[e].filter((function(e){return e!==t})):[]},t.trigger=function(e){var t=arguments,n=this;this.events[e]&&this.events[e].forEach((function(e){return e.call.apply(e,[n,n].concat([].slice.call(t,1)))}))},t.getFromDataset=function(e){var t=e.dataset;return{state:t[this.options.dataAttr],show:t[this.options.dataAttr+"Show"],text:t[this.options.dataAttr+"Text"],icon:t[this.options.dataAttr+"Icon"],img:t[this.options.dataAttr+"Img"],video:t[this.options.dataAttr+"Video"],stick:t[this.options.dataAttr+"Stick"]}},t.destroy=function(){this.trigger("destroy"),this.gsap.ticker.remove(this.ticker),this.container.removeEventListener("mouseleave",this.event.mouseleave),this.container.removeEventListener("mouseenter",this.event.mouseenter),this.container.removeEventListener("mousedown",this.event.mousedown),this.container.removeEventListener("mouseup",this.event.mouseup),this.container.removeEventListener("mousemove",this.event.mousemove),this.container.removeEventListener("mousemove",this.event.mousemoveOnce),this.container.removeEventListener("mouseover",this.event.mouseover),this.container.removeEventListener("mouseout",this.event.mouseout),this.el&&(this.container.removeChild(this.el),this.el=null,this.mediaImg=null,this.mediaVideo=null)},e}()},"./node_modules/@firebase/app/dist/esm/index.esm2017.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{FirebaseError:()=>r.FirebaseError,SDK_VERSION:()=>E,_DEFAULT_ENTRY_NAME:()=>u,_addComponent:()=>m,_addOrOverwriteComponent:()=>_,_apps:()=>p,_clearComponents:()=>w,_components:()=>f,_getProvider:()=>v,_registerComponent:()=>g,_removeServiceInstance:()=>y,deleteApp:()=>x,getApp:()=>I,getApps:()=>k,initializeApp:()=>T,onLog:()=>P,registerVersion:()=>N,setLogLevel:()=>D});var i=n("./node_modules/@firebase/component/dist/esm/index.esm2017.js"),s=n("./node_modules/@firebase/logger/dist/esm/index.esm2017.js"),r=n("./node_modules/@firebase/util/dist/index.esm2017.js"),o=n("./node_modules/idb/build/index.js");class a{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null})).filter((e=>e)).join(" ")}}const l="@firebase/app",c="0.9.28",h=new s.Logger("@firebase/app"),u="[DEFAULT]",d={[l]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},p=new Map,f=new Map;function m(e,t){try{e.container.addComponent(t)}catch(n){h.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function _(e,t){e.container.addOrOverwriteComponent(t)}function g(e){const t=e.name;if(f.has(t))return h.debug(`There were multiple attempts to register component ${t}.`),!1;f.set(t,e);for(const t of p.values())m(t,e);return!0}function v(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function y(e,t,n=u){v(e,t).clearInstance(n)}function w(){f.clear()}const b={"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","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}."},C=new r.ErrorFactory("app","Firebase",b);class S{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new i.Component("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw C.create("app-deleted",{appName:this._name})}}const E="10.8.1";function T(e,t={}){let n=e;if("object"!=typeof t){t={name:t}}const s=Object.assign({name:u,automaticDataCollectionEnabled:!1},t),o=s.name;if("string"!=typeof o||!o)throw C.create("bad-app-name",{appName:String(o)});if(n||(n=(0,r.getDefaultAppConfig)()),!n)throw C.create("no-options");const a=p.get(o);if(a){if((0,r.deepEqual)(n,a.options)&&(0,r.deepEqual)(s,a.config))return a;throw C.create("duplicate-app",{appName:o})}const l=new i.ComponentContainer(o);for(const e of f.values())l.addComponent(e);const c=new S(n,s,l);return p.set(o,c),c}function I(e=u){const t=p.get(e);if(!t&&e===u&&(0,r.getDefaultAppConfig)())return T();if(!t)throw C.create("no-app",{appName:e});return t}function k(){return Array.from(p.values())}async function x(e){const t=e.name;p.has(t)&&(p.delete(t),await Promise.all(e.container.getProviders().map((e=>e.delete()))),e.isDeleted=!0)}function N(e,t,n){var s;let r=null!==(s=d[e])&&void 0!==s?s:e;n&&(r+=`-${n}`);const o=r.match(/\s|\//),a=t.match(/\s|\//);if(o||a){const e=[`Unable to register library "${r}" with version "${t}":`];return o&&e.push(`library name "${r}" contains illegal characters (whitespace or "/")`),o&&a&&e.push("and"),a&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void h.warn(e.join(" "))}g(new i.Component(`${r}-version`,(()=>({library:r,version:t})),"VERSION"))}function P(e,t){if(null!==e&&"function"!=typeof e)throw C.create("invalid-log-argument");(0,s.setUserLogHandler)(e,t)}function D(e){(0,s.setLogLevel)(e)}const R="firebase-heartbeat-database",A=1,L="firebase-heartbeat-store";let O=null;function M(){return O||(O=(0,o.openDB)(R,A,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(L)}catch(e){console.warn(e)}}}).catch((e=>{throw C.create("idb-open",{originalErrorMessage:e.message})}))),O}async function F(e,t){try{const n=(await M()).transaction(L,"readwrite"),i=n.objectStore(L);await i.put(t,q(e)),await n.done}catch(e){if(e instanceof r.FirebaseError)h.warn(e.message);else{const t=C.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});h.warn(t.message)}}}function q(e){return`${e.name}!${e.options.appId}`}class B{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new W(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){var e,t;const n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=j();if((null!=(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||(this._heartbeatsCache=await this._heartbeatsCachePromise,null!=(null===(t=this._heartbeatsCache)||void 0===t?void 0:t.heartbeats)))&&this._heartbeatsCache.lastSentHeartbeatDate!==i&&!this._heartbeatsCache.heartbeats.some((e=>e.date===i)))return this._heartbeatsCache.heartbeats.push({date:i,agent:n}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}async getHeartbeatsHeader(){var e;if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";const t=j(),{heartbeatsToSend:n,unsentEntries:i}=function(e,t=1024){const n=[];let i=e.slice();for(const s of e){const e=n.find((e=>e.agent===s.agent));if(e){if(e.dates.push(s.date),U(n)>t){e.dates.pop();break}}else if(n.push({agent:s.agent,dates:[s.date]}),U(n)>t){n.pop();break}i=i.slice(1)}return{heartbeatsToSend:n,unsentEntries:i}}(this._heartbeatsCache.heartbeats),s=(0,r.base64urlEncodeWithoutPadding)(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),s}}function j(){return(new Date).toISOString().substring(0,10)}class W{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!(0,r.isIndexedDBAvailable)()&&(0,r.validateIndexedDBOpenable)().then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=(await M()).transaction(L),n=await t.objectStore(L).get(q(e));return await t.done,n}catch(e){if(e instanceof r.FirebaseError)h.warn(e.message);else{const t=C.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});h.warn(t.message)}}}(this.app);return(null==e?void 0:e.heartbeats)?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return F(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return F(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function U(e){return(0,r.base64urlEncodeWithoutPadding)(JSON.stringify({version:2,heartbeats:e})).length}var z;z="",g(new i.Component("platform-logger",(e=>new a(e)),"PRIVATE")),g(new i.Component("heartbeat",(e=>new B(e)),"PRIVATE")),N(l,c,z),N(l,c,"esm2017"),N("fire-js","")},"./node_modules/@firebase/component/dist/esm/index.esm2017.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{Component:()=>s,ComponentContainer:()=>a,Provider:()=>o});var i=n("./node_modules/@firebase/util/dist/index.esm2017.js");class s{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const r="[DEFAULT]";class o{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new i.Deferred;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),i=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(i)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(i)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:r})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=r){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(e=r){return this.instances.has(e)}getOptions(e=r){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const i=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries()){n===this.normalizeInstanceIdentifier(e)&&t.resolve(i)}return i}onInit(e,t){var n;const i=this.normalizeInstanceIdentifier(t),s=null!==(n=this.onInitCallbacks.get(i))&&void 0!==n?n:new Set;s.add(e),this.onInitCallbacks.set(i,s);const r=this.instances.get(i);return r&&e(r,i),()=>{s.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const i of n)try{i(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(i=e,i===r?void 0:i),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var i;return n||null}normalizeInstanceIdentifier(e=r){return this.component?this.component.multipleInstances?e:r:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class a{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new o(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}},"./node_modules/@firebase/logger/dist/esm/index.esm2017.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{LogLevel:()=>s,Logger:()=>c,setLogLevel:()=>h,setUserLogHandler:()=>u});const i=[];var s;!function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(s||(s={}));const r={debug:s.DEBUG,verbose:s.VERBOSE,info:s.INFO,warn:s.WARN,error:s.ERROR,silent:s.SILENT},o=s.INFO,a={[s.DEBUG]:"log",[s.VERBOSE]:"log",[s.INFO]:"info",[s.WARN]:"warn",[s.ERROR]:"error"},l=(e,t,...n)=>{if(t<e.logLevel)return;const i=(new Date).toISOString(),s=a[t];if(!s)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[s](`[${i}] ${e.name}:`,...n)};class c{constructor(e){this.name=e,this._logLevel=o,this._logHandler=l,this._userLogHandler=null,i.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in s))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?r[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,s.DEBUG,...e),this._logHandler(this,s.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,s.VERBOSE,...e),this._logHandler(this,s.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,s.INFO,...e),this._logHandler(this,s.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,s.WARN,...e),this._logHandler(this,s.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,s.ERROR,...e),this._logHandler(this,s.ERROR,...e)}}function h(e){i.forEach((t=>{t.setLogLevel(e)}))}function u(e,t){for(const n of i){let i=null;t&&t.level&&(i=r[t.level]),n.userLogHandler=null===e?null:(t,n,...r)=>{const o=r.map((e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}})).filter((e=>e)).join(" ");n>=(null!=i?i:t.logLevel)&&e({level:s[n].toLowerCase(),message:o,args:r,type:t.name})}}}},"./node_modules/@studio-freight/lenis/dist/lenis.mjs":(e,t,n)=>{"use strict";function i(e,t,n){return Math.max(e,Math.min(t,n))}n.r(t),n.d(t,{default:()=>l});class s{advance(e){if(!this.isRunning)return;let t=!1;if(this.lerp)this.value=(n=this.value,s=this.to,r=60*this.lerp,o=e,function(e,t,n){return(1-n)*e+n*t}(n,s,1-Math.exp(-r*o))),Math.round(this.value)===this.to&&(this.value=this.to,t=!0);else{this.currentTime+=e;const n=i(0,this.currentTime/this.duration,1);t=n>=1;const s=t?1:this.easing(n);this.value=this.from+(this.to-this.from)*s}var n,s,r,o;this.onUpdate?.(this.value,t),t&&this.stop()}stop(){this.isRunning=!1}fromTo(e,t,{lerp:n=.1,duration:i=1,easing:s=(e=>e),onStart:r,onUpdate:o}){this.from=this.value=e,this.to=t,this.lerp=n,this.duration=i,this.easing=s,this.currentTime=0,this.isRunning=!0,r?.(),this.onUpdate=o}}class r{constructor({wrapper:e,content:t,autoResize:n=!0,debounce:i=250}={}){this.wrapper=e,this.content=t,n&&(this.debouncedResize=function(e,t){let n;return function(){let i=arguments,s=this;clearTimeout(n),n=setTimeout((function(){e.apply(s,i)}),t)}}(this.resize,i),this.wrapper===window?window.addEventListener("resize",this.debouncedResize,!1):(this.wrapperResizeObserver=new ResizeObserver(this.debouncedResize),this.wrapperResizeObserver.observe(this.wrapper)),this.contentResizeObserver=new ResizeObserver(this.debouncedResize),this.contentResizeObserver.observe(this.content)),this.resize()}destroy(){this.wrapperResizeObserver?.disconnect(),this.contentResizeObserver?.disconnect(),window.removeEventListener("resize",this.debouncedResize,!1)}resize=()=>{this.onWrapperResize(),this.onContentResize()};onWrapperResize=()=>{this.wrapper===window?(this.width=window.innerWidth,this.height=window.innerHeight):(this.width=this.wrapper.clientWidth,this.height=this.wrapper.clientHeight)};onContentResize=()=>{this.wrapper===window?(this.scrollHeight=this.content.scrollHeight,this.scrollWidth=this.content.scrollWidth):(this.scrollHeight=this.wrapper.scrollHeight,this.scrollWidth=this.wrapper.scrollWidth)};get limit(){return{x:this.scrollWidth-this.width,y:this.scrollHeight-this.height}}}class o{constructor(){this.events={}}emit(e,...t){let n=this.events[e]||[];for(let e=0,i=n.length;e<i;e++)n[e](...t)}on(e,t){return this.events[e]?.push(t)||(this.events[e]=[t]),()=>{this.events[e]=this.events[e]?.filter((e=>t!==e))}}off(e,t){this.events[e]=this.events[e]?.filter((e=>t!==e))}destroy(){this.events={}}}class a{constructor(e,{wheelMultiplier:t=1,touchMultiplier:n=2,normalizeWheel:i=!1}){this.element=e,this.wheelMultiplier=t,this.touchMultiplier=n,this.normalizeWheel=i,this.touchStart={x:null,y:null},this.emitter=new o,this.element.addEventListener("wheel",this.onWheel,{passive:!1}),this.element.addEventListener("touchstart",this.onTouchStart,{passive:!1}),this.element.addEventListener("touchmove",this.onTouchMove,{passive:!1}),this.element.addEventListener("touchend",this.onTouchEnd,{passive:!1})}on(e,t){return this.emitter.on(e,t)}destroy(){this.emitter.destroy(),this.element.removeEventListener("wheel",this.onWheel,{passive:!1}),this.element.removeEventListener("touchstart",this.onTouchStart,{passive:!1}),this.element.removeEventListener("touchmove",this.onTouchMove,{passive:!1}),this.element.removeEventListener("touchend",this.onTouchEnd,{passive:!1})}onTouchStart=e=>{const{clientX:t,clientY:n}=e.targetTouches?e.targetTouches[0]:e;this.touchStart.x=t,this.touchStart.y=n,this.lastDelta={x:0,y:0},this.emitter.emit("scroll",{deltaX:0,deltaY:0,event:e})};onTouchMove=e=>{const{clientX:t,clientY:n}=e.targetTouches?e.targetTouches[0]:e,i=-(t-this.touchStart.x)*this.touchMultiplier,s=-(n-this.touchStart.y)*this.touchMultiplier;this.touchStart.x=t,this.touchStart.y=n,this.lastDelta={x:i,y:s},this.emitter.emit("scroll",{deltaX:i,deltaY:s,event:e})};onTouchEnd=e=>{this.emitter.emit("scroll",{deltaX:this.lastDelta.x,deltaY:this.lastDelta.y,event:e})};onWheel=e=>{let{deltaX:t,deltaY:n}=e;this.normalizeWheel&&(t=i(-100,t,100),n=i(-100,n,100)),t*=this.wheelMultiplier,n*=this.wheelMultiplier,this.emitter.emit("scroll",{deltaX:t,deltaY:n,event:e})}}class l{constructor({wrapper:e=window,content:t=document.documentElement,wheelEventsTarget:n=e,eventsTarget:i=n,smoothWheel:l=!0,syncTouch:c=!1,syncTouchLerp:h=.075,touchInertiaMultiplier:u=35,duration:d,easing:p=(e=>Math.min(1,1.001-Math.pow(2,-10*e))),lerp:f=!d&&.1,infinite:m=!1,orientation:_="vertical",gestureOrientation:g="vertical",touchMultiplier:v=1,wheelMultiplier:y=1,normalizeWheel:w=!1,autoResize:b=!0,__experimental__naiveDimensions:C=!1}={}){this.__isSmooth=!1,this.__isScrolling=!1,this.__isStopped=!1,this.__isLocked=!1,this.onVirtualScroll=({deltaX:e,deltaY:t,event:n})=>{if(n.ctrlKey)return;const i=n.type.includes("touch"),s=n.type.includes("wheel");if(this.options.syncTouch&&i&&"touchstart"===n.type)return void this.reset();const r=0===e&&0===t,o="vertical"===this.options.gestureOrientation&&0===t||"horizontal"===this.options.gestureOrientation&&0===e;if(r||o)return;let a=n.composedPath();if(a=a.slice(0,a.indexOf(this.rootElement)),a.find((e=>{var t,n,r,o,a;return(null===(t=e.hasAttribute)||void 0===t?void 0:t.call(e,"data-lenis-prevent"))||i&&(null===(n=e.hasAttribute)||void 0===n?void 0:n.call(e,"data-lenis-prevent-touch"))||s&&(null===(r=e.hasAttribute)||void 0===r?void 0:r.call(e,"data-lenis-prevent-wheel"))||(null===(o=e.classList)||void 0===o?void 0:o.contains("lenis"))&&!(null===(a=e.classList)||void 0===a?void 0:a.contains("lenis-stopped"))})))return;if(this.isStopped||this.isLocked)return void n.preventDefault();if(this.isSmooth=this.options.syncTouch&&i||this.options.smoothWheel&&s,!this.isSmooth)return this.isScrolling=!1,void this.animate.stop();n.preventDefault();let l=t;"both"===this.options.gestureOrientation?l=Math.abs(t)>Math.abs(e)?t:e:"horizontal"===this.options.gestureOrientation&&(l=e);const c=i&&this.options.syncTouch,h=i&&"touchend"===n.type&&Math.abs(l)>5;h&&(l=this.velocity*this.options.touchInertiaMultiplier),this.scrollTo(this.targetScroll+l,Object.assign({programmatic:!1},c?{lerp:h?this.options.syncTouchLerp:1}:{lerp:this.options.lerp,duration:this.options.duration,easing:this.options.easing}))},this.onNativeScroll=()=>{if(!this.__preventNextScrollEvent&&!this.isScrolling){const e=this.animatedScroll;this.animatedScroll=this.targetScroll=this.actualScroll,this.velocity=0,this.direction=Math.sign(this.animatedScroll-e),this.emit()}},window.lenisVersion="1.0.39",e!==document.documentElement&&e!==document.body||(e=window),this.options={wrapper:e,content:t,wheelEventsTarget:n,eventsTarget:i,smoothWheel:l,syncTouch:c,syncTouchLerp:h,touchInertiaMultiplier:u,duration:d,easing:p,lerp:f,infinite:m,gestureOrientation:g,orientation:_,touchMultiplier:v,wheelMultiplier:y,normalizeWheel:w,autoResize:b,__experimental__naiveDimensions:C},this.animate=new s,this.emitter=new o,this.dimensions=new r({wrapper:e,content:t,autoResize:b}),this.toggleClassName("lenis",!0),this.velocity=0,this.isLocked=!1,this.isStopped=!1,this.isSmooth=c||l,this.isScrolling=!1,this.targetScroll=this.animatedScroll=this.actualScroll,this.options.wrapper.addEventListener("scroll",this.onNativeScroll,{passive:!1}),this.virtualScroll=new a(i,{touchMultiplier:v,wheelMultiplier:y,normalizeWheel:w}),this.virtualScroll.on("scroll",this.onVirtualScroll)}destroy(){this.emitter.destroy(),this.options.wrapper.removeEventListener("scroll",this.onNativeScroll,{passive:!1}),this.virtualScroll.destroy(),this.dimensions.destroy(),this.toggleClassName("lenis",!1),this.toggleClassName("lenis-smooth",!1),this.toggleClassName("lenis-scrolling",!1),this.toggleClassName("lenis-stopped",!1),this.toggleClassName("lenis-locked",!1)}on(e,t){return this.emitter.on(e,t)}off(e,t){return this.emitter.off(e,t)}setScroll(e){this.isHorizontal?this.rootElement.scrollLeft=e:this.rootElement.scrollTop=e}resize(){this.dimensions.resize()}emit(){this.emitter.emit("scroll",this)}reset(){this.isLocked=!1,this.isScrolling=!1,this.animatedScroll=this.targetScroll=this.actualScroll,this.velocity=0,this.animate.stop()}start(){this.isStopped&&(this.isStopped=!1,this.reset())}stop(){this.isStopped||(this.isStopped=!0,this.animate.stop(),this.reset())}raf(e){const t=e-(this.time||e);this.time=e,this.animate.advance(.001*t)}scrollTo(e,{offset:t=0,immediate:n=!1,lock:s=!1,duration:r=this.options.duration,easing:o=this.options.easing,lerp:a=!r&&this.options.lerp,onComplete:l,force:c=!1,programmatic:h=!0}={}){if(!this.isStopped&&!this.isLocked||c){if(["top","left","start"].includes(e))e=0;else if(["bottom","right","end"].includes(e))e=this.limit;else{let n;if("string"==typeof e?n=document.querySelector(e):(null==e?void 0:e.nodeType)&&(n=e),n){if(this.options.wrapper!==window){const e=this.options.wrapper.getBoundingClientRect();t-=this.isHorizontal?e.left:e.top}const i=n.getBoundingClientRect();e=(this.isHorizontal?i.left:i.top)+this.animatedScroll}}if("number"==typeof e){if(e+=t,e=Math.round(e),this.options.infinite?h&&(this.targetScroll=this.animatedScroll=this.scroll):e=i(0,e,this.limit),n)return this.animatedScroll=this.targetScroll=e,this.setScroll(this.scroll),this.reset(),void(null==l||l(this));if(!h){if(e===this.targetScroll)return;this.targetScroll=e}this.animate.fromTo(this.animatedScroll,e,{duration:r,easing:o,lerp:a,onStart:()=>{s&&(this.isLocked=!0),this.isScrolling=!0},onUpdate:(e,t)=>{this.isScrolling=!0,this.velocity=e-this.animatedScroll,this.direction=Math.sign(this.velocity),this.animatedScroll=e,this.setScroll(this.scroll),h&&(this.targetScroll=e),t||this.emit(),t&&(this.reset(),this.emit(),null==l||l(this),this.__preventNextScrollEvent=!0,requestAnimationFrame((()=>{delete this.__preventNextScrollEvent})))}})}}}get rootElement(){return this.options.wrapper===window?document.documentElement:this.options.wrapper}get limit(){return this.options.__experimental__naiveDimensions?this.isHorizontal?this.rootElement.scrollWidth-this.rootElement.clientWidth:this.rootElement.scrollHeight-this.rootElement.clientHeight:this.dimensions.limit[this.isHorizontal?"x":"y"]}get isHorizontal(){return"horizontal"===this.options.orientation}get actualScroll(){return this.isHorizontal?this.rootElement.scrollLeft:this.rootElement.scrollTop}get scroll(){return this.options.infinite?(this.animatedScroll%(e=this.limit)+e)%e:this.animatedScroll;var e}get progress(){return 0===this.limit?1:this.scroll/this.limit}get isSmooth(){return this.__isSmooth}set isSmooth(e){this.__isSmooth!==e&&(this.__isSmooth=e,this.toggleClassName("lenis-smooth",e))}get isScrolling(){return this.__isScrolling}set isScrolling(e){this.__isScrolling!==e&&(this.__isScrolling=e,this.toggleClassName("lenis-scrolling",e))}get isStopped(){return this.__isStopped}set isStopped(e){this.__isStopped!==e&&(this.__isStopped=e,this.toggleClassName("lenis-stopped",e))}get isLocked(){return this.__isLocked}set isLocked(e){this.__isLocked!==e&&(this.__isLocked=e,this.toggleClassName("lenis-locked",e))}get className(){let e="lenis";return this.isStopped&&(e+=" lenis-stopped"),this.isLocked&&(e+=" lenis-locked"),this.isScrolling&&(e+=" lenis-scrolling"),this.isSmooth&&(e+=" lenis-smooth"),e}toggleClassName(e,t){this.rootElement.classList.toggle(e,t),this.emitter.emit("className change",this)}}},"./node_modules/firebase/app/dist/esm/index.esm.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{FirebaseError:()=>i.FirebaseError,SDK_VERSION:()=>i.SDK_VERSION,_DEFAULT_ENTRY_NAME:()=>i._DEFAULT_ENTRY_NAME,_addComponent:()=>i._addComponent,_addOrOverwriteComponent:()=>i._addOrOverwriteComponent,_apps:()=>i._apps,_clearComponents:()=>i._clearComponents,_components:()=>i._components,_getProvider:()=>i._getProvider,_registerComponent:()=>i._registerComponent,_removeServiceInstance:()=>i._removeServiceInstance,deleteApp:()=>i.deleteApp,getApp:()=>i.getApp,getApps:()=>i.getApps,initializeApp:()=>i.initializeApp,onLog:()=>i.onLog,registerVersion:()=>i.registerVersion,setLogLevel:()=>i.setLogLevel});var i=n("./node_modules/@firebase/app/dist/esm/index.esm2017.js");(0,i.registerVersion)("firebase","10.8.1","app")},"./node_modules/firebase/database/dist/esm/index.esm.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{DataSnapshot:()=>i.DataSnapshot,Database:()=>i.Database,OnDisconnect:()=>i.OnDisconnect,QueryConstraint:()=>i.QueryConstraint,TransactionResult:()=>i.TransactionResult,_QueryImpl:()=>i._QueryImpl,_QueryParams:()=>i._QueryParams,_ReferenceImpl:()=>i._ReferenceImpl,_TEST_ACCESS_forceRestClient:()=>i._TEST_ACCESS_forceRestClient,_TEST_ACCESS_hijackHash:()=>i._TEST_ACCESS_hijackHash,_initStandalone:()=>i._initStandalone,_repoManagerDatabaseFromApp:()=>i._repoManagerDatabaseFromApp,_setSDKVersion:()=>i._setSDKVersion,_validatePathString:()=>i._validatePathString,_validateWritablePath:()=>i._validateWritablePath,child:()=>i.child,connectDatabaseEmulator:()=>i.connectDatabaseEmulator,enableLogging:()=>i.enableLogging,endAt:()=>i.endAt,endBefore:()=>i.endBefore,equalTo:()=>i.equalTo,forceLongPolling:()=>i.forceLongPolling,forceWebSockets:()=>i.forceWebSockets,get:()=>i.get,getDatabase:()=>i.getDatabase,goOffline:()=>i.goOffline,goOnline:()=>i.goOnline,increment:()=>i.increment,limitToFirst:()=>i.limitToFirst,limitToLast:()=>i.limitToLast,off:()=>i.off,onChildAdded:()=>i.onChildAdded,onChildChanged:()=>i.onChildChanged,onChildMoved:()=>i.onChildMoved,onChildRemoved:()=>i.onChildRemoved,onDisconnect:()=>i.onDisconnect,onValue:()=>i.onValue,orderByChild:()=>i.orderByChild,orderByKey:()=>i.orderByKey,orderByPriority:()=>i.orderByPriority,orderByValue:()=>i.orderByValue,push:()=>i.push,query:()=>i.query,ref:()=>i.ref,refFromURL:()=>i.refFromURL,remove:()=>i.remove,runTransaction:()=>i.runTransaction,serverTimestamp:()=>i.serverTimestamp,set:()=>i.set,setPriority:()=>i.setPriority,setWithPriority:()=>i.setWithPriority,startAfter:()=>i.startAfter,startAt:()=>i.startAt,update:()=>i.update});var i=n("./node_modules/@firebase/database/dist/index.esm2017.js")},"./node_modules/idb/build/index.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{deleteDB:()=>r,openDB:()=>s,unwrap:()=>i.u,wrap:()=>i.w});var i=n("./node_modules/idb/build/wrap-idb-value.js");function s(e,t,{blocked:n,upgrade:s,blocking:r,terminated:o}={}){const a=indexedDB.open(e,t),l=(0,i.w)(a);return s&&a.addEventListener("upgradeneeded",(e=>{s((0,i.w)(a.result),e.oldVersion,e.newVersion,(0,i.w)(a.transaction),e)})),n&&a.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),l.then((e=>{o&&e.addEventListener("close",(()=>o())),r&&e.addEventListener("versionchange",(e=>r(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),l}function r(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),(0,i.w)(n).then((()=>{}))}const o=["get","getKey","getAll","getAllKeys","count"],a=["put","add","delete","clear"],l=new Map;function c(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(l.get(t))return l.get(t);const n=t.replace(/FromIndex$/,""),i=t!==n,s=a.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!s&&!o.includes(n))return;const r=async function(e,...t){const r=this.transaction(e,s?"readwrite":"readonly");let o=r.store;return i&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),s&&r.done]))[0]};return l.set(t,r),r}(0,i.r)((e=>({...e,get:(t,n,i)=>c(t,n)||e.get(t,n,i),has:(t,n)=>!!c(t,n)||e.has(t,n)})))},"./node_modules/idb/build/wrap-idb-value.js":(e,t,n)=>{"use strict";n.r(t),n.d(t,{a:()=>h,i:()=>i,r:()=>d,u:()=>_,w:()=>m});const i=(e,t)=>t.some((t=>e instanceof t));let s,r;const o=new WeakMap,a=new WeakMap,l=new WeakMap,c=new WeakMap,h=new WeakMap;let u={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return a.get(e);if("objectStoreNames"===t)return e.objectStoreNames||l.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return m(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function d(e){u=e(u)}function p(e){return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(r||(r=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(_(this),t),m(o.get(this))}:function(...t){return m(e.apply(_(this),t))}:function(t,...n){const i=e.call(_(this),t,...n);return l.set(i,t.sort?t.sort():[t]),m(i)}}function f(e){return"function"==typeof e?p(e):(e instanceof IDBTransaction&&function(e){if(a.has(e))return;const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",r),e.removeEventListener("abort",r)},s=()=>{t(),i()},r=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",s),e.addEventListener("error",r),e.addEventListener("abort",r)}));a.set(e,t)}(e),i(e,s||(s=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,u):e)}function m(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const i=()=>{e.removeEventListener("success",s),e.removeEventListener("error",r)},s=()=>{t(m(e.result)),i()},r=()=>{n(e.error),i()};e.addEventListener("success",s),e.addEventListener("error",r)}));return t.then((t=>{t instanceof IDBCursor&&o.set(t,e)})).catch((()=>{})),h.set(t,e),t}(e);if(c.has(e))return c.get(e);const t=f(e);return t!==e&&(c.set(e,t),h.set(t,e)),t}const _=e=>h.get(e)}},t={};function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}n.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};(()=>{"use strict";n.r(i);var e=n("./node_modules/mouse-follower/dist/index.module.js"),t=n("./node_modules/@studio-freight/lenis/dist/lenis.mjs"),s=n("./node_modules/firebase/app/dist/esm/index.esm.js"),r=n("./node_modules/firebase/database/dist/esm/index.esm.js"),o=n("./node_modules/lozad/dist/lozad.min.js"),a=n.n(o),l=n("./js/main/code-anime/item.js");function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}var h=function(e){return document.querySelector(e)},u=function(e){return document.querySelectorAll(e)};document.addEventListener("DOMContentLoaded",(function(){a()(".lozad",{rootMargin:"100px 0px",loaded:function(e){}}).observe()})),"serviceWorker"in navigator&&window.addEventListener("load",(function(){navigator.serviceWorker.register("hypercritical-worker.js").catch((function(e){return console.log("Error:",e)}))}));var d=h(".mid-moon"),p=h(".action--close");h(".action--menuUzi").addEventListener("click",(function(){d.classList.add("mid-moon--light"),d.classList.remove("mid-moon--dark")})),p.addEventListener("click",(function(){d.classList.add("mid-moon--dark"),d.classList.remove("mid-moon--light")})),new Promise((function(e,t){document.addEventListener("DOMContentLoaded",(function(){fetch("includes/config.json").then((function(e){return e.json()})).then((function(t){!function(e){var t=function(t){e.hasOwnProperty(t)&&u(t).forEach((function(n){n?n.href=e[t]:console.error("Elements matching selector ".concat(t," not found."))}))};for(var n in e)t(n)}(t),e()})).catch((function(e){console.error("Error loading config:",e),t(e)}))}))})).then((function(){console.log("%c Greetings from Hypercritical","color:white;background:#c389e1; font-size: 26px;font-family:sans-serif")})).catch((function(e){console.error("Failed to load configuration or assign links:",e)})),document.addEventListener("DOMContentLoaded",(function(){var e=h(".menuUzi__item-link"),t=e.querySelector(".contact-emoji"),n=gsap.timeline();e.addEventListener("mouseover",(function(){n.to(t,{duration:1,rotation:-360,repeat:-1,ease:"linear"})})),e.addEventListener("mouseout",(function(){n.kill()}))}));var f=new t.default({duration:3,easing:function(e){return Math.min(1,1.001-Math.pow(2,-10*e))},direction:"vertical",gestureDirection:"vertical",smooth:!0,smoothTouch:!1,touchMultiplier:2,infinite:!1,autoResize:!0});f.on("scroll",(function(e){})),requestAnimationFrame((function e(t){f.raf(t),requestAnimationFrame(e)})),gsap.registerPlugin(ScrollTrigger),gsap.registerPlugin(ScrollToPlugin),gsap.registerPlugin(SplitText);var m=h(".hero-largelogo");new SplitText(m,{type:"words",wordsClass:"hero-words"});u(".split-chars").forEach((function(e){new SplitText(e,{type:"chars",charsClass:"otherchars"})}));var _=u(".hero-words"),g=h(".below-line"),v=h(".hero-image"),y=h(".parallax-hero");document.addEventListener("DOMContentLoaded",(function(){gsap.timeline({defaults:{ease:"expo.out",delay:.5}}).set(y,{y:"-47.8vh"},"=-1").addLabel("start").fromTo(g,{width:0},{duration:1.75,width:"100%",stagger:.095},"start").fromTo(_,{y:"110%"},{delay:0,duration:2.3,y:"0",stagger:.17,ease:"expo.inOut"},"start+=0.28").fromTo(v,{width:0},{width:"100%",duration:1.5,ease:"expo.inOut",transformOrigin:"50% 50% 0"},"start+=0.7"),setTimeout((function(){u(".slide").forEach((function(e,t){var n=e.querySelector(".parallax-image");gsap.fromTo(n,{y:"-60vh"},{y:"60vh",scrollTrigger:{trigger:e,scrub:!0,start:"top bottom",end:"bottom top",markers:!1},ease:"none"})})),gsap.to(window,{duration:2,scrollTo:{y:"nav"},ease:"power2.inOut"})}),3e3)})),u("[line-trigger]").forEach((function(e){var t=e.getAttribute("line-trigger"),n=function(e){var t=gsap.timeline({defaults:{duration:3,ease:"power3.out"}});return t.fromTo(e,{scaleX:0,opacity:0,transformOrigin:"left left"},{scaleX:1,opacity:1}),t}(e);ScrollTrigger.create({trigger:t,start:"top 92%",animation:n,onEnter:function(){return n.play()},onLeaveBack:function(){return n.reverse({duration:6.5})}})})),document.addEventListener("DOMContentLoaded",(function(){var e=h("#toTop");function t(){(window.scrollY||document.documentElement.scrollTop)>1.2*window.innerHeight?e.style.display="block":e.style.display="none"}t(),window.addEventListener("scroll",t),e.addEventListener("click",(function(){gsap.to(window,{duration:2,delay:0,scrollTo:{y:".hero-main"},ease:function(e){return Math.min(1,1.001-Math.pow(2,-10*e))}})}))})),document.addEventListener("DOMContentLoaded",(function(){function t(){if(innerWidth>767)new e.default}t(),window.addEventListener("res",t)}));var w=u("details");w.forEach((function(e){e.addEventListener("click",(function(t){w.forEach((function(t){t!=e&&t.removeAttribute("open")}))}))}));var b=h(".c-elephant_himself"),C=h(".elephant-boundary");C.addEventListener("mouseenter",(function(){new e.default({el:b,container:C,speed:22.5})}));var S,E=h(".ourservices"),T=new e.default;E.addEventListener("mouseenter",(function(){T.setImg("./../../assets/images/peanut.webp")})),E.addEventListener("mouseleave",(function(){T.removeImg()})),document.addEventListener("DOMContentLoaded",(function(){gsap.registerPlugin(ScrollTrigger);var e=gsap.utils.toArray(".white-section"),t=h(".top-arrow-wrapper"),n=h(".top-arrow-path"),i=h(".menu-name"),s=u(".menu-dot-line");function r(){n.style.stroke="var(--color-bg)",t.style.fill="var(--color-black)",s.forEach((function(e){e.style.background="var(--color-black)"})),i.style.color="var(--color-black)"}function o(){n.style.stroke="var(--color-black)",t.style.fill="var(--color-bg)",s.forEach((function(e){e.style.background="var(--color-bg)"})),i.style.color="var(--color-bg)"}e.forEach((function(e,t){gsap.timeline({scrollTrigger:{trigger:e,id:t+1,start:"top top",endtrigger:e,end:"bottom bottom",scrub:!0,onEnter:function(){return o()},onLeave:function(){return r()},onEnterBack:function(){return o()},onLeaveBack:function(){return r()}}})}))})),(S=u(".grid-itemz > .grid__item-img"),function(e){if(Array.isArray(e))return c(e)}(S)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(S)||function(e,t){if(e){if("string"==typeof e)return c(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?c(e,t):void 0}}(S)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()).forEach((function(e){return new l.Item(e)}));var I=h(".global-video"),k=h("#video-background");gsap.registerPlugin(ScrollTrigger),gsap.timeline({scrollTrigger:{trigger:I,start:"top bottom",end:"top top",scrub:!0,markers:!1,toggleActions:"play none none reverse"}}).fromTo(k,{scaleX:.9,borderRadius:"45px"},{scaleX:1,borderRadius:"0px"});gsap.timeline({scrollTrigger:{trigger:k,start:"top bottom",end:"bottom top",scrub:!0,onEnter:function(){k.paused&&k.play().catch((function(e){"NotAllowedError"===e.name?console.log("Play request was interrupted by a pause call."):console.error("An unexpected error occurred:",e)}))},onLeave:function(){k.paused||k.pause()},onEnterBack:function(){k.paused&&k.play().catch((function(e){"NotAllowedError"===e.name?console.log("Play request was interrupted by a pause call."):console.error("An unexpected error occurred:",e)}))},onLeaveBack:function(){k.paused||k.pause()}}});var x=k.play();void 0!==x&&x.then((function(e){})).catch((function(e){})),document.addEventListener("DOMContentLoaded",(function(){var e=h(".carousel"),t=h(".-prev"),n=h(".-next"),i=0;function s(t){var n=e.children[0].offsetWidth,s=(e.offsetWidth,e.children.length);"next"===t?i=(i+1)%s:"back"===t&&(i=(i-1+s)%s),e.style.transform="translateX(-".concat(i*n,"px)")}t.addEventListener("click",(function(){s("back")})),n.addEventListener("click",(function(){s("next")}))}));var N=(0,s.initializeApp)({apiKey:"AIzaSyCd-ad_ExUqBU-Z-kn_U_6BR4gfKoydHx4",authDomain:"hypercritical-c0acf.firebaseapp.com",databaseURL:"https://hypercritical-c0acf-default-rtdb.firebaseio.com",projectId:"hypercritical-c0acf",storageBucket:"hypercritical-c0acf.appspot.com",messagingSenderId:"615546380060",appId:"1:615546380060:web:a124c49f5be5b5142ca4d9",measurementId:"G-TDXEWBCNFH"}),P=(0,r.getDatabase)(N);document.getElementById("consultationForm").addEventListener("submit",(function(e){e.preventDefault();var t=document.getElementById("message").value,n=document.getElementById("email").value,i=document.getElementById("yourname").value,s="";document.getElementById("Web-Design").checked&&(s+="Web Design, "),document.getElementById("SEO").checked&&(s+="SEO, "),document.getElementById("Development").checked&&(s+="Development, "),document.getElementById("Other").checked&&(s+="Other, "),s=s.slice(0,-2);for(var o="",a=document.getElementsByName("priceGroup"),l=0;l<a.length;l++)if(a[l].checked){o=a[l].id;break}var c=(0,r.push)((0,r.ref)(P,"consultations"));(0,r.set)(c,{name:i,message:t,budget:o,consultationType:s,email:n,date:(new Date).toISOString()}),gsap.to("#overlay",{duration:.5,opacity:1,scale:1,onComplete:function(){gsap.to("#dialog",{duration:.5,scale:1,opacity:1,ease:"bounce"})}}),document.getElementById("consultationForm").reset()})),h(".close-dialog").addEventListener("click",(function(){gsap.to("#dialog",{duration:.5,scale:0,opacity:0,onComplete:function(){gsap.to("#overlay",{duration:.5,opacity:0,scale:0})}})}));var D=u('input[type="checkbox"]'),R=function(e){e.target.parentNode.querySelector(".checkbox-input").classList.toggle("clicked-color"),e.target.parentNode.querySelector(".checkbox-text").classList.toggle("clicked-text")};D.forEach((function(e){e.addEventListener("change",R)}));var A=u('input[type="radio"]'),L=function(e){var t=e.target.parentNode.querySelector(".radio-text");u(".radio-text").forEach((function(e){return e.parentElement.classList.remove("clicked")})),t.parentElement.classList.add("clicked")};A.forEach((function(e){e.addEventListener("change",L)}));var O=u(".grid-item-vid");O.forEach((function(e){e.addEventListener("mouseenter",(function(){var t;e.querySelector(".grid__item-video").style.display="block",t=e,gsap.timeline({defaults:{ease:"expo.out",delay:0}}).fromTo(t.querySelector(".grid__item-video"),{y:"0%"},{duration:1.25,y:"101%",ease:"expo.inOut"},0)}))})),O.forEach((function(e){e.addEventListener("mouseout",(function(){var t,n=e.querySelector(".grid__item-video");t=e,gsap.timeline({defaults:{ease:"expo.out",delay:0}}).fromTo(t.querySelector(".grid__item-video"),{y:"101%"},{duration:1.25,y:"0%",ease:"expo.inOut"},0),setTimeout((function(){!function(e){var t=e.querySelector(".grid__item-video");t.pause(),t.currentTime=0}(e),n.style.display="none"}),2e3)}))}))})()})();