@llmnative/runner 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +9 -3
  3. package/bin/runner.mjs +21 -10
  4. package/bin/setup-server.mjs +160 -0
  5. package/bin/ssh-keys.mjs +15 -0
  6. package/dist/setup-app/assets/NetworkCanvasImpl-DIYuzg6x-CVEzQpWc.js +7 -0
  7. package/dist/setup-app/assets/dist-9W_fpPLL.js +11 -0
  8. package/dist/setup-app/assets/index-BAksVWhQ.js +32 -0
  9. package/dist/setup-app/assets/index-CmPc3Q2I.css +2 -0
  10. package/dist/setup-app/assets/index.es-DFOx5a43.js +1 -0
  11. package/dist/setup-app/assets/index.esm-7HxyOcz9.js +9 -0
  12. package/dist/setup-app/assets/index.esm-Bo_uP467.js +1 -0
  13. package/dist/setup-app/assets/index.esm-D6oehhSQ.js +1 -0
  14. package/dist/setup-app/assets/index.esm-D983b7TD.js +1 -0
  15. package/dist/setup-app/assets/index.esm-H_whZvB-.js +4 -0
  16. package/dist/setup-app/assets/index.esm-NAFJB7JL.js +31 -0
  17. package/dist/setup-app/assets/lucide-react-DpJIOtaQ.js +1 -0
  18. package/dist/setup-app/assets/prism-BjaHQ1lq.js +2 -0
  19. package/dist/setup-app/assets/prism-bash-D6zCJ74D.js +1 -0
  20. package/dist/setup-app/assets/prism-c-04YixN25.js +1 -0
  21. package/dist/setup-app/assets/prism-clike-DapgWyxx.js +1 -0
  22. package/dist/setup-app/assets/prism-cpp-C-lJbC-6.js +1 -0
  23. package/dist/setup-app/assets/prism-csharp-XPn2bw0d.js +1 -0
  24. package/dist/setup-app/assets/prism-css-CPgOzxXp.js +1 -0
  25. package/dist/setup-app/assets/prism-docker-DkT6yOFj.js +1 -0
  26. package/dist/setup-app/assets/prism-git-BZB8f0uj.js +1 -0
  27. package/dist/setup-app/assets/prism-go-C_8qAH5n.js +1 -0
  28. package/dist/setup-app/assets/prism-graphql-XjvHrdQl.js +1 -0
  29. package/dist/setup-app/assets/prism-ini-BESK3y0r.js +1 -0
  30. package/dist/setup-app/assets/prism-java-6wtusvIl.js +1 -0
  31. package/dist/setup-app/assets/prism-javascript-BnO-swvr.js +1 -0
  32. package/dist/setup-app/assets/prism-json-Dp_-W-Hv.js +1 -0
  33. package/dist/setup-app/assets/prism-jsx-D-D0NWtC.js +1 -0
  34. package/dist/setup-app/assets/prism-markup-Cp04rIa1.js +1 -0
  35. package/dist/setup-app/assets/prism-php-Co4fM40K.js +1 -0
  36. package/dist/setup-app/assets/prism-powershell-Cvud8pPk.js +1 -0
  37. package/dist/setup-app/assets/prism-python-CfiSVtM6.js +1 -0
  38. package/dist/setup-app/assets/prism-ruby-Cb5nlQRI.js +1 -0
  39. package/dist/setup-app/assets/prism-sql-CYhVDMEE.js +1 -0
  40. package/dist/setup-app/assets/prism-tsx-p6J2Kc_4.js +1 -0
  41. package/dist/setup-app/assets/prism-typescript-BMqONzxf.js +1 -0
  42. package/dist/setup-app/assets/prism-yaml-C0JHu8gr.js +1 -0
  43. package/dist/setup-app/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  44. package/dist/setup-app/assets/style-DLioOiRN.css +1 -0
  45. package/dist/setup-app/index.html +15 -0
  46. package/dist/setup.js +1 -1
  47. package/dist/setup.js.map +1 -1
  48. package/dist/setup.mjs +21 -1
  49. package/dist/setup.mjs.map +1 -1
  50. package/dist/steps.js +1 -1
  51. package/dist/steps.js.map +1 -1
  52. package/dist/steps.mjs +2 -2
  53. package/dist/steps.mjs.map +1 -1
  54. package/dist/types/setup/index.d.ts +8 -0
  55. package/dist/types/ui/RunnersSettings.d.ts +2 -0
  56. package/dist/types/ui/texts.d.ts +6 -0
  57. package/dist/ui.js +3 -3
  58. package/dist/ui.js.map +1 -1
  59. package/dist/ui.mjs +54 -38
  60. package/dist/ui.mjs.map +1 -1
  61. package/install/compose.yaml +18 -1
  62. package/install/coolify.yaml +2 -2
  63. package/install/install.sh +51 -6
  64. package/llms.txt +1 -1
  65. package/package.json +23 -7
