UNPKG

firetruss

Version:

Advanced data sync layer for Firebase and Vue.js

1 lines 64.8 kB
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("lodash"),require("vue")):"function"==typeof define&&define.amd?define(["lodash","vue"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).Truss=t(e._,e.Vue)})(this,function(U,I){function e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var _=e(U),u=e(I);function i(){a.digestRequest>n||(a.digestRequest=n+1)}let a,n=0,o=!1,c={active:"undefined"!=typeof window&&window.angular};if(c.active){let t=window.angular.module("firetruss",[]);c.digest=i,c.watch=function(){throw new Error("Angular watch proxy not yet initialized")},c.defineModule=function(e){t.constant("Truss",e)},c.debounceDigest=function(t){if(t){let e=_.default.debounce(i,t);c.digest=function(){a.digestRequest>n||(o?i:e)()}}else c.digest=i},t.config(["$provide",function(e){e.decorator("$rootScope",["$delegate","$exceptionHandler",function(t,e){let r=t;c.watch=r.$watch.bind(r);var t=Object.getPrototypeOf(r),s=t.$digest,t=(t.$digest=i,t.$digest.original=s,(a=new u.default({data:{digestRequest:0}})).$watch(()=>a.digestRequest,()=>{a.digestRequest>n?u.default.nextTick(()=>{a.digestRequest<=n||(o=!0,r.$digest.original.call(r),n=a.digestRequest=a.digestRequest+1)}):o=!1}),_.default.last(a._watchers||a._scope.effects));t.id=1/0;{let e=(s=Object.getPrototypeOf(t)).get;s.get=function(){try{return e.call(this)}catch(e){if(this.vm._watcher!==this||!u.default.config.errorHandler)throw e;u.default.config.errorHandler(e,this.vm,"uncaught render error")}}}return r}])}])}else _.default.forEach(["digest","watch","defineModule","debounceDigest"],e=>{c[e]=_.default.noop});class q{constructor(e,t){this.key=e,this.value=t,this.touch()}touch(){this.timestamp=Date.now()}}let F=new class{constructor(e,t){this._items=Object.create(null),this._size=0,this._maxSize=e,this._pruningSize=t||Math.ceil(.1*e)}has(e){return Boolean(this._items[e])}get(e){e=this._items[e];if(e)return e.touch(),e.value}set(e,t){var r=this._items[e];r?r.value=t:(this._size>=this._maxSize&&this._prune(),this._items[e]=new q(e,t),this._size+=1)}delete(e){this._items[e]&&(delete this._items[e],--this._size)}_prune(){var e;for(e of _.default(this._items).toArray().sortBy("timestamp").take(this._pruningSize).value())this.delete(e.key)}}(1e3),r={};function p(e){return e&&e.toString().replace(/[\x00-\x1f\\.$#[\]\x7f/]/g,e=>"\\"+_.default.padStart(e.charCodeAt(0).toString(16),2,"0"))}function d(e){return e&&e.toString().replace(/\\[0-9a-f]{2}/gi,e=>String.fromCharCode(parseInt(e.slice(1),16)))}function f(e){if(!_.default.isObject(e)||!Object.isExtensible(e))return e;let t=e;for(var r in e){var s,i,a;Object.hasOwn(e,r)&&(s=e[r],i=p(r),a=f(s),i===r&&a===s||((t=t===e?_.default.clone(e):t)[i]=a,t[r]===s&&delete t[r]))}return t}function m(){var e,t=[];for(e of arguments)"/"===(e=_.default.isString(e)?e:""+e).charAt(0)&&t.splice(0,t.length),t.push(e);return"/"===t[0]&&(t[0]=""),t.join("/")}function g(e,t){var r=(t?"esc:":"")+e;let s=F.get(r);return s||(s=e.split("/"),t||(s=_.default.map(s,d)),F.set(r,s)),s}class V{constructor(e){this.variables=[];var t=_.default.endsWith(e,"/$*"),r=(e=t?e.slice(0,-3):e).replace(/\/\$[^/]*/g,e=>(1<e.length&&this.variables.push(e.slice(1)),""));if(Object.freeze(this.variables),/[.$#[\]]|\\(?![0-9a-f][0-9a-f])/i.test(r))throw new Error("Path pattern has unescaped keys: "+e);this._regex=new RegExp("^"+r.replace(/\u0001/g,"/([^/]+)")+(t?"($|/)":"$"))}match(e){this._regex.lastIndex=0;var t=this._regex.exec(e);if(t){var r={};for(let e=0;e<this.variables.length;e++)r[this.variables[e]]=d(t[e+1]);return r}}test(e){return this._regex.test(e)}toString(){return this._regex.toString()}}function l(e){let t=r[e];return t||(t=new V(e),1e3===_.default.size(r)&&delete r[_.default.keys(r)[0]],r[e]=t),t}let W="4.0.0";class h{constructor({path:e,value:t,exists:r,writeSerial:s}){this._path=e,this._value=t,this._exists=void 0===t?r||!1:null!==t,this._writeSerial=s}get path(){return this._path}get exists(){return this._exists}get value(){if(void 0===this._value)throw new Error("Value omitted from snapshot");return this._value}get key(){return void 0===this._key&&(this._key=d(this._path.replace(/.*\//,""))),this._key}get writeSerial(){return this._writeSerial}}class N{constructor(e){this._idCounter=0,this._deferreds={},this._suspended=!1,this._servers={},this._callbacks={},this._log=_.default.noop,this._inboundMessages=[],this._outboundMessages=[],this._flushMessageQueue=this._flushMessageQueue.bind(this),this._port=e.port||e,this._shared=!!e.port,this._dead=void 0,Object.seal(this),this._port.onmessage=this._receive.bind(this)}init(e,t){var r=[];try{var s=window.localStorage||window.sessionStorage;if(!s)throw new Error("localStorage and sessionStorage not available");for(let e=0;e<s.length;e++){var i=s.key(e);r.push({key:i,value:s.getItem(i)})}}catch{}return this._send({msg:"init",storage:r,config:t,lockName:e}).then(e=>{var t=e.version.match(/^(\d+)\.(\d+)\.(\d+)(-.*)?$/);if(t){var r=W.match(/^(\d+)\.(\d+)\.(\d+)(-.*)?$/);if(!(t[1]===r[1]&&(t[2]>r[2]||t[2]===r[2]&&t[3]>=r[3])))return Promise.reject(new Error(`Incompatible Firetruss worker version: ${e.version} `+`(${W} or better required)`))}return e.livenessLockName&&navigator.locks.request(e.livenessLockName,()=>{this.crash({error:{name:"Error",message:"worker terminated",extra:{shared:this._shared}}})}),e})}suspend(e){this._suspended===(e=void 0===e?!0:e)||(this._suspended=e)||(this._receiveMessages(this._inboundMessages),this._inboundMessages=[],this._outboundMessages.length&&Promise.resolve().then(this._flushMessageQueue))}enableLogging(e){e?(!0===e&&(e=console.log.bind(console),this._send({msg:"enableFirebaseLogging",value:!0})),this._log=e):(this._send({msg:"enableFirebaseLogging",value:!1}),this._log=_.default.noop)}_send(r){r.id=++this._idCounter;let e;var t;return this._dead?Promise.reject(this._dead):(r.oneWay?e=Promise.resolve():(e=new Promise((e,t)=>{this._deferreds[r.id]={resolve:e,reject:t}}),(t=this._deferreds[r.id]).promise=e,t.params=r),this._outboundMessages.length||this._suspended||Promise.resolve().then(this._flushMessageQueue),this._log("send:",r),this._outboundMessages.push(r),e)}_flushMessageQueue(){this._log("flush:",this._outboundMessages.length,"messages");try{this._port.postMessage(this._outboundMessages),this._outboundMessages=[]}catch(e){throw this._log("flush failed:",e),e.extra={messages:this._outboundMessages},e}}_receive(e){this._dead||(this._suspended?this._inboundMessages=this._inboundMessages.concat(e.data):this._receiveMessages(e.data))}_receiveMessages(e){for(var t of e){this._log("recv:",t);var r=this[t.msg];if(!_.default.isFunction(r))throw new Error("Unknown message: "+t.msg);r.call(this,t)}}bindExposedFunction(e){return function(){return this._send({msg:"call",name:e,args:Array.prototype.slice.call(arguments)})}.bind(this)}resolve(e){var t=this._deferreds[e.id];if(!t)throw new Error("Received resolution to inexistent Firebase call");delete this._deferreds[e.id],t.resolve(e.result)}reject(e){var t=this._deferreds[e.id];if(!t)throw new Error("Received rejection of inexistent Firebase call");delete this._deferreds[e.id],t.reject(L(e.error,t.params))}crash(e){let t=`Internal worker error: ${e.error.name}: `+e.error.message;throw e.error.cause&&(t+=` (caused by ${e.error.cause})`),this._dead=new Error(t),e.error.extra&&(this._dead.extra=e.error.extra),_.default.forEach(this._deferreds,({reject:e})=>{e(this._dead)}),this._deferreds={},this._dead}updateLocalStorage({items:e}){try{var t,r=window.localStorage||window.sessionStorage;for(t of e)null===t.value?r.removeItem(t.key):r.setItem(t.key,t.value)}catch{}}trackServer(e){if(Object.hasOwn(this._servers,e))return Promise.resolve();var t=this._servers[e]={authListeners:[]},t=this._registerCallback(this._authCallback.bind(this,t));this._send({msg:"onAuth",url:e,callbackId:t})}_authCallback(e,t){e.auth=t;for(var r of e.authListeners)r(t)}onAuth(e,t,r){var s=t.bind(r);s.callback=t,s.context=r,this._servers[e].authListeners.push(s),s(this.getAuth(e))}offAuth(e,t,r){var s=this._servers[e].authListeners;for(let e=0;e<s.length;e++){var i=s[e];if(i.callback===t&&i.context===r){s.splice(e,1);break}}}getAuth(e){return this._servers[e].auth}authWithCustomToken(e,t){return this._send({msg:"authWithCustomToken",url:e,authToken:t})}authAnonymously(e){return this._send({msg:"authAnonymously",url:e})}unauth(e){return this._send({msg:"unauth",url:e})}set(e,t,r){return this._send({msg:"set",url:e,value:t,writeSerial:r})}update(e,t,r){return this._send({msg:"update",url:e,value:t,writeSerial:r})}once(e,t){return this._send({msg:"once",url:e,writeSerial:t}).then(e=>new h(e))}on(e,t,r,s,i,a,n,o){a={listenerKey:e,eventType:s,snapshotCallback:i,cancelCallback:a,context:n,params:{msg:"on",listenerKey:e,url:t,spec:r,eventType:s,options:o}};let h=this._onCallback.bind(this,a);this._registerCallback(h,a),i.__callbackIds=i.__callbackIds||[],i.__callbackIds.push(a.id),this._send({msg:"on",listenerKey:e,url:t,spec:r,eventType:s,callbackId:a.id,options:o}).catch(e=>{h(e)})}off(t,e,r,s,i,a){let n=[],o;if(i){if(!(o=this._findAndRemoveCallbackId(i,e=>_.default.isMatch(e,{listenerKey:t,eventType:s,context:a}))))return Promise.resolve();n.push(o)}else for(var h of _.default.keys(this._callbacks)){var l=this._callbacks[h];l.listenerKey!==t||s&&l.eventType!==s||n.push(h)}for(var u of n)this._nullifyCallback(u);return this._send({msg:"off",listenerKey:t,url:e,spec:r,eventType:s,callbackId:o}).then(()=>{for(var e of n)this._deregisterCallback(e)})}_onCallback(e,t,r){t?(this._deregisterCallback(e.id),t=L(t,e.params),e.cancelCallback?e.cancelCallback.call(e.context,t):console.error(t)):e.snapshotCallback.call(e.context,new h(r))}transaction(e,t,r,s){return this._send({msg:"transaction",url:e,oldValue:t,relativeUpdates:r,writeSerial:s}).then(e=>(e.snapshots&&(e.snapshots=_.default.map(e.snapshots,e=>new h(e))),e))}onDisconnect(e,t,r){return this._send({msg:"onDisconnect",url:e,method:t,value:r})}bounceConnection(){return this._send({msg:"bounceConnection"})}callback({id:e,args:t}){var r=this._callbacks[e];if(!r)throw new Error("Unregistered callback: "+e);r.callback.apply(null,t)}_registerCallback(e,t){return(t=t||{}).callback=e,t.id="cb"+ ++this._idCounter,(this._callbacks[t.id]=t).id}_nullifyCallback(e){this._callbacks[e].callback=_.default.noop}_deregisterCallback(e){delete this._callbacks[e]}_findAndRemoveCallbackId(t,r){if(t.__callbackIds){let e=0;for(;e<t.__callbackIds.length;){var s=t.__callbackIds[e],i=this._callbacks[s];if(i){if(r(i))return t.__callbackIds.splice(e,1),s;e+=1}else t.__callbackIds.splice(e,1)}}}}function L(e,t){if(!e||_.default.isError(e))return e;var r=new Error(e.message);try{for(var s in r.params=t,e)if("message"!==s&&Object.hasOwn(e,s))try{r[s]=e[s]}catch{r.extra=r.extra||{},r.extra[s]=e[s]}}catch(e){if(!/object is not extensible/.test(e.message))throw e}return r}let z={};Object.freeze(z);class y{constructor(e,t,r){this._tree=e,this._path=t.replace(/^\/*/,"/").replace(/\/$/,"")||"/",r&&(this._annotations=r,Object.freeze(r))}get $ref(){return this}get key(){return this._key||(this._key=d(this._path.replace(/.*\//,""))),this._key}get path(){return this._path}get _pathPrefix(){return"/"===this._path?"":this._path}get parent(){return new b(this._tree,this._path.replace(/\/[^/]*$/,""),this._annotations)}get annotations(){return this._annotations||z}child(){if(!arguments.length)return this;var e,t=[];for(e of arguments){if(_.default.isNil(e))return;t.push(p(e))}return new b(this._tree,this._pathPrefix+"/"+t.join("/"),this._annotations)}children(){if(!arguments.length)return this;var t=[];for(let e=0;e<arguments.length;e++){var r=arguments[e];if(_.default.isArray(r)){var s,i={},a=this._pathPrefix+(t.length?"/"+t.join("/"):""),n=_.default.slice(arguments,e+1);for(s of r){var o=new b(this._tree,a+"/"+p(s),this._annotations),o=o.children.apply(o,n);o&&(i[s]=o)}return i}if(_.default.isNil(r))return;t.push(p(r))}return new b(this._tree,this._pathPrefix+"/"+t.join("/"),this._annotations)}peek(e){return this._tree.truss.peek(this,e)}match(e){return l(e).match(this.path)}test(e){return l(e).test(this.path)}isEqual(e){return e instanceof y&&this._tree===e._tree&&this.toString()===e.toString()&&_.default.isEqual(this._annotations,e._annotations)}belongsTo(e){return this._tree.truss===e}}class t extends y{constructor(e,t,r,s){super(e,t,s),this._spec=this._copyAndValidateSpec(r);e=_.default(this._spec).map((e,t)=>t+"="+encodeURIComponent(JSON.stringify(e))).sortBy().join("&");this._string=this._path+"?"+e,Object.freeze(this)}get ready(){return this._tree.isQueryReady(this)}get constraints(){return this._spec}annotate(e){return new t(this._tree,this._path,this._spec,_.default.assign({},this._annotations,e))}_copyAndValidateSpec(t){if(!t.by)throw new Error('Query needs "by" clause: '+JSON.stringify(t));if(1<("at"in t)+("from"in t)+("to"in t))throw new Error('Query must contain at most one of "at", "from", or "to" clauses: '+JSON.stringify(t));if(1<("first"in t)+("last"in t))throw new Error('Query must contain at most one of "first" or "last" clauses: '+JSON.stringify(t));if(!_.default.some(["at","from","to","first","last"],e=>e in t))throw new Error('Query must contain at least one of "at", "from", "to", "first", or "last" clauses: '+JSON.stringify(t));if("$key"!==(t=_.default.clone(t)).by&&"$value"!==t.by){if(!(t.by instanceof b))throw new Error('Query "by" value must be a reference: '+t.by);let e=t.by.toString();if(!_.default.startsWith(e,this._path))throw new Error('Query "by" value must be a descendant of target reference: '+t.by);if(e=e.slice(this._path.length).replace(/^\/?/,""),!_.default.includes(e,"/"))throw new Error('Query "by" value must not be a direct child of target reference: '+t.by);t.by=e.replace(/.*?\//,"")}return Object.freeze(t),t}toString(){return this._string}toJSON(){return"query → "+this.toString()}}class b extends y{constructor(e,t,r){super(e,t,r),Object.freeze(this)}get ready(){return this._tree.isReferenceReady(this)}get value(){return this._tree.getObject(this.path)}toString(){return this._path}toJSON(){return"reference → "+this.toString()}annotate(e){return new b(this._tree,this._path,_.default.assign({},this._annotations,e))}query(e){return new t(this._tree,this._path,e,this._annotations)}set(e){return this._checkForUndefinedPath(),this._tree.update(this,"set",{[this.path]:e})}update(e){return this._checkForUndefinedPath(),this._tree.update(this,"update",e)}override(e){return this._checkForUndefinedPath(),this._tree.update(this,"override",{[this.path]:e})}commit(e){return this._checkForUndefinedPath(),this._tree.commit(this,e)}_checkForUndefinedPath(){if("/undefined"===this.path)throw new Error("Invalid path for operation: "+this.path)}}let K=Object.freeze({".sv":"timestamp"});function v(e,t){return _.default.isEqualWith(e,t,H)}function H(e,t){return e===t||null==e||null==t||e.$truss||t.$truss?e===t:e.isEqual?e.isEqual(t):void 0}function Q(e,t){for(var r of Object.getOwnPropertyNames(e.prototype))"constructor"!==r&&Object.defineProperty(t.prototype,r,Object.getOwnPropertyDescriptor(e.prototype,r))}class w{constructor(e){_.default.assign(this,{name:e,numRecomputes:0,numUpdates:0,computeTime:0,updateTime:0})}add(e){this.computeTime+=e.computeTime,this.updateTime+=e.updateTime,this.numUpdates+=e.numUpdates,this.numRecomputes+=e.numRecomputes}get runtime(){return this.computeTime+this.updateTime}get runtimePerRecompute(){return this.numRecomputes?this.computeTime/this.numRecomputes:0}get runtimePerUpdate(){return this.numUpdates?this.updateTime/this.numUpdates:0}toLogParts(e){return[this.name+":",` ${(this.runtime/1e3).toFixed(2)}s`,`(${(this.runtime/e.runtime*100).toFixed(1)}%)`,` ${this.numUpdates} upd /`,this.numRecomputes+" runs",`(${(this.numUpdates/this.numRecomputes*100).toFixed(1)}%)`,` ${this.runtimePerRecompute.toFixed(2)}ms / run`,` ${this.runtimePerUpdate.toFixed(2)}ms / upd`]}}var $=new class{constructor(){this._items={}}for(e){return this._items[e]||(this._items[e]=new w(e)),this._items[e]}get list(){return _.default(this._items).values().sortBy(e=>-e.runtime).value()}log(i=10){var a=this.list;if(a.length){let t=new w("=== Total"),r=(_.default.forEach(a,e=>{t.add(e)}),a=_.default.take(a,i),new w("--- Above")),e=(_.default.forEach(a,e=>{r.add(e)}),_.default.map(a,e=>e.toLogParts(t))),s=(e.push(r.toLogParts(t)),e.push(t.toLogParts(t)),_.default.map(_.default.range(e[0].length),t=>_.default(e).map(e=>e[t].length).max()));_.default.forEach(e,e=>{console.log(_.default.map(e,(e,t)=>_.default.padStart(e,s[t])).join(" "))})}}wrap(s,e,i){let a=this.for(e+"."+i);return function(){var e=performance.now(),t=this._computedWatchers&&this._computedWatchers[i].value;try{var r=s.call(this);return v(t,r)||(a.numUpdates+=1),r}finally{a.computeTime+=performance.now()-e,a.numRecomputes+=1}}}};class k{constructor(e,t,r,s,i){Object.freeze(t),this._scope=e,this._connections=t,this._tree=r,this._method=s,this._subConnectors={},this._disconnects={},this._angularUnwatches=void 0,this._data={},this._vue=new u.default({data:{descriptors:{},refs:i||{},values:_.default.mapValues(t,_.default.constant(void 0))}}),this.destroy=this.destroy,Object.seal(this),this._linkScopeProperties(),_.default.forEach(t,(e,t)=>{_.default.isFunction(e)?this._bindComputedConnection(t,e):this._connect(t,e)}),c.active&&e&&e.$on&&e.$id&&e.$on("$destroy",()=>{this.destroy()})}get ready(){return _.default.every(this._connections,(e,t)=>{var r=this._vue.descriptors[t];return!!r&&(r instanceof y?r:this._subConnectors[t]).ready})}get at(){return this._vue.refs}get data(){return this._data}destroy(){this._unlinkScopeProperties(),_.default.forEach(this._angularUnwatches,e=>{e()}),_.default.forEach(this._connections,(e,t)=>{this._disconnect(t)}),this._vue.$destroy()}_linkScopeProperties(){var e=_.default.mapValues(this._connections,(e,t)=>({configurable:!0,enumerable:!1,get:()=>{var e=this._vue.descriptors[t];return e instanceof b?e.value:this._vue.values[t]}}));if(Object.defineProperties(this._data,e),this._scope){for(var t in this._connections)if(t in this._scope)throw new Error("Property already defined on connection target: "+t);Object.defineProperties(this._scope,e),this._scope.__ob__&&this._scope.__ob__.dep.notify()}}_unlinkScopeProperties(){this._scope&&_.default.forEach(this._connections,(e,t)=>{delete this._scope[t]})}_bindComputedConnection(e,t){var r=$.for("connection.at."+e),s=this._computeConnection.bind(this,t,r),e=this._updateComputedConnection.bind(this,e,t,r),r=c.active&&!t.angularWatchSuppressed;this._vue.$watch(s,e,{immediate:!r}),r&&(this._angularUnwatches||(this._angularUnwatches=[]),this._angularUnwatches.push(c.watch(s,e,!0)))}_computeConnection(e,t){var r=performance.now();try{return B(e.call(this._scope))}finally{t.computeTime+=performance.now()-r,t.numRecomputes+=1}}_updateComputedConnection(e,t,r){var t=_.default.isFunction(t)?t(this._scope):t,s=!v(this._vue.descriptors[e],t);s&&(r&&s&&(r.numUpdates+=1),t?(t instanceof y||!_.default.has(this._subConnectors,e)?(this._disconnect(e),this._connect(e,t)):this._subConnectors[e]._updateConnections(t),u.default.set(this._vue.descriptors,e,t),c.digest()):this._disconnect(e))}_updateConnections(r){_.default.forEach(r,(e,t)=>{this._updateComputedConnection(t,e)}),_.default.forEach(this._connections,(e,t)=>{_.default.has(r,t)||this._updateComputedConnection(t)}),this._connections=r}_connect(i,a){if(u.default.set(this._vue.descriptors,i,a),c.digest(),a)if(u.default.set(this._vue.values,i,void 0),a instanceof b)u.default.set(this._vue.refs,i,a),this._disconnects[i]=this._tree.connectReference(a,this._method);else if(a instanceof t){u.default.set(this._vue.refs,i,a);var e=this._updateQueryValue.bind(this,i);this._disconnects[i]=this._tree.connectQuery(a,e,this._method)}else{let t={},e={},r=(u.default.set(this._vue.refs,i,e),this._subConnectors[i]=new k(t,a,this._tree,this._method,e)),s=this._disconnects[i]=this._tree.truss.observe(()=>r.ready,e=>{e&&(s(),delete this._disconnects[i],u.default.set(this._vue.values,i,t),c.digest())})}}_disconnect(e){u.default.delete(this._vue.refs,e),this._updateRefValue(e,void 0),_.default.has(this._subConnectors,e)&&(this._subConnectors[e].destroy(),delete this._subConnectors[e]),this._disconnects[e]&&this._disconnects[e](),delete this._disconnects[e],u.default.delete(this._vue.descriptors,e),c.digest()}_updateRefValue(e,t){this._vue.values[e]!==t&&(u.default.set(this._vue.values,e,t),c.digest())}_updateQueryValue(e,t){this._vue.values[e]||(u.default.set(this._vue.values,e,{}),c.digest());var r,s=this._vue.values[e];for(r in s)!Object.hasOwn(s,r)||_.default.includes(t,r)||(u.default.delete(s,r),c.digest());var i,a=this._tree.getObject(this._vue.descriptors[e].path);for(i of t)Object.hasOwn(s,i)||(u.default.set(s,i,a[i]),c.digest())}}function B(e){if(e)return e instanceof y?e.toString():_.default.mapValues(e,B)}function O(e){return function(){try{return Promise.resolve(e.apply(this,arguments))}catch(e){return Promise.reject(e)}}}function E(e,t){return(e=P(e,()=>{t=null})).cancel=()=>{t&&(t(),t=null)},function s(i,a){let n=i.then,r=i.catch;i.then=(e,t)=>{let r=n.call(i,e,t);return r[a]=i[a],s(r,a),r};i.catch=e=>{let t=r.call(i,e);return t[a]=i[a],s(t,a),t};return i}(e,"cancel"),e}function P(e,t){return t?(t=O(t),e.then(e=>t().then(()=>e),e=>t().then(()=>Promise.reject(e)))):e}let J=["read","write","auth","set","update","commit","connect","peek","authenticate","unathenticate","certify","all"],s=[];class G{constructor(e,t,r){this._operation=e,this._delay=t,this._callback=r,this._fired=!1}initiate(){this.cancel(),this._fired=!1;var e=Date.now()-this._operation._startTimestamp;this._timeoutId=setTimeout(()=>{this._fired=!0,this._callback(this._operation)},this._delay-e)}cancel(){this._fired&&this._callback(this._operation),this._timeoutId&&clearTimeout(this._timeoutId)}}class Y{constructor(e,t,r,s){this._type=e,this._method=t,this._target=r,this._operand=s,this._ready=!1,this._running=!1,this._ended=!1,this._tries=0,this._startTimestamp=Date.now(),this._slowHandles=[]}get type(){return this._type}get method(){return this._method}get target(){return this._target}get targets(){return"update"!==this._method?[this._target]:_.default.map(this._operand,(e,t)=>new b(this._target._tree,m(this._target.path,t),this._target._annotations))}get operand(){return this._operand}get ready(){return this._ready}get running(){return this._running}get ended(){return this._ended}get tries(){return this._tries}get error(){return this._error}onSlow(e,t){e=new G(this,e,t);this._slowHandles.push(e),e.initiate()}_setRunning(e){this._running=e}_setEnded(e){this._ended=e}_markReady(e){this._ready=!0,e||(this._tries=0),_.default.forEach(this._slowHandles,e=>e.cancel())}_clearReady(){this._ready=!0,this._startTimestamp=Date.now(),_.default.forEach(this._slowHandles,e=>e.initiate()),this._ready=!1}_incrementTries(){this._tries++}}class X{constructor(e){this._bridge=e,this._callbacks={},Object.freeze(this)}intercept(e,t){if(!_.default.includes(J,e))throw new Error("Unknown intercept operation type: "+e);var r=_.default.difference(_.default.keys(t),["onBefore","onAfter","onError","onFailure"]);if(r.length)throw new Error("Unknown intercept callback types: "+r.join(", "));r={onBefore:this._addCallback("onBefore",e,t.onBefore),onAfter:this._addCallback("onAfter",e,t.onAfter),onError:this._addCallback("onError",e,t.onError),onFailure:this._addCallback("onFailure",e,t.onFailure)};return this._removeCallbacks.bind(this,e,r)}_addCallback(e,t,r){if(r)return e=this._getCallbacksKey(e,t),t=O(r),(this._callbacks[e]||(this._callbacks[e]=[])).push(t),t}_removeCallback(e,t,r){r&&(e=this._getCallbacksKey(e,t),this._callbacks[e])&&_.default.pull(this._callbacks[e],r)}_removeCallbacks(r,e){_.default.forEach(e,(e,t)=>{this._removeCallback(t,r,e)})}_getCallbacks(e,t,r){return[].concat(this._callbacks[this._getCallbacksKey(e,r)]||s,this._callbacks[this._getCallbacksKey(e,t)]||s,this._callbacks[this._getCallbacksKey(e,"all")]||s)}_getCallbacksKey(e,t){return e+"_"+t}execute(e,t,r,s,i){i=O(i);let a=this.createOperation(e,t,r,s);return this.begin(a).then(()=>{let t=()=>i().catch(e=>this._retryOrEnd(a,e).then(t));return t()}).then(e=>this.end(a).then(()=>e))}createOperation(e,t,r,s){return new Y(e,t,r,s)}begin(t){return Promise.all(_.default.map(this._getCallbacks("onBefore",t.type,t.method),e=>e(t))).then(()=>{t.ended||t._setRunning(!0)},e=>this.end(t,e))}markReady(e){e._markReady()}clearReady(e){e._clearReady()}retry(t,r){return t._incrementTries(),t._error=r,Promise.all(_.default.map(this._getCallbacks("onError",t.type,t.method),e=>e(t,r))).then(e=>{if(!t.ended)return(e=_.default.some(e))&&delete t._error,e})}_retryOrEnd(t,r){return this.retry(t,r).then(e=>{if(!e)return this.end(t,r)},e=>this.end(t,e))}end(t,e){return t.ended?Promise.resolve():(t._setRunning(!1),t._setEnded(!0),e?t._error=e:delete t._error,Promise.all(_.default.map(this._getCallbacks("onAfter",t.type,t.method),e=>e(t))).then(()=>this._afterEnd(t),e=>(t._error=e,this._afterEnd(t))))}_afterEnd(t){if(t._markReady(!0),!t.error)return Promise.resolve();let e=this._getCallbacks("onFailure",t.type,t.method);return e&&setTimeout(()=>{_.default.forEach(e,e=>e(t))},0),Promise.reject(t.error)}}let Z="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ee=window.crypto&&window.crypto.getRandomValues&&window.crypto.getRandomValues.bind(window.crypto);class te{constructor(){this._lastUniqueKeyTime=0,this._lastRandomValues=[]}generateUniqueKey(e){e=e||Date.now();var t=new Array(20);let r=e;for(let e=7;0<=e;e--)t[e]=Z.charAt(63&r),r=Math.floor(r/64);if(e===this._lastUniqueKeyTime){let e=11;for(;0<=e&&63===this._lastRandomValues[e];)this._lastRandomValues[e]=0,--e;if(-1===e)throw new Error("Internal assertion failure: ran out of unique IDs for this millisecond");this._lastRandomValues[e]+=1}else if(this._lastUniqueKeyTime=e,ee){var s=new Uint8Array(12);ee(s);for(let e=0;e<12;e++)this._lastRandomValues[e]=s[e]&(e?63:15)}else for(let e=0;e<12;e++)this._lastRandomValues[e]=Math.floor(Math.random()*(e?64:16));for(let e=0;e<12;e++)t[e+8]=Z[this._lastRandomValues[e]];return t.join("")}}class re{constructor(e,t,r,s){this._rootUrl=e,this._tree=t,this._dispatcher=s,this._bridge=r,this._vue=new u.default({data:{$root:{connected:void 0,timeOffset:0,user:void 0,userid:void 0,nowAtInterval(e){let t="now"+e;var r;return Object.hasOwn(this,t)||((r=()=>{u.default.set(this,t,Date.now()+this.timeOffset),c.digest()})(),setInterval(r,e)),this[t]}}}}),this._auth={serial:0,initialAuthChangeReceived:!1,changePromise:Promise.resolve()},r.onAuth(e,this._handleAuthChange,this),this._connectInfoProperty("serverTimeOffset","timeOffset"),this._connectInfoProperty("connected","connected"),Object.freeze(this)}get root(){return this._vue.$data.$root}destroy(){this._bridge.offAuth(this._rootUrl,this._handleAuthChange,this),this._vue.$destroy()}authenticate(e){return this._auth.serial++,this._dispatcher.execute("auth","authenticate",new b(this._tree,"/"),e,()=>(e?this._bridge.authWithCustomToken(this._rootUrl,e):this._bridge.authAnonymously(this._rootUrl)).then(()=>this._auth.changePromise))}unauthenticate(){return this._auth.serial++,this._handleAuthChange(null).then(e=>{if(e)return this._dispatcher.execute("auth","unauthenticate",new b(this._tree,"/"),void 0,()=>this._bridge.unauth(this._rootUrl))})}_handleAuthChange(r){var e=!this._auth.initialAuthChangeReceived&&this._auth.serial;if(void 0!==r&&(this._auth.initialAuthChangeReceived=!0),!e){let e=this._auth.serial;if(this.root.user===r)return Promise.resolve(!1);let t=this._dispatcher.execute("auth","certify",new b(this._tree,"/"),r,()=>this.root.user!==r&&e===this._auth.serial&&(r&&Object.freeze(r),this.root.user=r,this.root.userid=r&&r.uid,c.digest(),!0));return this._auth.changePromise=this._auth.changePromise.then(()=>t).catch(),t}}_isAuthChangeStale(e){return this.root.user===e}_connectInfoProperty(e,t){var r=new URL(this._rootUrl);r.pathname=encodeURI("/.info/"+e),this._bridge.on(r.href,r.href,null,"value",e=>{this.root[t]=e.value,c.digest()})}}let se={__ob__:!0},ie=new Set(["beforeMount","mounted","beforeUpdate","updated","activated","deactivated","errorCaptured"]),ae=new Set(_.default.map(ie,e=>"hook:"+e)),ne=Symbol("last-computed-value"),j,C;class S{get $info(){return this.$truss.info}get $store(){return this.$truss.store}get $now(){return this.$truss.now}$newKey(){return this.$truss.newKey()}$intercept(e,t){if(this.$destroyed)throw new Error("Object already destroyed");let r=this.$truss.intercept(e,t),s=()=>{r(),this.$off("hook:destroyed",s)};return this.$on("hook:destroyed",s),s}$connect(e,t){if(this.$destroyed)throw new Error("Object already destroyed");t||(t=e,e=void 0);let r=this.$truss.connect(e,function t(r,s){if(!s||s instanceof y)return s;if(_.default.isFunction(s)){let e=function(){return r.$$touchThis(),t(r,s.call(this))};return e.angularWatchSuppressed=!0,e}return _.default.mapValues(s,e=>t(r,e))}(this,t)),s=r.destroy,i=()=>(this.$off("hook:destroyed",i),s.call(r));return this.$on("hook:destroyed",i),r.destroy=i,r}$peek(e,t){if(this.$destroyed)throw new Error("Object already destroyed");let r=P(this.$truss.peek(e,t),()=>{this.$off("hook:destroyed",r.cancel)});return this.$on("hook:destroyed",r.cancel),r}$observe(e,t,r){if(this.$destroyed)throw new Error("Object already destroyed");let s,i=this.$truss.observe(()=>(this.$$touchThis(),e.call(this)),t.bind(this),{...r,vm:this});return s=()=>{i(),this.$off("hook:destroyed",s)},this.$on("hook:destroyed",s),s}$when(e,t){if(this.$destroyed)throw new Error("Object already destroyed");let r=this.$truss.when(()=>(this.$$touchThis(),e.call(this)),t);return P(r,()=>{this.$off("hook:destroyed",r.cancel)}),this.$on("hook:destroyed",r.cancel),r}}class R{get $parent(){return j.$parent.value}get $path(){return j.$path.value}get $truss(){return Object.defineProperty(this,"$truss",{value:this.$parent.$truss}),this.$truss}get $ref(){return Object.defineProperty(this,"$ref",{value:new b(this.$truss._tree,this.$path)}),this.$ref}get $refs(){return this.$ref}get $key(){return Object.defineProperty(this,"$key",{value:d(this.$path.slice(this.$path.lastIndexOf("/")+1))}),this.$key}get $data(){return this}get $hidden(){return!1}get $empty(){return _.default.isEmpty(this.$data)}get $keys(){return _.default.keys(this.$data)}get $values(){return _.default.values(this.$data)}get $ready(){return this.$ref.ready}get $overridden(){return!1}$nextTick(){if(this.$destroyed)throw new Error("Object already destroyed");let e=this.$truss.nextTick();return P(e,()=>{this.$off("hook:destroyed",e.cancel)}),this.$on("hook:destroyed",e.cancel),e}$freezeComputedProperty(){if(!_.default.isBoolean(C))throw new Error("Cannot freeze a computed property outside of its getter function");C=!0}get $lastComputedValue(){if(_.default.isBoolean(C))return ne;throw new Error("Cannot use last computed value of a property outside of its getter function")}$set(e){return this.$ref.set(e)}$update(e){return this.$ref.update(e)}$override(e){return this.$ref.override(e)}$commit(e,t){return this.$ref.commit(e,t)}$$touchThis(){this.__ob__?this.__ob__.dep.depend():this.$parent?(Object.hasOwn(this.$parent,"$data")?this.$parent.$data:this.$parent)[this.$key]:this.$store}get $destroyed(){return!1}$on(e,t){if(this.$destroyed)throw new Error("Object already destroyed");if(ae.has(e))throw new Error(`Models don't support the "${e}" lifecycle event`);return(this.$$hooks[e]=this.$$hooks[e]||[]).push(t),this}$once(t,r){let s=this;function i(...e){s.$off(t,i),r(...e)}return i.fn=r,this.$on(t,i)}$off(e,t){if(e)if(t){if(_.default.isArray(e))for(var r of e)this.$off(r,t);else if(this.$$hooks[e]){var s=this.$$hooks[e];for(let e=0;e<s.length;e++){var i=s[e];if(i===t||i.fn===t){s.splice(e,1);break}}}}else delete this.$$hooks[e];else for(var a of _.default.keys(this.$$hooks))delete this.$$hooks[a];return this}$emit(t,...r){return _.default.has(this,"$$hooks")&&_.default.forEach(_.default.clone(this.$$hooks[t]),e=>{e.$once&&e.$once[t]&&(--e.$once[t],this.$off(t,e)),e(...r)}),this}get $$hooks(){return Object.defineProperty(this,"$$hooks",{value:{},writable:!1,enumerable:!1,configurable:!1}),this.$$hooks}}Q(S,R),_.default.forEach(R.prototype,(e,t)=>{Object.defineProperty(R.prototype,t,{value:e,enumerable:!1,configurable:!1,writable:!1})});class x{constructor(e){this.error=e}}class oe{constructor(e){this.value=e}}class he{constructor(e,t){this._vue=e,this._trie={Class:R},this._debug=t,Object.freeze(this)}init(e,t){_.default.isPlainObject(e)&&(_.default.forEach(e,(e,t)=>{e.$trussMount||(e.$$trussMount=e.$$trussMount||[],e.$$trussMount.push(t))}),e=_.default.values(e),_.default.forEach(e,e=>{!e.$trussMount&&e.$$trussMount&&(e.$trussMount=e.$$trussMount,delete e.$$trussMount)})),e=_.default.uniq(e),_.default.forEach(e,e=>this._mountClass(e,t)),this._decorateTrie(this._trie)}destroy(){}_getMount(e,t,r){var s;let i;for(s of g(e,!0)){let e=s?i.children&&(i.children[s]||!t&&i.children.$):this._trie;if(!e){if(!t)return;i.children=i.children||{},e=i.children[s]={Class:R}}if(i=e,r&&r(i))break}return i}_findMount(e,t){if(e(t=t||this._trie))return t;for(var r of _.default.keys(t.children)){r=this._findMount(e,t.children[r]);if(r)return r}}_decorateTrie(t){_.default.forEach(t.children,e=>{this._decorateTrie(e),(e.local||e.localDescendants)&&(t.localDescendants=!0)})}_augmentClass(e){let t,r=e.prototype;for(;r&&r.constructor!==Object;){for(var s of Object.getOwnPropertyNames(r)){var i=Object.getOwnPropertyDescriptor(r,s);if("$"===s.charAt(0)){if(_.default.isEqual(i,Object.getOwnPropertyDescriptor(R.prototype,s)))continue;throw new Error(`Property names starting with "$" are reserved: ${e.name}.`+s)}if(ie.has(s)&&_.default.isFunction(r[s]))throw new Error(`Models don't support the "${s}" lifecycle method`);!i.get||t&&t[s]||((t=t||{})[s]={name:s,fullName:r.constructor.name+"."+s,get:i.get,set:i.set})}r=Object.getPrototypeOf(r)}for(var a of Object.getOwnPropertyNames(R.prototype))"constructor"===a||Object.hasOwn(e.prototype,a)||Object.defineProperty(e.prototype,a,Object.getOwnPropertyDescriptor(R.prototype,a));return t}_mountClass(a,n){let o=this._augmentClass(a),h=[],e=a.$trussMount;if(!e)throw new Error(`Class ${a.name} lacks a $trussMount static property`);_.default.isArray(e)||(e=[e]),_.default.forEach(e,e=>{if(_.default.isString(e)&&(e={path:e}),!n&&"/"===e.path)throw new Error("Data root already accessed, too late to mount class");var t,r=l(e.path);for(t of r.variables){if("$"===t||"$"===t.charAt(1))throw new Error("Invalid variable name: "+t);if("$"===t.charAt(0)&&(_.default.has(R.prototype,t)||se[t]))throw new Error("Variable name conflicts with built-in property or method: "+t);h.push(t)}var s=e.path.match(/\/([^/]*)$/)[1];if("$"===s.charAt(0)){if(e.placeholder)throw new Error(`Class ${a.name} mounted at wildcard ${s} cannot be a placeholder`)}else _.default.has(e,"placeholder")||(e.placeholder={});var i=this._getMount(e.path.replace(/\$[^/]*/g,"$"),!0);if(i.matcher&&(i.escapedKey===s||"$"===i.escapedKey.charAt(0)&&"$"===s.charAt(0)))throw new Error(`Multiple classes mounted at ${e.path}: ${i.Class.name}, `+a.name);_.default.assign(i,{Class:a,matcher:r,computedProperties:o,escapedKey:s},_.default.pick(e,"placeholder","local","keysUnsafe","hidden"))}),_.default(h).uniq().forEach(e=>{Object.defineProperty(a.prototype,e,{get(){return j?j[e]&&j[e].value:void 0}})})}createObject(e,r){var s=this._getMount(e)||{Class:R};try{if(s.matcher){var i,a=s.matcher.match(e);for(i in a)r[i]={value:a[i]}}j=r;let t=new s.Class;return j=null,c.active&&this._wrapProperties(t),s.keysUnsafe&&(r.$data={value:Object.create(null),configurable:!0,enumerable:!0}),s.hidden&&(r.$hidden={value:!0}),s.computedProperties&&_.default.forEach(s.computedProperties,e=>{r[e.name]=this._buildComputedPropertyDescriptor(t,e)}),t}catch(e){throw e.extra=_.default.assign({mount:s,properties:r,className:s.Class&&s.Class.name},e.extra),e}}_wrapProperties(s){_.default.forEach(s,(e,t)=>{let r="$_"+t;Object.defineProperties(s,{[r]:{value:e,writable:!0},[t]:{get:()=>s[r],set:e=>{s[r]=e,c.digest()},enumerable:!0,configurable:!0}})})}_buildComputedPropertyDescriptor(i,a){let n=$.for(a.fullName),o,h,l=!1,u=()=>{let e=!1;var t=function(e,r){if(!this.$destroyed){this.$$touchThis();var s=C,i=(C=!1,performance.now());let t;try{try{t=e.get.call(this)}catch(e){t=new x(e)}finally{r.computeTime+=performance.now()-i,r.numRecomputes+=1}return t=C?new oe(t):t}finally{C=s}}}.bind(i,a,n);t.toString=_.default.constant("compute "+a.fullName);let r=()=>{e=!0};r=this._vue.$watch(t,e=>{if(i.$destroyed)r();else if(h&&(h.cancel&&h.cancel(),h=void 0),_.default.isObject(e)&&_.default.isFunction(e.then)){let t=e.then(e=>{t===h&&s(e)},e=>{if(t===h&&s(new x(e))&&!e.trussExpectedException)throw e});h=t}else if(s(e)&&(c.digest(),e instanceof x)&&!e.error.trussExpectedException)throw e.error},{immediate:!0});t=_.default.last(this._vue._watchers||this._vue._scope.effects);function s(e){var t=performance.now();return e instanceof oe&&(e=e.value,r(),i.$off("hook:destroyed",r)),e!==ne&&!v(o,e)&&(l=!0,i[a.name]=e,l=!1,function t(e){if(_.default.isNil(e)||!_.default.isObject(e)||Object.isFrozen(e)||e.$truss)return e;e=Object.freeze(e);if(_.default.isArray(e))return _.default.map(e,e=>t(e));return _.default.mapValues(e,e=>t(e))}(e),n.numUpdates+=1,n.updateTime+=performance.now()-t,1)}t.id=-t.id,e?r():i.$on("hook:destroyed",r),i.$off("hook:created",u)};return i.$on("hook:created",u),{enumerable:!0,configurable:!0,get(){if(!l&&o instanceof x)throw o.error;return o},set(e){if(l)o=e;else{if(!a.set)throw new Error("You cannot set a computed property: "+a.name);a.set.call(this,e)}}}}destroyObject(e){Object.defineProperty(e,"$destroyed",{value:!0,enumerable:!1,configurable:!1})}emitLifecycleHook(e,t){_.default.isFunction(e[t])&&e[t](),e.$emit("hook:"+t)}isPlaceholder(e){e=this._getMount(e);return e&&e.placeholder}isLocal(e,t){e=this._getMount(e,!1,e=>e.local);if(e&&e.local)return!0;if(this._hasLocalProperties(e,t))throw new Error("Write on a mix of local and remote tree paths.");return!1}_hasLocalProperties(e,t){if(e){if(e.local)return!0;if(e.localDescendants&&_.default.isObject(t))for(var r in t)if(this._hasLocalProperties(e.children[p(r)]||e.children.$,t[r]))return!0}return!1}forEachPlaceholderChild(e,t){e=this._getMount(e);_.default.forEach(e&&e.children,e=>{e.placeholder&&t(e)})}checkVueObject(i,e,t){t||(t=new Set);var r=new Map;let s=this._findMount(e=>e.Class===i.constructor);var a,n,o,h,l,u,c,d=_.default(i).thru(Object.getOwnPropertyNames).reject(e=>se[e]||Object.hasOwn(R.prototype,e)||/^\$_/.test(e)).reject(e=>s&&s.matcher&&_.default.includes(s.matcher.variables,e)).map(e=>{let t;try{if((t=i[e])instanceof RegExp)return}catch{return}var r=Object.getOwnPropertyDescriptor(i,e),s=!r.enumerable&&r.set&&!Object.hasOwn(i,"$_"+e);return{key:e,value:t,descriptor:r,computed:s}}).compact().value();for({key:a,value:n,descriptor:o,computed:h}of d){if(!_.default.isArray(i)||!/^\d+$/.test(a)&&"length"!==a){if("value"in o||!o.get)throw new Error(`Value at ${e}, contained in a Firetruss object, has a rogue property: `+a);if(i.$truss&&o.enumerable)try{throw i[a]=n,new Error(`Firetruss object at ${e} has an enumerable non-Firebase property: `+a)}catch(e){if("firebase_overwrite"!==e.trussCode)throw e}}_.default.isObject(n)&&(t.has(n)||Object.isSealed(n)||_.default.isFunction(n)||_.default.isElement(n)||n instanceof Promise||(t.add(n),this.checkVueObject(n,m(e,p(a)),t)),h||n.$truss||r.set(n,a))}for({key:l,value:u,computed:c}of d)if(c&&_.default.isObject(u)&&!u.$truss){var f=r.get(u);if(f)throw new Error(`Firetruss object at ${e} has properties ${l} `+`and ${f} with an aliased value`)}}}class le{constructor(e,t){this._coupler=e,this._query=t,this._listeners=[],this._keys=[],this._coupler._url.pathname=encodeURI(t.path),this._url=this._coupler._url.toString(),this._segments=g(t.path,!0),this._listening=!1,this.ready=!1}attach(e,t){this._listen(),this._listeners.push({operation:e,keysCallback:t}),this.ready&&(this._coupler._dispatcher.markReady(e),t)&&t(this._keys)}detach(e){e=_.default.findIndex(this._listeners,{operation:e});return 0<=e&&this._listeners.splice(e,1),this._listeners.length}_listen(){this._listening||(this._coupler._bridge.on(this._query.toString(),this._url,this._query.constraints,"value",this._handleSnapshot,this._handleError,this,{sync:!0}),this._listening=!0)}destroy(){this._coupler._bridge.off(this._query.toString(),this._url,this._query.constraints,"value",this._handleSnapshot,this),this._listening=!1,this.ready=!1,c.digest();for(var e of this._keys)this._coupler._decoupleSegments(this._segments.concat(e))}_handleSnapshot(s){this._coupler._queueSnapshotCallback(()=>{if(this._listeners.length&&this._listening){var e=this._updateKeysAndApplySnapshot(s);if(!this.ready){this.ready=!0,c.digest();for(var t of this._listeners)this._coupler._dispatcher.markReady(t.operation)}if(e)for(var r of this._listeners)r.keysCallback&&r.keysCallback(e)}})}_updateKeysAndApplySnapshot(e){let t;if(e.path===this._query.path){if((t=_.default.keys(e.value)).sort(),_.default.isEqual(this._keys,t))t=null;else{for(var r of _.default.difference(t,this._keys))this._coupler._coupleSegments(this._segments.concat(r));for(var s of _.default.difference(this._keys,t))this._coupler._decoupleSegments(this._segments.concat(s));this._keys=t}if(e.exists){var i,a=e.value,n=e.path;for(i of this._keys)e._path=n+"/"+i,e._key=void 0,e._value=a[i],this._coupler._applySnapshot(e);e._path=n,e._key=void 0,e._value=a}}else{var o;e.path.replace(/\/[^/]+/,"")===this._query.path&&(o=_.default.includes(this._keys,e.key),e.value?o||(this._coupler._coupleSegments(this._segments.concat(e.key)),this._keys.push(e.key),this._keys.sort(),t=this._keys):o&&(this._coupler._decoupleSegments(this._segments.concat(e.key)),_.default.pull(this._keys,e.key),this._keys.sort(),t=this._keys),this._coupler._applySnapshot(e))}return t}_handleError(r){if(this._listeners.length&&this._listening){this._listening=!1,this.ready=!1;for(var e of this._keys)this._coupler._decoupleSegments(this._segments.concat(e));this._keys=[],c.digest(),Promise.all(_.default.map(this._listeners,t=>(this._coupler._dispatcher.clearReady(t.operation),this._coupler._dispatcher.retry(t.operation,r).catch(e=>(t.operation._disconnect(e),!1))))).then(e=>{if(_.default.some(e))this._listeners.length&&this._listen();else for(var t of this._listeners)t.operation._disconnect(r)})}}}class ue{constructor(e,t,r){this._coupler=e,this.path=t,this.parent=r,this._coupler._url.pathname=encodeURI(t),this.url=this._coupler._url.toString(),this.operations=[],this.queryCount=0,this.listening=!1,this.ready=!1,this.children={}}get active(){return this.count||this.queryCount}get count(){return this.operations.length}listen(e){!e&&this.count?this.listening||(_.default.forEach(this.operations,e=>{this._coupler._dispatcher.clearReady(e)}),this._coupler._bridge.on(this.url,this.url,null,"value",this._handleSnapshot,this._handleError,this,{sync:!0}),this.listening=!0):_.default.forEach(this.children,e=>{e.listen()})}unlisten(e){!e&&this.listening?(this._coupler._bridge.off(this.url,this.url,null,"value",this._handleSnapshot,this),this.listening=!1,this._forAllDescendants(e=>{if(e.listening)return!1;e.ready&&(e.ready=!1,c.digest())})):_.default.forEach(this.children,e=>{e.unlisten()})}_handleSnapshot(e){this._coupler._queueSnapshotCallback(()=>{this.listening&&this._coupler.isTrunkCoupled(e.path)&&(this._coupler._applySnapshot(e),this.ready||e.path!==this.path||(this.ready=!0,c.digest(),this.unlisten(!0),this._forAllDescendants(e=>{for(var t of e.operations)this._coupler._dispatcher.markReady(t)})))})}_handleError(r){if(this.count&&this.listening)return this.listening=!1,this._forAllDescendants(e=>{if(e.listening)return!1;e.ready&&(e.ready=!1,c.digest());for(var t of e.operations)this._coupler._dispatcher.clearReady(t)}),this._coupler._prunePath(this.path),Promise.all(_.default.map(this.operations,t=>this._coupler._dispatcher.retry(t,r).catch(e=>(t._disconnect(e),!1)))).then(e=>{if(_.default.some(e))this.count&&this.listen();else for(var t of this.operations)t._disconnect(r)})}_forAllDescendants(t){!1!==t(this)&&_.default.forEach(this.children,e=>e._forAllDescendants(t))}collectCoupledDescendantPaths(t){return(t=t||{})[this.path]=this.active,this.active||_.default.forEach(this.children,e=>{e.collectCoupledDescendantPaths(t)}),t}}class ce{constructor(e,t,r,s,i){this._url=new URL(e),this._bridge=t,this._dispatcher=r,this._applySnapshot=s,this._pendingSnapshotCallbacks=[],this._throttled={processPendingSnapshots:this._processPendingSnapshots},this._prunePath=i,this._vue=new u.default({data:{root:void 0,queryHandlers:{}}}),this._vue._renderProxy=this._vue,this._nodeIndex=Object.create(null),Object.freeze(this),this._vue.$data.root=new ue(this,"/"),this._nodeIndex["/"]=this._root}get _root(){return this._vue.$data.root}get _queryHandlers(){return this._vue.$data.queryHandlers}destroy(){_.default.forEach(this._queryHandlers,e=>{e.destroy()}),this._root.unlisten(),this._vue.$destroy()}couple(e,t){return this._coupleSegments(g(e,!0),t)}_coupleSegments(e,t){let r,s=!t,i=!1;for(var a of e){let e=a?r.children&&r.children[a]:this._root;e||(e=new ue(this,`${"/"===r.path?"":r.path}/`+a,r),u.default.set(r.children,a,e),this._nodeIndex[e.path]=e),s=s||e.listening,i=i||e.ready,r=e}t?r.operations.push(t):r.queryCount++,s?t&&i&&this._dispatcher.markReady(t):r.listen()}decouple(e,t){return this._decoupleSegments(g(e,!0),t)}_decoupleSegments(t,e){var r,s=[];let i;for(r of t){if(!(i=r?i.children&&i.children[r]:this._root))break;s.push(i)}if(!i||!(e?i.count:i.queryCount))throw new Error("Path not coupled: "+(t.join("/")||"/"));if(e?_.default.pull(i.operations,e):i.queryCount--,e&&!i.count&&(i.listen(),i.listening)&&i.unlisten(),!i.active){for(let e=s.length-1;0<e&&((i=s[e])!==this._root&&!i.active&&_.default.isEmpty(i.children));e--)u.default.delete(s[e-1].children,t[e]),i.ready=void 0,delete this._nodeIndex[i.path];e=t.join("/")||"/";this._prunePath(e,this.findCoupledDescendantPaths(e))}}subscribe(e,t,r){let s=this._queryHandlers[e.toString()];s||(s=new le(this,e),u.default.set(this._queryHandlers,e.toString(),s)),s.attach(t,r)}unsubscribe(e,t){var r=this._queryHandlers[e.toString()];r&&!r.detach(t)&&(r.destroy(),u.default.delete(this._queryHandlers,e.toString()))}isTrunkCoupled(e){var t;let r;for(t of g(e,!0)){if(!(r=t?r.children&&r.children[t]:this._root))return!1;if(r.active)return!0}return!1}findCoupledDescendantPaths(e){let t;for(var r of g(e,!0)){if((t=r?t.children&&t.children[r]:this._root)&&t.active)return{[e]:t.active};if(!t)break}return t&&t.collectCoupledDescendantPaths()}isSubtreeReady(e){let t,r;function s(e){return r=e.slice(1),""}for(;!(t=this._nodeIndex[e]);)e=e.replace(/\/[^/]*$/,s)||"/";for(r&&t.children;t;){if(t.ready)return!0;t=t.parent}return!1}isQueryReady(e){e=this._queryHandlers[e.toString()];return e&&e.ready}_queueSnapshotCallback(e){this._pendingSnapshotCallbacks.push(e),this._throttled.processPendingSnapshots.call(this)}_processPendingSnapshots(){for(var e of this._pendingSnapshotCallbacks)e();this._pendingSnapshotCallbacks.splice(0,1/0)}throttleSnapshots(e){this._throttled.processPendingSnapshots=e?_.default.debounce(_.default.throttle(this._processPendingSnapshots,e)):this._processPendingSnapshots}}class de{constructor(e){this._ref=e,this._outcome=void 0,this._values=void 0}get currentValue(){return this._ref.value}get outcome(){return this._outcome}get values(){return this._values}_setOutcome(e){if(this._outcome)throw new Error("Transaction already resolved with "+this._outcome);this._outcome=e}abort(){this._setOutcome("abort")}cancel(){this._setOutcome("cancel")}set(e){if(void 0===e)throw new Error("Invalid argument: undefined");this._setOutcome("set"),this._values={"":e}}update(e){if(void 0===e)throw new Error("Invalid argument: undefined");if(_.default.isEmpty(e))return this.cancel();this._setOutcome("update"),this._values=e}}class fe{constructor(e,t,r,s){this._truss=e,this._url=new URL(t),this._bridge=r,this._dispatcher=s,this._firebasePropertyEditAllowed=!1,this._writeSerial=0,this._localWrites={},this._localWriteTimestamp=null,this._initialized=!1,this._vue=new u.default({data:{$root:void 0}}),this._modeler=new he(this._vue,"dev"===e.constructor.VERSION),this._coupler=new ce(t,r,s,this._integrateSnapshot.bind(this),this._prune.bind(this)),Object.seal(this)}get root(){return this._vue.$data.$root||(this._vue.$data.$root=this._createObject("/"),this._fixObject(this._vue.$data.$root),this._completeCreateObject(this._vue.$data.$root),c.digest()),this._vue.$data.$root}get truss(){return this._truss}init(e){if(this._initialized)throw new Error("Data objects already created, too late to mount classes");this._initialized=!0,this._modeler.init(e,!this._vue.$data.$root);var t,e=[];this._plantPlaceholders(this.root,"/",void 0,e);for(t of e)this._completeCreateObject(t)}destroy(){this._coupler.destroy(),this._modeler&&this._modeler.destroy(),this._vue.$destroy()}connectReference(e,t){this._checkHandle(e);let r=this._dispatcher.createOperation("read",t,e);return r._disconnect=this._disconnectReference.bind(this,e,r,void 0),this._dispatcher.begin(r).then(()=>{r.running&&!r._disconnected&&(this._coupler.couple(e.path,r),r._coupled=!0)}).catch(_.default.noop),r._disconnect}_disconnectReference(e,t,r,s){t._disconnected||(t._disconnected=!0,r&&r(),t._coupled&&(this._coupler.decouple(e.path,t),t._coupled=!1),this._dispatcher.end(t,s).catch(_.default.noop))}isReferenceReady(e){return this._checkHandle(e),this._coupler.isSubtreeReady(e.path)}connectQuery(e,t,r){this._checkHandle(e);let s=this._dispatcher.createOperation("read",r,e);return s._disconnect=this._disconnectQuery.bind(this,e,s),this._dispatcher.begin(s).then(()=>{s.running&&!s._disconnected&&(this._coupler.subscribe(e,s,t),s._coupled=!0)}).catch(_.default.noop),s._disconnect}_disconnectQuery(e,t,r){t._disconnected||(t.