@@ -0,0 +1,4 @@
1
+ import{B as e,C as t,D as n,E as r,G as i,H as a,I as o,J as s,L as c,M as l,N as u,O as d,P as f,Q as ee,R as te,T as ne,V as re,X as ie,_t as p,at as ae,c as oe,ct as se,dt as ce,et as le,f as ue,ft as de,g as fe,gt as pe,ht as me,it as m,j as he,lt as ge,mt as _e,n as ve,rt as ye,u as be,ut as xe,w as Se,x as Ce}from"./index.esm-D6oehhSQ.js";var we=`@firebase/database`,Te=`1.1.5`,Ee=``;function De(e){Ee=e}var Oe=class{constructor(e){this.domStorage_=e,this.prefix_=`firebase:`}set(e,t){t==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),p(t))}get(e){let t=this.domStorage_.getItem(this.prefixedName_(e));return t==null?null:ge(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}},ke=class{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){t==null?delete this.cache_[e]:this.cache_[e]=t}get(e){return c(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}},Ae=function(e){try{if(typeof window<`u`&&window[e]!==void 0){let t=window[e];return t.setItem(`firebase:sentinel`,`cache`),t.removeItem(`firebase:sentinel`),new Oe(t)}}catch{}return new ke},je=Ae(`localStorage`),Me=Ae(`sessionStorage`),Ne=new Se(`@firebase/database`),Pe=(function(){let e=1;return function(){return e++}})(),Fe=function(e){let t=pe(e),n=new he;n.update(t);let r=n.digest();return f.encodeByteArray(r)},Ie=function(...e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];Array.isArray(r)||r&&typeof r==`object`&&typeof r.length==`number`?t+=Ie.apply(null,r):t+=typeof r==`object`?p(r):r,t+=` `}return t},Le=null,Re=!0,ze=function(e,n){l(!n||e===!0||e===!1,`Can't turn on custom loggers persistently.`),e===!0?(Ne.logLevel=t.VERBOSE,Le=Ne.log.bind(Ne),n&&Me.set(`logging_enabled`,!0)):typeof e==`function`?Le=e:(Le=null,Me.remove(`logging_enabled`))},h=function(...e){if(Re===!0&&(Re=!1,Le===null&&Me.get(`logging_enabled`)===!0&&ze(!0)),Le){let t=Ie.apply(null,e);Le(t)}},Be=function(e){return function(...t){h(e,...t)}},Ve=function(...e){let t=`FIREBASE INTERNAL ERROR: `+Ie(...e);Ne.error(t)},g=function(...e){let t=`FIREBASE FATAL ERROR: ${Ie(...e)}`;throw Ne.error(t),Error(t)},_=function(...e){let t=`FIREBASE WARNING: `+Ie(...e);Ne.warn(t)},He=function(){typeof window<`u`&&window.location&&window.location.protocol&&window.location.protocol.indexOf(`https:`)!==-1&&_(`Insecure Firebase access from a secure page. Please use https in calls to new Firebase().`)},Ue=function(e){return typeof e==`number`&&(e!==e||e===1/0||e===-1/0)},We=function(e){if(m()||document.readyState===`complete`)e();else{let t=!1,n=function(){document.body?t||(t=!0,e()):setTimeout(n,10)};document.addEventListener?(document.addEventListener(`DOMContentLoaded`,n,!1),window.addEventListener(`load`,n,!1)):document.attachEvent&&(document.attachEvent(`onreadystatechange`,()=>{document.readyState===`complete`&&n()}),window.attachEvent(`onload`,n))}},v=`[MIN_NAME]`,y=`[MAX_NAME]`,Ge=function(e,t){if(e===t)return 0;if(e===v||t===y)return-1;if(t===v||e===y)return 1;{let n=rt(e),r=rt(t);return n===null?r===null&&e<t?-1:1:r===null?-1:n-r===0?e.length-t.length:n-r}},Ke=function(e,t){return e===t?0:e<t?-1:1},qe=function(e,t){if(t&&e in t)return t[e];throw Error(`Missing required key (`+e+`) in object: `+p(t))},Je=function(e){if(typeof e!=`object`||!e)return p(e);let t=[];for(let n in e)t.push(n);t.sort();let n=`{`;for(let r=0;r<t.length;r++)r!==0&&(n+=`,`),n+=p(t[r]),n+=`:`,n+=Je(e[t[r]]);return n+=`}`,n},Ye=function(e,t){let n=e.length;if(n<=t)return[e];let r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r};function b(e,t){for(let n in e)e.hasOwnProperty(n)&&t(n,e[n])}var Xe=function(e){l(!Ue(e),`Invalid JSON number`);let t=1023,n,r,i,a,o;e===0?(r=0,i=0,n=+(1/e==-1/0)):(n=e<0,e=Math.abs(e),e>=2**-1022?(a=Math.min(Math.floor(Math.log(e)/Math.LN2),t),r=a+t,i=Math.round(e*2**(52-a)-2**52)):(r=0,i=Math.round(e/2**-1074)));let s=[];for(o=52;o;--o)s.push(i%2?1:0),i=Math.floor(i/2);for(o=11;o;--o)s.push(r%2?1:0),r=Math.floor(r/2);s.push(+!!n),s.reverse();let c=s.join(``),u=``;for(o=0;o<64;o+=8){let e=parseInt(c.substr(o,8),2).toString(16);e.length===1&&(e=`0`+e),u+=e}return u.toLowerCase()},Ze=function(){return!!(typeof window==`object`&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},Qe=function(){return typeof Windows==`object`&&typeof Windows.UI==`object`};function $e(e,t){let n=`Unknown Error`;e===`too_big`?n=`The data requested exceeds the maximum size that can be accessed with a single request.`:e===`permission_denied`?n=`Client doesn't have permission to access the desired data.`:e===`unavailable`&&(n=`The service is unavailable`);let r=Error(e+` at `+t._path.toString()+`: `+n);return r.code=e.toUpperCase(),r}var et=RegExp(`^-?(0*)\\d{1,10}$`),tt=-2147483648,nt=2147483647,rt=function(e){if(et.test(e)){let t=Number(e);if(t>=tt&&t<=nt)return t}return null},it=function(e){try{e()}catch(e){setTimeout(()=>{throw _(`Exception was thrown by user callback.`,e.stack||``),e},0)}},at=function(){return(typeof window==`object`&&window.navigator&&window.navigator.userAgent||``).search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},ot=function(e,t){let n=setTimeout(e,t);return typeof n==`number`&&typeof Deno<`u`&&Deno.unrefTimer?Deno.unrefTimer(n):typeof n==`object`&&n.unref&&n.unref(),n},st=class{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,be(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t?.getImmediate({optional:!0}),this.appCheck||t?.get().then(e=>this.appCheck=e)}getToken(e){if(this.serverAppAppCheckToken){if(e)throw Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}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){this.appCheckProvider?.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){_(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}},ct=class{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&&e.code===`auth/token-not-initialized`?(h(`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/.`,_(e)}},lt=class{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}};lt.OWNER=`owner`;var ut=`5`,dt=`v`,ft=`s`,pt=`r`,mt=`f`,ht=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,gt=`ls`,_t=`p`,vt=`ac`,yt=`websocket`,bt=`long_polling`,xt=class{constructor(e,t,n,r,i=!1,a=``,o=!1,s=!1,c=null){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=a,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=s,this.emulatorOptions=c,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(`.`)+1),this.internalHost=je.get(`host:`+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)===`s-`}isCustomHost(){return this._domain!==`firebaseio.com`&&this._domain!==`firebaseio-demo.com`}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&je.set(`host:`+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+=`<`+this.persistenceKey+`>`),e}toURLString(){let e=this.secure?`https://`:`http://`,t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:``;return`${e}${this.host}/${t}`}};function St(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams}function Ct(e,t,n){l(typeof t==`string`,`typeof type must == string`),l(typeof n==`object`,`typeof params must == object`);let r;if(t===yt)r=(e.secure?`wss://`:`ws://`)+e.internalHost+`/.ws?`;else if(t===bt)r=(e.secure?`https://`:`http://`)+e.internalHost+`/.lp?`;else throw Error(`Unknown connection type: `+t);St(e)&&(n.ns=e.namespace);let i=[];return b(n,(e,t)=>{i.push(e+`=`+t)}),r+i.join(`&`)}var wt=class{constructor(){this.counters_={}}incrementCounter(e,t=1){c(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return e(this.counters_)}},Tt={},Et={};function Dt(e){let t=e.toString();return Tt[t]||(Tt[t]=new wt),Tt[t]}function Ot(e,t){let n=e.toString();return Et[n]||(Et[n]=t()),Et[n]}var kt=class{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){let e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&it(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&=(this.onClose(),null);break}this.currentResponseNum++}}},At=`start`,jt=`close`,Mt=`pLPCommand`,Nt=`pRTLPCB`,Pt=`id`,Ft=`pw`,It=`ser`,Lt=`cb`,Rt=`dframe`,zt=1870,Bt=30,Vt=1840,Ht=25e3,Ut=3e4,Wt=class e{constructor(e,t,n,r,i,a,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=a,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=Be(e),this.stats_=Dt(t),this.urlFn=e=>(this.appCheckToken&&(e[vt]=this.appCheckToken),Ct(t,bt,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new kt(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_(`Timed out trying to connect.`),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Ut)),We(()=>{if(this.isClosed_)return;this.scriptTagHolder=new Gt((...e)=>{let[t,n,r,i,a]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder){if(this.connectTimeoutTimer_&&=(clearTimeout(this.connectTimeoutTimer_),null),this.everConnected_=!0,t===At)this.id=n,this.password=r;else if(t===jt)n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_();else throw Error(`Unrecognized command received: `+t)}},(...e)=>{let[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);let e={};e[At]=`t`,e[It]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(e[Lt]=this.scriptTagHolder.uniqueCallbackIdentifier),e[dt]=ut,this.transportSessionId&&(e[ft]=this.transportSessionId),this.lastSessionId&&(e[gt]=this.lastSessionId),this.applicationId&&(e[_t]=this.applicationId),this.appCheckToken&&(e[vt]=this.appCheckToken),typeof location<`u`&&location.hostname&&ht.test(location.hostname)&&(e[pt]=mt);let 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(){e.forceAllow_=!0}static forceDisallow(){e.forceDisallow_=!0}static isAvailable(){return m()?!1:e.forceAllow_?!0:!e.forceDisallow_&&typeof document<`u`&&document.createElement!=null&&!Ze()&&!Qe()}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&=(this.scriptTagHolder.close(),null),this.myDisconnFrame&&=(document.body.removeChild(this.myDisconnFrame),null),this.connectTimeoutTimer_&&=(clearTimeout(this.connectTimeoutTimer_),null)}onClosed_(){this.isClosed_||(this.log_(`Longpoll is closing itself`),this.shutdown_(),this.onDisconnect_&&=(this.onDisconnect_(this.everConnected_),null))}close(){this.isClosed_||(this.log_(`Longpoll is being closed.`),this.shutdown_())}send(e){let t=p(e);this.bytesSent+=t.length,this.stats_.incrementCounter(`bytes_sent`,t.length);let n=Ye(o(t),Vt);for(let e=0;e<n.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[e]),this.curSegmentNum++}addDisconnectPingFrame(e,t){if(m())return;this.myDisconnFrame=document.createElement(`iframe`);let n={};n[Rt]=`t`,n[Pt]=e,n[Ft]=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display=`none`,document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){let t=p(e).length;this.bytesReceived+=t,this.stats_.incrementCounter(`bytes_received`,t)}},Gt=class e{constructor(t,n,r,i){if(this.onDisconnect=r,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(Math.random()*1e8),this.sendNewPolls=!0,m())this.commandCB=t,this.onMessageCB=n;else{this.uniqueCallbackIdentifier=Pe(),window[Mt+this.uniqueCallbackIdentifier]=t,window[Nt+this.uniqueCallbackIdentifier]=n,this.myIFrame=e.createIFrame_();let r=``;this.myIFrame.src&&this.myIFrame.src.substr(0,11)===`javascript:`&&(r=`<script>document.domain="`+document.domain+`";<\/script>`);let i=`<html><body>`+r+`</body></html>`;try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){h(`frame writing exception`),e.stack&&h(e.stack),h(e)}}}static createIFrame_(){let e=document.createElement(`iframe`);if(e.style.display=`none`,document.body){document.body.appendChild(e);try{e.contentWindow.document||h(`No IE domain setting required`)}catch{e.src=`javascript:void((function(){document.open();document.domain='`+document.domain+`';document.close();})())`}}else throw`Document body has not initialized. Wait to initialize Firebase until after the document is ready.`;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(()=>{this.myIFrame!==null&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},0));let 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++;let e={};e[Pt]=this.myID,e[Ft]=this.myPW,e[It]=this.currentSerial;let t=this.urlFn(e),n=``,r=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+Bt+n.length<=zt;){let e=this.pendingSegs.shift();n=n+`&seg`+r+`=`+e.seg+`&ts`+r+`=`+e.ts+`&d`+r+`=`+e.d,r++}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);let n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(Ht));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,t){m()?this.doNodeLongPoll(e,t):setTimeout(()=>{try{if(!this.sendNewPolls)return;let n=this.myIFrame.doc.createElement(`script`);n.type=`text/javascript`,n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){let e=n.readyState;e&&e!==`loaded`&&e!==`complete`||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{h(`Long-poll script failed to load: `+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch{}},1)}},Kt=16384,qt=45e3,Jt=null;typeof MozWebSocket<`u`?Jt=MozWebSocket:typeof WebSocket<`u`&&(Jt=WebSocket);var x=class e{constructor(t,n,r,i,a,o,s){this.connId=t,this.applicationId=r,this.appCheckToken=i,this.authToken=a,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=Be(this.connId),this.stats_=Dt(n),this.connURL=e.connectionURL_(n,o,s,i,r),this.nodeAdmin=n.nodeAdmin}static connectionURL_(e,t,n,r,i){let a={};return a[dt]=ut,!m()&&typeof location<`u`&&location.hostname&&ht.test(location.hostname)&&(a[pt]=mt),t&&(a[ft]=t),n&&(a[gt]=n),r&&(a[vt]=r),i&&(a[_t]=i),Ct(e,yt,a)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_(`Websocket connecting to `+this.connURL),this.everConnected_=!1,je.set(`previous_websocket_failure`,!0);try{let e;if(m()){let t=this.nodeAdmin?`AdminNode`:`Node`;e={headers:{"User-Agent":`Firebase/${ut}/${Ee}/${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);let n={},r=this.connURL.indexOf(`wss://`)===0?n.HTTPS_PROXY||n.https_proxy:n.HTTP_PROXY||n.http_proxy;r&&(e.proxy={origin:r})}this.mySock=new Jt(this.connURL,[],e)}catch(e){this.log_(`Error instantiating WebSocket.`);let t=e.message||e.data;t&&this.log_(t),this.onClosed_();return}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.`);let t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){e.forceDisallow_=!0}static isAvailable(){let t=!1;if(typeof navigator<`u`&&navigator.userAgent){let e=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);e&&e.length>1&&parseFloat(e[1])<4.4&&(t=!0)}return!t&&Jt!==null&&!e.forceDisallow_}static previouslyFailed(){return je.isInMemoryStorage||je.get(`previous_websocket_failure`)===!0}markConnectionHealthy(){je.remove(`previous_websocket_failure`)}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){let e=this.frames.join(``);this.frames=null;let t=ge(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(l(this.frames===null,`We already have a frame buffer`),e.length<=6){let t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(this.mySock===null)return;let t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter(`bytes_received`,t.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(t);else{let e=this.extractFrameCount_(t);e!==null&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();let t=p(e);this.bytesSent+=t.length,this.stats_.incrementCounter(`bytes_sent`,t.length);let n=Ye(t,Kt);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),null),this.mySock&&=(this.mySock.close(),null)}onClosed_(){this.isClosed_||(this.log_(`WebSocket is closing itself`),this.shutdown_(),this.onDisconnect&&=(this.onDisconnect(this.everConnected_),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(qt))}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)}}};x.responsesRequiredToBeHealthy=2,x.healthyTimeout=3e4;var Yt=class e{static get ALL_TRANSPORTS(){return[Wt,x]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(t){let n=x&&x.isAvailable(),r=n&&!x.previouslyFailed();if(t.webSocketOnly&&(n||_(`wss:// URL used, but browser isn't known to support websockets. Trying anyway.`),r=!0),r)this.transports_=[x];else{let t=this.transports_=[];for(let n of e.ALL_TRANSPORTS)n&&n.isAvailable()&&t.push(n);e.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw Error(`No transports available`)}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}};Yt.globalTransportInitialized_=!1;var Xt=6e4,Zt=5e3,Qt=10240,$t=102400,en=`t`,tn=`d`,nn=`s`,rn=`r`,an=`e`,on=`o`,sn=`a`,cn=`n`,ln=`p`,un=`h`,dn=class{constructor(e,t,n,r,i,a,o,s,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=a,this.onReady_=o,this.onDisconnect_=s,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=Be(`c:`+this.id+`:`),this.transportManager_=new Yt(t),this.log_(`Connection created`),this.start_()}start_(){let e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;let t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},0);let r=e.healthyTimeout||0;r>0&&(this.healthyTimeout_=ot(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>$t?(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>Qt?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(r)))}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=>{this.state_!==2&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_(`message on old connection`))}}sendRequest(e){let 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(en in e){let t=e[en];t===sn?this.upgradeIfSecondaryHealthy_():t===rn?(this.log_(`Got a reset on secondary, closing it`),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):t===on&&(this.log_(`got pong on secondary.`),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){let t=qe(`t`,e),n=qe(`d`,e);if(t===`c`)this.onSecondaryControl_(n);else if(t===`d`)this.pendingDataMessages.push(n);else throw Error(`Unknown protocol layer: `+t)}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:ln,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_(`sending client ack on secondary`),this.secondaryConn_.send({t:`c`,d:{t:sn,d:{}}}),this.log_(`Ending transmission on primary`),this.conn_.send({t:`c`,d:{t:cn,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){let t=qe(`t`,e),n=qe(`d`,e);t===`c`?this.onControl_(n):t===`d`&&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){let t=qe(en,e);if(tn in e){let n=e[tn];if(t===un){let e={...n};this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if(t===cn){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 t===nn?this.onConnectionShutdown_(n):t===rn?this.onReset_(n):t===an?Ve(`Server Error: `+n):t===on?(this.log_(`got pong on primary.`),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Ve(`Unknown control packet command: `+t)}}onHandshake_(e){let t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,this.state_===0&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),ut!==n&&_(`Protocol version mismatch detected`),this.tryStartUpgrade_())}tryStartUpgrade_(){let 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;let t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),ot(()=>{this.secondaryConn_&&(this.log_(`Timed out trying to upgrade.`),this.secondaryConn_.close())},Math.floor(Xt))}onReset_(e){this.log_(`Reset packet received. New host: `+e),this.repoInfo_.host=e,this.state_===1?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),null),this.primaryResponsesRequired_===0?(this.log_(`Primary connection is healthy.`),this.isHealthy_=!0):ot(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(Zt))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_(`sending ping on primary.`),this.sendData_({t:`c`,d:{t:ln,d:{}}}))}onSecondaryConnectionLost_(){let e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,!e&&this.state_===0?(this.log_(`Realtime connection failed.`),this.repoInfo_.isCacheableHost()&&(je.remove(`host:`+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_(`Realtime connection lost.`),this.close()}onConnectionShutdown_(e){this.log_(`Connection shutdown command received. Shutting down...`),this.onKill_&&=(this.onKill_(e),null),this.onDisconnect_=null,this.close()}sendData_(e){if(this.state_!==1)throw`Connection is not connected`;this.tx_.send(e)}close(){this.state_!==2&&(this.log_(`Closing realtime connection.`),this.state_=2,this.closeConnections_(),this.onDisconnect_&&=(this.onDisconnect_(),null))}closeConnections_(){this.log_(`Shutting down all connections`),this.conn_&&=(this.conn_.close(),null),this.secondaryConn_&&=(this.secondaryConn_.close(),null),this.healthyTimeout_&&=(clearTimeout(this.healthyTimeout_),null)}},fn=class{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}},pn=class{constructor(e){this.allowedEvents_=e,this.listeners_={},l(Array.isArray(e)&&e.length>0,`Requires a non-empty array`)}trigger(e,...t){if(Array.isArray(this.listeners_[e])){let 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});let r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);let r=this.listeners_[e]||[];for(let e=0;e<r.length;e++)if(r[e].callback===t&&(!n||n===r[e].context)){r.splice(e,1);return}}validateEventType_(e){l(this.allowedEvents_.find(t=>t===e),`Unknown event: `+e)}},mn=class e extends pn{static getInstance(){return new e}constructor(){super([`online`]),this.online_=!0,typeof window<`u`&&window.addEventListener!==void 0&&!ye()&&(window.addEventListener(`online`,()=>{this.online_||(this.online_=!0,this.trigger(`online`,!0))},!1),window.addEventListener(`offline`,()=>{this.online_&&(this.online_=!1,this.trigger(`online`,!1))},!1))}getInitialEvent(e){return l(e===`online`,`Unknown event type: `+e),[this.online_]}currentlyOnline(){return this.online_}},hn=32,gn=768,S=class{constructor(e,t){if(t===void 0){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 C(){return new S(``)}function w(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function T(e){return e.pieces_.length-e.pieceNum_}function E(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new S(e.pieces_,t)}function _n(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function vn(e){let t=``;for(let n=e.pieceNum_;n<e.pieces_.length;n++)e.pieces_[n]!==``&&(t+=`/`+encodeURIComponent(String(e.pieces_[n])));return t||`/`}function yn(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function bn(e){if(e.pieceNum_>=e.pieces_.length)return null;let t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new S(t,0)}function D(e,t){let n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof S)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{let e=t.split(`/`);for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new S(n,0)}function O(e){return e.pieceNum_>=e.pieces_.length}function k(e,t){let n=w(e),r=w(t);if(n===null)return t;if(n===r)return k(E(e),E(t));throw Error(`INTERNAL ERROR: innerPath (`+t+`) is not within outerPath (`+e+`)`)}function xn(e,t){let n=yn(e,0),r=yn(t,0);for(let e=0;e<n.length&&e<r.length;e++){let t=Ge(n[e],r[e]);if(t!==0)return t}return n.length===r.length?0:n.length<r.length?-1:1}function Sn(e,t){if(T(e)!==T(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function A(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(T(e)>T(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}var Cn=class{constructor(e,t){this.errorPrefix_=t,this.parts_=yn(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=me(this.parts_[e]);En(this)}};function wn(e,t){e.parts_.length>0&&(e.byteLength_+=1),e.parts_.push(t),e.byteLength_+=me(t),En(e)}function Tn(e){let t=e.parts_.pop();e.byteLength_-=me(t),e.parts_.length>0&&--e.byteLength_}function En(e){if(e.byteLength_>gn)throw Error(e.errorPrefix_+`has a key path longer than 768 bytes (`+e.byteLength_+`).`);if(e.parts_.length>hn)throw Error(e.errorPrefix_+`path specified exceeds the maximum depth that can be written (32) or object contains a cycle `+Dn(e))}function Dn(e){return e.parts_.length===0?``:`in property '`+e.parts_.join(`.`)+`'`}var On=class e extends pn{static getInstance(){return new e}constructor(){super([`visible`]);let e,t;typeof document<`u`&&document.addEventListener!==void 0&&(document.hidden===void 0?document.mozHidden===void 0?document.msHidden===void 0?document.webkitHidden!==void 0&&(t=`webkitvisibilitychange`,e=`webkitHidden`):(t=`msvisibilitychange`,e=`msHidden`):(t=`mozvisibilitychange`,e=`mozHidden`):(t=`visibilitychange`,e=`hidden`)),this.visible_=!0,t&&document.addEventListener(t,()=>{let t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger(`visible`,t))},!1)}getInitialEvent(e){return l(e===`visible`,`Unknown event type: `+e),[this.visible_]}},kn=1e3,An=3e5,jn=3e4,Mn=1.3,Nn=3e4,Pn=`server_kill`,Fn=3,j=class e extends fn{constructor(t,n,r,i,a,o,s,c){if(super(),this.repoInfo_=t,this.applicationId_=n,this.onDataUpdate_=r,this.onConnectStatus_=i,this.onServerInfoUpdate_=a,this.authTokenProvider_=o,this.appCheckTokenProvider_=s,this.authOverride_=c,this.id=e.nextPersistentConnectionId_++,this.log_=Be(`p:`+this.id+`:`),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=kn,this.maxReconnectDelay_=An,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,c&&!m())throw Error(`Auth override specified in options, but not supported on non Node.js platforms`);On.getInstance().on(`visible`,this.onVisible_,this),t.host.indexOf(`fblocal`)===-1&&mn.getInstance().on(`online`,this.onOnline_,this)}sendRequest(e,t,n){let r=++this.requestNumber_,i={r,a:e,b:t};this.log_(p(i)),l(this.connected_,`sendRequest call when we're not connected not allowed.`),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();let t=new d,n={action:`g`,request:{p:e._path.toString(),q:e._queryObject},onComplete:e=>{let n=e.d;e.s===`ok`?t.resolve(n):t.reject(n)}};this.outstandingGets_.push(n),this.outstandingGetCount_++;let r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),t.promise}listen(e,t,n,r){this.initConnection_();let i=e._queryIdentifier,a=e._path.toString();this.log_(`Listen called for `+a+` `+i),this.listens.has(a)||this.listens.set(a,new Map),l(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),`listen() called for non-default but complete query`),l(!this.listens.get(a).has(i),`listen() called twice for same path/queryId.`);let o={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(a).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(e){let t=this.outstandingGets_[e];this.sendRequest(`g`,t.request,n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)})}sendListen_(t){let n=t.query,r=n._path.toString(),i=n._queryIdentifier;this.log_(`Listen on `+r+` for `+i);let a={p:r};t.tag&&(a.q=n._queryObject,a.t=t.tag),a.h=t.hashFn(),this.sendRequest(`q`,a,a=>{let o=a.d,s=a.s;e.warnOnListenWarnings_(o,n),(this.listens.get(r)&&this.listens.get(r).get(i))===t&&(this.log_(`listen response`,a),s!==`ok`&&this.removeListen_(r,i),t.onComplete&&t.onComplete(s,o))})}static warnOnListenWarnings_(e,t){if(e&&typeof e==`object`&&c(e,`w`)){let n=_e(e,`w`);Array.isArray(n)&&~n.indexOf(`no_index`)&&_(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${`".indexOn": "`+t._queryParams.getIndex().toString()+`"`} at ${t._path.toString()} 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&&e.length===40||ie(e))&&(this.log_(`Admin auth credential detected. Reducing max reconnect time.`),this.maxReconnectDelay_=jn)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_(`App check token refreshed`),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest(`unappeck`,{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let e=this.authToken_,t=se(e)?`auth`:`gauth`,n={cred:e};this.authOverride_===null?n.noauth=!0:typeof this.authOverride_==`object`&&(n.authvar=this.authOverride_),this.sendRequest(t,n,t=>{let n=t.s,r=t.d||`error`;this.authToken_===e&&(n===`ok`?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,r))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest(`appcheck`,{token:this.appCheckToken_},e=>{let t=e.s,n=e.d||`error`;t===`ok`?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){let n=e._path.toString(),r=e._queryIdentifier;this.log_(`Unlisten called for `+n+` `+r),l(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),`unlisten() called for non-default but complete query`),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_(`Unlisten on `+e+` for `+t);let i={p:e};r&&(i.q=n,i.t=r),this.sendRequest(`n`,i)}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,r){let i={p:t,d:n};this.log_(`onDisconnect `+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},0)})}put(e,t,n,r){this.putInternal(`p`,e,t,n,r)}merge(e,t,n,r){this.putInternal(`m`,e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();let a={p:t,d:n};i!==void 0&&(a.h=i),this.outstandingPuts_.push({action:e,request:a,onComplete:r}),this.outstandingPutCount_++;let o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_(`Buffering put: `+t)}sendPut_(e){let t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,r=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_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),r&&r(n.s,n.d)})}reportStats(e){if(this.connected_){let t={c:e};this.log_(`reportStats`,t),this.sendRequest(`s`,t,e=>{if(e.s!==`ok`){let t=e.d;this.log_(`reportStats`,`Error sending stats: `+t)}})}}onDataMessage_(e){if(`r`in e){this.log_(`from server: `+p(e));let 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;else`a`in e&&this.onDataPush_(e.a,e.b)}onDataPush_(e,t){this.log_(`handleServerMessage`,e,t),e===`d`?this.onDataUpdate_(t.p,t.d,!1,t.t):e===`m`?this.onDataUpdate_(t.p,t.d,!0,t.t):e===`c`?this.onListenRevoked_(t.p,t.q):e===`ac`?this.onAuthRevoked_(t.s,t.d):e===`apc`?this.onAppCheckRevoked_(t.s,t.d):e===`sd`?this.onSecurityDebugPacket_(t):Ve(`Unrecognized action received from server: `+p(e)+`
2
+ Are 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){l(!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_=kn,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_(`Browser went online.`),this.reconnectDelay_=kn,this.realtime_||this.scheduleConnect_(0)):(this.log_(`Browser went offline. Killing connection.`),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_(`data client disconnected`),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&=(new Date().getTime()-this.lastConnectionEstablishedTime_>Nn&&(this.reconnectDelay_=kn),null):(this.log_(`Window isn't visible. Delaying reconnect.`),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());let e=Math.max(0,new Date().getTime()-this.lastConnectionAttemptTime_),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_,this.reconnectDelay_*Mn)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_(`Making a connection attempt`),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;let t=this.onDataMessage_.bind(this),n=this.onReady_.bind(this),r=this.onRealtimeDisconnect_.bind(this),i=this.id+`:`+e.nextConnectionId_++,a=this.lastSessionId,o=!1,s=null,c=function(){s?s.close():(o=!0,r())},u=function(e){l(s,`sendRequest call when we're not connected not allowed.`),s.sendRequest(e)};this.realtime_={close:c,sendRequest:u};let d=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{let[e,c]=await Promise.all([this.authTokenProvider_.getToken(d),this.appCheckTokenProvider_.getToken(d)]);o?h(`getToken() completed but was canceled`):(h(`getToken() completed. Creating connection.`),this.authToken_=e&&e.accessToken,this.appCheckToken_=c&&c.token,s=new dn(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,t,n,r,e=>{_(e+` (`+this.repoInfo_.toString()+`)`),this.interrupt(Pn)},a))}catch(e){this.log_(`Failed to get token: `+e),o||(this.repoInfo_.nodeAdmin&&_(e),c())}}}interrupt(e){h(`Interrupting connection for reason: `+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&=(clearTimeout(this.establishConnectionTimer_),null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){h(`Resuming connection for reason: `+e),delete this.interruptReasons_[e],le(this.interruptReasons_)&&(this.reconnectDelay_=kn,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){let t=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){let t=this.outstandingPuts_[e];t&&`h`in t.request&&t.queued&&(t.onComplete&&t.onComplete(`disconnect`),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}this.outstandingPutCount_===0&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>Je(e)).join(`$`):`default`;let r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete(`permission_denied`)}removeListen_(e,t){let n=new S(e).toString(),r;if(this.listens.has(n)){let e=this.listens.get(n);r=e.get(t),e.delete(t),e.size===0&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){h(`Auth token revoked: `+e+`/`+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(e===`invalid_token`||e===`permission_denied`)&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=Fn&&(this.reconnectDelay_=jn,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){h(`App check token revoked: `+e+`/`+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(e===`invalid_token`||e===`permission_denied`)&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=Fn&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):`msg`in e&&console.log(`FIREBASE: `+e.msg.replace(`
3
+ `,`
4
+ FIREBASE: `))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(let e of this.listens.values())for(let 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;){let 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_(){let e={},t=`js`;m()&&(t=this.repoInfo_.nodeAdmin?`admin_node`:`node`),e[`sdk.`+t+`.`+Ee.replace(/\./g,`-`)]=1,ye()?e[`framework.cordova`]=1:ae()&&(e[`framework.reactnative`]=1),this.reportStats(e)}shouldReconnect_(){let e=mn.getInstance().currentlyOnline();return le(this.interruptReasons_)&&e}};j.nextPersistentConnectionId_=0,j.nextConnectionId_=0;var M=class e{constructor(e,t){this.name=e,this.node=t}static Wrap(t,n){return new e(t,n)}},In=class{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){let n=new M(v,e),r=new M(v,t);return this.compare(n,r)!==0}minPost(){return M.MIN}},Ln,Rn=class extends In{static get __EMPTY_NODE(){return Ln}static set __EMPTY_NODE(e){Ln=e}compare(e,t){return Ge(e.name,t.name)}isDefinedOn(e){throw u(`KeyIndex.isDefinedOn not expected to be called.`)}indexedValueChanged(e,t){return!1}minPost(){return M.MIN}maxPost(){return new M(y,Ln)}makePost(e,t){return l(typeof e==`string`,`KeyIndex indexValue must always be a string.`),new M(e,Ln)}toString(){return`.key`}},N=new Rn,zn=class{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let a=1;for(;!e.isEmpty();)if(e=e,a=t?n(e.key,t):1,r&&(a*=-1),a<0)e=this.isReverse_?e.left:e.right;else if(a===0){this.nodeStack_.push(e);break}else this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}getNext(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}},P=class e{constructor(t,n,r,i,a){this.key=t,this.value=n,this.color=r??e.RED,this.left=i??F.EMPTY_NODE,this.right=a??F.EMPTY_NODE}copy(t,n,r,i,a){return new e(t??this.key,n??this.value,r??this.color,i??this.left,a??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 r=this,i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):i===0?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return F.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,r;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_()),t(e,n.key)===0){if(n.right.isEmpty())return F.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.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_(){let t=this.copy(null,null,e.RED,null,this.right.left);return this.right.copy(null,null,this.color,t,null)}rotateRight_(){let t=this.copy(null,null,e.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,t)}colorFlip_(){let 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_(){return 2**this.check_()<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw Error(`Red node has red child(`+this.key+`,`+this.value+`)`);if(this.right.isRed_())throw Error(`Right child of (`+this.key+`,`+this.value+`) is red`);let e=this.left.check_();if(e!==this.right.check_())throw Error(`Black depths differ`);return e+ +!this.isRed_()}};P.RED=!0,P.BLACK=!1;var Bn=class{copy(e,t,n,r,i){return this}insert(e,t,n){return new P(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}},F=class e{constructor(t,n=e.EMPTY_NODE){this.comparator_=t,this.root_=n}insert(t,n){return new e(this.comparator_,this.root_.insert(t,n,this.comparator_).copy(null,null,P.BLACK,null,null))}remove(t){return new e(this.comparator_,this.root_.remove(t,this.comparator_).copy(null,null,P.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),t===0)return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(t=this.comparator_(e,n.key),t===0){if(!n.left.isEmpty()){for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}return r?r.key:null}t<0?n=n.left:t>0&&(r=n,n=n.right)}throw 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 zn(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new zn(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new zn(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new zn(this.root_,null,this.comparator_,!0,e)}};F.EMPTY_NODE=new Bn;function Vn(e,t){return Ge(e.name,t.name)}function Hn(e,t){return Ge(e,t)}var Un;function Wn(e){Un=e}var Gn=function(e){return typeof e==`number`?`number:`+Xe(e):`string:`+e},Kn=function(e){if(e.isLeafNode()){let t=e.val();l(typeof t==`string`||typeof t==`number`||typeof t==`object`&&c(t,`.sv`),`Priority must be a string or number.`)}else l(e===Un||e.isEmpty(),`priority of unexpected type.`);l(e===Un||e.getPriority().isEmpty(),`Priority nodes can't have a priority of their own.`)},qn,Jn=class e{static set __childrenNodeConstructor(e){qn=e}static get __childrenNodeConstructor(){return qn}constructor(t,n=e.__childrenNodeConstructor.EMPTY_NODE){this.value_=t,this.priorityNode_=n,this.lazyHash_=null,l(this.value_!==void 0&&this.value_!==null,`LeafNode shouldn't be created with null/undefined value.`),Kn(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(t){return new e(this.value_,t)}getImmediateChild(t){return t===`.priority`?this.priorityNode_:e.__childrenNodeConstructor.EMPTY_NODE}getChild(t){return O(t)?this:w(t)===`.priority`?this.priorityNode_:e.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(t,n){return t===`.priority`?this.updatePriority(n):n.isEmpty()&&t!==`.priority`?this:e.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(t,n).updatePriority(this.priorityNode_)}updateChild(t,n){let r=w(t);return r===null?n:n.isEmpty()&&r!==`.priority`?this:(l(r!==`.priority`||T(t)===1,`.priority must be the last token in a path`),this.updateImmediateChild(r,e.__childrenNodeConstructor.EMPTY_NODE.updateChild(E(t),n)))}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(this.lazyHash_===null){let e=``;this.priorityNode_.isEmpty()||(e+=`priority:`+Gn(this.priorityNode_.val())+`:`);let t=typeof this.value_;e+=t+`:`,e+=t===`number`?Xe(this.value_):this.value_,this.lazyHash_=Fe(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(t){return t===e.__childrenNodeConstructor.EMPTY_NODE?1:t instanceof e.__childrenNodeConstructor?-1:(l(t.isLeafNode(),`Unknown node type`),this.compareToLeafNode_(t))}compareToLeafNode_(t){let n=typeof t.value_,r=typeof this.value_,i=e.VALUE_TYPE_ORDER.indexOf(n),a=e.VALUE_TYPE_ORDER.indexOf(r);return l(i>=0,`Unknown leaf type: `+n),l(a>=0,`Unknown leaf type: `+r),i===a?r===`object`?0:this.value_<t.value_?-1:this.value_===t.value_?0:1:a-i}withIndex(){return this}isIndexed(){return!0}equals(e){if(e===this)return!0;if(e.isLeafNode()){let t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}return!1}};Jn.VALUE_TYPE_ORDER=[`object`,`boolean`,`number`,`string`];var Yn,Xn;function Zn(e){Yn=e}function Qn(e){Xn=e}var I=new class extends In{compare(e,t){let n=e.node.getPriority(),r=t.node.getPriority(),i=n.compareTo(r);return i===0?Ge(e.name,t.name):i}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return M.MIN}maxPost(){return new M(y,new Jn(`[PRIORITY-POST]`,Xn))}makePost(e,t){return new M(t,new Jn(`[PRIORITY-POST]`,Yn(e)))}toString(){return`.priority`}},$n=Math.log(2),er=class{constructor(e){let t=e=>parseInt(Math.log(e)/$n,10),n=e=>parseInt(Array(e+1).join(`1`),2);this.count=t(e+1),this.current_=this.count-1;let r=n(this.count);this.bits_=e+1&r}nextBitIsOne(){let e=!(this.bits_&1<<this.current_);return this.current_--,e}},tr=function(e,t,n,r){e.sort(t);let i=function(t,r){let a=r-t,o,s;if(a===0)return null;if(a===1)return o=e[t],s=n?n(o):o,new P(s,o.node,P.BLACK,null,null);{let c=parseInt(a/2,10)+t,l=i(t,c),u=i(c+1,r);return o=e[c],s=n?n(o):o,new P(s,o.node,P.BLACK,l,u)}},a=function(t){let r=null,a=null,o=e.length,s=function(t,r){let a=o-t,s=o;o-=t;let l=i(a+1,s),u=e[a],d=n?n(u):u;c(new P(d,u.node,r,null,l))},c=function(e){r?(r.left=e,r=e):(a=e,r=e)};for(let e=0;e<t.count;++e){let n=t.nextBitIsOne(),r=2**(t.count-(e+1));n?s(r,P.BLACK):(s(r,P.BLACK),s(r,P.RED))}return a}(new er(e.length));return new F(r||t,a)},nr,rr={},ir=class e{static get Default(){return l(rr&&I,`ChildrenNode.ts has not been loaded`),nr||=new e({".priority":rr},{".priority":I}),nr}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){let t=_e(this.indexes_,e);if(!t)throw Error(`No index defined for `+e);return t instanceof F?t:null}hasIndex(e){return c(this.indexSet_,e.toString())}addIndex(t,n){l(t!==N,`KeyIndex always exists and isn't meant to be added to the IndexMap.`);let r=[],i=!1,a=n.getIterator(M.Wrap),o=a.getNext();for(;o;)i||=t.isDefinedOn(o.node),r.push(o),o=a.getNext();let s;s=i?tr(r,t.getCompare()):rr;let c=t.toString(),u={...this.indexSet_};u[c]=t;let d={...this.indexes_};return d[c]=s,new e(d,u)}addToIndexes(t,n){let r=xe(this.indexes_,(e,r)=>{let i=_e(this.indexSet_,r);if(l(i,`Missing index implementation for `+r),e===rr){if(i.isDefinedOn(t.node)){let e=[],r=n.getIterator(M.Wrap),a=r.getNext();for(;a;)a.name!==t.name&&e.push(a),a=r.getNext();return e.push(t),tr(e,i.getCompare())}return rr}{let r=n.get(t.name),i=e;return r&&(i=i.remove(new M(t.name,r))),i.insert(t,t.node)}});return new e(r,this.indexSet_)}removeFromIndexes(t,n){let r=xe(this.indexes_,e=>{if(e===rr)return e;{let r=n.get(t.name);return r?e.remove(new M(t.name,r)):e}});return new e(r,this.indexSet_)}},ar,L=class e{static get EMPTY_NODE(){return ar||=new e(new F(Hn),null,ir.Default)}constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&Kn(this.priorityNode_),this.children_.isEmpty()&&l(!this.priorityNode_||this.priorityNode_.isEmpty(),`An empty node cannot have a priority`)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||ar}updatePriority(t){return this.children_.isEmpty()?this:new e(this.children_,t,this.indexMap_)}getImmediateChild(e){if(e===`.priority`)return this.getPriority();{let t=this.children_.get(e);return t===null?ar:t}}getChild(e){let t=w(e);return t===null?this:this.getImmediateChild(t).getChild(E(e))}hasChild(e){return this.children_.get(e)!==null}updateImmediateChild(t,n){if(l(n,`We should always be passing snapshot nodes`),t===`.priority`)return this.updatePriority(n);{let r=new M(t,n),i,a;n.isEmpty()?(i=this.children_.remove(t),a=this.indexMap_.removeFromIndexes(r,this.children_)):(i=this.children_.insert(t,n),a=this.indexMap_.addToIndexes(r,this.children_));let o=i.isEmpty()?ar:this.priorityNode_;return new e(i,o,a)}}updateChild(e,t){let n=w(e);if(n===null)return t;{l(w(e)!==`.priority`||T(e)===1,`.priority must be the last token in a path`);let r=this.getImmediateChild(n).updateChild(E(e),t);return this.updateImmediateChild(n,r)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(t){if(this.isEmpty())return null;let n={},r=0,i=0,a=!0;if(this.forEachChild(I,(o,s)=>{n[o]=s.val(t),r++,a&&e.INTEGER_REGEXP_.test(o)?i=Math.max(i,Number(o)):a=!1}),!t&&a&&i<2*r){let e=[];for(let t in n)e[t]=n[t];return e}return t&&!this.getPriority().isEmpty()&&(n[`.priority`]=this.getPriority().val()),n}hash(){if(this.lazyHash_===null){let e=``;this.getPriority().isEmpty()||(e+=`priority:`+Gn(this.getPriority().val())+`:`),this.forEachChild(I,(t,n)=>{let r=n.hash();r!==``&&(e+=`:`+t+`:`+r)}),this.lazyHash_=e===``?``:Fe(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){let r=this.resolveIndex_(n);if(r){let n=r.getPredecessorKey(new M(e,t));return n?n.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){let t=this.resolveIndex_(e);if(t){let e=t.minKey();return e&&e.name}return this.children_.minKey()}getFirstChild(e){let t=this.getFirstChildName(e);return t?new M(t,this.children_.get(t)):null}getLastChildName(e){let t=this.resolveIndex_(e);if(t){let e=t.maxKey();return e&&e.name}return this.children_.maxKey()}getLastChild(e){let t=this.getLastChildName(e);return t?new M(t,this.children_.get(t)):null}forEachChild(e,t){let 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){let n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,e=>e);{let n=this.children_.getIteratorFrom(e.name,M.Wrap),r=n.peek();for(;r!=null&&t.compare(r,e)<0;)n.getNext(),r=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){let n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,e=>e);{let n=this.children_.getReverseIteratorFrom(e.name,M.Wrap),r=n.peek();for(;r!=null&&t.compare(r,e)>0;)n.getNext(),r=n.peek();return n}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===or?-1:0}withIndex(t){if(t===N||this.indexMap_.hasIndex(t))return this;{let n=this.indexMap_.addIndex(t,this.children_);return new e(this.children_,this.priorityNode_,n)}}isIndexed(e){return e===N||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{let t=e;if(!this.getPriority().equals(t.getPriority()))return!1;if(this.children_.count()===t.children_.count()){let e=this.getIterator(I),n=t.getIterator(I),r=e.getNext(),i=n.getNext();for(;r&&i;){if(r.name!==i.name||!r.node.equals(i.node))return!1;r=e.getNext(),i=n.getNext()}return r===null&&i===null}return!1}}resolveIndex_(e){return e===N?null:this.indexMap_.get(e.toString())}};L.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;var or=new class extends L{constructor(){super(new F(Hn),L.EMPTY_NODE,ir.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return L.EMPTY_NODE}isEmpty(){return!1}};Object.defineProperties(M,{MIN:{value:new M(v,L.EMPTY_NODE)},MAX:{value:new M(y,or)}}),Rn.__EMPTY_NODE=L.EMPTY_NODE,Jn.__childrenNodeConstructor=L,Wn(or),Qn(or);var sr=!0;function R(e,t=null){if(e===null)return L.EMPTY_NODE;if(typeof e==`object`&&`.priority`in e&&(t=e[`.priority`]),l(t===null||typeof t==`string`||typeof t==`number`||typeof t==`object`&&`.sv`in t,`Invalid priority type found: `+typeof t),typeof e==`object`&&`.value`in e&&e[`.value`]!==null&&(e=e[`.value`]),typeof e!=`object`||`.sv`in e)return new Jn(e,R(t));if(!(e instanceof Array)&&sr){let n=[],r=!1;if(b(e,(e,t)=>{if(e.substring(0,1)!==`.`){let i=R(t);i.isEmpty()||(r||=!i.getPriority().isEmpty(),n.push(new M(e,i)))}}),n.length===0)return L.EMPTY_NODE;let i=tr(n,Vn,e=>e.name,Hn);if(r){let e=tr(n,I.getCompare());return new L(i,R(t),new ir({".priority":e},{".priority":I}))}return new L(i,R(t),ir.Default)}{let n=L.EMPTY_NODE;return b(e,(t,r)=>{if(c(e,t)&&t.substring(0,1)!==`.`){let e=R(r);(e.isLeafNode()||!e.isEmpty())&&(n=n.updateImmediateChild(t,e))}}),n.updatePriority(R(t))}}Zn(R);var cr=class extends In{constructor(e){super(),this.indexPath_=e,l(!O(e)&&w(e)!==`.priority`,`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){let n=this.extractChild(e.node),r=this.extractChild(t.node),i=n.compareTo(r);return i===0?Ge(e.name,t.name):i}makePost(e,t){let n=R(e);return new M(t,L.EMPTY_NODE.updateChild(this.indexPath_,n))}maxPost(){return new M(y,L.EMPTY_NODE.updateChild(this.indexPath_,or))}toString(){return yn(this.indexPath_,0).join(`/`)}},lr=new class extends In{compare(e,t){let n=e.node.compareTo(t.node);return n===0?Ge(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return M.MIN}maxPost(){return M.MAX}makePost(e,t){return new M(t,R(e))}toString(){return`.value`}};function ur(e){return{type:`value`,snapshotNode:e}}function dr(e,t){return{type:`child_added`,snapshotNode:t,childName:e}}function fr(e,t){return{type:`child_removed`,snapshotNode:t,childName:e}}function pr(e,t,n){return{type:`child_changed`,snapshotNode:t,childName:e,oldSnap:n}}function mr(e,t){return{type:`child_moved`,snapshotNode:t,childName:e}}var hr=class{constructor(e){this.index_=e}updateChild(e,t,n,r,i,a){l(e.isIndexed(this.index_),`A node must be indexed if only a child is updated`);let o=e.getImmediateChild(t);return o.getChild(r).equals(n.getChild(r))&&o.isEmpty()===n.isEmpty()||(a!=null&&(n.isEmpty()?e.hasChild(t)?a.trackChildChange(fr(t,o)):l(e.isLeafNode(),`A child remove without an old child only makes sense on a leaf node`):o.isEmpty()?a.trackChildChange(dr(t,n)):a.trackChildChange(pr(t,n,o))),e.isLeafNode()&&n.isEmpty())?e:e.updateImmediateChild(t,n).withIndex(this.index_)}updateFullNode(e,t,n){return n!=null&&(e.isLeafNode()||e.forEachChild(I,(e,r)=>{t.hasChild(e)||n.trackChildChange(fr(e,r))}),t.isLeafNode()||t.forEachChild(I,(t,r)=>{if(e.hasChild(t)){let i=e.getImmediateChild(t);i.equals(r)||n.trackChildChange(pr(t,r,i))}else n.trackChildChange(dr(t,r))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?L.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}},gr=class e{constructor(t){this.indexedFilter_=new hr(t.getIndex()),this.index_=t.getIndex(),this.startPost_=e.getStartPost_(t),this.endPost_=e.getEndPost_(t),this.startIsInclusive_=!t.startAfterSet_,this.endIsInclusive_=!t.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){let 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,r,i,a){return this.matches(new M(t,n))||(n=L.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,a)}updateFullNode(e,t,n){t.isLeafNode()&&(t=L.EMPTY_NODE);let r=t.withIndex(this.index_);r=r.updatePriority(L.EMPTY_NODE);let i=this;return t.forEachChild(I,(e,t)=>{i.matches(new M(e,t))||(r=r.updateImmediateChild(e,L.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){let t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){let t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}},_r=class{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=>{let t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{let t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new gr(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,r,i,a){return this.rangedFilter_.matches(new M(t,n))||(n=L.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,a):this.fullLimitUpdateChild_(e,t,n,i,a)}updateFullNode(e,t,n){let r;if(t.isLeafNode()||t.isEmpty())r=L.EMPTY_NODE.withIndex(this.index_);else if(this.limit_*2<t.numChildren()&&t.isIndexed(this.index_)){r=L.EMPTY_NODE.withIndex(this.index_);let e;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_;){let t=e.getNext();if(this.withinDirectionalStart(t)){if(this.withinDirectionalEnd(t))r=r.updateImmediateChild(t.name,t.node),n++;else break}}}else{r=t.withIndex(this.index_),r=r.updatePriority(L.EMPTY_NODE);let e;e=this.reverse_?r.getReverseIterator(this.index_):r.getIterator(this.index_);let n=0;for(;e.hasNext();){let t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:r=r.updateImmediateChild(t.name,L.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let a;if(this.reverse_){let e=this.index_.getCompare();a=(t,n)=>e(n,t)}else a=this.index_.getCompare();let o=e;l(o.numChildren()===this.limit_,``);let s=new M(t,n),c=this.reverse_?o.getFirstChild(this.index_):o.getLastChild(this.index_),u=this.rangedFilter_.matches(s);if(o.hasChild(t)){let e=o.getImmediateChild(t),l=r.getChildAfterChild(this.index_,c,this.reverse_);for(;l!=null&&(l.name===t||o.hasChild(l.name));)l=r.getChildAfterChild(this.index_,l,this.reverse_);let d=l==null?1:a(l,s);if(u&&!n.isEmpty()&&d>=0)return i?.trackChildChange(pr(t,n,e)),o.updateImmediateChild(t,n);{i?.trackChildChange(fr(t,e));let n=o.updateImmediateChild(t,L.EMPTY_NODE);return l!=null&&this.rangedFilter_.matches(l)?(i?.trackChildChange(dr(l.name,l.node)),n.updateImmediateChild(l.name,l.node)):n}}return n.isEmpty()?e:u&&a(c,s)>=0?(i!=null&&(i.trackChildChange(fr(c.name,c.node)),i.trackChildChange(dr(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(c.name,L.EMPTY_NODE)):e}},vr=class e{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_=I}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===``?this.startSet_:this.viewFrom_===`l`}getIndexStartValue(){return l(this.startSet_,`Only valid if start has been set`),this.indexStartValue_}getIndexStartName(){return l(this.startSet_,`Only valid if start has been set`),this.startNameSet_?this.indexStartName_:v}hasEnd(){return this.endSet_}getIndexEndValue(){return l(this.endSet_,`Only valid if end has been set`),this.indexEndValue_}getIndexEndName(){return l(this.endSet_,`Only valid if end has been set`),this.endNameSet_?this.indexEndName_:y}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==``}getLimit(){return l(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_===I}copy(){let t=new e;return t.limitSet_=this.limitSet_,t.limit_=this.limit_,t.startSet_=this.startSet_,t.startAfterSet_=this.startAfterSet_,t.indexStartValue_=this.indexStartValue_,t.startNameSet_=this.startNameSet_,t.indexStartName_=this.indexStartName_,t.endSet_=this.endSet_,t.endBeforeSet_=this.endBeforeSet_,t.indexEndValue_=this.indexEndValue_,t.endNameSet_=this.endNameSet_,t.indexEndName_=this.indexEndName_,t.index_=this.index_,t.viewFrom_=this.viewFrom_,t}};function yr(e){return e.loadsAllData()?new hr(e.getIndex()):e.hasLimit()?new _r(e):new gr(e)}function br(e,t){let n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_=`l`,n}function xr(e,t){let n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_=`r`,n}function Sr(e,t,n){let r=e.copy();return r.startSet_=!0,t===void 0&&(t=null),r.indexStartValue_=t,n==null?(r.startNameSet_=!1,r.indexStartName_=``):(r.startNameSet_=!0,r.indexStartName_=n),r}function Cr(e,t,n){let r;return r=e.index_===N||n?Sr(e,t,n):Sr(e,t,y),r.startAfterSet_=!0,r}function wr(e,t,n){let r=e.copy();return r.endSet_=!0,t===void 0&&(t=null),r.indexEndValue_=t,n===void 0?(r.endNameSet_=!1,r.indexEndName_=``):(r.endNameSet_=!0,r.indexEndName_=n),r}function Tr(e,t,n){let r;return r=e.index_===N||n?wr(e,t,n):wr(e,t,v),r.endBeforeSet_=!0,r}function Er(e,t){let n=e.copy();return n.index_=t,n}function Dr(e){let t={};if(e.isDefault())return t;let n;if(e.index_===I?n=`$priority`:e.index_===lr?n=`$value`:e.index_===N?n=`$key`:(l(e.index_ instanceof cr,`Unrecognized index type!`),n=e.index_.toString()),t.orderBy=p(n),e.startSet_){let n=e.startAfterSet_?`startAfter`:`startAt`;t[n]=p(e.indexStartValue_),e.startNameSet_&&(t[n]+=`,`+p(e.indexStartName_))}if(e.endSet_){let n=e.endBeforeSet_?`endBefore`:`endAt`;t[n]=p(e.indexEndValue_),e.endNameSet_&&(t[n]+=`,`+p(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function Or(e){let 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_!==I&&(t.i=e.index_.toString()),t}var kr=class e extends fn{reportStats(e){throw Error(`Method not implemented.`)}static getListenId_(e,t){return t===void 0?(l(e._queryParams.isDefault(),`should have a tag if it's not a default query.`),e._path.toString()):`tag$`+t}constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=Be(`p:rest:`),this.listens_={}}listen(t,n,r,i){let a=t._path.toString();this.log_(`Listen called for `+a+` `+t._queryIdentifier);let o=e.getListenId_(t,r),s={};this.listens_[o]=s;let c=Dr(t._queryParams);this.restRequest_(a+`.json`,c,(e,t)=>{let n=t;if(e===404&&(n=null,e=null),e===null&&this.onDataUpdate_(a,n,!1,r),_e(this.listens_,o)===s){let t;t=e?e===401?`permission_denied`:`rest_error:`+e:`ok`,i(t,null)}})}unlisten(t,n){let r=e.getListenId_(t,n);delete this.listens_[r]}get(e){let t=Dr(e._queryParams),n=e._path.toString(),r=new d;return this.restRequest_(n+`.json`,t,(e,t)=>{let i=t;e===404&&(i=null,e=null),e===null?(this.onDataUpdate_(n,i,!1,null),r.resolve(i)):r.reject(Error(i))}),r.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format=`export`,Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([r,i])=>{r&&r.accessToken&&(t.auth=r.accessToken),i&&i.token&&(t.ac=i.token);let a=(this.repoInfo_.secure?`https://`:`http://`)+this.repoInfo_.host+e+`?ns=`+this.repoInfo_.namespace+de(t);this.log_(`Sending REST request for `+a);let o=new XMLHttpRequest;o.onreadystatechange=()=>{if(n&&o.readyState===4){this.log_(`REST Response for `+a+` received. status:`,o.status,`response:`,o.responseText);let e=null;if(o.status>=200&&o.status<300){try{e=ge(o.responseText)}catch{_(`Failed to parse JSON response for `+a+`: `+o.responseText)}n(null,e)}else o.status!==401&&o.status!==404&&_(`Got unsuccessful REST response for `+a+` Status: `+o.status),n(o.status);n=null}},o.open(`GET`,a,!0),o.send()})}},Ar=class{constructor(){this.rootNode_=L.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}};function jr(){return{value:null,children:new Map}}function Mr(e,t,n){if(O(t))e.value=n,e.children.clear();else if(e.value!==null)e.value=e.value.updateChild(t,n);else{let r=w(t);e.children.has(r)||e.children.set(r,jr());let i=e.children.get(r);t=E(t),Mr(i,t,n)}}function Nr(e,t){if(O(t))return e.value=null,e.children.clear(),!0;if(e.value!==null){if(e.value.isLeafNode())return!1;{let n=e.value;return e.value=null,n.forEachChild(I,(t,n)=>{Mr(e,new S(t),n)}),Nr(e,t)}}if(e.children.size>0){let n=w(t);return t=E(t),e.children.has(n)&&Nr(e.children.get(n),t)&&e.children.delete(n),e.children.size===0}return!0}function Pr(e,t,n){e.value===null?Fr(e,(e,r)=>{Pr(r,new S(t.toString()+`/`+e),n)}):n(t,e.value)}function Fr(e,t){e.children.forEach((e,n)=>{t(n,e)})}var Ir=class{constructor(e){this.collection_=e,this.last_=null}get(){let e=this.collection_.get(),t={...e};return this.last_&&b(this.last_,(e,n)=>{t[e]=t[e]-n}),this.last_=e,t}},Lr=1e4,Rr=3e5,zr=class{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Ir(e);let n=Lr+2e4*Math.random();ot(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){let e=this.statsListener_.get(),t={},n=!1;b(e,(e,r)=>{r>0&&c(this.statsToReport_,e)&&(t[e]=r,n=!0)}),n&&this.server_.reportStats(t),ot(this.reportStats_.bind(this),Math.floor(Math.random()*2*Rr))}},z;(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`})(z||={});function Br(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function Vr(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function Hr(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}var Ur=class e{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=z.ACK_USER_WRITE,this.source=Br()}operationForChild(t){if(!O(this.path))return l(w(this.path)===t,`operationForChild called for unrelated child.`),new e(E(this.path),this.affectedTree,this.revert);if(this.affectedTree.value!=null)return l(this.affectedTree.children.isEmpty(),`affectedTree should not have overlapping affected paths.`),this;{let n=this.affectedTree.subtree(new S(t));return new e(C(),n,this.revert)}}},Wr=class e{constructor(e,t){this.source=e,this.path=t,this.type=z.LISTEN_COMPLETE}operationForChild(t){return O(this.path)?new e(this.source,C()):new e(this.source,E(this.path))}},Gr=class e{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=z.OVERWRITE}operationForChild(t){return O(this.path)?new e(this.source,C(),this.snap.getImmediateChild(t)):new e(this.source,E(this.path),this.snap)}},Kr=class e{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=z.MERGE}operationForChild(t){if(O(this.path)){let n=this.children.subtree(new S(t));return n.isEmpty()?null:n.value?new Gr(this.source,C(),n.value):new e(this.source,C(),n)}return l(w(this.path)===t,`Can't get a merge for a child not on the path of the operation`),new e(this.source,E(this.path),this.children)}toString(){return`Operation(`+this.path+`: `+this.source.toString()+` merge: `+this.children.toString()+`)`}},B=class{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(O(e))return this.isFullyInitialized()&&!this.filtered_;let t=w(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}},qr=class{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}};function Jr(e,t,n,r){let i=[],a=[];return t.forEach(t=>{t.type===`child_changed`&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)&&a.push(mr(t.childName,t.snapshotNode))}),Yr(e,i,`child_removed`,t,r,n),Yr(e,i,`child_added`,t,r,n),Yr(e,i,`child_moved`,a,r,n),Yr(e,i,`child_changed`,t,r,n),Yr(e,i,`value`,t,r,n),i}function Yr(e,t,n,r,i,a){let o=r.filter(e=>e.type===n);o.sort((t,n)=>Zr(e,t,n)),o.forEach(n=>{let r=Xr(e,n,a);i.forEach(i=>{i.respondsTo(n.type)&&t.push(i.createEvent(r,e.query_))})})}function Xr(e,t,n){return t.type===`value`||t.type===`child_removed`||(t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_)),t}function Zr(e,t,n){if(t.childName==null||n.childName==null)throw u(`Should only compare child_ events.`);let r=new M(t.childName,t.snapshotNode),i=new M(n.childName,n.snapshotNode);return e.index_.compare(r,i)}function Qr(e,t){return{eventCache:e,serverCache:t}}function $r(e,t,n,r){return Qr(new B(t,n,r),e.serverCache)}function ei(e,t,n,r){return Qr(e.eventCache,new B(t,n,r))}function ti(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function ni(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}var ri,ii=()=>(ri||=new F(Ke),ri),V=class e{static fromObject(t){let n=new e(null);return b(t,(e,t)=>{n=n.set(new S(e),t)}),n}constructor(e,t=ii()){this.value=e,this.children=t}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(this.value!=null&&t(this.value))return{path:C(),value:this.value};if(O(e))return null;{let n=w(e),r=this.children.get(n);if(r!==null){let i=r.findRootMostMatchingPathAndValue(E(e),t);return i==null?null:{path:D(new S(n),i.path),value:i.value}}return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(t){if(O(t))return this;{let n=w(t),r=this.children.get(n);return r===null?new e(null):r.subtree(E(t))}}set(t,n){if(O(t))return new e(n,this.children);{let r=w(t),i=(this.children.get(r)||new e(null)).set(E(t),n),a=this.children.insert(r,i);return new e(this.value,a)}}remove(t){if(O(t))return this.children.isEmpty()?new e(null):new e(null,this.children);{let n=w(t),r=this.children.get(n);if(r){let i=r.remove(E(t)),a;return a=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),this.value===null&&a.isEmpty()?new e(null):new e(this.value,a)}return this}}get(e){if(O(e))return this.value;{let t=w(e),n=this.children.get(t);return n?n.get(E(e)):null}}setTree(t,n){if(O(t))return n;{let r=w(t),i=(this.children.get(r)||new e(null)).setTree(E(t),n),a;return a=i.isEmpty()?this.children.remove(r):this.children.insert(r,i),new e(this.value,a)}}fold(e){return this.fold_(C(),e)}fold_(e,t){let n={};return this.children.inorderTraversal((r,i)=>{n[r]=i.fold_(D(e,r),t)}),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,C(),t)}findOnPath_(e,t,n){let r=this.value?n(t,this.value):!1;if(r)return r;if(O(e))return null;{let r=w(e),i=this.children.get(r);return i?i.findOnPath_(E(e),D(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,C(),t)}foreachOnPath_(t,n,r){if(O(t))return this;{this.value&&r(n,this.value);let i=w(t),a=this.children.get(i);return a?a.foreachOnPath_(E(t),D(n,i),r):new e(null)}}foreach(e){this.foreach_(C(),e)}foreach_(e,t){this.children.inorderTraversal((n,r)=>{r.foreach_(D(e,n),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,n)=>{n.value&&e(t,n.value)})}},H=class e{constructor(e){this.writeTree_=e}static empty(){return new e(new V(null))}};function ai(e,t,n){if(O(t))return new H(new V(n));{let r=e.writeTree_.findRootMostValueAndPath(t);if(r!=null){let i=r.path,a=r.value,o=k(i,t);return a=a.updateChild(o,n),new H(e.writeTree_.set(i,a))}{let r=new V(n);return new H(e.writeTree_.setTree(t,r))}}}function oi(e,t,n){let r=e;return b(n,(e,n)=>{r=ai(r,D(t,e),n)}),r}function si(e,t){return O(t)?H.empty():new H(e.writeTree_.setTree(t,new V(null)))}function ci(e,t){return li(e,t)!=null}function li(e,t){let n=e.writeTree_.findRootMostValueAndPath(t);return n==null?null:e.writeTree_.get(n.path).getChild(k(n.path,t))}function ui(e){let t=[],n=e.writeTree_.value;return n==null?e.writeTree_.children.inorderTraversal((e,n)=>{n.value!=null&&t.push(new M(e,n.value))}):n.isLeafNode()||n.forEachChild(I,(e,n)=>{t.push(new M(e,n))}),t}function U(e,t){if(O(t))return e;{let n=li(e,t);return n==null?new H(e.writeTree_.subtree(t)):new H(new V(n))}}function di(e){return e.writeTree_.isEmpty()}function fi(e,t){return pi(C(),e.writeTree_,t)}function pi(e,t,n){if(t.value!=null)return n.updateChild(e,t.value);{let r=null;return t.children.inorderTraversal((t,i)=>{t===`.priority`?(l(i.value!==null,`Priority writes must always be leaf nodes`),r=i.value):n=pi(D(e,t),i,n)}),!n.getChild(e).isEmpty()&&r!==null&&(n=n.updateChild(D(e,`.priority`),r)),n}}function mi(e,t){return Li(t,e)}function hi(e,t,n,r,i){l(r>e.lastWriteId,`Stacking an older write on top of newer ones`),i===void 0&&(i=!0),e.allWrites.push({path:t,snap:n,writeId:r,visible:i}),i&&(e.visibleWrites=ai(e.visibleWrites,t,n)),e.lastWriteId=r}function gi(e,t,n,r){l(r>e.lastWriteId,`Stacking an older merge on top of newer ones`),e.allWrites.push({path:t,children:n,writeId:r,visible:!0}),e.visibleWrites=oi(e.visibleWrites,t,n),e.lastWriteId=r}function _i(e,t){for(let n=0;n<e.allWrites.length;n++){let r=e.allWrites[n];if(r.writeId===t)return r}return null}function vi(e,t){let n=e.allWrites.findIndex(e=>e.writeId===t);l(n>=0,`removeWrite called with nonexistent writeId.`);let r=e.allWrites[n];e.allWrites.splice(n,1);let i=r.visible,a=!1,o=e.allWrites.length-1;for(;i&&o>=0;){let t=e.allWrites[o];t.visible&&(o>=n&&yi(t,r.path)?i=!1:A(r.path,t.path)&&(a=!0)),o--}if(!i)return!1;if(a)return bi(e),!0;if(r.snap)e.visibleWrites=si(e.visibleWrites,r.path);else{let t=r.children;b(t,t=>{e.visibleWrites=si(e.visibleWrites,D(r.path,t))})}return!0}function yi(e,t){if(e.snap)return A(e.path,t);for(let n in e.children)if(e.children.hasOwnProperty(n)&&A(D(e.path,n),t))return!0;return!1}function bi(e){e.visibleWrites=Si(e.allWrites,xi,C()),e.lastWriteId=e.allWrites.length>0?e.allWrites[e.allWrites.length-1].writeId:-1}function xi(e){return e.visible}function Si(e,t,n){let r=H.empty();for(let i=0;i<e.length;++i){let a=e[i];if(t(a)){let e=a.path,t;if(a.snap)A(n,e)?(t=k(n,e),r=ai(r,t,a.snap)):A(e,n)&&(t=k(e,n),r=ai(r,C(),a.snap.getChild(t)));else if(a.children){if(A(n,e))t=k(n,e),r=oi(r,t,a.children);else if(A(e,n)){if(t=k(e,n),O(t))r=oi(r,C(),a.children);else{let e=_e(a.children,w(t));if(e){let n=e.getChild(E(t));r=ai(r,C(),n)}}}}else throw u(`WriteRecord should have .snap or .children`)}}return r}function Ci(e,t,n,r,i){if(!r&&!i){let r=li(e.visibleWrites,t);if(r!=null)return r;{let r=U(e.visibleWrites,t);return di(r)?n:n==null&&!ci(r,C())?null:fi(r,n||L.EMPTY_NODE)}}{let a=U(e.visibleWrites,t);return!i&&di(a)?n:!i&&n==null&&!ci(a,C())?null:fi(Si(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(A(e.path,t)||A(t,e.path))},t),n||L.EMPTY_NODE)}}function wi(e,t,n){let r=L.EMPTY_NODE,i=li(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(I,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){let i=U(e.visibleWrites,t);return n.forEachChild(I,(e,t)=>{let n=fi(U(i,new S(e)),t);r=r.updateImmediateChild(e,n)}),ui(i).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return ui(U(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}function Ti(e,t,n,r,i){l(r||i,`Either existingEventSnap or existingServerSnap must exist`);let a=D(t,n);if(ci(e.visibleWrites,a))return null;{let t=U(e.visibleWrites,a);return di(t)?i.getChild(n):fi(t,i.getChild(n))}}function Ei(e,t,n,r){let i=D(t,n);return li(e.visibleWrites,i)??(r.isCompleteForChild(n)?fi(U(e.visibleWrites,i),r.getNode().getImmediateChild(n)):null)}function Di(e,t){return li(e.visibleWrites,t)}function Oi(e,t,n,r,i,a,o){let s,c=U(e.visibleWrites,t),l=li(c,C());if(l!=null)s=l;else if(n!=null)s=fi(c,n);else return[];if(s=s.withIndex(o),!s.isEmpty()&&!s.isLeafNode()){let e=[],t=o.getCompare(),n=a?s.getReverseIteratorFrom(r,o):s.getIteratorFrom(r,o),c=n.getNext();for(;c&&e.length<i;)t(c,r)!==0&&e.push(c),c=n.getNext();return e}return[]}function ki(){return{visibleWrites:H.empty(),allWrites:[],lastWriteId:-1}}function Ai(e,t,n,r){return Ci(e.writeTree,e.treePath,t,n,r)}function ji(e,t){return wi(e.writeTree,e.treePath,t)}function Mi(e,t,n,r){return Ti(e.writeTree,e.treePath,t,n,r)}function Ni(e,t){return Di(e.writeTree,D(e.treePath,t))}function Pi(e,t,n,r,i,a){return Oi(e.writeTree,e.treePath,t,n,r,i,a)}function Fi(e,t,n){return Ei(e.writeTree,e.treePath,t,n)}function Ii(e,t){return Li(D(e.treePath,t),e.writeTree)}function Li(e,t){return{treePath:e,writeTree:t}}var Ri=class{constructor(){this.changeMap=new Map}trackChildChange(e){let t=e.type,n=e.childName;l(t===`child_added`||t===`child_changed`||t===`child_removed`,`Only child changes supported for tracking`),l(n!==`.priority`,`Only non-priority child changes can be tracked.`);let r=this.changeMap.get(n);if(r){let i=r.type;if(t===`child_added`&&i===`child_removed`)this.changeMap.set(n,pr(n,e.snapshotNode,r.snapshotNode));else if(t===`child_removed`&&i===`child_added`)this.changeMap.delete(n);else if(t===`child_removed`&&i===`child_changed`)this.changeMap.set(n,fr(n,r.oldSnap));else if(t===`child_changed`&&i===`child_added`)this.changeMap.set(n,dr(n,e.snapshotNode));else if(t===`child_changed`&&i===`child_changed`)this.changeMap.set(n,pr(n,e.snapshotNode,r.oldSnap));else throw u(`Illegal combination of changes: `+e+` occurred after `+r)}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}},zi=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}},Bi=class{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){let t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{let t=this.optCompleteServerCache_==null?this.viewCache_.serverCache:new B(this.optCompleteServerCache_,!0,!1);return Fi(this.writes_,e,t)}}getChildAfterChild(e,t,n){let r=this.optCompleteServerCache_==null?ni(this.viewCache_):this.optCompleteServerCache_,i=Pi(this.writes_,r,t,1,n,e);return i.length===0?null:i[0]}};function Vi(e){return{filter:e}}function Hi(e,t){l(t.eventCache.getNode().isIndexed(e.filter.getIndex()),`Event snap not indexed`),l(t.serverCache.getNode().isIndexed(e.filter.getIndex()),`Server snap not indexed`)}function Ui(e,t,n,r,i){let a=new Ri,o,s;if(n.type===z.OVERWRITE){let c=n;c.source.fromUser?o=qi(e,t,c.path,c.snap,r,i,a):(l(c.source.fromServer,`Unknown source.`),s=c.source.tagged||t.serverCache.isFiltered()&&!O(c.path),o=Ki(e,t,c.path,c.snap,r,i,s,a))}else if(n.type===z.MERGE){let c=n;c.source.fromUser?o=Yi(e,t,c.path,c.children,r,i,a):(l(c.source.fromServer,`Unknown source.`),s=c.source.tagged||t.serverCache.isFiltered(),o=Zi(e,t,c.path,c.children,r,i,s,a))}else if(n.type===z.ACK_USER_WRITE){let s=n;o=s.revert?ea(e,t,s.path,r,i,a):Qi(e,t,s.path,s.affectedTree,r,i,a)}else if(n.type===z.LISTEN_COMPLETE)o=$i(e,t,n.path,r,a);else throw u(`Unknown operation type: `+n.type);let c=a.getChanges();return Wi(t,o,c),{viewCache:o,changes:c}}function Wi(e,t,n){let r=t.eventCache;if(r.isFullyInitialized()){let i=r.getNode().isLeafNode()||r.getNode().isEmpty(),a=ti(e);(n.length>0||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(a)||!r.getNode().getPriority().equals(a.getPriority()))&&n.push(ur(ti(t)))}}function Gi(e,t,n,r,i,a){let o=t.eventCache;if(Ni(r,n)!=null)return t;{let s,c;if(O(n)){if(l(t.serverCache.isFullyInitialized(),`If change path is empty, we must have complete server data`),t.serverCache.isFiltered()){let n=ni(t),i=ji(r,n instanceof L?n:L.EMPTY_NODE);s=e.filter.updateFullNode(t.eventCache.getNode(),i,a)}else{let n=Ai(r,ni(t));s=e.filter.updateFullNode(t.eventCache.getNode(),n,a)}}else{let u=w(n);if(u===`.priority`){l(T(n)===1,`Can't have a priority with additional path components`);let i=o.getNode();c=t.serverCache.getNode();let a=Mi(r,n,i,c);s=a==null?o.getNode():e.filter.updatePriority(i,a)}else{let l=E(n),d;if(o.isCompleteForChild(u)){c=t.serverCache.getNode();let e=Mi(r,n,o.getNode(),c);d=e==null?o.getNode().getImmediateChild(u):o.getNode().getImmediateChild(u).updateChild(l,e)}else d=Fi(r,u,t.serverCache);s=d==null?o.getNode():e.filter.updateChild(o.getNode(),u,d,l,i,a)}}return $r(t,s,o.isFullyInitialized()||O(n),e.filter.filtersNodes())}}function Ki(e,t,n,r,i,a,o,s){let c=t.serverCache,l,u=o?e.filter:e.filter.getIndexedFilter();if(O(n))l=u.updateFullNode(c.getNode(),r,null);else if(u.filtersNodes()&&!c.isFiltered()){let e=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),e,null)}else{let e=w(n);if(!c.isCompleteForPath(n)&&T(n)>1)return t;let i=E(n),a=c.getNode().getImmediateChild(e).updateChild(i,r);l=e===`.priority`?u.updatePriority(c.getNode(),a):u.updateChild(c.getNode(),e,a,i,zi,null)}let d=ei(t,l,c.isFullyInitialized()||O(n),u.filtersNodes());return Gi(e,d,n,i,new Bi(i,d,a),s)}function qi(e,t,n,r,i,a,o){let s=t.eventCache,c,l,u=new Bi(i,t,a);if(O(n))l=e.filter.updateFullNode(t.eventCache.getNode(),r,o),c=$r(t,l,!0,e.filter.filtersNodes());else{let i=w(n);if(i===`.priority`)l=e.filter.updatePriority(t.eventCache.getNode(),r),c=$r(t,l,s.isFullyInitialized(),s.isFiltered());else{let a=E(n),l=s.getNode().getImmediateChild(i),d;if(O(a))d=r;else{let e=u.getCompleteChild(i);d=e==null?L.EMPTY_NODE:_n(a)===`.priority`&&e.getChild(bn(a)).isEmpty()?e:e.updateChild(a,r)}c=l.equals(d)?t:$r(t,e.filter.updateChild(s.getNode(),i,d,a,u,o),s.isFullyInitialized(),e.filter.filtersNodes())}}return c}function Ji(e,t){return e.eventCache.isCompleteForChild(t)}function Yi(e,t,n,r,i,a,o){let s=t;return r.foreach((r,c)=>{let l=D(n,r);Ji(t,w(l))&&(s=qi(e,s,l,c,i,a,o))}),r.foreach((r,c)=>{let l=D(n,r);Ji(t,w(l))||(s=qi(e,s,l,c,i,a,o))}),s}function Xi(e,t,n){return n.foreach((e,n)=>{t=t.updateChild(e,n)}),t}function Zi(e,t,n,r,i,a,o,s){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let c=t,l;l=O(n)?r:new V(null).setTree(n,r);let u=t.serverCache.getNode();return l.children.inorderTraversal((n,r)=>{if(u.hasChild(n)){let l=Xi(e,t.serverCache.getNode().getImmediateChild(n),r);c=Ki(e,c,new S(n),l,i,a,o,s)}}),l.children.inorderTraversal((n,r)=>{let l=!t.serverCache.isCompleteForChild(n)&&r.value===null;if(!u.hasChild(n)&&!l){let l=Xi(e,t.serverCache.getNode().getImmediateChild(n),r);c=Ki(e,c,new S(n),l,i,a,o,s)}}),c}function Qi(e,t,n,r,i,a,o){if(Ni(i,n)!=null)return t;let s=t.serverCache.isFiltered(),c=t.serverCache;if(r.value!=null){if(O(n)&&c.isFullyInitialized()||c.isCompleteForPath(n))return Ki(e,t,n,c.getNode().getChild(n),i,a,s,o);if(O(n)){let r=new V(null);return c.getNode().forEachChild(N,(e,t)=>{r=r.set(new S(e),t)}),Zi(e,t,n,r,i,a,s,o)}return t}{let l=new V(null);return r.foreach((e,t)=>{let r=D(n,e);c.isCompleteForPath(r)&&(l=l.set(e,c.getNode().getChild(r)))}),Zi(e,t,n,l,i,a,s,o)}}function $i(e,t,n,r,i){let a=t.serverCache;return Gi(e,ei(t,a.getNode(),a.isFullyInitialized()||O(n),a.isFiltered()),n,r,zi,i)}function ea(e,t,n,r,i,a){let o;if(Ni(r,n)!=null)return t;{let s=new Bi(r,t,i),c=t.eventCache.getNode(),u;if(O(n)||w(n)===`.priority`){let n;if(t.serverCache.isFullyInitialized())n=Ai(r,ni(t));else{let e=t.serverCache.getNode();l(e instanceof L,`serverChildren would be complete if leaf node`),n=ji(r,e)}n=n,u=e.filter.updateFullNode(c,n,a)}else{let i=w(n),l=Fi(r,i,t.serverCache);l==null&&t.serverCache.isCompleteForChild(i)&&(l=c.getImmediateChild(i)),u=l==null?t.eventCache.getNode().hasChild(i)?e.filter.updateChild(c,i,L.EMPTY_NODE,E(n),s,a):c:e.filter.updateChild(c,i,l,E(n),s,a),u.isEmpty()&&t.serverCache.isFullyInitialized()&&(o=Ai(r,ni(t)),o.isLeafNode()&&(u=e.filter.updateFullNode(u,o,a)))}return o=t.serverCache.isFullyInitialized()||Ni(r,C())!=null,$r(t,u,o,e.filter.filtersNodes())}}var ta=class{constructor(e,t){this.query_=e,this.eventRegistrations_=[];let n=this.query_._queryParams,r=new hr(n.getIndex()),i=yr(n);this.processor_=Vi(i);let a=t.serverCache,o=t.eventCache,s=r.updateFullNode(L.EMPTY_NODE,a.getNode(),null),c=i.updateFullNode(L.EMPTY_NODE,o.getNode(),null),l=new B(s,a.isFullyInitialized(),r.filtersNodes()),u=new B(c,o.isFullyInitialized(),i.filtersNodes());this.viewCache_=Qr(u,l),this.eventGenerator_=new qr(this.query_)}get query(){return this.query_}};function na(e){return e.viewCache_.serverCache.getNode()}function ra(e){return ti(e.viewCache_)}function ia(e,t){let n=ni(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!O(t)&&!n.getImmediateChild(w(t)).isEmpty())?n.getChild(t):null}function aa(e){return e.eventRegistrations_.length===0}function oa(e,t){e.eventRegistrations_.push(t)}function sa(e,t,n){let r=[];if(n){l(t==null,`A cancel should cancel all event registrations.`);let i=e.query._path;e.eventRegistrations_.forEach(e=>{let t=e.createCancelEvent(n,i);t&&r.push(t)})}if(t){let n=[];for(let r=0;r<e.eventRegistrations_.length;++r){let i=e.eventRegistrations_[r];if(!i.matches(t))n.push(i);else if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(r+1));break}}e.eventRegistrations_=n}else e.eventRegistrations_=[];return r}function ca(e,t,n,r){t.type===z.MERGE&&t.source.queryId!==null&&(l(ni(e.viewCache_),`We should always have a full cache before handling merges`),l(ti(e.viewCache_),`Missing event cache, even though we have a server cache`));let i=e.viewCache_,a=Ui(e.processor_,i,t,n,r);return Hi(e.processor_,a.viewCache),l(a.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),`Once a server snap is complete, it should never go back`),e.viewCache_=a.viewCache,ua(e,a.changes,a.viewCache.eventCache.getNode(),null)}function la(e,t){let n=e.viewCache_.eventCache,r=[];return n.getNode().isLeafNode()||n.getNode().forEachChild(I,(e,t)=>{r.push(dr(e,t))}),n.isFullyInitialized()&&r.push(ur(n.getNode())),ua(e,r,n.getNode(),t)}function ua(e,t,n,r){let i=r?[r]:e.eventRegistrations_;return Jr(e.eventGenerator_,t,n,i)}var da,fa=class{constructor(){this.views=new Map}};function pa(e){l(!da,`__referenceConstructor has already been defined`),da=e}function ma(){return l(da,`Reference.ts has not been loaded`),da}function ha(e){return e.views.size===0}function ga(e,t,n,r){let i=t.source.queryId;if(i!==null){let a=e.views.get(i);return l(a!=null,`SyncTree gave us an op for an invalid query.`),ca(a,t,n,r)}{let i=[];for(let a of e.views.values())i=i.concat(ca(a,t,n,r));return i}}function _a(e,t,n,r,i){let a=t._queryIdentifier,o=e.views.get(a);if(!o){let e=Ai(n,i?r:null),a=!1;return e?a=!0:r instanceof L?(e=ji(n,r),a=!1):(e=L.EMPTY_NODE,a=!1),new ta(t,Qr(new B(e,a,!1),new B(r,i,!1)))}return o}function va(e,t,n,r,i,a){let o=_a(e,t,r,i,a);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),oa(o,n),la(o,n)}function ya(e,t,n,r){let i=t._queryIdentifier,a=[],o=[],s=G(e);if(i==="default")for(let[t,i]of e.views.entries())o=o.concat(sa(i,n,r)),aa(i)&&(e.views.delete(t),i.query._queryParams.loadsAllData()||a.push(i.query));else{let t=e.views.get(i);t&&(o=o.concat(sa(t,n,r)),aa(t)&&(e.views.delete(i),t.query._queryParams.loadsAllData()||a.push(t.query)))}return s&&!G(e)&&a.push(new(ma())(t._repo,t._path)),{removed:a,events:o}}function ba(e){let t=[];for(let n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function W(e,t){let n=null;for(let r of e.views.values())n||=ia(r,t);return n}function xa(e,t){if(t._queryParams.loadsAllData())return Ca(e);{let n=t._queryIdentifier;return e.views.get(n)}}function Sa(e,t){return xa(e,t)!=null}function G(e){return Ca(e)!=null}function Ca(e){for(let t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}var wa;function Ta(e){l(!wa,`__referenceConstructor has already been defined`),wa=e}function Ea(){return l(wa,`Reference.ts has not been loaded`),wa}var Da=1,Oa=class{constructor(e){this.listenProvider_=e,this.syncPointTree_=new V(null),this.pendingWriteTree_=ki(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}};function ka(e,t,n,r,i){return hi(e.pendingWriteTree_,t,n,r,i),i?Va(e,new Gr(Br(),t,n)):[]}function Aa(e,t,n,r){gi(e.pendingWriteTree_,t,n,r);let i=V.fromObject(n);return Va(e,new Kr(Br(),t,i))}function K(e,t,n=!1){let r=_i(e.pendingWriteTree_,t);if(vi(e.pendingWriteTree_,t)){let t=new V(null);return r.snap==null?b(r.children,e=>{t=t.set(new S(e),!0)}):t=t.set(C(),!0),Va(e,new Ur(r.path,t,n))}return[]}function ja(e,t,n){return Va(e,new Gr(Vr(),t,n))}function Ma(e,t,n){let r=V.fromObject(n);return Va(e,new Kr(Vr(),t,r))}function Na(e,t){return Va(e,new Wr(Vr(),t))}function Pa(e,t,n){let r=qa(e,n);if(r){let n=Ja(r),i=n.path,a=n.queryId,o=k(i,t);return Ya(e,i,new Wr(Hr(a),o))}return[]}function Fa(e,t,n,r,i=!1){let a=t._path,o=e.syncPointTree_.get(a),s=[];if(o&&(t._queryIdentifier==="default"||Sa(o,t))){let c=ya(o,t,n,r);ha(o)&&(e.syncPointTree_=e.syncPointTree_.remove(a));let l=c.removed;if(s=c.events,!i){let n=l.findIndex(e=>e._queryParams.loadsAllData())!==-1,i=e.syncPointTree_.findOnPath(a,(e,t)=>G(t));if(n&&!i){let t=e.syncPointTree_.subtree(a);if(!t.isEmpty()){let n=Xa(t);for(let t=0;t<n.length;++t){let r=n[t],i=r.query,a=Wa(e,r);e.listenProvider_.startListening(Za(i),Ga(e,i),a.hashFn,a.onComplete)}}}!i&&l.length>0&&!r&&(n?e.listenProvider_.stopListening(Za(t),null):l.forEach(t=>{let n=e.queryToTagMap.get(Ka(t));e.listenProvider_.stopListening(Za(t),n)}))}Qa(e,l)}return s}function Ia(e,t,n,r){let i=qa(e,r);if(i!=null){let r=Ja(i),a=r.path,o=r.queryId,s=k(a,t);return Ya(e,a,new Gr(Hr(o),s,n))}return[]}function La(e,t,n,r){let i=qa(e,r);if(i){let r=Ja(i),a=r.path,o=r.queryId,s=k(a,t),c=V.fromObject(n);return Ya(e,a,new Kr(Hr(o),s,c))}return[]}function Ra(e,t,n,r=!1){let i=t._path,a=null,o=!1;e.syncPointTree_.foreachOnPath(i,(e,t)=>{let n=k(e,i);a||=W(t,n),o||=G(t)});let s=e.syncPointTree_.get(i);s?(o||=G(s),a||=W(s,C())):(s=new fa,e.syncPointTree_=e.syncPointTree_.set(i,s));let c;a==null?(c=!1,a=L.EMPTY_NODE,e.syncPointTree_.subtree(i).foreachChild((e,t)=>{let n=W(t,C());n&&(a=a.updateImmediateChild(e,n))})):c=!0;let u=Sa(s,t);if(!u&&!t._queryParams.loadsAllData()){let n=Ka(t);l(!e.queryToTagMap.has(n),`View does not exist, but we have a tag`);let r=$a();e.queryToTagMap.set(n,r),e.tagToQueryMap.set(r,n)}let d=mi(e.pendingWriteTree_,i),f=va(s,t,n,d,a,c);if(!u&&!o&&!r){let n=xa(s,t);f=f.concat(eo(e,t,n))}return f}function za(e,t,n){let r=e.pendingWriteTree_;return Ci(r,t,e.syncPointTree_.findOnPath(t,(e,n)=>{let r=W(n,k(e,t));if(r)return r}),n,!0)}function Ba(e,t){let n=t._path,r=null;e.syncPointTree_.foreachOnPath(n,(e,t)=>{let i=k(e,n);r||=W(t,i)});let i=e.syncPointTree_.get(n);i?r||=W(i,C()):(i=new fa,e.syncPointTree_=e.syncPointTree_.set(n,i));let a=r!=null,o=a?new B(r,!0,!1):null,s=mi(e.pendingWriteTree_,t._path);return ra(_a(i,t,s,a?o.getNode():L.EMPTY_NODE,a))}function Va(e,t){return Ha(t,e.syncPointTree_,null,mi(e.pendingWriteTree_,C()))}function Ha(e,t,n,r){if(O(e.path))return Ua(e,t,n,r);{let i=t.get(C());n==null&&i!=null&&(n=W(i,C()));let a=[],o=w(e.path),s=e.operationForChild(o),c=t.children.get(o);if(c&&s){let e=n?n.getImmediateChild(o):null,t=Ii(r,o);a=a.concat(Ha(s,c,e,t))}return i&&(a=a.concat(ga(i,e,r,n))),a}}function Ua(e,t,n,r){let i=t.get(C());n==null&&i!=null&&(n=W(i,C()));let a=[];return t.children.inorderTraversal((t,i)=>{let o=n?n.getImmediateChild(t):null,s=Ii(r,t),c=e.operationForChild(t);c&&(a=a.concat(Ua(c,i,o,s)))}),i&&(a=a.concat(ga(i,e,r,n))),a}function Wa(e,t){let n=t.query,r=Ga(e,n);return{hashFn:()=>(na(t)||L.EMPTY_NODE).hash(),onComplete:t=>{if(t===`ok`)return r?Pa(e,n._path,r):Na(e,n._path);{let r=$e(t,n);return Fa(e,n,null,r)}}}}function Ga(e,t){let n=Ka(t);return e.queryToTagMap.get(n)}function Ka(e){return e._path.toString()+`$`+e._queryIdentifier}function qa(e,t){return e.tagToQueryMap.get(t)}function Ja(e){let t=e.indexOf(`$`);return l(t!==-1&&t<e.length-1,`Bad queryKey.`),{queryId:e.substr(t+1),path:new S(e.substr(0,t))}}function Ya(e,t,n){let r=e.syncPointTree_.get(t);return l(r,`Missing sync point for query tag that we're tracking`),ga(r,n,mi(e.pendingWriteTree_,t),null)}function Xa(e){return e.fold((e,t,n)=>{if(t&&G(t))return[Ca(t)];{let e=[];return t&&(e=ba(t)),b(n,(t,n)=>{e=e.concat(n)}),e}})}function Za(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new(Ea())(e._repo,e._path):e}function Qa(e,t){for(let n=0;n<t.length;++n){let r=t[n];if(!r._queryParams.loadsAllData()){let t=Ka(r),n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t),e.tagToQueryMap.delete(n)}}}function $a(){return Da++}function eo(e,t,n){let r=t._path,i=Ga(e,t),a=Wa(e,n),o=e.listenProvider_.startListening(Za(t),i,a.hashFn,a.onComplete),s=e.syncPointTree_.subtree(r);if(i)l(!G(s.value),`If we're adding a query, it shouldn't be shadowed`);else{let t=s.fold((e,t,n)=>{if(!O(e)&&t&&G(t))return[Ca(t).query];{let e=[];return t&&(e=e.concat(ba(t).map(e=>e.query))),b(n,(t,n)=>{e=e.concat(n)}),e}});for(let n=0;n<t.length;++n){let r=t[n];e.listenProvider_.stopListening(Za(r),Ga(e,r))}}return o}var to=class e{constructor(e){this.node_=e}getImmediateChild(t){let n=this.node_.getImmediateChild(t);return new e(n)}node(){return this.node_}},no=class e{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(t){let n=D(this.path_,t);return new e(this.syncTree_,n)}node(){return za(this.syncTree_,this.path_)}},ro=function(e){return e||={},e.timestamp=e.timestamp||new Date().getTime(),e},io=function(e,t,n){if(!e||typeof e!=`object`)return e;if(l(`.sv`in e,`Unexpected leaf node or priority contents`),typeof e[`.sv`]==`string`)return ao(e[`.sv`],t,n);if(typeof e[`.sv`]==`object`)return oo(e[`.sv`],t);l(!1,`Unexpected server value: `+JSON.stringify(e,null,2))},ao=function(e,t,n){switch(e){case`timestamp`:return n.timestamp;default:l(!1,`Unexpected server value: `+e)}},oo=function(e,t,n){e.hasOwnProperty(`increment`)||l(!1,`Unexpected server value: `+JSON.stringify(e,null,2));let r=e.increment;typeof r!=`number`&&l(!1,`Unexpected increment value: `+r);let i=t.node();if(l(i!=null,`Expected ChildrenNode.EMPTY_NODE for nulls`),!i.isLeafNode())return r;let a=i.getValue();return typeof a==`number`?a+r:r},so=function(e,t,n,r){return lo(t,new no(n,e),r)},co=function(e,t,n){return lo(e,new to(t),n)};function lo(e,t,n){let r=io(e.getPriority().val(),t.getImmediateChild(`.priority`),n),i;if(e.isLeafNode()){let i=e,a=io(i.getValue(),t,n);return a!==i.getValue()||r!==i.getPriority().val()?new Jn(a,R(r)):e}{let a=e;return i=a,r!==a.getPriority().val()&&(i=i.updatePriority(new Jn(r))),a.forEachChild(I,(e,r)=>{let a=lo(r,t.getImmediateChild(e),n);a!==r&&(i=i.updateImmediateChild(e,a))}),i}}var uo=class{constructor(e=``,t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}};function fo(e,t){let n=t instanceof S?t:new S(t),r=e,i=w(n);for(;i!==null;){let e=_e(r.node.children,i)||{children:{},childCount:0};r=new uo(i,r,e),n=E(n),i=w(n)}return r}function po(e){return e.node.value}function mo(e,t){e.node.value=t,xo(e)}function ho(e){return e.node.childCount>0}function go(e){return po(e)===void 0&&!ho(e)}function _o(e,t){b(e.node.children,(n,r)=>{t(new uo(n,e,r))})}function vo(e,t,n,r){n&&t(e),_o(e,e=>{vo(e,t,!0)})}function yo(e,t,n){let r=e.parent;for(;r!==null;){if(t(r))return!0;r=r.parent}return!1}function bo(e){return new S(e.parent===null?e.name:bo(e.parent)+`/`+e.name)}function xo(e){e.parent!==null&&So(e.parent,e.name,e)}function So(e,t,n){let r=go(n),i=c(e.node.children,t);r&&i?(delete e.node.children[t],e.node.childCount--,xo(e)):!r&&!i&&(e.node.children[t]=n.node,e.node.childCount++,xo(e))}var Co=/[\[\].#$\/\u0000-\u001F\u007F]/,wo=/[\[\].#$\u0000-\u001F\u007F]/,To=10485760,Eo=function(e){return typeof e==`string`&&e.length!==0&&!Co.test(e)},Do=function(e){return typeof e==`string`&&e.length!==0&&!wo.test(e)},Oo=function(e){return e&&=e.replace(/^\/*\.info(\/|$)/,`/`),Do(e)},ko=function(e){return e===null||typeof e==`string`||typeof e==`number`&&!Ue(e)||e&&typeof e==`object`&&c(e,`.sv`)},q=function(e,t,n,r){r&&t===void 0||Ao(a(e,`value`),t,n)},Ao=function(e,t,n){let r=n instanceof S?new Cn(n,e):n;if(t===void 0)throw Error(e+`contains undefined `+Dn(r));if(typeof t==`function`)throw Error(e+`contains a function `+Dn(r)+` with contents = `+t.toString());if(Ue(t))throw Error(e+`contains `+t.toString()+` `+Dn(r));if(typeof t==`string`&&t.length>To/3&&me(t)>To)throw Error(e+`contains a string greater than 10485760 utf8 bytes `+Dn(r)+` ('`+t.substring(0,50)+`...')`);if(t&&typeof t==`object`){let n=!1,i=!1;if(b(t,(t,a)=>{if(t===`.value`)n=!0;else if(t!==`.priority`&&t!==`.sv`&&(i=!0,!Eo(t)))throw Error(e+` contains an invalid key (`+t+`) `+Dn(r)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);wn(r,t),Ao(e,a,r),Tn(r)}),n&&i)throw Error(e+` contains ".value" child `+Dn(r)+` in addition to actual children.`)}},jo=function(e,t){let n,r;for(n=0;n<t.length;n++){r=t[n];let i=yn(r);for(let t=0;t<i.length;t++)if((i[t]!==`.priority`||t!==i.length-1)&&!Eo(i[t]))throw Error(e+`contains an invalid key (`+i[t]+`) in path `+r.toString()+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`)}t.sort(xn);let i=null;for(n=0;n<t.length;n++){if(r=t[n],i!==null&&A(i,r))throw Error(e+`contains a path `+i.toString()+` that is ancestor of another path `+r.toString());i=r}},Mo=function(e,t,n,r){let i=a(e,`values`);if(!(t&&typeof t==`object`)||Array.isArray(t))throw Error(i+` must be an object containing the children to replace.`);let o=[];b(t,(e,t)=>{let r=new S(e);if(Ao(i,t,D(n,r)),_n(r)===`.priority`&&!ko(t))throw Error(i+`contains an invalid value for '`+r.toString()+`', which must be a valid Firebase priority (a string, finite number, server value, or null).`);o.push(r)}),jo(i,o)},No=function(e,t,n){if(Ue(t))throw Error(a(e,`priority`)+`is `+t.toString()+`, but must be a valid Firebase priority (a string, finite number, server value, or null).`);if(!ko(t))throw Error(a(e,`priority`)+`must be a valid Firebase priority (a string, finite number, server value, or null).`)},Po=function(e,t,n,r){if(n!==void 0&&!Eo(n))throw Error(a(e,t)+`was an invalid key = "`+n+`". Firebase keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]").`)},Fo=function(e,t,n,r){if(!(r&&n===void 0)&&!Do(n))throw Error(a(e,t)+`was an invalid path = "`+n+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Io=function(e,t,n,r){n&&=n.replace(/^\/*\.info(\/|$)/,`/`),Fo(e,t,n,r)},J=function(e,t){if(w(t)===`.info`)throw Error(e+` failed = Can't modify data under /.info/`)},Lo=function(e,t){let n=t.path.toString();if(typeof t.repoInfo.host!=`string`||t.repoInfo.host.length===0||!Eo(t.repoInfo.namespace)&&t.repoInfo.host.split(`:`)[0]!==`localhost`||n.length!==0&&!Oo(n))throw Error(a(e,`url`)+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)},Ro=class{constructor(){this.eventLists_=[],this.recursionDepth_=0}};function zo(e,t){let n=null;for(let r=0;r<t.length;r++){let i=t[r],a=i.getPath();n!==null&&!Sn(a,n.path)&&(e.eventLists_.push(n),n=null),n===null&&(n={events:[],path:a}),n.events.push(i)}n&&e.eventLists_.push(n)}function Bo(e,t,n){zo(e,n),Vo(e,e=>Sn(e,t))}function Y(e,t,n){zo(e,n),Vo(e,e=>A(e,t)||A(t,e))}function Vo(e,t){e.recursionDepth_++;let n=!0;for(let r=0;r<e.eventLists_.length;r++){let i=e.eventLists_[r];if(i){let a=i.path;t(a)?(Ho(e.eventLists_[r]),e.eventLists_[r]=null):n=!1}}n&&(e.eventLists_=[]),e.recursionDepth_--}function Ho(e){for(let t=0;t<e.events.length;t++){let n=e.events[t];if(n!==null){e.events[t]=null;let r=n.getEventRunner();Le&&h(`event: `+n.toString()),it(r)}}}var Uo=`repo_interrupt`,Wo=25,Go=class{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Ro,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=jr(),this.transactionQueueTree_=new uo,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?`https://`:`http://`)+this.repoInfo_.host}};function Ko(e,t,n){if(e.stats_=Dt(e.repoInfo_),e.forceRestClient_||at())e.server_=new kr(e.repoInfo_,(t,n,r,i)=>{Yo(e,t,n,r,i)},e.authTokenProvider_,e.appCheckProvider_),setTimeout(()=>Xo(e,!0),0);else{if(n!=null){if(typeof n!=`object`)throw Error(`Only objects are supported for option databaseAuthVariableOverride`);try{p(n)}catch(e){throw Error(`Invalid authOverride provided: `+e)}}e.persistentConnection_=new j(e.repoInfo_,t,(t,n,r,i)=>{Yo(e,t,n,r,i)},t=>{Xo(e,t)},t=>{Zo(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_=Ot(e.repoInfo_,()=>new zr(e.stats_,e.server_)),e.infoData_=new Ar,e.infoSyncTree_=new Oa({startListening:(t,n,r,i)=>{let a=[],o=e.infoData_.getNode(t._path);return o.isEmpty()||(a=ja(e.infoSyncTree_,t._path,o),setTimeout(()=>{i(`ok`)},0)),a},stopListening:()=>{}}),Qo(e,`connected`,!1),e.serverSyncTree_=new Oa({startListening:(t,n,r,i)=>(e.server_.listen(t,r,n,(n,r)=>{let a=i(n,r);Y(e.eventQueue_,t._path,a)}),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function qo(e){let t=e.infoData_.getNode(new S(`.info/serverTimeOffset`)).val()||0;return new Date().getTime()+t}function Jo(e){return ro({timestamp:qo(e)})}function Yo(e,t,n,r,i){e.dataUpdateCount++;let a=new S(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(i){if(r){let t=xe(n,e=>R(e));o=La(e.serverSyncTree_,a,t,i)}else{let t=R(n);o=Ia(e.serverSyncTree_,a,t,i)}}else if(r){let t=xe(n,e=>R(e));o=Ma(e.serverSyncTree_,a,t)}else{let t=R(n);o=ja(e.serverSyncTree_,a,t)}let s=a;o.length>0&&(s=_s(e,a)),Y(e.eventQueue_,s,o)}function Xo(e,t){Qo(e,`connected`,t),t===!1&&rs(e)}function Zo(e,t){b(t,(t,n)=>{Qo(e,t,n)})}function Qo(e,t,n){let r=new S(`/.info/`+t),i=R(n);e.infoData_.updateSnapshot(r,i);let a=ja(e.infoSyncTree_,r,i);Y(e.eventQueue_,r,a)}function $o(e){return e.nextWriteId_++}function es(e,t,n){let r=Ba(e.serverSyncTree_,t);return r==null?e.server_.get(t).then(r=>{let i=R(r).withIndex(t._queryParams.getIndex());Ra(e.serverSyncTree_,t,n,!0);let a;if(t._queryParams.loadsAllData())a=ja(e.serverSyncTree_,t._path,i);else{let n=Ga(e.serverSyncTree_,t);a=Ia(e.serverSyncTree_,t._path,i,n)}return Y(e.eventQueue_,t._path,a),Fa(e.serverSyncTree_,t,n,null,!0),i},n=>(fs(e,`get for query `+p(t)+` failed: `+n),Promise.reject(Error(n)))):Promise.resolve(r)}function ts(e,t,n,r,i){fs(e,`set`,{path:t.toString(),value:n,priority:r});let a=Jo(e),o=R(n,r),s=co(o,za(e.serverSyncTree_,t),a),c=$o(e),l=ka(e.serverSyncTree_,t,s,c,!0);zo(e.eventQueue_,l),e.server_.put(t.toString(),o.val(!0),(n,r)=>{let a=n===`ok`;a||_(`set at `+t+` failed: `+n);let o=K(e.serverSyncTree_,c,!a);Y(e.eventQueue_,t,o),X(e,i,n,r)});let u=Cs(e,t);_s(e,u),Y(e.eventQueue_,u,[])}function ns(e,t,n,r){fs(e,`update`,{path:t.toString(),value:n});let i=!0,a=Jo(e),o={};if(b(n,(n,r)=>{i=!1,o[n]=so(D(t,n),R(r),e.serverSyncTree_,a)}),i)h(`update() called with empty data. Don't do anything.`),X(e,r,`ok`,void 0);else{let i=$o(e),a=Aa(e.serverSyncTree_,t,o,i);zo(e.eventQueue_,a),e.server_.merge(t.toString(),n,(n,a)=>{let o=n===`ok`;o||_(`update at `+t+` failed: `+n);let s=K(e.serverSyncTree_,i,!o),c=s.length>0?_s(e,t):t;Y(e.eventQueue_,c,s),X(e,r,n,a)}),b(n,n=>{_s(e,Cs(e,D(t,n)))}),Y(e.eventQueue_,t,[])}}function rs(e){fs(e,`onDisconnectEvents`);let t=Jo(e),n=jr();Pr(e.onDisconnect_,C(),(r,i)=>{let a=so(r,i,e.serverSyncTree_,t);Mr(n,r,a)});let r=[];Pr(n,C(),(t,n)=>{r=r.concat(ja(e.serverSyncTree_,t,n)),_s(e,Cs(e,t))}),e.onDisconnect_=jr(),Y(e.eventQueue_,C(),r)}function is(e,t,n){e.server_.onDisconnectCancel(t.toString(),(r,i)=>{r===`ok`&&Nr(e.onDisconnect_,t),X(e,n,r,i)})}function as(e,t,n,r){let i=R(n);e.server_.onDisconnectPut(t.toString(),i.val(!0),(n,a)=>{n===`ok`&&Mr(e.onDisconnect_,t,i),X(e,r,n,a)})}function os(e,t,n,r,i){let a=R(n,r);e.server_.onDisconnectPut(t.toString(),a.val(!0),(n,r)=>{n===`ok`&&Mr(e.onDisconnect_,t,a),X(e,i,n,r)})}function ss(e,t,n,r){le(n)?(h(`onDisconnect().update() called with empty data. Don't do anything.`),X(e,r,`ok`,void 0)):e.server_.onDisconnectMerge(t.toString(),n,(i,a)=>{i===`ok`&&b(n,(n,r)=>{let i=R(r);Mr(e.onDisconnect_,D(t,n),i)}),X(e,r,i,a)})}function cs(e,t,n){let r;r=w(t._path)===`.info`?Ra(e.infoSyncTree_,t,n):Ra(e.serverSyncTree_,t,n),Bo(e.eventQueue_,t._path,r)}function ls(e,t,n){let r;r=w(t._path)===`.info`?Fa(e.infoSyncTree_,t,n):Fa(e.serverSyncTree_,t,n),Bo(e.eventQueue_,t._path,r)}function us(e){e.persistentConnection_&&e.persistentConnection_.interrupt(Uo)}function ds(e){e.persistentConnection_&&e.persistentConnection_.resume(Uo)}function fs(e,...t){let n=``;e.persistentConnection_&&(n=e.persistentConnection_.id+`:`),h(n,...t)}function X(e,t,n,r){t&&it(()=>{if(n===`ok`)t(null);else{let e=(n||`error`).toUpperCase(),i=e;r&&(i+=`: `+r);let a=Error(i);a.code=e,t(a)}})}function ps(e,t,n,r,i,a){fs(e,`transaction on `+t);let o={path:t,update:n,onComplete:r,status:null,order:Pe(),applyLocally:a,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},s=ms(e,t,void 0);o.currentInputSnapshot=s;let u=o.update(s.val());if(u===void 0)o.unwatcher(),o.currentOutputSnapshotRaw=null,o.currentOutputSnapshotResolved=null,o.onComplete&&o.onComplete(null,!1,o.currentInputSnapshot);else{Ao(`transaction failed: Data returned `,u,o.path),o.status=0;let n=fo(e.transactionQueueTree_,t),r=po(n)||[];r.push(o),mo(n,r);let i;typeof u==`object`&&u&&c(u,`.priority`)?(i=_e(u,`.priority`),l(ko(i),`Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.`)):i=(za(e.serverSyncTree_,t)||L.EMPTY_NODE).getPriority().val();let a=Jo(e),d=R(u,i),f=co(d,s,a);o.currentOutputSnapshotRaw=d,o.currentOutputSnapshotResolved=f,o.currentWriteId=$o(e);let ee=ka(e.serverSyncTree_,t,f,o.currentWriteId,o.applyLocally);Y(e.eventQueue_,t,ee),hs(e,e.transactionQueueTree_)}}function ms(e,t,n){return za(e.serverSyncTree_,t,n)||L.EMPTY_NODE}function hs(e,t=e.transactionQueueTree_){if(t||Ss(e,t),po(t)){let n=bs(e,t);l(n.length>0,`Sending zero length transaction queue`),n.every(e=>e.status===0)&&gs(e,bo(t),n)}else ho(t)&&_o(t,t=>{hs(e,t)})}function gs(e,t,n){let r=ms(e,t,n.map(e=>e.currentWriteId)),i=r,a=r.hash();for(let e=0;e<n.length;e++){let r=n[e];l(r.status===0,`tryToSendTransactionQueue_: items in queue should all be run.`),r.status=1,r.retryCount++;let a=k(t,r.path);i=i.updateChild(a,r.currentOutputSnapshotRaw)}let o=i.val(!0),s=t;e.server_.put(s.toString(),o,r=>{fs(e,`transaction put response`,{path:s.toString(),status:r});let i=[];if(r===`ok`){let r=[];for(let t=0;t<n.length;t++)n[t].status=2,i=i.concat(K(e.serverSyncTree_,n[t].currentWriteId)),n[t].onComplete&&r.push(()=>n[t].onComplete(null,!0,n[t].currentOutputSnapshotResolved)),n[t].unwatcher();Ss(e,fo(e.transactionQueueTree_,t)),hs(e,e.transactionQueueTree_),Y(e.eventQueue_,t,i);for(let e=0;e<r.length;e++)it(r[e])}else{if(r===`datastale`)for(let e=0;e<n.length;e++)n[e].status===3?n[e].status=4:n[e].status=0;else{_(`transaction at `+s.toString()+` failed: `+r);for(let e=0;e<n.length;e++)n[e].status=4,n[e].abortReason=r}_s(e,t)}},a)}function _s(e,t){let n=ys(e,t),r=bo(n);return vs(e,bs(e,n),r),r}function vs(e,t,n){if(t.length===0)return;let r=[],i=[],a=t.filter(e=>e.status===0).map(e=>e.currentWriteId);for(let o=0;o<t.length;o++){let s=t[o],u=k(n,s.path),d=!1,f;if(l(u!==null,`rerunTransactionsUnderNode_: relativePath should not be null.`),s.status===4)d=!0,f=s.abortReason,i=i.concat(K(e.serverSyncTree_,s.currentWriteId,!0));else if(s.status===0){if(s.retryCount>=Wo)d=!0,f=`maxretry`,i=i.concat(K(e.serverSyncTree_,s.currentWriteId,!0));else{let n=ms(e,s.path,a);s.currentInputSnapshot=n;let r=t[o].update(n.val());if(r!==void 0){Ao(`transaction failed: Data returned `,r,s.path);let t=R(r);typeof r==`object`&&r&&c(r,`.priority`)||(t=t.updatePriority(n.getPriority()));let o=s.currentWriteId,l=Jo(e),u=co(t,n,l);s.currentOutputSnapshotRaw=t,s.currentOutputSnapshotResolved=u,s.currentWriteId=$o(e),a.splice(a.indexOf(o),1),i=i.concat(ka(e.serverSyncTree_,s.path,u,s.currentWriteId,s.applyLocally)),i=i.concat(K(e.serverSyncTree_,o,!0))}else d=!0,f=`nodata`,i=i.concat(K(e.serverSyncTree_,s.currentWriteId,!0))}}Y(e.eventQueue_,n,i),i=[],d&&(t[o].status=2,(function(e){setTimeout(e,0)})(t[o].unwatcher),t[o].onComplete&&(f===`nodata`?r.push(()=>t[o].onComplete(null,!1,t[o].currentInputSnapshot)):r.push(()=>t[o].onComplete(Error(f),!1,null))))}Ss(e,e.transactionQueueTree_);for(let e=0;e<r.length;e++)it(r[e]);hs(e,e.transactionQueueTree_)}function ys(e,t){let n,r=e.transactionQueueTree_;for(n=w(t);n!==null&&po(r)===void 0;)r=fo(r,n),t=E(t),n=w(t);return r}function bs(e,t){let n=[];return xs(e,t,n),n.sort((e,t)=>e.order-t.order),n}function xs(e,t,n){let r=po(t);if(r)for(let e=0;e<r.length;e++)n.push(r[e]);_o(t,t=>{xs(e,t,n)})}function Ss(e,t){let n=po(t);if(n){let e=0;for(let t=0;t<n.length;t++)n[t].status!==2&&(n[e]=n[t],e++);n.length=e,mo(t,n.length>0?n:void 0)}_o(t,t=>{Ss(e,t)})}function Cs(e,t){let n=bo(ys(e,t)),r=fo(e.transactionQueueTree_,t);return yo(r,t=>{ws(e,t)}),ws(e,r),vo(r,t=>{ws(e,t)}),n}function ws(e,t){let n=po(t);if(n){let r=[],i=[],a=-1;for(let t=0;t<n.length;t++)n[t].status===3||(n[t].status===1?(l(a===t-1,`All SENT items should be at beginning of queue.`),a=t,n[t].status=3,n[t].abortReason=`set`):(l(n[t].status===0,`Unexpected transaction status in abort`),n[t].unwatcher(),i=i.concat(K(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&r.push(n[t].onComplete.bind(null,Error(`set`),!1,null))));a===-1?mo(t,void 0):n.length=a+1,Y(e.eventQueue_,bo(t),i);for(let e=0;e<r.length;e++)it(r[e])}}function Ts(e){let t=``,n=e.split(`/`);for(let e=0;e<n.length;e++)if(n[e].length>0){let r=n[e];try{r=decodeURIComponent(r.replace(/\+/g,` `))}catch{}t+=`/`+r}return t}function Es(e){let t={};e.charAt(0)===`?`&&(e=e.substring(1));for(let n of e.split(`&`)){if(n.length===0)continue;let r=n.split(`=`);r.length===2?t[decodeURIComponent(r[0])]=decodeURIComponent(r[1]):_(`Invalid query segment '${n}' in query '${e}'`)}return t}var Ds=function(e,t){let n=Os(e),r=n.namespace;n.domain===`firebase.com`&&g(n.host+` is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead`),r&&r!==`undefined`||n.domain===`localhost`||g(`Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com`),n.secure||He();let i=n.scheme===`ws`||n.scheme===`wss`;return{repoInfo:new xt(n.host,n.secure,r,i,t,``,r!==n.subdomain),path:new S(n.pathString)}},Os=function(e){let t=``,n=``,r=``,i=``,a=``,o=!0,s=`https`,c=443;if(typeof e==`string`){let l=e.indexOf(`//`);l>=0&&(s=e.substring(0,l-1),e=e.substring(l+2));let u=e.indexOf(`/`);u===-1&&(u=e.length);let d=e.indexOf(`?`);d===-1&&(d=e.length),t=e.substring(0,Math.min(u,d)),u<d&&(i=Ts(e.substring(u,d)));let f=Es(e.substring(Math.min(e.length,d)));l=t.indexOf(`:`),l>=0?(o=s===`https`||s===`wss`,c=parseInt(t.substring(l+1),10)):l=t.length;let ee=t.slice(0,l);if(ee.toLowerCase()===`localhost`)n=`localhost`;else if(ee.split(`.`).length<=2)n=ee;else{let e=t.indexOf(`.`);r=t.substring(0,e).toLowerCase(),n=t.substring(e+1),a=r}`ns`in f&&(a=f.ns)}return{host:t,port:c,domain:n,subdomain:r,secure:o,scheme:s,pathString:i,namespace:a}},ks=`-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz`,As=(function(){let e=0,t=[];return function(n){let r=n===e;e=n;let i,a=Array(8);for(i=7;i>=0;i--)a[i]=ks.charAt(n%64),n=Math.floor(n/64);l(n===0,`Cannot push at time == 0`);let o=a.join(``);if(r){for(i=11;i>=0&&t[i]===63;i--)t[i]=0;t[i]++}else for(i=0;i<12;i++)t[i]=Math.floor(Math.random()*64);for(i=0;i<12;i++)o+=ks.charAt(t[i]);return l(o.length===20,`nextPushId: Length should be 20.`),o}})(),js=class{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){let e=this.snapshot.ref;return this.eventType===`value`?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+`:`+this.eventType+`:`+p(this.snapshot.exportVal())}},Ms=class{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`}},Ns=class{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return l(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||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}},Ps=class{constructor(e,t){this._repo=e,this._path=t}cancel(){let e=new d;return is(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){J(`OnDisconnect.remove`,this._path);let e=new d;return as(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){J(`OnDisconnect.set`,this._path),q(`OnDisconnect.set`,e,this._path,!1);let t=new d;return as(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){J(`OnDisconnect.setWithPriority`,this._path),q(`OnDisconnect.setWithPriority`,e,this._path,!1),No(`OnDisconnect.setWithPriority`,t);let n=new d;return os(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){J(`OnDisconnect.update`,this._path),Mo(`OnDisconnect.update`,e,this._path);let t=new d;return ss(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}},Z=class e{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return O(this._path)?null:_n(this._path)}get ref(){return new Q(this._repo,this._path)}get _queryIdentifier(){let e=Je(Or(this._queryParams));return e===`{}`?`default`:e}get _queryObject(){return Or(this._queryParams)}isEqual(t){if(t=s(t),!(t instanceof e))return!1;let n=this._repo===t._repo,r=Sn(this._path,t._path),i=this._queryIdentifier===t._queryIdentifier;return n&&r&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+vn(this._path)}};function Fs(e,t){if(e._orderByCalled===!0)throw Error(t+`: You can't combine multiple orderBy calls.`)}function Is(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===N){let r=`Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().`,i=`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()!==v)throw Error(r);if(typeof t!=`string`)throw Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==y)throw Error(r);if(typeof n!=`string`)throw Error(i)}}else if(e.getIndex()===I){if(t!=null&&!ko(t)||n!=null&&!ko(n))throw 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(l(e.getIndex()instanceof cr||e.getIndex()===lr,`unknown index type.`),typeof t==`object`&&t||typeof n==`object`&&n)throw Error(`Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.`)}function Ls(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw Error(`Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.`)}var Q=class e extends Z{constructor(e,t){super(e,t,new vr,!1)}get parent(){let t=bn(this._path);return t===null?null:new e(this._repo,t)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}},Rs=class e{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(t){let n=new S(t),r=Vs(this.ref,t);return new e(this._node.getChild(n),r,I)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(t){return!this._node.isLeafNode()&&!!this._node.forEachChild(this._index,(n,r)=>t(new e(r,Vs(this.ref,n),I)))}hasChild(e){let t=new S(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 zs(e,t){return e=s(e),e._checkNotDeleted(`ref`),t===void 0?e._root:Vs(e._root,t)}function Bs(e,t){e=s(e),e._checkNotDeleted(`refFromURL`);let n=Ds(t,e._repo.repoInfo_.nodeAdmin);Lo(`refFromURL`,n);let r=n.repoInfo;return!e._repo.repoInfo_.isCustomHost()&&r.host!==e._repo.repoInfo_.host&&g(`refFromURL: Host name does not match the current database: (found `+r.host+` but expected `+e._repo.repoInfo_.host+`)`),zs(e,n.path.toString())}function Vs(e,t){return e=s(e),w(e._path)===null?Io(`child`,`path`,t,!1):Fo(`child`,`path`,t,!1),new Q(e._repo,D(e._path,t))}function Hs(e){return e=s(e),new Ps(e._repo,e._path)}function Us(e,t){e=s(e),J(`push`,e._path),q(`push`,t,e._path,!0);let n=As(qo(e._repo)),r=Vs(e,n),i=Vs(e,n),a;return a=t==null?Promise.resolve(i):Gs(i,t).then(()=>i),r.then=a.then.bind(a),r.catch=a.then.bind(a,void 0),r}function Ws(e){return J(`remove`,e._path),Gs(e,null)}function Gs(e,t){e=s(e),J(`set`,e._path),q(`set`,t,e._path,!1);let n=new d;return ts(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Ks(e,t){e=s(e),J(`setPriority`,e._path),No(`setPriority`,t);let n=new d;return ts(e._repo,D(e._path,`.priority`),t,null,n.wrapCallback(()=>{})),n.promise}function qs(e,t,n){if(J(`setWithPriority`,e._path),q(`setWithPriority`,t,e._path,!1),No(`setWithPriority`,n),e.key===`.length`||e.key===`.keys`)throw`setWithPriority failed: `+e.key+` is a read-only object.`;let r=new d;return ts(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise}function Js(e,t){Mo(`update`,t,e._path);let n=new d;return ns(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function Ys(e){e=s(e);let t=new Xs(new Ns(()=>{}));return es(e._repo,e,t).then(t=>new Rs(t,new Q(e._repo,e._path),e._queryParams.getIndex()))}var Xs=class e{constructor(e){this.callbackContext=e}respondsTo(e){return e===`value`}createEvent(e,t){let n=t._queryParams.getIndex();return new js(`value`,this,new Rs(e.snapshotNode,new Q(t._repo,t._path),n))}getEventRunner(e){return e.getEventType()===`cancel`?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new Ms(this,e,t):null}matches(t){return t instanceof e?!t.callbackContext||!this.callbackContext||t.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}},Zs=class e{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t=e===`children_added`?`child_added`:e;return t=t===`children_removed`?`child_removed`:t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new Ms(this,e,t):null}createEvent(e,t){l(e.childName!=null,`Child events should have a childName.`);let n=Vs(new Q(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new js(e.type,this,new Rs(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return e.getEventType()===`cancel`?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(t){return t instanceof e&&this.eventType===t.eventType&&(!this.callbackContext||!t.callbackContext||this.callbackContext.matches(t.callbackContext))}hasAnyCallback(){return!!this.callbackContext}};function Qs(e,t,n,r,i){let a;if(typeof r==`object`&&(a=void 0,i=r),typeof r==`function`&&(a=r),i&&i.onlyOnce){let t=n,r=(n,r)=>{ls(e._repo,e,s),t(n,r)};r.userCallback=n.userCallback,r.context=n.context,n=r}let o=new Ns(n,a||void 0),s=t===`value`?new Xs(o):new Zs(t,o);return cs(e._repo,e,s),()=>ls(e._repo,e,s)}function $s(e,t,n,r){return Qs(e,`value`,t,n,r)}function ec(e,t,n,r){return Qs(e,`child_added`,t,n,r)}function tc(e,t,n,r){return Qs(e,`child_changed`,t,n,r)}function nc(e,t,n,r){return Qs(e,`child_moved`,t,n,r)}function rc(e,t,n,r){return Qs(e,`child_removed`,t,n,r)}function ic(e,t,n){let r=null,i=n?new Ns(n):null;t===`value`?r=new Xs(i):t&&(r=new Zs(t,i)),ls(e._repo,e,r)}var $=class{},ac=class extends ${constructor(e,t){super(),this._value=e,this._key=t,this.type=`endAt`}_apply(e){q(`endAt`,this._value,e._path,!0);let t=wr(e._queryParams,this._value,this._key);if(Ls(t),Is(t),e._queryParams.hasEnd())throw Error(`endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).`);return new Z(e._repo,e._path,t,e._orderByCalled)}};function oc(e,t){return Po(`endAt`,`key`,t),new ac(e,t)}var sc=class extends ${constructor(e,t){super(),this._value=e,this._key=t,this.type=`endBefore`}_apply(e){q(`endBefore`,this._value,e._path,!1);let t=Tr(e._queryParams,this._value,this._key);if(Ls(t),Is(t),e._queryParams.hasEnd())throw Error(`endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).`);return new Z(e._repo,e._path,t,e._orderByCalled)}};function cc(e,t){return Po(`endBefore`,`key`,t),new sc(e,t)}var lc=class extends ${constructor(e,t){super(),this._value=e,this._key=t,this.type=`startAt`}_apply(e){q(`startAt`,this._value,e._path,!0);let t=Sr(e._queryParams,this._value,this._key);if(Ls(t),Is(t),e._queryParams.hasStart())throw Error(`startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).`);return new Z(e._repo,e._path,t,e._orderByCalled)}};function uc(e=null,t){return Po(`startAt`,`key`,t),new lc(e,t)}var dc=class extends ${constructor(e,t){super(),this._value=e,this._key=t,this.type=`startAfter`}_apply(e){q(`startAfter`,this._value,e._path,!1);let t=Cr(e._queryParams,this._value,this._key);if(Ls(t),Is(t),e._queryParams.hasStart())throw Error(`startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).`);return new Z(e._repo,e._path,t,e._orderByCalled)}};function fc(e,t){return Po(`startAfter`,`key`,t),new dc(e,t)}var pc=class extends ${constructor(e){super(),this._limit=e,this.type=`limitToFirst`}_apply(e){if(e._queryParams.hasLimit())throw Error(`limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).`);return new Z(e._repo,e._path,br(e._queryParams,this._limit),e._orderByCalled)}};function mc(e){if(typeof e!=`number`||Math.floor(e)!==e||e<=0)throw Error(`limitToFirst: First argument must be a positive integer.`);return new pc(e)}var hc=class extends ${constructor(e){super(),this._limit=e,this.type=`limitToLast`}_apply(e){if(e._queryParams.hasLimit())throw Error(`limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).`);return new Z(e._repo,e._path,xr(e._queryParams,this._limit),e._orderByCalled)}};function gc(e){if(typeof e!=`number`||Math.floor(e)!==e||e<=0)throw Error(`limitToLast: First argument must be a positive integer.`);return new hc(e)}var _c=class extends ${constructor(e){super(),this._path=e,this.type=`orderByChild`}_apply(e){Fs(e,`orderByChild`);let t=new S(this._path);if(O(t))throw Error(`orderByChild: cannot pass in empty path. Use orderByValue() instead.`);let n=new cr(t),r=Er(e._queryParams,n);return Is(r),new Z(e._repo,e._path,r,!0)}};function vc(e){if(e===`$key`)throw Error(`orderByChild: "$key" is invalid. Use orderByKey() instead.`);if(e===`$priority`)throw Error(`orderByChild: "$priority" is invalid. Use orderByPriority() instead.`);if(e===`$value`)throw Error(`orderByChild: "$value" is invalid. Use orderByValue() instead.`);return Fo(`orderByChild`,`path`,e,!1),new _c(e)}var yc=class extends ${constructor(){super(...arguments),this.type=`orderByKey`}_apply(e){Fs(e,`orderByKey`);let t=Er(e._queryParams,N);return Is(t),new Z(e._repo,e._path,t,!0)}};function bc(){return new yc}var xc=class extends ${constructor(){super(...arguments),this.type=`orderByPriority`}_apply(e){Fs(e,`orderByPriority`);let t=Er(e._queryParams,I);return Is(t),new Z(e._repo,e._path,t,!0)}};function Sc(){return new xc}var Cc=class extends ${constructor(){super(...arguments),this.type=`orderByValue`}_apply(e){Fs(e,`orderByValue`);let t=Er(e._queryParams,lr);return Is(t),new Z(e._repo,e._path,t,!0)}};function wc(){return new Cc}var Tc=class extends ${constructor(e,t){super(),this._value=e,this._key=t,this.type=`equalTo`}_apply(e){if(q(`equalTo`,this._value,e._path,!1),e._queryParams.hasStart())throw Error(`equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).`);if(e._queryParams.hasEnd())throw Error(`equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).`);return new ac(this._value,this._key)._apply(new lc(this._value,this._key)._apply(e))}};function Ec(e,t){return Po(`equalTo`,`key`,t),new Tc(e,t)}function Dc(e,...t){let n=s(e);for(let e of t)n=e._apply(n);return n}pa(Q),Ta(Q);var Oc=`FIREBASE_DATABASE_EMULATOR_HOST`,kc={},Ac=!1;function jc(e,t,n,r){let i=t.lastIndexOf(`:`),a=t.substring(0,i);e.repoInfo_=new xt(t,ee(a),e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,!0,n),r&&(e.authTokenProvider_=r)}function Mc(e,t,n,r,i){let a=r||e.options.databaseURL;a===void 0&&(e.options.projectId||g(`Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp().`),h(`Using default host for project `,e.options.projectId),a=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o=Ds(a,i),s=o.repoInfo,c,l;typeof process<`u`&&(l={}[Oc]),l?(c=!0,a=`http://${l}?ns=${s.namespace}`,o=Ds(a,i),s=o.repoInfo):c=!o.repoInfo.secure;let u=i&&c?new lt(lt.OWNER):new ct(e.name,e.options,t);return Lo(`Invalid Firebase Database URL`,o),O(o.path)||g(`Database URL must point to the root of a Firebase Database (not including a child path).`),new Ic(Pc(s,e,u,new st(e,n)),e)}function Nc(e,t){let n=kc[t];n&&n[e.key]===e||g(`Database ${t}(${e.repoInfo_}) has already been deleted.`),us(e),delete n[e.key]}function Pc(e,t,n,r){let i=kc[t.name];i||(i={},kc[t.name]=i);let a=i[e.toURLString()];return a&&g(`Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.`),a=new Go(e,Ac,n,r),i[e.toURLString()]=a,a}function Fc(e){Ac=e}var Ic=class{constructor(e,t){this._repoInternal=e,this.app=t,this.type=`database`,this._instanceStarted=!1}get _repo(){return this._instanceStarted||=(Ko(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),!0),this._repoInternal}get _root(){return this._rootInternal||=new Q(this._repo,C()),this._rootInternal}_delete(){return this._rootInternal!==null&&(Nc(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&g(`Cannot call `+e+` on a deleted database.`)}};function Lc(){Yt.IS_TRANSPORT_INITIALIZED&&_(`Transport has already been initialized. Please call this function before calling ref or setting up a listener`)}function Rc(){Lc(),Wt.forceDisallow()}function zc(){Lc(),x.forceDisallow(),Wt.forceAllow()}function Bc(e=fe(),t){let n=oe(e,`database`).getImmediate({identifier:t});if(!n._instanceStarted){let e=i(`database`);e&&Vc(n,...e)}return n}function Vc(e,t,n,r={}){e=s(e),e._checkNotDeleted(`useEmulator`);let i=`${t}:${n}`,a=e._repoInternal;if(e._instanceStarted){if(i===e._repoInternal.repoInfo_.host&&re(r,a.repoInfo_.emulatorOptions))return;g(`connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.`)}let o;a.repoInfo_.nodeAdmin?(r.mockUserToken&&g(`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 lt(lt.OWNER)):r.mockUserToken&&(o=new lt(typeof r.mockUserToken==`string`?r.mockUserToken:te(r.mockUserToken,e.app.options.projectId))),ee(t)&&ce(t),jc(a,i,r,o)}function Hc(e){e=s(e),e._checkNotDeleted(`goOffline`),us(e._repo)}function Uc(e){e=s(e),e._checkNotDeleted(`goOnline`),ds(e._repo)}function Wc(e,t){ze(e,t)}function Gc(e){De(ve),ue(new ne(`database`,(e,{instanceIdentifier:t})=>Mc(e.getProvider(`app`).getImmediate(),e.getProvider(`auth-internal`),e.getProvider(`app-check-internal`),t),`PUBLIC`).setMultipleInstances(!0)),Ce(we,Te,e),Ce(we,Te,`esm2020`)}var Kc={".sv":`timestamp`};function qc(){return Kc}function Jc(e){return{".sv":{increment:e}}}var Yc=class{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}};function Xc(e,t,n){if(e=s(e),J(`Reference.transaction`,e._path),e.key===`.length`||e.key===`.keys`)throw`Reference.transaction failed: `+e.key+` is a read-only object.`;let r=n?.applyLocally??!0,i=new d,a=(t,n,r)=>{let a=null;t?i.reject(t):(a=new Rs(r,new Q(e._repo,e._path),I),i.resolve(new Yc(n,a)))},o=$s(e,()=>{});return ps(e._repo,e._path,t,a,o,r),i.promise}j.prototype.simpleListen=function(e,t){this.sendRequest(`q`,{p:e},t)},j.prototype.echo=function(e,t){this.sendRequest(`echo`,{d:e},t)};var Zc=function(e){let t=j.prototype.put;return j.prototype.put=function(n,r,i,a){a!==void 0&&(a=e()),t.call(this,n,r,i,a)},function(){j.prototype.put=t}},Qc=function(e){Fc(e)};function $c({app:e,url:t,version:i,customAuthImpl:a,customAppCheckImpl:o,nodeAdmin:s=!1}){De(i);let c=new r(`database-standalone`),l=new n(`auth-internal`,c),u;return o&&(u=new n(`app-check-internal`,c),u.setComponent(new ne(`app-check-internal`,()=>o,`PRIVATE`))),l.setComponent(new ne(`auth-internal`,()=>a,`PRIVATE`)),Mc(e,l,u,t,s)}Gc();export{Rs as DataSnapshot,Ic as Database,Ps as OnDisconnect,$ as QueryConstraint,Yc as TransactionResult,Z as _QueryImpl,vr as _QueryParams,Q as _ReferenceImpl,Qc as _TEST_ACCESS_forceRestClient,Zc as _TEST_ACCESS_hijackHash,$c as _initStandalone,Mc as _repoManagerDatabaseFromApp,De as _setSDKVersion,Fo as _validatePathString,J as _validateWritablePath,Vs as child,Vc as connectDatabaseEmulator,Wc as enableLogging,oc as endAt,cc as endBefore,Ec as equalTo,zc as forceLongPolling,Rc as forceWebSockets,Ys as get,Bc as getDatabase,Hc as goOffline,Uc as goOnline,Jc as increment,mc as limitToFirst,gc as limitToLast,ic as off,ec as onChildAdded,tc as onChildChanged,nc as onChildMoved,rc as onChildRemoved,Hs as onDisconnect,$s as onValue,vc as orderByChild,bc as orderByKey,Sc as orderByPriority,wc as orderByValue,Us as push,Dc as query,zs as ref,Bs as refFromURL,Ws as remove,Xc as runTransaction,qc as serverTimestamp,Gs as set,Ks as setPriority,qs as setWithPriority,fc as startAfter,uc as startAt,Js as update};