From f808facc71cb0eb5437d771dc77c41ca1383bf68 Mon Sep 17 00:00:00 2001 From: Ewout Stortenbeker Date: Mon, 19 Dec 2022 21:34:45 +0100 Subject: [PATCH] Webmanager: use acebase-client v1.20.0 --- webmanager/acebase-client-browser.min.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webmanager/acebase-client-browser.min.js b/webmanager/acebase-client-browser.min.js index 794ec50..782f88d 100644 --- a/webmanager/acebase-client-browser.min.js +++ b/webmanager/acebase-client-browser.min.js @@ -4,7 +4,7 @@ const fireThisEvent=!causedByUs||!cacheEnabled;const updateCache=!causedByUs&&ca * AceBaseClient * (c) 2018-2022 Ewout Stortenbeker * Released under MIT license - */var acebase_client_1=require("./acebase-client");Object.defineProperty(exports,"AceBaseClient",{enumerable:true,get:function(){return acebase_client_1.AceBaseClient}});var auth_1=require("./auth");Object.defineProperty(exports,"AceBaseClientAuth",{enumerable:true,get:function(){return auth_1.AceBaseClientAuth}});var user_1=require("./user");Object.defineProperty(exports,"AceBaseUser",{enumerable:true,get:function(){return user_1.AceBaseUser}});var server_date_1=require("./server-date");Object.defineProperty(exports,"ServerDate",{enumerable:true,get:function(){return server_date_1.ServerDate}});var errors_1=require("./errors");Object.defineProperty(exports,"CachedValueUnavailableError",{enumerable:true,get:function(){return errors_1.CachedValueUnavailableError}});var acebase_core_1=require("acebase-core");Object.defineProperty(exports,"DataReference",{enumerable:true,get:function(){return acebase_core_1.DataReference}});Object.defineProperty(exports,"DataSnapshot",{enumerable:true,get:function(){return acebase_core_1.DataSnapshot}});Object.defineProperty(exports,"DataSnapshotsArray",{enumerable:true,get:function(){return acebase_core_1.DataSnapshotsArray}});Object.defineProperty(exports,"DataReferencesArray",{enumerable:true,get:function(){return acebase_core_1.DataReferencesArray}});Object.defineProperty(exports,"EventStream",{enumerable:true,get:function(){return acebase_core_1.EventStream}});Object.defineProperty(exports,"EventSubscription",{enumerable:true,get:function(){return acebase_core_1.EventSubscription}});Object.defineProperty(exports,"PathReference",{enumerable:true,get:function(){return acebase_core_1.PathReference}});Object.defineProperty(exports,"TypeMappings",{enumerable:true,get:function(){return acebase_core_1.TypeMappings}});Object.defineProperty(exports,"ObjectCollection",{enumerable:true,get:function(){return acebase_core_1.ObjectCollection}});Object.defineProperty(exports,"ID",{enumerable:true,get:function(){return acebase_core_1.ID}});Object.defineProperty(exports,"proxyAccess",{enumerable:true,get:function(){return acebase_core_1.proxyAccess}});Object.defineProperty(exports,"PartialArray",{enumerable:true,get:function(){return acebase_core_1.PartialArray}});Object.defineProperty(exports,"Transport",{enumerable:true,get:function(){return acebase_core_1.Transport}})},{"./acebase-client":1,"./auth":3,"./errors":6,"./server-date":12,"./user":13,"acebase-core":25}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=performance},{}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.promiseTimeout=exports.PromiseTimeoutError=void 0;class PromiseTimeoutError extends Error{}exports.PromiseTimeoutError=PromiseTimeoutError;function promiseTimeout(promise,ms,comment){return new Promise(((resolve,reject)=>{const timeout=setTimeout((()=>reject(new PromiseTimeoutError(`Promise ${comment?`"${comment}" `:""}timed out after ${ms}ms`))),ms);function success(result){clearTimeout(timeout);resolve(result)}promise.then(success).catch(reject)}))}exports.promiseTimeout=promiseTimeout},{}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const error_1=require("./error");async function request(method,url,options={accessToken:null,data:null,dataReceivedCallback:null,dataRequestCallback:null,context:null}){var _a;let postData=options.data;if(typeof postData==="undefined"||postData===null){postData=""}else if(typeof postData==="object"){postData=JSON.stringify(postData)}const headers={"AceBase-Context":JSON.stringify(options.context||null)};const init={method:method,headers:headers,body:undefined};if(typeof options.dataRequestCallback==="function"){headers["Content-Type"]="text/plain";const supportsStreaming=false;if(supportsStreaming){let canceled=false;init.body=new ReadableStream({async pull(controller){var _a;const chunkSize=controller.desiredSize||1024*16;const chunk=await((_a=options.dataRequestCallback)===null||_a===void 0?void 0:_a.call(options,chunkSize));if(canceled||[null,""].includes(chunk)){controller.close()}else{controller.enqueue(chunk)}},async start(controller){},cancel(){canceled=true}})}else{postData="";const chunkSize=1024*512;let chunk;while(chunk=await options.dataRequestCallback(chunkSize)){postData+=chunk}init.body=postData}}else if(postData.length>0){headers["Content-Type"]="application/json";init.body=postData}if(options.accessToken){headers["Authorization"]=`Bearer ${options.accessToken}`}const request={url:url,method:method,headers:headers,body:undefined};const res=await fetch(request.url,init).catch((err=>{throw new error_1.AceBaseRequestError(request,null,"fetch_failed",err.message)}));let data="";if(typeof options.dataReceivedCallback==="function"){const reader=(_a=res.body)===null||_a===void 0?void 0:_a.getReader();await new Promise(((resolve,reject)=>{(async function readNext(){var _a;try{const result=await(reader===null||reader===void 0?void 0:reader.read());(_a=options.dataReceivedCallback)===null||_a===void 0?void 0:_a.call(options,result===null||result===void 0?void 0:result.value);if(result===null||result===void 0?void 0:result.done){return resolve()}readNext()}catch(err){reader===null||reader===void 0?void 0:reader.cancel("error");reject(err)}})()}))}else{data=await res.text()}const isJSON=data[0]==="{"||data[0]==="[";if(res.status===200){const contextHeader=res.headers.get("AceBase-Context");let context;if(contextHeader&&contextHeader[0]==="{"){context=JSON.parse(contextHeader)}else{context={}}if(isJSON){data=JSON.parse(data)}return{context:context,data:data}}else{request.body=postData;const response={statusCode:res.status,statusMessage:res.statusText,headers:res.headers,body:data};let code=res.status,message=res.statusText;if(isJSON){const err=JSON.parse(data);if(err.code){code=err.code}if(err.message){message=err.message}}throw new error_1.AceBaseRequestError(request,response,code,message)}}exports.default=request},{"./error":11}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NOT_CONNECTED_ERROR_MESSAGE=exports.AceBaseRequestError=void 0;class AceBaseRequestError extends Error{constructor(request,response,code,message="unknown error"){super(message);this.request=request;this.response=response;this.code=code;this.message=message}get isNetworkError(){return this.response===null}}exports.AceBaseRequestError=AceBaseRequestError;exports.NOT_CONNECTED_ERROR_MESSAGE="remote database is not connected"},{}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ServerDate=exports.setServerBias=void 0;const acebase_core_1=require("acebase-core");const performance_1=require("./performance");const time={serverBias:0,localBias:0,lastTime:Date.now(),lastPerf:performance_1.default.now(),get bias(){return this.serverBias+this.localBias}};function biasChanged(){console.log(`Bias changed. server bias = ${time.serverBias}ms, local bias = ${time.localBias}ms`);acebase_core_1.ID.timeBias=time.bias}const interval=1e4;function checkLocalTime(){const now=Date.now(),perf=performance_1.default.now(),msPassed=perf-time.lastPerf,expected=time.lastTime+Math.round(msPassed),diff=expected-now;if(Math.abs(diff)>1){console.log(`Local time changed. diff = ${diff}ms`);time.localBias+=diff;biasChanged()}time.lastTime=now;time.lastPerf=perf;scheduleLocalTimeCheck()}function scheduleLocalTimeCheck(){const timeout=setTimeout(checkLocalTime,interval);timeout.unref&&timeout.unref()}scheduleLocalTimeCheck();function setServerBias(bias){if(typeof bias==="number"){time.serverBias=bias;time.localBias=0;biasChanged()}}exports.setServerBias=setServerBias;class ServerDate extends Date{constructor(){const biasedTime=Date.now()+time.bias;super(biasedTime)}}exports.ServerDate=ServerDate},{"./performance":8,"acebase-core":25}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AceBaseUser=void 0;class AceBaseUser{constructor(user){var _a,_b,_c;this.emailVerified=false;this.changePassword=false;Object.assign(this,user);if(!user.uid){throw new Error("User details is missing required uid field")}this.uid=user.uid;this.displayName=(_a=user.displayName)!==null&&_a!==void 0?_a:"unknown";this.created=(_b=user.created)!==null&&_b!==void 0?_b:new Date(0).toISOString();this.settings=(_c=user.settings)!==null&&_c!==void 0?_c:{}}}exports.AceBaseUser=AceBaseUser},{}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AceBaseBase=exports.AceBaseBaseSettings=void 0;const simple_event_emitter_1=require("./simple-event-emitter");const data_reference_1=require("./data-reference");const type_mappings_1=require("./type-mappings");const optional_observable_1=require("./optional-observable");const debug_1=require("./debug");const simple_colors_1=require("./simple-colors");class AceBaseBaseSettings{constructor(options){this.logLevel="log";this.logColors=true;this.info="realtime database";this.sponsor=false;if(typeof options!=="object"){options={}}if(typeof options.logLevel==="string"){this.logLevel=options.logLevel}if(typeof options.logColors==="boolean"){this.logColors=options.logColors}if(typeof options.info==="string"){this.info=options.info}if(typeof options.sponsor==="boolean"){this.sponsor=options.sponsor}}}exports.AceBaseBaseSettings=AceBaseBaseSettings;class AceBaseBase extends simple_event_emitter_1.SimpleEventEmitter{constructor(dbname,options={}){super();this._ready=false;options=new AceBaseBaseSettings(options);this.name=dbname;this.debug=new debug_1.DebugLogger(options.logLevel,`[${dbname}]`);(0,simple_colors_1.SetColorsEnabled)(options.logColors);const logoStyle=[simple_colors_1.ColorStyle.magenta,simple_colors_1.ColorStyle.bold];const logo=" ___ ______ "+"\n"+" / _ \\ | ___ \\ "+"\n"+" / /_\\ \\ ___ ___| |_/ / __ _ ___ ___ "+"\n"+" | _ |/ __/ _ \\ ___ \\/ _` / __|/ _ \\"+"\n"+" | | | | (_| __/ |_/ / (_| \\__ \\ __/"+"\n"+" \\_| |_/\\___\\___\\____/ \\__,_|___/\\___|";const info=options.info?"".padStart(40-options.info.length," ")+options.info+"\n":"";if(!options.sponsor){this.debug.write(logo.colorize(logoStyle));info&&this.debug.write(info.colorize(simple_colors_1.ColorStyle.magenta))}this.types=new type_mappings_1.TypeMappings(this);this.once("ready",(()=>{this._ready=true}))}async ready(callback){if(!this._ready){await new Promise((resolve=>this.on("ready",resolve)))}callback===null||callback===void 0?void 0:callback()}get isReady(){return this._ready}setObservable(ObservableImpl){(0,optional_observable_1.setObservable)(ObservableImpl)}ref(path){return new data_reference_1.DataReference(this,path)}get root(){return this.ref("")}query(path){const ref=new data_reference_1.DataReference(this,path);return new data_reference_1.DataReferenceQuery(ref)}get indexes(){return{get:()=>this.api.getIndexes(),create:(path,key,options)=>this.api.createIndex(path,key,options),delete:async filePath=>this.api.deleteIndex(filePath)}}get schema(){return{get:path=>this.api.getSchema(path),set:(path,schema)=>this.api.setSchema(path,schema),all:()=>this.api.getSchemas(),check:(path,value,isUpdate)=>this.api.validateSchema(path,value,isUpdate)}}}exports.AceBaseBase=AceBaseBase},{"./data-reference":21,"./debug":23,"./optional-observable":27,"./simple-colors":34,"./simple-event-emitter":35,"./type-mappings":38}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Api=void 0;class NotImplementedError extends Error{constructor(name){super(`${name} is not implemented`)}}class Api{constructor(){}stats(options){throw new NotImplementedError("stats")}subscribe(path,event,callback,settings){throw new NotImplementedError("subscribe")}unsubscribe(path,event,callback){throw new NotImplementedError("unsubscribe")}update(path,updates,options){throw new NotImplementedError("update")}set(path,value,options){throw new NotImplementedError("set")}get(path,options){throw new NotImplementedError("get")}transaction(path,callback,options){throw new NotImplementedError("transaction")}exists(path){throw new NotImplementedError("exists")}query(path,query,options){throw new NotImplementedError("query")}reflect(path,type,args){throw new NotImplementedError("reflect")}export(path,write,options){throw new NotImplementedError("export")}import(path,read,options){throw new NotImplementedError("import")}createIndex(path,key,options){throw new NotImplementedError("createIndex")}getIndexes(){throw new NotImplementedError("getIndexes")}deleteIndex(filePath){throw new NotImplementedError("deleteIndex")}setSchema(path,schema){throw new NotImplementedError("setSchema")}getSchema(path){throw new NotImplementedError("getSchema")}getSchemas(){throw new NotImplementedError("getSchemas")}validateSchema(path,value,isUpdate){throw new NotImplementedError("validateSchema")}getMutations(filter){throw new NotImplementedError("getMutations")}getChanges(filter){throw new NotImplementedError("getChanges")}}exports.Api=Api},{}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ascii85=void 0;function c(input,length,result){const b=[0,0,0,0,0];for(let i=0;i";return ret}exports.ascii85={encode:function(arr){if(arr instanceof ArrayBuffer){arr=new Uint8Array(arr,0,arr.byteLength)}return encode(arr)},decode:function(input){if(!input.startsWith("<~")||!input.endsWith("~>")){throw new Error("Invalid input string")}input=input.substr(2,input.length-4);const n=input.length,r=[],b=[0,0,0,0,0];let t,x,y,d;for(let i=0;i>>=8;y=t&255;t>>>=8;r.push(t>>>8,t&255,y,x);for(let j=d;j<5;++j,r.pop());i+=4}const data=new Uint8Array(r);return data.buffer.slice(data.byteOffset,data.byteOffset+data.byteLength)}}},{}],17:[function(require,module,exports){"use strict";var _a,_b;Object.defineProperty(exports,"__esModule",{value:true});const pad_1=require("../pad");const env=typeof window==="object"?window:self,globalCount=Object.keys(env).length,mimeTypesLength=(_b=(_a=navigator.mimeTypes)===null||_a===void 0?void 0:_a.length)!==null&&_b!==void 0?_b:0,clientId=(0,pad_1.default)((mimeTypesLength+navigator.userAgent.length).toString(36)+globalCount.toString(36),4);function fingerprint(){return clientId}exports.default=fingerprint},{"../pad":19}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const fingerprint_1=require("./fingerprint");const pad_1=require("./pad");let c=0;const blockSize=4,base=36,discreteValues=Math.pow(base,blockSize);function randomBlock(){return(0,pad_1.default)((Math.random()*discreteValues<<0).toString(base),blockSize)}function safeCounter(){c=ct2[i]===key))}static isAncestor(ancestor,other){return ancestor.lengthother[i]===key))}static isDescendant(descendant,other){return descendant.length>other.length&&other.every(((key,i)=>descendant[i]===key))}}const isProxy=Symbol("isProxy");class LiveDataProxy{static async create(ref,options){var _a;ref=new data_reference_1.DataReference(ref.db,ref.path);let cache,loaded=false;let latestCursor=options===null||options===void 0?void 0:options.cursor;let proxy;const proxyId=id_1.ID.generate();const clientSubscriptions=[];const clientEventEmitter=new simple_event_emitter_1.SimpleEventEmitter;clientEventEmitter.on("cursor",(cursor=>latestCursor=cursor));clientEventEmitter.on("error",(err=>{console.error(err.message,err.details)}));const applyChange=(keys,newValue)=>{if(keys.length===0){cache=newValue;return true}const allowCreation=false;if(allowCreation){cache=typeof keys[0]==="number"?[]:{}}let target=cache;const trailKeys=keys.slice();while(trailKeys.length>1){const key=trailKeys.shift();if(!(key in target)){if(allowCreation){target[key]=typeof key==="number"?[]:{}}else{return false}}target=target[key]}const prop=trailKeys.shift();if(newValue===null){target instanceof Array?target.splice(prop,1):delete target[prop]}else{target[prop]=newValue}return true};const syncFallback=async()=>{if(!loaded){return}await reload()};const subscription=ref.on("mutations",{syncFallback:syncFallback}).subscribe((async snap=>{var _a;if(!loaded){return}const context=snap.context();const isRemote=((_a=context.acebase_proxy)===null||_a===void 0?void 0:_a.id)!==proxyId;if(!isRemote){return}const mutations=snap.val(false);const proceed=mutations.every((mutation=>{if(!applyChange(mutation.target,mutation.val)){return false}const changeRef=mutation.target.reduce(((ref,key)=>ref.child(key)),ref);const changeSnap=new data_snapshot_1.DataSnapshot(changeRef,mutation.val,false,mutation.prev,snap.context());clientEventEmitter.emit("mutation",{snapshot:changeSnap,isRemote:isRemote});return true}));if(proceed){clientEventEmitter.emit("cursor",context.acebase_cursor);localMutationsEmitter.emit("mutations",{origin:"remote",snap:snap})}else{console.warn(`Cached value of live data proxy on "${ref.path}" appears outdated, will be reloaded`);await reload()}}));let processPromise=Promise.resolve();const mutationQueue=[];const transactions=[];const pushLocalMutations=async()=>{const mutations=[];for(let i=0,m=mutationQueue[0];iRelativeNodeTarget.areEqual(t.target,m.target)||RelativeNodeTarget.isAncestor(t.target,m.target)))){mutationQueue.splice(i,1);i--;mutations.push(m)}}if(mutations.length===0){return}mutations.forEach((mutation=>{mutation.value=(0,utils_1.cloneObject)(getTargetValue(cache,mutation.target))}));process_1.default.nextTick((()=>{const context={acebase_proxy:{id:proxyId,source:"update"}};mutations.forEach((mutation=>{const mutationRef=mutation.target.reduce(((ref,key)=>ref.child(key)),ref);const mutationSnap=new data_snapshot_1.DataSnapshot(mutationRef,mutation.value,false,mutation.previous,context);clientEventEmitter.emit("mutation",{snapshot:mutationSnap,isRemote:false})}));const snap=new data_snapshot_1.MutationsDataSnapshot(ref,mutations.map((m=>({target:m.target,val:m.value,prev:m.previous}))),context);localMutationsEmitter.emit("mutations",{origin:"local",snap:snap})}));processPromise=mutations.reduce(((mutations,m,i,arr)=>{if(!arr.some((other=>RelativeNodeTarget.isAncestor(other.target,m.target)))){mutations.push(m)}return mutations}),[]).reduce(((updates,m)=>{const target=m.target;if(target.length===0){updates.push({ref:ref,target:target,value:cache,type:"set",previous:m.previous})}else{const parentTarget=target.slice(0,-1);const key=target.slice(-1)[0];const parentRef=parentTarget.reduce(((ref,key)=>ref.child(key)),ref);const parentUpdate=updates.find((update=>update.ref.path===parentRef.path));const cacheValue=getTargetValue(cache,target);const prevValue=m.previous;if(parentUpdate){parentUpdate.value[key]=cacheValue;parentUpdate.previous[key]=prevValue}else{updates.push({ref:parentRef,target:parentTarget,value:{[key]:cacheValue},type:"update",previous:{[key]:prevValue}})}}return updates}),[]).reduce((async(promise,update)=>{const context={acebase_proxy:{id:proxyId,source:update.type}};await promise;await update.ref.context(context)[update.type](update.value).catch((err=>{clientEventEmitter.emit("error",{source:"update",message:`Error processing update of "/${ref.path}"`,details:err});const context={acebase_proxy:{id:proxyId,source:"update-rollback"}};const mutations=[];if(update.type==="set"){setTargetValue(cache,update.target,update.previous);const mutationSnap=new data_snapshot_1.DataSnapshot(update.ref,update.previous,false,update.value,context);clientEventEmitter.emit("mutation",{snapshot:mutationSnap,isRemote:false});mutations.push({target:update.target,val:update.previous,prev:update.value})}else{Object.keys(update.previous).forEach((key=>{setTargetValue(cache,update.target.concat(key),update.previous[key]);const mutationSnap=new data_snapshot_1.DataSnapshot(update.ref.child(key),update.previous[key],false,update.value[key],context);clientEventEmitter.emit("mutation",{snapshot:mutationSnap,isRemote:false});mutations.push({target:update.target.concat(key),val:update.previous[key],prev:update.value[key]})}))}mutations.forEach((m=>{const mutationRef=m.target.reduce(((ref,key)=>ref.child(key)),ref);const mutationSnap=new data_snapshot_1.DataSnapshot(mutationRef,m.val,false,m.prev,context);clientEventEmitter.emit("mutation",{snapshot:mutationSnap,isRemote:false})}));const snap=new data_snapshot_1.MutationsDataSnapshot(update.ref,mutations,context);localMutationsEmitter.emit("mutations",{origin:"local",snap:snap})}));if(update.ref.cursor){clientEventEmitter.emit("cursor",update.ref.cursor)}}),processPromise);await processPromise};let syncInProgress=false;const syncPromises=[];const syncCompleted=()=>{let resolve;const promise=new Promise((rs=>resolve=rs));syncPromises.push({resolve:resolve});return promise};let processQueueTimeout=null;const scheduleSync=()=>{if(!processQueueTimeout){processQueueTimeout=setTimeout((async()=>{syncInProgress=true;processQueueTimeout=null;await pushLocalMutations();syncInProgress=false;syncPromises.splice(0).forEach((p=>p.resolve()))}),0)}};const flagOverwritten=target=>{if(!mutationQueue.find((m=>RelativeNodeTarget.areEqual(m.target,target)))){mutationQueue.push({target:target,previous:(0,utils_1.cloneObject)(getTargetValue(cache,target))})}scheduleSync()};const localMutationsEmitter=new simple_event_emitter_1.SimpleEventEmitter;const addOnChangeHandler=(target,callback)=>{const isObject=val=>val!==null&&typeof val==="object";const mutationsHandler=async details=>{var _a;const{snap:snap,origin:origin}=details;const context=snap.context();const causedByOurProxy=((_a=context.acebase_proxy)===null||_a===void 0?void 0:_a.id)===proxyId;if(details.origin==="remote"&&causedByOurProxy){console.error("DEV ISSUE: mutationsHandler was called from remote event originating from our own proxy");return}const mutations=snap.val(false).filter((mutation=>mutation.target.slice(0,target.length).every(((key,i)=>target[i]===key))));if(mutations.length===0){return}let newValue,previousValue;const singleMutation=mutations.find((m=>m.target.length<=target.length));if(singleMutation){const trailKeys=target.slice(singleMutation.target.length);newValue=trailKeys.reduce(((val,key)=>!isObject(val)||!(key in val)?null:val[key]),singleMutation.val);previousValue=trailKeys.reduce(((val,key)=>!isObject(val)||!(key in val)?null:val[key]),singleMutation.prev)}else{const currentValue=getTargetValue(cache,target);newValue=(0,utils_1.cloneObject)(currentValue);previousValue=(0,utils_1.cloneObject)(newValue);mutations.forEach((mutation=>{const trailKeys=mutation.target.slice(target.length);for(let i=0,val=newValue,prev=previousValue;i{let keepSubscription=true;try{keepSubscription=false!==callback(Object.freeze(newValue),Object.freeze(previousValue),!causedByOurProxy,context)}catch(err){clientEventEmitter.emit("error",{source:origin==="remote"?"remote_update":"local_update",message:"Error running subscription callback",details:err})}if(keepSubscription===false){stop()}}))};localMutationsEmitter.on("mutations",mutationsHandler);const stop=()=>{localMutationsEmitter.off("mutations").off("mutations",mutationsHandler);clientSubscriptions.splice(clientSubscriptions.findIndex((cs=>cs.stop===stop)),1)};clientSubscriptions.push({target:target,stop:stop});return{stop:stop}};const handleFlag=(flag,target,args)=>{if(flag==="write"){return flagOverwritten(target)}else if(flag==="onChange"){return addOnChangeHandler(target,args.callback)}else if(flag==="subscribe"||flag==="observe"){const subscribe=subscriber=>{const currentValue=getTargetValue(cache,target);subscriber.next(currentValue);const subscription=addOnChangeHandler(target,(value=>{subscriber.next(value)}));return function unsubscribe(){subscription.stop()}};if(flag==="subscribe"){return subscribe}const Observable=(0,optional_observable_1.getObservable)();return new Observable(subscribe)}else if(flag==="transaction"){const hasConflictingTransaction=transactions.some((t=>RelativeNodeTarget.areEqual(target,t.target)||RelativeNodeTarget.isAncestor(target,t.target)||RelativeNodeTarget.isDescendant(target,t.target)));if(hasConflictingTransaction){return Promise.reject(new Error("Cannot start transaction because it conflicts with another transaction"))}return new Promise((async resolve=>{const hasPendingMutations=mutationQueue.some((m=>RelativeNodeTarget.areEqual(target,m.target)||RelativeNodeTarget.isAncestor(target,m.target)));if(hasPendingMutations){if(!syncInProgress){scheduleSync()}await syncCompleted()}const tx={target:target,status:"started",transaction:null};transactions.push(tx);tx.transaction={get status(){return tx.status},get completed(){return tx.status!=="started"},get mutations(){return mutationQueue.filter((m=>RelativeNodeTarget.areEqual(tx.target,m.target)||RelativeNodeTarget.isAncestor(tx.target,m.target)))},get hasMutations(){return this.mutations.length>0},async commit(){if(this.completed){throw new Error(`Transaction has completed already (status '${tx.status}')`)}tx.status="finished";transactions.splice(transactions.indexOf(tx),1);if(syncInProgress){await syncCompleted()}scheduleSync();await syncCompleted()},rollback(){if(this.completed){throw new Error(`Transaction has completed already (status '${tx.status}')`)}tx.status="canceled";const mutations=[];for(let i=0;i{if(m.target.length===0){cache=m.previous}else{setTargetValue(cache,m.target,m.previous)}}));transactions.splice(transactions.indexOf(tx),1)}};resolve(tx.transaction)}))}};const snap=await ref.get({cache_mode:"allow",cache_cursor:options===null||options===void 0?void 0:options.cursor});if(snap.context().acebase_origin!=="cache"){clientEventEmitter.emit("cursor",(_a=ref.cursor)!==null&&_a!==void 0?_a:null)}loaded=true;cache=snap.val();if(cache===null&&typeof(options===null||options===void 0?void 0:options.defaultValue)!=="undefined"){cache=options.defaultValue;const context={acebase_proxy:{id:proxyId,source:"default"}};await ref.context(context).set(cache)}proxy=createProxy({root:{ref:ref,get cache(){return cache}},target:[],id:proxyId,flag:handleFlag});const assertProxyAvailable=()=>{if(proxy===null){throw new Error("Proxy was destroyed")}};const reload=async()=>{assertProxyAvailable();mutationQueue.splice(0);const snap=await ref.get({allow_cache:false});const oldVal=cache,newVal=snap.val();cache=newVal;const mutations=(0,utils_1.getMutations)(oldVal,newVal);if(mutations.length===0){return}const context=snap.context();context.acebase_proxy={id:proxyId,source:"reload"};mutations.forEach((m=>{const targetRef=getTargetRef(ref,m.target);const newSnap=new data_snapshot_1.DataSnapshot(targetRef,m.val,m.val===null,m.prev,context);clientEventEmitter.emit("mutation",{snapshot:newSnap,isRemote:true})}));const mutationsSnap=new data_snapshot_1.MutationsDataSnapshot(ref,mutations,context);localMutationsEmitter.emit("mutations",{origin:"local",snap:mutationsSnap})};return{async destroy(){await processPromise;const promises=[subscription.stop(),...clientSubscriptions.map((cs=>cs.stop()))];await Promise.all(promises);["cursor","mutation","error"].forEach((event=>clientEventEmitter.off(event)));cache=null;proxy=null},stop(){this.destroy()},get value(){assertProxyAvailable();return proxy},get hasValue(){assertProxyAvailable();return cache!==null},set value(val){assertProxyAvailable();if(val!==null&&typeof val==="object"&&val[isProxy]){val=val.valueOf()}flagOverwritten([]);cache=val},get ref(){return ref},get cursor(){return latestCursor},reload:reload,onMutation(callback){assertProxyAvailable();clientEventEmitter.off("mutation");clientEventEmitter.on("mutation",(({snapshot:snapshot,isRemote:isRemote})=>{try{callback(snapshot,isRemote)}catch(err){clientEventEmitter.emit("error",{source:"mutation_callback",message:"Error in dataproxy onMutation callback",details:err})}}))},onError(callback){assertProxyAvailable();clientEventEmitter.off("error");clientEventEmitter.on("error",(err=>{try{callback(err)}catch(err){console.error(`Error in dataproxy onError callback: ${err.message}`)}}))},on(event,callback){clientEventEmitter.on(event,callback)},off(event,callback){clientEventEmitter.off(event,callback)}}}}exports.LiveDataProxy=LiveDataProxy;function getTargetValue(obj,target){let val=obj;for(const key of target){val=typeof val==="object"&&val!==null&&key in val?val[key]:null}return val}function setTargetValue(obj,target,value){if(target.length===0){throw new Error("Cannot update root target, caller must do that itself!")}const targetObject=target.slice(0,-1).reduce(((obj,key)=>obj[key]),obj);const prop=target.slice(-1)[0];if(value===null||typeof value==="undefined"){targetObject instanceof Array?targetObject.splice(prop,1):delete targetObject[prop]}else{targetObject[prop]=value}}function getTargetRef(ref,target){const path=path_info_1.PathInfo.get(ref.path).childPath(target);return new data_reference_1.DataReference(ref.db,path)}function createProxy(context){const targetRef=getTargetRef(context.root.ref,context.target);const childProxies=[];const handler={get(target,prop,receiver){target=getTargetValue(context.root.cache,context.target);if(typeof prop==="symbol"){if(prop.toString()===Symbol.iterator.toString()){prop="values"}else if(prop.toString()===isProxy.toString()){return true}else{return Reflect.get(target,prop,receiver)}}if(prop==="valueOf"){return function valueOf(){return target}}if(target===null||typeof target!=="object"){throw new Error(`Cannot read property "${prop}" of ${target}. Value of path "/${targetRef.path}" is not an object (anymore)`)}if(target instanceof Array&&typeof prop==="string"&&/^[0-9]+$/.test(prop)){prop=parseInt(prop)}const value=target[prop];if(value===null){delete target[prop];return}const childProxy=childProxies.find((proxy=>proxy.prop===prop));if(childProxy){if(childProxy.typeof===typeof value){return childProxy.value}childProxies.splice(childProxies.indexOf(childProxy),1)}const proxifyChildValue=prop=>{const value=target[prop];const childProxy=childProxies.find((child=>child.prop===prop));if(childProxy){if(childProxy.typeof===typeof value){return childProxy.value}childProxies.splice(childProxies.indexOf(childProxy),1)}if(typeof value!=="object"){return value}const newChildProxy=createProxy({root:context.root,target:context.target.concat(prop),id:context.id,flag:context.flag});childProxies.push({typeof:typeof value,prop:prop,value:newChildProxy});return newChildProxy};const unproxyValue=value=>value!==null&&typeof value==="object"&&value[isProxy]?value.getTarget():value;if(["string","number","boolean"].includes(typeof value)||value instanceof Date||value instanceof path_reference_1.PathReference||value instanceof ArrayBuffer||typeof value==="object"&&"buffer"in value){return value}const isArray=target instanceof Array;if(prop==="toString"){return function toString(){return`[LiveDataProxy for "${targetRef.path}"]`}}if(typeof value==="undefined"){if(prop==="push"){return function push(item){const childRef=targetRef.push();context.flag("write",context.target.concat(childRef.key));target[childRef.key]=item;return childRef.key}}if(prop==="getTarget"){return function(warn=true){warn&&console.warn("Use getTarget with caution - any changes will not be synchronized!");return target}}if(prop==="getRef"){return function getRef(){const ref=getTargetRef(context.root.ref,context.target);return ref}}if(prop==="forEach"){return function forEach(callback){const keys=Object.keys(target);let stop=false;for(let i=0;!stop&&iproxifyChildValue(key)));if(sortFn){arr.sort(sortFn)}return arr}}if(prop==="onChanged"){return function onChanged(callback){return context.flag("onChange",context.target,{callback:callback})}}if(prop==="subscribe"){return function subscribe(){return context.flag("subscribe",context.target)}}if(prop==="getObservable"){return function getObservable(){return context.flag("observe",context.target)}}if(prop==="getOrderedCollection"){return function getOrderedCollection(orderProperty,orderIncrement){return new OrderedCollectionProxy(this,orderProperty,orderIncrement)}}if(prop==="startTransaction"){return function startTransaction(){return context.flag("transaction",context.target)}}if(prop==="remove"&&!isArray){return function remove(){if(context.target.length===0){throw new Error("Can't remove proxy root value")}const parent=getTargetValue(context.root.cache,context.target.slice(0,-1));const key=context.target.slice(-1)[0];context.flag("write",context.target);delete parent[key]}}return}else if(typeof value==="function"){if(isArray){const writeArray=action=>{context.flag("write",context.target);return action()};const cleanArrayValues=values=>values.map((value=>{value=unproxyValue(value);removeVoidProperties(value);return value}));if(prop==="push"){return function push(...items){items=cleanArrayValues(items);return writeArray((()=>target.push(...items)))}}if(prop==="pop"){return function pop(){return writeArray((()=>target.pop()))}}if(prop==="splice"){return function splice(start,deleteCount,...items){items=cleanArrayValues(items);return writeArray((()=>target.splice(start,deleteCount,...items)))}}if(prop==="shift"){return function shift(){return writeArray((()=>target.shift()))}}if(prop==="unshift"){return function unshift(...items){items=cleanArrayValues(items);return writeArray((()=>target.unshift(...items)))}}if(prop==="sort"){return function sort(compareFn){return writeArray((()=>target.sort(compareFn)))}}if(prop==="reverse"){return function reverse(){return writeArray((()=>target.reverse()))}}if(["indexOf","lastIndexOf"].includes(prop)){return function indexOf(item,start){if(item!==null&&typeof item==="object"&&item[isProxy]){item=item.getTarget(false)}return target[prop](item,start)}}if(["forEach","every","some","filter","map"].includes(prop)){return function iterate(callback){return target[prop](((value,i)=>callback(proxifyChildValue(i),i,proxy)))}}if(["reduce","reduceRight"].includes(prop)){return function reduce(callback,initialValue){return target[prop](((prev,value,i)=>callback(prev,proxifyChildValue(i),i,proxy)),initialValue)}}if(["find","findIndex"].includes(prop)){return function find(callback){let value=target[prop](((value,i)=>callback(proxifyChildValue(i),i,proxy)));if(prop==="find"&&value){const index=target.indexOf(value);value=proxifyChildValue(index)}return value}}if(["values","entries","keys"].includes(prop)){return function*generator(){for(let i=0;itypeof key==="number"))){context.flag("write",context.target.slice(0,context.target.findIndex((key=>typeof key==="number"))))}else if(target instanceof Array){context.flag("write",context.target)}else{context.flag("write",context.target.concat(prop))}if(value===null){delete target[prop]}else{removeVoidProperties(value);target[prop]=value}return true},deleteProperty(target,prop){target=getTargetValue(context.root.cache,context.target);if(target===null){throw new Error(`Cannot delete property ${prop.toString()} of null`)}if(typeof prop==="symbol"){return Reflect.deleteProperty(target,prop)}if(!(prop in target)){return true}context.flag("write",context.target.concat(prop));delete target[prop];return true},ownKeys(target){target=getTargetValue(context.root.cache,context.target);return Reflect.ownKeys(target)},has(target,prop){target=getTargetValue(context.root.cache,context.target);return Reflect.has(target,prop)},getOwnPropertyDescriptor(target,prop){target=getTargetValue(context.root.cache,context.target);const descriptor=Reflect.getOwnPropertyDescriptor(target,prop);if(descriptor){descriptor.configurable=true}return descriptor},getPrototypeOf(target){target=getTargetValue(context.root.cache,context.target);return Reflect.getPrototypeOf(target)}};const proxy=new Proxy({},handler);return proxy}function removeVoidProperties(obj){if(typeof obj!=="object"){return}Object.keys(obj).forEach((key=>{const val=obj[key];if(val===null||typeof val==="undefined"){delete obj[key]}else if(typeof val==="object"){removeVoidProperties(val)}}))}function proxyAccess(proxiedValue){if(typeof proxiedValue!=="object"||!proxiedValue[isProxy]){throw new Error("Given value is not proxied. Make sure you are referencing the value through the live data proxy.")}return proxiedValue}exports.proxyAccess=proxyAccess;class OrderedCollectionProxy{constructor(collection,orderProperty="order",orderIncrement=10){this.collection=collection;this.orderProperty=orderProperty;this.orderIncrement=orderIncrement;if(typeof collection!=="object"||!collection[isProxy]){throw new Error("Collection is not proxied")}if(collection.valueOf()instanceof Array){throw new Error("Collection is an array, not an object collection")}if(!Object.keys(collection).every((key=>typeof collection[key]==="object"))){throw new Error("Collection has non-object children")}const ok=Object.keys(collection).every((key=>typeof collection[key][orderProperty]==="number"));if(!ok){const keys=Object.keys(collection);for(let i=0;i{const subscription=this.getObservable().subscribe((()=>{const newArray=this.getArray();subscriber.next(newArray)}));return function unsubscribe(){subscription.unsubscribe()}}))}getArray(){const arr=proxyAccess(this.collection).toArray(((a,b)=>a[this.orderProperty]-b[this.orderProperty]));return arr}add(item,index,from){const arr=this.getArray();let minOrder=Number.POSITIVE_INFINITY,maxOrder=Number.NEGATIVE_INFINITY;for(let i=0;ithis.collection[key]===item));if(!fromKey){throw new Error("item not found in collection")}if(from===index){return{key:fromKey,index:index}}if(Math.abs(from-index)===1){const otherItem=arr[index];const otherOrder=otherItem[this.orderProperty];otherItem[this.orderProperty]=item[this.orderProperty];item[this.orderProperty]=otherOrder;return{key:fromKey,index:index}}else{arr.splice(from,1)}}if(typeof index!=="number"||index>=arr.length){index=arr.length;item[this.orderProperty]=arr.length==0?0:maxOrder+this.orderIncrement}else if(index===0){item[this.orderProperty]=arr.length==0?0:minOrder-this.orderIncrement}else{const orders=arr.map((item=>item[this.orderProperty]));const gap=orders[index]-orders[index-1];if(gap>1){item[this.orderProperty]=orders[index]-Math.floor(gap/2)}else{arr.splice(index,0,item);for(let i=0;ithis.collection[key]===item));if(!key){throw new Error("Cannot find target object to delete")}this.collection[key]=null;return{key:key,index:index}}move(fromIndex,toIndex){const arr=this.getArray();return this.add(arr[fromIndex],toIndex,fromIndex)}sort(sortFn){const arr=this.getArray();arr.sort(sortFn);for(let i=0;i{newContext[key]=context[key]}))}this[_private].context=newContext;return this}else if(typeof context==="undefined"){console.warn("Use snap.context() instead of snap.ref.context() to get updating context in event callbacks");return currentContext}else{throw new Error("Invalid context argument")}}get cursor(){return this[_private].cursor}set cursor(value){var _a;this[_private].cursor=value;(_a=this.onCursor)===null||_a===void 0?void 0:_a.call(this,value)}get path(){return this[_private].path}get key(){const key=this[_private].key;return typeof key==="number"?`[${key}]`:key}get index(){const key=this[_private].key;if(typeof key!=="number"){throw new Error(`"${key}" is not a number`)}return key}get parent(){const currentPath=path_info_1.PathInfo.fillVariables2(this.path,this.vars);const info=path_info_1.PathInfo.get(currentPath);if(info.parentPath===null){return null}return new DataReference(this.db,info.parentPath).context(this[_private].context)}get vars(){return this[_private].vars}child(childPath){childPath=typeof childPath==="number"?childPath:childPath.replace(/^\/|\/$/g,"");const currentPath=path_info_1.PathInfo.fillVariables2(this.path,this.vars);const targetPath=path_info_1.PathInfo.getChildPath(currentPath,childPath);return new DataReference(this.db,targetPath).context(this[_private].context)}async set(value,onComplete){try{if(this.isWildcardPath){throw new Error(`Cannot set the value of wildcard path "/${this.path}"`)}if(this.parent===null){throw new Error("Cannot set the root object. Use update, or set individual child properties")}if(typeof value==="undefined"){throw new TypeError(`Cannot store undefined value in "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}value=this.db.types.serialize(this.path,value);const{cursor:cursor}=await this.db.api.set(this.path,value,{context:this[_private].context});this.cursor=cursor;if(typeof onComplete==="function"){try{onComplete(null,this)}catch(err){console.error("Error in onComplete callback:",err)}}}catch(err){if(typeof onComplete==="function"){try{onComplete(err,this)}catch(err){console.error("Error in onComplete callback:",err)}}else{throw err}}return this}async update(updates,onComplete){try{if(this.isWildcardPath){throw new Error(`Cannot update the value of wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}if(typeof updates!=="object"||updates instanceof Array||updates instanceof ArrayBuffer||updates instanceof Date){await this.set(updates)}else if(Object.keys(updates).length===0){console.warn(`update called on path "/${this.path}", but there is nothing to update`)}else{updates=this.db.types.serialize(this.path,updates);const{cursor:cursor}=await this.db.api.update(this.path,updates,{context:this[_private].context});this.cursor=cursor}if(typeof onComplete==="function"){try{onComplete(null,this)}catch(err){console.error("Error in onComplete callback:",err)}}}catch(err){if(typeof onComplete==="function"){try{onComplete(err,this)}catch(err){console.error("Error in onComplete callback:",err)}}else{throw err}}return this}async transaction(callback){if(this.isWildcardPath){throw new Error(`Cannot start a transaction on wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}let throwError;const cb=currentValue=>{currentValue=this.db.types.deserialize(this.path,currentValue);const snap=new data_snapshot_1.DataSnapshot(this,currentValue);let newValue;try{newValue=callback(snap)}catch(err){throwError=err;return}if(newValue instanceof Promise){return newValue.then((val=>this.db.types.serialize(this.path,val))).catch((err=>{throwError=err;return}))}else{return this.db.types.serialize(this.path,newValue)}};const{cursor:cursor}=await this.db.api.transaction(this.path,cb,{context:this[_private].context});this.cursor=cursor;if(throwError){throw throwError}return this}on(event,callback,cancelCallback){if(this.path===""&&["value","child_changed"].includes(event)){console.warn("WARNING: Listening for value and child_changed events on the root node is a bad practice. These events require loading of all data (value event), or potentially lots of data (child_changed event) each time they are fired")}let eventPublisher=null;const eventStream=new subscription_1.EventStream((publisher=>{eventPublisher=publisher}));const cb={event:event,stream:eventStream,userCallback:typeof callback==="function"&&callback,ourCallback:(err,path,newValue,oldValue,eventContext)=>{if(err){this.db.debug.error(`Error getting data for event ${event} on path "${path}"`,err);return}const ref=this.db.ref(path);ref[_private].vars=path_info_1.PathInfo.extractVariables(this.path,path);let callbackObject;if(event.startsWith("notify_")){callbackObject=ref.context(eventContext||{})}else{const values={previous:this.db.types.deserialize(path,oldValue),current:this.db.types.deserialize(path,newValue)};if(event==="child_removed"){callbackObject=new data_snapshot_1.DataSnapshot(ref,values.previous,true,values.previous,eventContext)}else if(event==="mutations"){callbackObject=new data_snapshot_1.MutationsDataSnapshot(ref,values.current,eventContext)}else{const isRemoved=event==="mutated"&&values.current===null;callbackObject=new data_snapshot_1.DataSnapshot(ref,values.current,isRemoved,values.previous,eventContext)}}eventPublisher.publish(callbackObject);if(eventContext===null||eventContext===void 0?void 0:eventContext.acebase_cursor){this.cursor=eventContext.acebase_cursor}}};this[_private].callbacks.push(cb);const subscribe=()=>{if(typeof callback==="function"){eventStream.subscribe(callback,((activated,cancelReason)=>{if(!activated){cancelCallback&&cancelCallback(cancelReason)}}))}const advancedOptions=typeof callback==="object"?callback:{newOnly:!callback};if(typeof advancedOptions.newOnly!=="boolean"){advancedOptions.newOnly=false}if(this.isWildcardPath){advancedOptions.newOnly=true}const cancelSubscription=err=>{const callbacks=this[_private].callbacks;callbacks.splice(callbacks.indexOf(cb),1);this.db.api.unsubscribe(this.path,event,cb.ourCallback);this.db.debug.error(`Subscription "${event}" on path "/${this.path}" canceled because of an error: ${err.message}`);eventPublisher.cancel(err.message)};const authorized=this.db.api.subscribe(this.path,event,cb.ourCallback,{newOnly:advancedOptions.newOnly,cancelCallback:cancelSubscription,syncFallback:advancedOptions.syncFallback});const allSubscriptionsStoppedCallback=()=>{const callbacks=this[_private].callbacks;callbacks.splice(callbacks.indexOf(cb),1);return this.db.api.unsubscribe(this.path,event,cb.ourCallback)};if(authorized instanceof Promise){authorized.then((()=>{eventPublisher.start(allSubscriptionsStoppedCallback)})).catch(cancelSubscription)}else{eventPublisher.start(allSubscriptionsStoppedCallback)}if(!advancedOptions.newOnly){if(event==="value"){this.get((snap=>{eventPublisher.publish(snap)}))}else if(event==="child_added"){this.get((snap=>{const val=snap.val();if(val===null||typeof val!=="object"){return}Object.keys(val).forEach((key=>{const childSnap=new data_snapshot_1.DataSnapshot(this.child(key),val[key]);eventPublisher.publish(childSnap)}))}))}else if(event==="notify_child_added"){const step=100,limit=step;let skip=0;const more=async()=>{const children=await this.db.api.reflect(this.path,"children",{limit:limit,skip:skip});children.list.forEach((child=>{const childRef=this.child(child.key);eventPublisher.publish(childRef)}));if(children.more){skip+=step;more()}};more()}}};if(this.db.isReady){subscribe()}else{this.db.ready(subscribe)}return eventStream}off(event,callback){const subscriptions=this[_private].callbacks;const stopSubs=subscriptions.filter((sub=>(!event||sub.event===event)&&(!callback||sub.userCallback===callback)));if(stopSubs.length===0){this.db.debug.warn(`Can't find event subscriptions to stop (path: "${this.path}", event: ${event||"(any)"}, callback: ${callback})`)}stopSubs.forEach((sub=>{sub.stream.stop()}));return this}get(optionsOrCallback,callback){if(!this.db.isReady){const promise=this.db.ready().then((()=>this.get(optionsOrCallback,callback)));return typeof optionsOrCallback!=="function"&&typeof callback!=="function"?promise:undefined}callback=typeof optionsOrCallback==="function"?optionsOrCallback:typeof callback==="function"?callback:undefined;if(this.isWildcardPath){const error=new Error(`Cannot get value of wildcard path "/${this.path}". Use .query() instead`);if(typeof callback==="function"){throw error}return Promise.reject(error)}const options=new DataRetrievalOptions(typeof optionsOrCallback==="object"?optionsOrCallback:{cache_mode:"allow"});const promise=this.db.api.get(this.path,options).then((result=>{var _a;const isNewApiResult="context"in result&&"value"in result;if(!isNewApiResult){console.warn("AceBase api.get method returned an old response value. Update your acebase or acebase-client package");result={value:result,context:{}}}const value=this.db.types.deserialize(this.path,result.value);const snapshot=new data_snapshot_1.DataSnapshot(this,value,undefined,undefined,result.context);if((_a=result.context)===null||_a===void 0?void 0:_a.acebase_cursor){this.cursor=result.context.acebase_cursor}return snapshot}));if(callback){promise.then(callback).catch((err=>{console.error("Uncaught error:",err)}));return}else{return promise}}once(event,options){if(event==="value"&&!this.isWildcardPath){return this.get(options)}return new Promise((resolve=>{const callback=snap=>{this.off(event,callback);resolve(snap)};this.on(event,callback)}))}push(value,onComplete){if(this.isWildcardPath){const error=new Error(`Cannot push to wildcard path "/${this.path}"`);if(typeof value==="undefined"||typeof onComplete==="function"){throw error}return Promise.reject(error)}const id=id_1.ID.generate();const ref=this.child(id);ref[_private].pushed=true;if(typeof value!=="undefined"){return ref.set(value,onComplete).then((()=>ref))}else{return ref}}async remove(){if(this.isWildcardPath){throw new Error(`Cannot remove wildcard path "/${this.path}". Use query().remove instead`)}if(this.parent===null){throw new Error("Cannot remove the root node")}return this.set(null)}async exists(){if(this.isWildcardPath){throw new Error(`Cannot check wildcard path "/${this.path}" existence`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.exists(this.path)}get isWildcardPath(){return this.path.indexOf("*")>=0||this.path.indexOf("$")>=0}query(){return new DataReferenceQuery(this)}async count(){const info=await this.reflect("info",{child_count:true});return info.children.count}async reflect(type,args){if(this.isWildcardPath){throw new Error(`Cannot reflect on wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.reflect(this.path,type,args)}async export(write,options={format:"json",type_safe:true}){if(this.isWildcardPath){throw new Error(`Cannot export wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}const writeFn=typeof write==="function"?write:write.write.bind(write);return this.db.api.export(this.path,writeFn,options)}async import(read,options={format:"json",suppress_events:false}){if(this.isWildcardPath){throw new Error(`Cannot import to wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.import(this.path,read,options)}proxy(options){const isOptionsArg=typeof options==="object"&&(typeof options.cursor!=="undefined"||typeof options.defaultValue!=="undefined");if(typeof options!=="undefined"&&!isOptionsArg){this.db.debug.warn("Warning: live data proxy is being initialized with a deprecated method signature. Use ref.proxy(options) instead of ref.proxy(defaultValue)");options={defaultValue:options}}return data_proxy_1.LiveDataProxy.create(this,options)}observe(options){if(options){throw new Error("observe does not support data retrieval options yet")}if(this.isWildcardPath){throw new Error(`Cannot observe wildcard path "/${this.path}"`)}const Observable=(0,optional_observable_1.getObservable)();return new Observable((observer=>{let cache,resolved=false;let promise=this.get(options).then((snap=>{resolved=true;cache=snap.val();observer.next(cache)}));const updateCache=snap=>{if(!resolved){promise=promise.then((()=>updateCache(snap)));return}const mutatedPath=snap.ref.path;if(mutatedPath===this.path){cache=snap.val();return observer.next(cache)}const trailKeys=path_info_1.PathInfo.getPathKeys(mutatedPath).slice(path_info_1.PathInfo.getPathKeys(this.path).length);let target=cache;while(trailKeys.length>1){const key=trailKeys.shift();if(!(key in target)){target[key]=typeof trailKeys[0]==="number"?[]:{}}target=target[key]}const prop=trailKeys.shift();const newValue=snap.val();if(newValue===null){target instanceof Array&&typeof prop==="number"?target.splice(prop,1):delete target[prop]}else{target[prop]=newValue}observer.next(cache)};this.on("mutated",updateCache);return()=>{this.off("mutated",updateCache)}}))}async forEach(callbackOrOptions,callback){let options;if(typeof callbackOrOptions==="function"){callback=callbackOrOptions}else{options=callbackOrOptions}if(typeof callback!=="function"){throw new TypeError("No callback function given")}const info=await this.reflect("children",{limit:0,skip:0});const summary={canceled:false,total:info.list.length,processed:0};for(let i=0;ithis.get(optionsOrCallback,callback)));return typeof optionsOrCallback!=="function"&&typeof callback!=="function"?promise:undefined}callback=typeof optionsOrCallback==="function"?optionsOrCallback:typeof callback==="function"?callback:undefined;const options=new QueryDataRetrievalOptions(typeof optionsOrCallback==="object"?optionsOrCallback:{snapshots:true,cache_mode:"allow"});options.allow_cache=options.cache_mode!=="bypass";options.eventHandler=ev=>{if(!this[_private].events[ev.name]){return false}const listeners=this[_private].events[ev.name];if(typeof listeners!=="object"||listeners.length===0){return false}if(["add","change","remove"].includes(ev.name)){const eventData={name:ev.name,ref:new DataReference(this.ref.db,ev.path)};if(options.snapshots&&ev.name!=="remove"){const val=db.types.deserialize(ev.path,ev.value);eventData.snapshot=new data_snapshot_1.DataSnapshot(eventData.ref,val,false)}ev=eventData}listeners.forEach((callback=>{try{callback(ev)}catch(e){}}))};options.monitor={add:false,change:false,remove:false};if(this[_private].events){if(this[_private].events["add"]&&this[_private].events["add"].length>0){options.monitor.add=true}if(this[_private].events["change"]&&this[_private].events["change"].length>0){options.monitor.change=true}if(this[_private].events["remove"]&&this[_private].events["remove"].length>0){options.monitor.remove=true}}this.stop();const db=this.ref.db;return db.api.query(this.ref.path,this[_private],options).catch((err=>{throw new Error(err)})).then((res=>{const{stop:stop}=res;let{results:results,context:context}=res;this.stop=async()=>{await stop()};if(!("results"in res&&"context"in res)){console.warn("Query results missing context. Update your acebase and/or acebase-client packages");results=res,context={}}if(options.snapshots){const snaps=results.map((result=>{const val=db.types.deserialize(result.path,result.val);return new data_snapshot_1.DataSnapshot(db.ref(result.path),val,false,undefined,context)}));return DataSnapshotsArray.from(snaps)}else{const refs=results.map((path=>db.ref(path)));return DataReferencesArray.from(refs)}})).then((results=>{callback&&callback(results);return results}))}async stop(){}getRefs(callback){return this.get({snapshots:false},callback)}find(){return this.get({snapshots:false})}async count(){const refs=await this.find();return refs.length}async exists(){const originalTake=this[_private].take;const p=this.take(1).find();this.take(originalTake);const refs=await p;return refs.length!==0}async remove(callback){const refs=await this.find();const parentUpdates=refs.reduce(((parents,ref)=>{const parent=parents[ref.parent.path];if(!parent){parents[ref.parent.path]=[ref]}else{parent.push(ref)}return parents}),{});const db=this.ref.db;const promises=Object.keys(parentUpdates).map((async parentPath=>{const updates=refs.reduce(((updates,ref)=>{updates[ref.key]=null;return updates}),{});const ref=db.ref(parentPath);try{await ref.update(updates);return{ref:ref,success:true}}catch(error){return{ref:ref,success:false,error:error}}}));const results=await Promise.all(promises);callback&&callback(results);return results}on(event,callback){if(!this[_private].events[event]){this[_private].events[event]=[]}this[_private].events[event].push(callback);return this}off(event,callback){if(typeof event==="undefined"){this[_private].events={};return this}if(!this[_private].events[event]){return this}if(typeof callback==="undefined"){delete this[_private].events[event];return this}const index=this[_private].events[event].indexOf(callback);if(!~index){return this}this[_private].events[event].splice(index,1);return this}async forEach(callbackOrOptions,callback){let options;if(typeof callbackOrOptions==="function"){callback=callbackOrOptions}else{options=callbackOrOptions}if(typeof callback!=="function"){throw new TypeError("No callback function given")}const refs=await this.find();const summary={canceled:false,total:refs.length,processed:0};for(let i=0;iarr[i]=snap));return arr}getValues(){return this.map((snap=>snap.val()))}}exports.DataSnapshotsArray=DataSnapshotsArray;class DataReferencesArray extends Array{static from(refs){const arr=new DataReferencesArray(refs.length);refs.forEach(((ref,i)=>arr[i]=ref));return arr}getPaths(){return this.map((ref=>ref.path))}}exports.DataReferencesArray=DataReferencesArray},{"./data-proxy":20,"./data-snapshot":22,"./id":24,"./optional-observable":27,"./path-info":29,"./subscription":36}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MutationsDataSnapshot=exports.DataSnapshot=void 0;const path_info_1=require("./path-info");function getChild(snapshot,path,previous=false){if(!snapshot.exists()){return null}let child=previous?snapshot.previous():snapshot.val();if(typeof path==="number"){return child[path]}path_info_1.PathInfo.getPathKeys(path).every((key=>{child=child[key];return typeof child!=="undefined"}));return child||null}function getChildren(snapshot){if(!snapshot.exists()){return[]}const value=snapshot.val();if(value instanceof Array){return new Array(value.length).map(((v,i)=>i))}if(typeof value==="object"){return Object.keys(value)}return[]}class DataSnapshot{constructor(ref,value,isRemoved=false,prevValue,context){this.ref=ref;this.val=()=>value;this.previous=()=>prevValue;this.exists=()=>{if(isRemoved){return false}return value!==null&&typeof value!=="undefined"};this.context=()=>context||{}}exists(){return false}static for(ref,value){return new DataSnapshot(ref,value)}child(path){const val=getChild(this,path,false);const prev=getChild(this,path,true);return new DataSnapshot(this.ref.child(path),val,false,prev)}hasChild(path){return getChild(this,path)!==null}hasChildren(){return getChildren(this).length>0}numChildren(){return getChildren(this).length}forEach(callback){const value=this.val();const prev=this.previous();return getChildren(this).every((key=>{const snap=new DataSnapshot(this.ref.child(key),value[key],false,prev[key]);return callback(snap)}))}get key(){return this.ref.key}}exports.DataSnapshot=DataSnapshot;class MutationsDataSnapshot extends DataSnapshot{constructor(ref,mutations,context){super(ref,mutations,false,undefined,context);this.previous=()=>{throw new Error("Iterate values to get previous values for each mutation")};this.val=(warn=true)=>{if(warn){console.warn("Unless you know what you are doing, it is best not to use the value of a mutations snapshot directly. Use child methods and forEach to iterate the mutations instead")}return mutations}}forEach(callback){const mutations=this.val();return mutations.every((mutation=>{const ref=mutation.target.reduce(((ref,key)=>ref.child(key)),this.ref);const snap=new DataSnapshot(ref,mutation.val,false,mutation.prev);return callback(snap)}))}child(index){if(typeof index!=="number"){throw new Error("child index must be a number")}const mutation=this.val()[index];const ref=mutation.target.reduce(((ref,key)=>ref.child(key)),this.ref);return new DataSnapshot(ref,mutation.val,false,mutation.prev)}}exports.MutationsDataSnapshot=MutationsDataSnapshot},{"./path-info":29}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DebugLogger=void 0;const process_1=require("./process");const noop=()=>{};class DebugLogger{constructor(level="log",prefix=""){this.level=level;this.prefix=prefix;this.setLevel(level)}setLevel(level){const prefix=this.prefix?this.prefix+" %s":"";this.verbose=["verbose"].includes(level)?prefix?console.log.bind(console,prefix):console.log.bind(console):noop;this.log=["verbose","log"].includes(level)?prefix?console.log.bind(console,prefix):console.log.bind(console):noop;this.warn=["verbose","log","warn"].includes(level)?prefix?console.warn.bind(console,prefix):console.warn.bind(console):noop;this.error=["verbose","log","warn","error"].includes(level)?prefix?console.error.bind(console,prefix):console.error.bind(console):noop;this.write=text=>{const isRunKit=typeof process_1.default!=="undefined"&&process_1.default.env&&typeof process_1.default.env.RUNKIT_ENDPOINT_PATH==="string";if(text&&isRunKit){text.split("\n").forEach((line=>console.log(line)))}else{console.log(text)}}}}exports.DebugLogger=DebugLogger},{"./process":31}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ID=void 0;const cuid_1=require("./cuid");let timeBias=0;class ID{static set timeBias(bias){if(typeof bias!=="number"){return}timeBias=bias}static generate(){return(0,cuid_1.default)(timeBias).slice(1)}}exports.ID=ID},{"./cuid":18}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ObjectCollection=exports.PartialArray=exports.SimpleObservable=exports.SchemaDefinition=exports.Colorize=exports.ColorStyle=exports.SimpleEventEmitter=exports.SimpleCache=exports.ascii85=exports.PathInfo=exports.Utils=exports.TypeMappings=exports.Transport=exports.EventSubscription=exports.EventPublisher=exports.EventStream=exports.PathReference=exports.ID=exports.DebugLogger=exports.OrderedCollectionProxy=exports.proxyAccess=exports.MutationsDataSnapshot=exports.DataSnapshot=exports.DataReferencesArray=exports.DataSnapshotsArray=exports.QueryDataRetrievalOptions=exports.DataRetrievalOptions=exports.DataReferenceQuery=exports.DataReference=exports.Api=exports.AceBaseBaseSettings=exports.AceBaseBase=void 0;var acebase_base_1=require("./acebase-base");Object.defineProperty(exports,"AceBaseBase",{enumerable:true,get:function(){return acebase_base_1.AceBaseBase}});Object.defineProperty(exports,"AceBaseBaseSettings",{enumerable:true,get:function(){return acebase_base_1.AceBaseBaseSettings}});var api_1=require("./api");Object.defineProperty(exports,"Api",{enumerable:true,get:function(){return api_1.Api}});var data_reference_1=require("./data-reference");Object.defineProperty(exports,"DataReference",{enumerable:true,get:function(){return data_reference_1.DataReference}});Object.defineProperty(exports,"DataReferenceQuery",{enumerable:true,get:function(){return data_reference_1.DataReferenceQuery}});Object.defineProperty(exports,"DataRetrievalOptions",{enumerable:true,get:function(){return data_reference_1.DataRetrievalOptions}});Object.defineProperty(exports,"QueryDataRetrievalOptions",{enumerable:true,get:function(){return data_reference_1.QueryDataRetrievalOptions}});Object.defineProperty(exports,"DataSnapshotsArray",{enumerable:true,get:function(){return data_reference_1.DataSnapshotsArray}});Object.defineProperty(exports,"DataReferencesArray",{enumerable:true,get:function(){return data_reference_1.DataReferencesArray}});var data_snapshot_1=require("./data-snapshot");Object.defineProperty(exports,"DataSnapshot",{enumerable:true,get:function(){return data_snapshot_1.DataSnapshot}});Object.defineProperty(exports,"MutationsDataSnapshot",{enumerable:true,get:function(){return data_snapshot_1.MutationsDataSnapshot}});var data_proxy_1=require("./data-proxy");Object.defineProperty(exports,"proxyAccess",{enumerable:true,get:function(){return data_proxy_1.proxyAccess}});Object.defineProperty(exports,"OrderedCollectionProxy",{enumerable:true,get:function(){return data_proxy_1.OrderedCollectionProxy}});var debug_1=require("./debug");Object.defineProperty(exports,"DebugLogger",{enumerable:true,get:function(){return debug_1.DebugLogger}});var id_1=require("./id");Object.defineProperty(exports,"ID",{enumerable:true,get:function(){return id_1.ID}});var path_reference_1=require("./path-reference");Object.defineProperty(exports,"PathReference",{enumerable:true,get:function(){return path_reference_1.PathReference}});var subscription_1=require("./subscription");Object.defineProperty(exports,"EventStream",{enumerable:true,get:function(){return subscription_1.EventStream}});Object.defineProperty(exports,"EventPublisher",{enumerable:true,get:function(){return subscription_1.EventPublisher}});Object.defineProperty(exports,"EventSubscription",{enumerable:true,get:function(){return subscription_1.EventSubscription}});exports.Transport=require("./transport");var type_mappings_1=require("./type-mappings");Object.defineProperty(exports,"TypeMappings",{enumerable:true,get:function(){return type_mappings_1.TypeMappings}});exports.Utils=require("./utils");var path_info_1=require("./path-info");Object.defineProperty(exports,"PathInfo",{enumerable:true,get:function(){return path_info_1.PathInfo}});var ascii85_1=require("./ascii85");Object.defineProperty(exports,"ascii85",{enumerable:true,get:function(){return ascii85_1.ascii85}});var simple_cache_1=require("./simple-cache");Object.defineProperty(exports,"SimpleCache",{enumerable:true,get:function(){return simple_cache_1.SimpleCache}});var simple_event_emitter_1=require("./simple-event-emitter");Object.defineProperty(exports,"SimpleEventEmitter",{enumerable:true,get:function(){return simple_event_emitter_1.SimpleEventEmitter}});var simple_colors_1=require("./simple-colors");Object.defineProperty(exports,"ColorStyle",{enumerable:true,get:function(){return simple_colors_1.ColorStyle}});Object.defineProperty(exports,"Colorize",{enumerable:true,get:function(){return simple_colors_1.Colorize}});var schema_1=require("./schema");Object.defineProperty(exports,"SchemaDefinition",{enumerable:true,get:function(){return schema_1.SchemaDefinition}});var optional_observable_1=require("./optional-observable");Object.defineProperty(exports,"SimpleObservable",{enumerable:true,get:function(){return optional_observable_1.SimpleObservable}});var partial_array_1=require("./partial-array");Object.defineProperty(exports,"PartialArray",{enumerable:true,get:function(){return partial_array_1.PartialArray}});const object_collection_1=require("./object-collection");Object.defineProperty(exports,"ObjectCollection",{enumerable:true,get:function(){return object_collection_1.ObjectCollection}})},{"./acebase-base":14,"./api":15,"./ascii85":16,"./data-proxy":20,"./data-reference":21,"./data-snapshot":22,"./debug":23,"./id":24,"./object-collection":26,"./optional-observable":27,"./partial-array":28,"./path-info":29,"./path-reference":30,"./schema":32,"./simple-cache":33,"./simple-colors":34,"./simple-event-emitter":35,"./subscription":36,"./transport":37,"./type-mappings":38,"./utils":39}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ObjectCollection=void 0;const id_1=require("./id");class ObjectCollection{static from(array){const collection={};array.forEach((child=>{collection[id_1.ID.generate()]=child}));return collection}}exports.ObjectCollection=ObjectCollection},{"./id":24}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SimpleObservable=exports.setObservable=exports.getObservable=void 0;const utils_1=require("./utils");let _shimRequested=false;let _observable;(async()=>{const global=(0,utils_1.getGlobalObject)();if(typeof global.Observable!=="undefined"){_observable=global.Observable;return}try{const{Observable:Observable}=await Promise.resolve().then((()=>require("rxjs")));_observable=Observable}catch(_a){_observable=SimpleObservable}})();function getObservable(){if(_observable===SimpleObservable&&!_shimRequested){console.warn("Using AceBase's simple Observable implementation because rxjs is not available. "+'Add it to your project with "npm install rxjs", add it to AceBase using db.setObservable(Observable), '+'or call db.setObservable("shim") to suppress this warning')}if(_observable){return _observable}throw new Error("RxJS Observable could not be loaded. ")}exports.getObservable=getObservable;function setObservable(Observable){if(Observable==="shim"){_observable=SimpleObservable;_shimRequested=true}else{_observable=Observable}}exports.setObservable=setObservable;class SimpleObservable{constructor(create){this._active=false;this._subscribers=[];this._create=create}subscribe(subscriber){if(!this._active){const next=value=>{this._subscribers.forEach((s=>{try{s(value)}catch(err){console.error("Error in subscriber callback:",err)}}))};const observer={next:next};this._cleanup=this._create(observer);this._active=true}this._subscribers.push(subscriber);const unsubscribe=()=>{this._subscribers.splice(this._subscribers.indexOf(subscriber),1);if(this._subscribers.length===0){this._active=false;this._cleanup()}};const subscription={unsubscribe:unsubscribe};return subscription}}exports.SimpleObservable=SimpleObservable},{"./utils":39,rxjs:40}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PartialArray=void 0;class PartialArray{constructor(sparseArray){if(sparseArray instanceof Array){for(let i=0;ikey.startsWith("[")?parseInt(key.slice(1,-1)):key))}class PathInfo{constructor(path){if(typeof path==="string"){this.keys=getPathKeys(path)}else if(path instanceof Array){this.keys=path}this.path=this.keys.reduce(((path,key,i)=>i===0?`${key}`:typeof key==="string"?`${path}/${key}`:`${path}[${key}]`),"")}static get(path){return new PathInfo(path)}static getChildPath(path,childKey){return PathInfo.get(path).child(childKey).path}static getPathKeys(path){return getPathKeys(path)}get key(){return this.keys.length===0?null:this.keys.slice(-1)[0]}get parent(){if(this.keys.length==0){return null}const parentKeys=this.keys.slice(0,-1);return new PathInfo(parentKeys)}get parentPath(){return this.keys.length===0?null:this.parent.path}child(childKey){if(typeof childKey==="string"){if(childKey.length===0){throw new Error(`child key for path "${this.path}" cannot be empty`)}const keys=getPathKeys(childKey);keys.forEach((key=>{if(typeof key!=="string"){return}if(/[\x00-\x08\x0b\x0c\x0e-\x1f/[\]\\]/.test(key)){throw new Error(`Invalid child key "${key}" for path "${this.path}". Keys cannot contain control characters or any of the following characters: \\ / [ ]`)}if(key.length>128){throw new Error(`child key "${key}" for path "${this.path}" is too long. Max key length is 128`)}if(key.length===0){throw new Error(`child key for path "${this.path}" cannot be empty`)}}));childKey=keys}return new PathInfo(this.keys.concat(childKey))}childPath(childKey){return this.child(childKey).path}get pathKeys(){return this.keys}static extractVariables(varPath,fullPath){if(!varPath.includes("*")&&!varPath.includes("$")){return[]}const keys=getPathKeys(varPath);const pathKeys=getPathKeys(fullPath);let count=0;const variables={get length(){return count}};keys.forEach(((key,index)=>{const pathKey=pathKeys[index];if(key==="*"){variables[count++]=pathKey}else if(typeof key==="string"&&key[0]==="$"){variables[count++]=pathKey;variables[key]=pathKey;const varName=key.slice(1);if(typeof variables[varName]==="undefined"){variables[varName]=pathKey}}}));return variables}static fillVariables(varPath,fullPath){if(varPath.indexOf("*")<0&&varPath.indexOf("$")<0){return varPath}const keys=getPathKeys(varPath);const pathKeys=getPathKeys(fullPath);const merged=keys.map(((key,index)=>{if(key===pathKeys[index]||index>=pathKeys.length){return key}else if(typeof key==="string"&&(key==="*"||key[0]==="$")){return pathKeys[index]}else{throw new Error(`Path "${fullPath}" cannot be used to fill variables of path "${varPath}" because they do not match`)}}));let mergedPath="";merged.forEach((key=>{if(typeof key==="number"){mergedPath+=`[${key}]`}else{if(mergedPath.length>0){mergedPath+="/"}mergedPath+=key}}));return mergedPath}static fillVariables2(varPath,vars){if(typeof vars!=="object"||Object.keys(vars).length===0){return varPath}const pathKeys=getPathKeys(varPath);let n=0;const targetPath=pathKeys.reduce(((path,key)=>{if(typeof key==="string"&&(key==="*"||key.startsWith("$"))){return PathInfo.getChildPath(path,vars[n++])}else{return PathInfo.getChildPath(path,key)}}),"");return targetPath}equals(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(this.path===other.path){return true}if(this.keys.length!==other.keys.length){return false}return this.keys.every(((key,index)=>{const otherKey=other.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isAncestorOf(descendantPath){const descendant=descendantPath instanceof PathInfo?descendantPath:new PathInfo(descendantPath);if(descendant.path===""||this.path===descendant.path){return false}if(this.path===""){return true}if(this.keys.length>=descendant.keys.length){return false}return this.keys.every(((key,index)=>{const otherKey=descendant.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isDescendantOf(ancestorPath){const ancestor=ancestorPath instanceof PathInfo?ancestorPath:new PathInfo(ancestorPath);if(this.path===""||this.path===ancestor.path){return false}if(ancestorPath===""){return true}if(ancestor.keys.length>=this.keys.length){return false}return ancestor.keys.every(((key,index)=>{const otherKey=this.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isOnTrailOf(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(this.path.length===0||other.path.length===0){return true}if(this.path===other.path){return true}return this.pathKeys.every(((key,index)=>{if(index>=other.keys.length){return true}const otherKey=other.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isChildOf(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(this.path===""){return false}return this.parent.equals(other)}isParentOf(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(other.path===""){return false}return this.equals(other.parent)}}exports.PathInfo=PathInfo},{}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PathReference=void 0;class PathReference{constructor(path){this.path=path}}exports.PathReference=PathReference},{}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default={nextTick(fn){setTimeout(fn,0)}}},{}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SchemaDefinition=void 0;function parse(definition){let pos=0;function consumeSpaces(){let c;while(c=definition[pos],[" ","\r","\n","\t"].includes(c)){pos++}}function consumeCharacter(c){if(definition[pos]!==c){throw new Error(`Unexpected character at position ${pos}. Expected: '${c}', found '${definition[pos]}'`)}pos++}function readProperty(){consumeSpaces();const prop={name:"",optional:false,wildcard:false};let c;while(c=definition[pos],c==="_"||c==="$"||c>="a"&&c<="z"||c>="A"&&c<="Z"||prop.name.length>0&&c>="0"&&c<="9"||prop.name.length===0&&c==="*"){prop.name+=c;pos++}if(prop.name.length===0){throw new Error(`Property name expected at position ${pos}, found: ${definition.slice(pos,pos+10)}..`)}if(definition[pos]==="?"){prop.optional=true;pos++}if(prop.name==="*"||prop.name[0]==="$"){prop.optional=true;prop.wildcard=true}consumeSpaces();consumeCharacter(":");return prop}function readType(){consumeSpaces();let type={typeOf:"any"},c;let name="";while(c=definition[pos],c>="a"&&c<="z"||c>="A"&&c<="Z"){name+=c;pos++}if(name.length===0){if(definition[pos]==="*"){consumeCharacter("*");type.typeOf="any"}else if(["'",'"',"`"].includes(definition[pos])){type.typeOf="string";type.value="";const quote=definition[pos];consumeCharacter(quote);while(c=definition[pos],c&&c!==quote){type.value+=c;pos++}consumeCharacter(quote)}else if(definition[pos]>="0"&&definition[pos]<="9"){type.typeOf="number";let nr="";while(c=definition[pos],c==="."||c==="n"||c>="0"&&c<="9"){nr+=c;pos++}if(nr.endsWith("n")){type.value=BigInt(nr)}else if(nr.includes(".")){type.value=parseFloat(nr)}else{type.value=parseInt(nr)}}else if(definition[pos]==="{"){consumeCharacter("{");type.typeOf="object";type.instanceOf=Object;type.children=[];while(true){const prop=readProperty();const types=readTypes();type.children.push({name:prop.name,optional:prop.optional,wildcard:prop.wildcard,types:types});consumeSpaces();if(definition[pos]==="}"){break}consumeCharacter(",")}consumeCharacter("}")}else if(definition[pos]==="/"){consumeCharacter("/");let pattern="",flags="";while(c=definition[pos],c!=="/"||pattern.endsWith("\\")){pattern+=c;pos++}consumeCharacter("/");while(c=definition[pos],["g","i","m","s","u","y","d"].includes(c)){flags+=c;pos++}type.typeOf="string";type.matches=new RegExp(pattern,flags)}else{throw new Error(`Expected a type definition at position ${pos}, found character '${definition[pos]}'`)}}else if(["string","number","boolean","bigint","undefined","String","Number","Boolean","BigInt"].includes(name)){type.typeOf=name.toLowerCase()}else if(name==="Object"||name==="object"){type.typeOf="object";type.instanceOf=Object}else if(name==="Date"){type.typeOf="object";type.instanceOf=Date}else if(name==="Binary"||name==="binary"){type.typeOf="object";type.instanceOf=ArrayBuffer}else if(name==="any"){type.typeOf="any"}else if(name==="null"){type.typeOf="object";type.value=null}else if(name==="Array"){consumeCharacter("<");type.typeOf="object";type.instanceOf=Array;type.genericTypes=readTypes();consumeCharacter(">")}else if(["true","false"].includes(name)){type.typeOf="boolean";type.value=name==="true"}else{throw new Error(`Unknown type at position ${pos}: "${type}"`)}consumeSpaces();while(definition[pos]==="["){consumeCharacter("[");consumeCharacter("]");type={typeOf:"object",instanceOf:Array,genericTypes:[type]}}return type}function readTypes(){consumeSpaces();const types=[readType()];while(definition[pos]==="|"){consumeCharacter("|");types.push(readType());consumeSpaces()}return types}return readType()}function checkObject(path,properties,obj,partial){const invalidProperties=properties.find((prop=>prop.name==="*"||prop.name[0]==="$"))?[]:Object.keys(obj).filter((key=>![null,undefined].includes(obj[key])&&!properties.find((prop=>prop.name===key))));if(invalidProperties.length>0){return{ok:false,reason:`Object at path "${path}" cannot have propert${invalidProperties.length===1?"y":"ies"} ${invalidProperties.map((p=>`"${p}"`)).join(", ")}`}}function checkProperty(property){const hasValue=![null,undefined].includes(obj[property.name]);if(!property.optional&&(partial?obj[property.name]===null:!hasValue)){return{ok:false,reason:`Property at path "${path}/${property.name}" is not optional`}}if(hasValue&&property.types.length===1){return checkType(`${path}/${property.name}`,property.types[0],obj[property.name],false)}if(hasValue&&!property.types.some((type=>checkType(`${path}/${property.name}`,type,obj[property.name],false).ok))){return{ok:false,reason:`Property at path "${path}/${property.name}" does not match any of ${property.types.length} allowed types`}}return{ok:true}}const namedProperties=properties.filter((prop=>!prop.wildcard));const failedProperty=namedProperties.find((prop=>!checkProperty(prop).ok));if(failedProperty){const reason=checkProperty(failedProperty).reason;return{ok:false,reason:reason}}const wildcardProperty=properties.find((prop=>prop.wildcard));if(!wildcardProperty){return{ok:true}}const wildcardChildKeys=Object.keys(obj).filter((key=>!namedProperties.find((prop=>prop.name===key))));let result={ok:true};for(let i=0;i0){if(type.typeOf!=="object"){return{ok:false,reason:`path "${path}" must be typeof ${type.typeOf}`}}if(!type.children){return ok}const childKey=trailKeys[0];let property=type.children.find((prop=>prop.name===childKey));if(!property){property=type.children.find((prop=>prop.name==="*"||prop.name[0]==="$"))}if(!property){return{ok:false,reason:`Object at path "${path}" cannot have property "${childKey}"`}}if(property.optional&&value===null&&trailKeys.length===1){return ok}let result;property.types.some((type=>{const childPath=typeof childKey==="number"?`${path}[${childKey}]`:`${path}/${childKey}`;result=checkType(childPath,type,value,partial,trailKeys.slice(1));return result.ok}));return result}if(value===null){return ok}if(type.instanceOf===Object&&(typeof value!=="object"||value instanceof Array||value instanceof Date)){return{ok:false,reason:`path "${path}" must be an object collection`}}if(type.instanceOf&&(typeof value!=="object"||value.constructor!==type.instanceOf)){return{ok:false,reason:`path "${path}" must be an instance of ${type.instanceOf.name}`}}if("value"in type&&value!==type.value){return{ok:false,reason:`path "${path}" must be value: ${type.value}`}}if(typeof value!==type.typeOf){return{ok:false,reason:`path "${path}" must be typeof ${type.typeOf}`}}if(type.instanceOf===Array&&type.genericTypes&&!value.every((v=>type.genericTypes.some((t=>checkType(path,t,v,false).ok))))){return{ok:false,reason:`every array value of path "${path}" must match one of the specified types`}}if(type.typeOf==="object"&&type.children){return checkObject(path,type.children,value,partial)}if(type.matches&&!type.matches.test(value)){return{ok:false,reason:`path "${path}" must match regular expression /${type.matches.source}/${type.matches.flags}`}}return ok}function getConstructorType(val){switch(val){case String:return"string";case Number:return"number";case Boolean:return"boolean";case Date:return"Date";case BigInt:return"bigint";case Array:throw new Error("Schema error: Array cannot be used without a type. Use string[] or Array instead");default:throw new Error(`Schema error: unknown type used: ${val.name}`)}}class SchemaDefinition{constructor(definition){this.source=definition;if(typeof definition==="object"){const toTS=obj=>"{"+Object.keys(obj).map((key=>{let val=obj[key];if(val===undefined){val="undefined"}else if(val instanceof RegExp){val=`/${val.source}/${val.flags}`}else if(typeof val==="object"){val=toTS(val)}else if(typeof val==="function"){val=getConstructorType(val)}else if(!["string","number","boolean","bigint"].includes(typeof val)){throw new Error(`Type definition for key "${key}" must be a string, number, boolean, bigint, object, regular expression, or one of these classes: String, Number, Boolean, Date, BigInt`)}return`${key}:${val}`})).join(",")+"}";this.text=toTS(definition)}else if(typeof definition==="string"){this.text=definition}else{throw new Error("Type definiton must be a string or an object")}this.type=parse(this.text)}check(path,value,partial,trailKeys){return checkType(path,this.type,value,partial,trailKeys)}}exports.SchemaDefinition=SchemaDefinition},{}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SimpleCache=void 0;const utils_1=require("./utils");const calculateExpiryTime=expirySeconds=>expirySeconds>0?Date.now()+expirySeconds*1e3:Infinity;class SimpleCache{constructor(options){var _a;this.enabled=true;if(typeof options==="number"){options={expirySeconds:options}}options.cloneValues=options.cloneValues!==false;if(typeof options.expirySeconds!=="number"&&typeof options.maxEntries!=="number"){throw new Error("Either expirySeconds or maxEntries must be specified")}this.options=options;this.cache=new Map;const interval=setInterval((()=>{this.cleanUp()}),60*1e3);(_a=interval.unref)===null||_a===void 0?void 0:_a.call(interval)}get size(){return this.cache.size}has(key){if(!this.enabled){return false}return this.cache.has(key)}get(key){if(!this.enabled){return null}const entry=this.cache.get(key);if(!entry){return null}entry.expires=calculateExpiryTime(this.options.expirySeconds);entry.accessed=Date.now();return this.options.cloneValues?(0,utils_1.cloneObject)(entry.value):entry.value}set(key,value){if(this.options.maxEntries>0&&this.cache.size>=this.options.maxEntries&&!this.cache.has(key)){let oldest=null;const now=Date.now();for(const[key,entry]of this.cache.entries()){if(entry.expires<=now){this.cache.delete(key);oldest=null;break}if(!oldest||entry.accessed{if(entry.expires<=now){this.cache.delete(key)}}))}}exports.SimpleCache=SimpleCache},{"./utils":39}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Colorize=exports.SetColorsEnabled=exports.ColorsSupported=exports.ColorStyle=void 0;const process_1=require("./process");const FontCode={bold:1,dim:2,italic:3,underline:4,inverse:7,hidden:8,strikethrough:94};const ColorCode={black:30,red:31,green:32,yellow:33,blue:34,magenta:35,cyan:36,white:37,grey:90,brightRed:91};const BgColorCode={bgBlack:40,bgRed:41,bgGreen:42,bgYellow:43,bgBlue:44,bgMagenta:45,bgCyan:46,bgWhite:47,bgGrey:100,bgBrightRed:101};const ResetCode={all:0,color:39,background:49,bold:22,dim:22,italic:23,underline:24,inverse:27,hidden:28,strikethrough:29};var ColorStyle;(function(ColorStyle){ColorStyle["reset"]="reset";ColorStyle["bold"]="bold";ColorStyle["dim"]="dim";ColorStyle["italic"]="italic";ColorStyle["underline"]="underline";ColorStyle["inverse"]="inverse";ColorStyle["hidden"]="hidden";ColorStyle["strikethrough"]="strikethrough";ColorStyle["black"]="black";ColorStyle["red"]="red";ColorStyle["green"]="green";ColorStyle["yellow"]="yellow";ColorStyle["blue"]="blue";ColorStyle["magenta"]="magenta";ColorStyle["cyan"]="cyan";ColorStyle["grey"]="grey";ColorStyle["bgBlack"]="bgBlack";ColorStyle["bgRed"]="bgRed";ColorStyle["bgGreen"]="bgGreen";ColorStyle["bgYellow"]="bgYellow";ColorStyle["bgBlue"]="bgBlue";ColorStyle["bgMagenta"]="bgMagenta";ColorStyle["bgCyan"]="bgCyan";ColorStyle["bgWhite"]="bgWhite";ColorStyle["bgGrey"]="bgGrey"})(ColorStyle=exports.ColorStyle||(exports.ColorStyle={}));function ColorsSupported(){if(typeof process_1.default==="undefined"||!process_1.default.stdout||!process_1.default.env||!process_1.default.platform||process_1.default.platform==="browser"){return false}if(process_1.default.platform==="win32"){return true}const env=process_1.default.env;if(env.COLORTERM){return true}if(env.TERM==="dumb"){return false}if(env.CI||env.TEAMCITY_VERSION){return!!env.TRAVIS}if(["iTerm.app","HyperTerm","Hyper","MacTerm","Apple_Terminal","vscode"].includes(env.TERM_PROGRAM)){return true}if(/^xterm-256|^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(env.TERM)){return true}return false}exports.ColorsSupported=ColorsSupported;let _enabled=ColorsSupported();function SetColorsEnabled(enabled){_enabled=ColorsSupported()&&enabled}exports.SetColorsEnabled=SetColorsEnabled;function Colorize(str,style){if(!_enabled){return str}const openCodes=[],closeCodes=[];const addStyle=style=>{if(style===ColorStyle.reset){openCodes.push(ResetCode.all)}else if(style in FontCode){openCodes.push(FontCode[style]);closeCodes.push(ResetCode[style])}else if(style in ColorCode){openCodes.push(ColorCode[style]);closeCodes.push(ResetCode.color)}else if(style in BgColorCode){openCodes.push(BgColorCode[style]);closeCodes.push(ResetCode.background)}};if(style instanceof Array){style.forEach(addStyle)}else{addStyle(style)}const open=openCodes.map((code=>"["+code+"m")).join("");const close=closeCodes.map((code=>"["+code+"m")).join("");return str.split("\n").map((line=>open+line+close)).join("\n")}exports.Colorize=Colorize;String.prototype.colorize=function(style){return Colorize(this,style)}},{"./process":31}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SimpleEventEmitter=void 0;function runCallback(callback,data){try{callback(data)}catch(err){console.error("Error in subscription callback",err)}}class SimpleEventEmitter{constructor(){this._subscriptions=[];this._oneTimeEvents=new Map}on(event,callback){if(this._oneTimeEvents.has(event)){return runCallback(callback,this._oneTimeEvents.get(event))}this._subscriptions.push({event:event,callback:callback,once:false});return this}off(event,callback){this._subscriptions=this._subscriptions.filter((s=>s.event!==event||callback&&s.callback!==callback));return this}once(event,callback){return new Promise((resolve=>{const ourCallback=data=>{resolve(data);callback===null||callback===void 0?void 0:callback(data)};if(this._oneTimeEvents.has(event)){runCallback(ourCallback,this._oneTimeEvents.get(event))}else{this._subscriptions.push({event:event,callback:ourCallback,once:true})}}))}emit(event,data){if(this._oneTimeEvents.has(event)){throw new Error(`Event "${event}" was supposed to be emitted only once`)}for(let i=0;i{if(this._internal.state==="active"){return resolve()}else if(this._internal.state==="canceled"&&!callback){return reject(new Error(this._internal.cancelReason))}const noop=()=>{};this._internal.activatePromises.push({resolve:resolve,reject:callback?noop:reject})}))}_setActivationState(activated,cancelReason){this._internal.cancelReason=cancelReason;this._internal.state=activated?"active":"canceled";while(this._internal.activatePromises.length>0){const p=this._internal.activatePromises.shift();if(activated){p.callback&&p.callback(true);p.resolve&&p.resolve()}else{p.callback&&p.callback(false,cancelReason);p.reject&&p.reject(cancelReason)}}}}exports.EventSubscription=EventSubscription;class EventPublisher{constructor(publish,start,cancel){this.publish=publish;this.start=start;this.cancel=cancel}}exports.EventPublisher=EventPublisher;class EventStream{constructor(eventPublisherCallback){const subscribers=[];let noMoreSubscribersCallback;let activationState;const STATE_STOPPED="stopped (no more subscribers)";this.subscribe=(callback,activationCallback)=>{if(typeof callback!=="function"){throw new TypeError("callback must be a function")}else if(activationState===STATE_STOPPED){throw new Error("stream can't be used anymore because all subscribers were stopped")}const sub={callback:callback,activationCallback:function(activated,cancelReason){activationCallback===null||activationCallback===void 0?void 0:activationCallback(activated,cancelReason);this.subscription._setActivationState(activated,cancelReason)},subscription:new EventSubscription((function stop(){subscribers.splice(subscribers.indexOf(this),1);return checkActiveSubscribers()}))};subscribers.push(sub);if(typeof activationState!=="undefined"){if(activationState===true){activationCallback===null||activationCallback===void 0?void 0:activationCallback(true);sub.subscription._setActivationState(true)}else if(typeof activationState==="string"){activationCallback===null||activationCallback===void 0?void 0:activationCallback(false,activationState);sub.subscription._setActivationState(false,activationState)}}return sub.subscription};const checkActiveSubscribers=()=>{let ret;if(subscribers.length===0){ret=noMoreSubscribersCallback===null||noMoreSubscribersCallback===void 0?void 0:noMoreSubscribersCallback();activationState=STATE_STOPPED}return Promise.resolve(ret)};this.unsubscribe=callback=>{const remove=callback?subscribers.filter((sub=>sub.callback===callback)):subscribers;remove.forEach((sub=>{const i=subscribers.indexOf(sub);subscribers.splice(i,1)}));checkActiveSubscribers()};this.stop=()=>{subscribers.splice(0);checkActiveSubscribers()};const publish=val=>{subscribers.forEach((sub=>{try{sub.callback(val)}catch(err){console.error(`Error running subscriber callback: ${err.message}`)}}));if(subscribers.length===0){checkActiveSubscribers()}return subscribers.length>0};const start=allSubscriptionsStoppedCallback=>{activationState=true;noMoreSubscribersCallback=allSubscriptionsStoppedCallback;subscribers.forEach((sub=>{var _a;(_a=sub.activationCallback)===null||_a===void 0?void 0:_a.call(sub,true)}))};const cancel=reason=>{activationState=reason;subscribers.forEach((sub=>{var _a;(_a=sub.activationCallback)===null||_a===void 0?void 0:_a.call(sub,false,reason||new Error("unknown reason"))}));subscribers.splice(0)};const publisher=new EventPublisher(publish,start,cancel);eventPublisherCallback(publisher)}}exports.EventStream=EventStream},{}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.deserialize2=exports.serialize2=exports.serialize=exports.detectSerializeVersion=exports.deserialize=void 0;const path_reference_1=require("./path-reference");const utils_1=require("./utils");const ascii85_1=require("./ascii85");const path_info_1=require("./path-info");const partial_array_1=require("./partial-array");const deserialize=data=>{if(data.map===null||typeof data.map==="undefined"){if(typeof data.val==="undefined"){throw new Error("serialized value must have a val property")}return data.val}const deserializeValue=(type,val)=>{if(type==="date"){return new Date(val)}else if(type==="binary"){return ascii85_1.ascii85.decode(val)}else if(type==="reference"){return new path_reference_1.PathReference(val)}else if(type==="regexp"){return new RegExp(val.pattern,val.flags)}else if(type==="array"){return new partial_array_1.PartialArray(val)}else if(type==="bigint"){return BigInt(val)}return val};if(typeof data.map==="string"){return deserializeValue(data.map,data.val)}Object.keys(data.map).forEach((path=>{const type=data.map[path];const keys=path_info_1.PathInfo.getPathKeys(path);let parent=data;let key="val";let val=data.val;keys.forEach((k=>{key=k;parent=val;val=val[key]}));parent[key]=deserializeValue(type,val)}));return data.val};exports.deserialize=deserialize;const detectSerializeVersion=data=>{if(typeof data!=="object"||data===null){return 2}if("map"in data&&"val"in data){return 1}else if("val"in data){if(Object.keys(data).length>1){return 2}return 1}return 2};exports.detectSerializeVersion=detectSerializeVersion;const serialize=obj=>{var _a;if(obj===null||typeof obj!=="object"||obj instanceof Date||obj instanceof ArrayBuffer||obj instanceof path_reference_1.PathReference||obj instanceof RegExp){const ser=(0,exports.serialize)({value:obj});return{map:(_a=ser.map)===null||_a===void 0?void 0:_a.value,val:ser.val.value}}obj=(0,utils_1.cloneObject)(obj);const process=(obj,mappings,prefix)=>{if(obj instanceof partial_array_1.PartialArray){mappings[prefix]="array"}Object.keys(obj).forEach((key=>{const val=obj[key];const path=prefix.length===0?key:`${prefix}/${key}`;if(typeof val==="bigint"){obj[key]=val.toString();mappings[path]="bigint"}else if(val instanceof Date){obj[key]=val.toISOString();mappings[path]="date"}else if(val instanceof ArrayBuffer){obj[key]=ascii85_1.ascii85.encode(val);mappings[path]="binary"}else if(val instanceof path_reference_1.PathReference){obj[key]=val.path;mappings[path]="reference"}else if(val instanceof RegExp){obj[key]={pattern:val.source,flags:val.flags};mappings[path]="regexp"}else if(typeof val==="object"&&val!==null){process(val,mappings,path)}}))};const mappings={};process(obj,mappings,"");const serialized={val:obj};if(Object.keys(mappings).length>0){serialized.map=mappings}return serialized};exports.serialize=serialize;const serialize2=obj=>{const getSerializedValue=val=>{if(typeof val==="bigint"){return{".type":"bigint",".val":val.toString()}}else if(val instanceof Date){return{".type":"date",".val":val.toISOString()}}else if(val instanceof ArrayBuffer){return{".type":"binary",".val":ascii85_1.ascii85.encode(val)}}else if(val instanceof path_reference_1.PathReference){return{".type":"reference",".val":val.path}}else if(val instanceof RegExp){return{".type":"regexp",".val":`/${val.source}/${val.flags}`}}else if(typeof val==="object"&&val!==null){if(val instanceof Array){const copy=[];for(let i=0;i{if(typeof data!=="object"||data===null){return data}if(typeof data[".type"]==="undefined"){if(data instanceof Array){const copy=[];const arr=data;for(let i=0;i{const mkeys=path_info_1.PathInfo.getPathKeys(mpath);if(mkeys.length!==keys.length){return false}return mkeys.every(((mkey,index)=>{if(mkey==="*"||typeof mkey==="string"&&mkey[0]==="$"){return true}return mkey===keys[index]}))}));const mapping=mappings[mappedPath];return mapping}function map(mappings,path){const targetPath=path_info_1.PathInfo.get(path).parentPath;if(targetPath===null){return}return get(mappings,targetPath)}function mapDeep(mappings,entryPath){entryPath=entryPath.replace(/^\/|\/$/g,"");const pathInfo=path_info_1.PathInfo.get(entryPath);const startPath=pathInfo.parentPath;const keys=startPath?path_info_1.PathInfo.getPathKeys(startPath):[];const matches=Object.keys(mappings).reduce(((m,mpath)=>{const mkeys=path_info_1.PathInfo.getPathKeys(mpath);if(mkeys.length{if(index>=keys.length){return false}else if(mkey==="*"||typeof mkey==="string"&&mkey[0]==="$"||mkey===keys[index]){return true}else{isMatch=false;return false}}))}if(isMatch){const mapping=mappings[mpath];m.push({path:mpath,type:mapping})}return m}),[]);return matches}function process(db,mappings,path,obj,action){if(obj===null||typeof obj!=="object"){return obj}const keys=path_info_1.PathInfo.getPathKeys(path);const m=mapDeep(mappings,path);const changes=[];m.sort(((a,b)=>path_info_1.PathInfo.getPathKeys(a.path).length>path_info_1.PathInfo.getPathKeys(b.path).length?-1:1));m.forEach((mapping=>{const mkeys=path_info_1.PathInfo.getPathKeys(mapping.path);mkeys.push("*");const mTrailKeys=mkeys.slice(keys.length);if(mTrailKeys.length===0){const vars=path_info_1.PathInfo.extractVariables(mapping.path,path);const ref=new data_reference_1.DataReference(db,path,vars);if(action==="serialize"){obj=mapping.type.serialize(obj,ref)}else if(action==="deserialize"){const snap=new data_snapshot_1.DataSnapshot(ref,obj);obj=mapping.type.deserialize(snap)}return}const process=(parentPath,parent,keys)=>{if(obj===null||typeof obj!=="object"){return obj}const key=keys[0];let children=[];if(key==="*"||typeof key==="string"&&key[0]==="$"){if(parent instanceof Array){children=parent.map(((val,index)=>({key:index,val:val})))}else{children=Object.keys(parent).map((k=>({key:k,val:parent[k]})))}}else{const child=parent[key];if(typeof child==="object"){children.push({key:key,val:child})}}children.forEach((child=>{const childPath=path_info_1.PathInfo.getChildPath(parentPath,child.key);const vars=path_info_1.PathInfo.extractVariables(mapping.path,childPath);const ref=new data_reference_1.DataReference(db,childPath,vars);if(keys.length===1){if(action==="serialize"){changes.push({parent:parent,key:child.key,original:parent[child.key]});parent[child.key]=mapping.type.serialize(child.val,ref)}else if(action==="deserialize"){const snap=new data_snapshot_1.DataSnapshot(ref,child.val);parent[child.key]=mapping.type.deserialize(snap)}}else{process(childPath,child.val,keys.slice(1))}}))};process(path,obj,mTrailKeys)}));if(action==="serialize"){obj=(0,utils_1.cloneObject)(obj);if(changes.length>0){changes.forEach((change=>{change.parent[change.key]=change.original}))}}return obj}const _mappings=Symbol("mappings");class TypeMappings{constructor(db){this.db=db;this[_mappings]={}}get mappings(){return this[_mappings]}map(path){return map(this[_mappings],path)}bind(path,type,options={}){if(typeof path!=="string"){throw new TypeError("path must be a string")}if(typeof type!=="function"){throw new TypeError("constructor must be a function")}if(typeof options.serializer==="undefined"){}else if(typeof options.serializer==="string"){if(typeof type.prototype[options.serializer]==="function"){options.serializer=type.prototype[options.serializer]}else{throw new TypeError(`${type.name}.prototype.${options.serializer} is not a function, cannot use it as serializer`)}}else if(typeof options.serializer!=="function"){throw new TypeError(`serializer for class ${type.name} must be a function, or the name of a prototype method`)}if(typeof options.creator==="undefined"){if(typeof type.create==="function"){options.creator=type.create}}else if(typeof options.creator==="string"){if(typeof type[options.creator]==="function"){options.creator=type[options.creator]}else{throw new TypeError(`${type.name}.${options.creator} is not a function, cannot use it as creator`)}}else if(typeof options.creator!=="function"){throw new TypeError(`creator for class ${type.name} must be a function, or the name of a static method`)}path=path.replace(/^\/|\/$/g,"");this[_mappings][path]={db:this.db,type:type,creator:options.creator,serializer:options.serializer,deserialize(snap){let obj;if(this.creator){obj=this.creator.call(this.type,snap)}else{obj=new this.type(snap)}return obj},serialize(obj,ref){if(this.serializer){obj=this.serializer.call(obj,ref,obj)}else if(obj&&typeof obj.serialize==="function"){obj=obj.serialize(ref,obj)}return obj}}}serialize(path,obj){return process(this.db,this[_mappings],path,obj,"serialize")}deserialize(path,obj){return process(this.db,this[_mappings],path,obj,"deserialize")}}exports.TypeMappings=TypeMappings},{"./data-reference":21,"./data-snapshot":22,"./path-info":29,"./utils":39}],39:[function(require,module,exports){(function(global,Buffer){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getGlobalObject=exports.defer=exports.getChildValues=exports.getMutations=exports.compareValues=exports.ObjectDifferences=exports.valuesAreEqual=exports.cloneObject=exports.concatTypedArrays=exports.decodeString=exports.encodeString=exports.bytesToBigint=exports.bigintToBytes=exports.bytesToNumber=exports.numberToBytes=void 0;const path_reference_1=require("./path-reference");const process_1=require("./process");const partial_array_1=require("./partial-array");function numberToBytes(number){const bytes=new Uint8Array(8);const view=new DataView(bytes.buffer);view.setFloat64(0,number);return new Array(...bytes)}exports.numberToBytes=numberToBytes;function bytesToNumber(bytes){const length=Array.isArray(bytes)?bytes.length:bytes.byteLength;if(length!==8){throw new TypeError("must be 8 bytes")}const bin=new Uint8Array(bytes);const view=new DataView(bin.buffer);const nr=view.getFloat64(0);return nr}exports.bytesToNumber=bytesToNumber;const big={zero:BigInt(0),one:BigInt(1),two:BigInt(2),eight:BigInt(8),ff:BigInt(255)};function bigintToBytes(number){if(typeof number!=="bigint"){throw new Error("number must be a bigint")}const bytes=[];const negative=number>big.eight}while(number!==(negative?-big.one:big.zero));bytes.reverse();if(negative?bytes[0]<128:bytes[0]>=128){bytes.unshift(negative?255:0)}return bytes}exports.bigintToBytes=bigintToBytes;function bytesToBigint(bytes){const negative=bytes[0]>=128;let number=big.zero;for(let b of bytes){if(negative){b=~b&255}number=(number<128){if((code&55296)===55296){const nextCode=str.charCodeAt(i+1);if((nextCode&56320)!==56320){throw new Error("follow-up utf-16 character does not start with 0xDC00")}i++;const p1=code&1023;const p2=nextCode&1023;code=65536|p1<<10|p2}if(code<2048){const b1=192|code>>6&31;const b2=128|code&63;arr.push(b1,b2)}else if(code<65536){const b1=224|code>>12&15;const b2=128|code>>6&63;const b3=128|code&63;arr.push(b1,b2,b3)}else if(code<2097152){const b1=240|code>>18&7;const b2=128|code>>12&63;const b3=128|code>>6&63;const b4=128|code&63;arr.push(b1,b2,b3,b4)}else{throw new Error(`Cannot convert character ${str.charAt(i)} (code ${code}) to utf-8`)}}else{arr.push(code<128?code:63)}}return new Uint8Array(arr)}}exports.encodeString=encodeString;function decodeString(buffer){if(typeof TextDecoder!=="undefined"){const decoder=new TextDecoder;if(buffer instanceof Uint8Array){return decoder.decode(buffer)}const buf=Uint8Array.from(buffer);return decoder.decode(buf)}else if(typeof Buffer==="function"){if(buffer instanceof Array){buffer=Uint8Array.from(buffer)}if(!(buffer instanceof Buffer)&&"buffer"in buffer&&buffer.buffer instanceof ArrayBuffer){const typedArray=buffer;buffer=Buffer.from(typedArray.buffer,typedArray.byteOffset,typedArray.byteLength)}if(!(buffer instanceof Buffer)){throw new Error("Unsupported buffer argument")}return buffer.toString("utf-8")}else{if(!(buffer instanceof Uint8Array)&&"buffer"in buffer&&buffer["buffer"]instanceof ArrayBuffer){const typedArray=buffer;buffer=new Uint8Array(typedArray.buffer,typedArray.byteOffset,typedArray.byteLength)}if(buffer instanceof Buffer||buffer instanceof Array||buffer instanceof Uint8Array){let str="";for(let i=0;i128){if((code&240)===240){const b1=code,b2=buffer[i+1],b3=buffer[i+2],b4=buffer[i+3];code=(b1&7)<<18|(b2&63)<<12|(b3&63)<<6|b4&63;i+=3}else if((code&224)===224){const b1=code,b2=buffer[i+1],b3=buffer[i+2];code=(b1&15)<<12|(b2&63)<<6|b3&63;i+=2}else if((code&192)===192){const b1=code,b2=buffer[i+1];code=(b1&31)<<6|b2&63;i++}else{throw new Error("invalid utf-8 data")}}if(code>=65536){code^=65536;const p1=55296|code>>10;const p2=56320|code&1023;str+=String.fromCharCode(p1);str+=String.fromCharCode(p2)}else{str+=String.fromCharCode(code)}}return str}else{throw new Error("Unsupported buffer argument")}}}exports.decodeString=decodeString;function concatTypedArrays(a,b){const c=new a.constructor(a.length+b.length);c.set(a);c.set(b,a.length);return c}exports.concatTypedArrays=concatTypedArrays;function cloneObject(original,stack){var _a;if(((_a=original===null||original===void 0?void 0:original.constructor)===null||_a===void 0?void 0:_a.name)==="DataSnapshot"){throw new TypeError(`Object to clone is a DataSnapshot (path "${original.ref.path}")`)}const checkAndFixTypedArray=obj=>{if(obj!==null&&typeof obj==="object"&&typeof obj.constructor==="function"&&typeof obj.constructor.name==="string"&&["Buffer","Uint8Array","Int8Array","Uint16Array","Int16Array","Uint32Array","Int32Array","BigUint64Array","BigInt64Array"].includes(obj.constructor.name)){obj=obj.buffer.slice(obj.byteOffset,obj.byteOffset+obj.byteLength)}return obj};original=checkAndFixTypedArray(original);if(typeof original!=="object"||original===null||original instanceof Date||original instanceof ArrayBuffer||original instanceof path_reference_1.PathReference||original instanceof RegExp){return original}const cloneValue=val=>{if(stack.indexOf(val)>=0){throw new ReferenceError("object contains a circular reference")}val=checkAndFixTypedArray(val);if(val===null||val instanceof Date||val instanceof ArrayBuffer||val instanceof path_reference_1.PathReference||val instanceof RegExp){return val}else if(typeof val==="object"){stack.push(val);val=cloneObject(val,stack);stack.pop();return val}else{return val}};if(typeof stack==="undefined"){stack=[original]}const clone=original instanceof Array?[]:original instanceof partial_array_1.PartialArray?new partial_array_1.PartialArray:{};Object.keys(original).forEach((key=>{const val=original[key];if(typeof val==="function"){return}clone[key]=cloneValue(val)}));return clone}exports.cloneObject=cloneObject;const isTypedArray=val=>typeof val==="object"&&["ArrayBuffer","Buffer","Uint8Array","Uint16Array","Uint32Array","Int8Array","Int16Array","Int32Array"].includes(val.constructor.name);function valuesAreEqual(val1,val2){if(val1===val2){return true}if(typeof val1!==typeof val2){return false}if(typeof val1==="object"||typeof val2==="object"){if(val1===null||val2===null){return false}if(val1 instanceof path_reference_1.PathReference||val2 instanceof path_reference_1.PathReference){return val1 instanceof path_reference_1.PathReference&&val2 instanceof path_reference_1.PathReference&&val1.path===val2.path}if(val1 instanceof Date||val2 instanceof Date){return val1 instanceof Date&&val2 instanceof Date&&val1.getTime()===val2.getTime()}if(val1 instanceof Array||val2 instanceof Array){return val1 instanceof Array&&val2 instanceof Array&&val1.length===val2.length&&val1.every(((item,i)=>valuesAreEqual(val1[i],val2[i])))}if(isTypedArray(val1)||isTypedArray(val2)){if(!isTypedArray(val1)||!isTypedArray(val2)||val1.byteLength===val2.byteLength){return false}const typed1=val1 instanceof ArrayBuffer?new Uint8Array(val1):new Uint8Array(val1.buffer,val1.byteOffset,val1.byteLength),typed2=val2 instanceof ArrayBuffer?new Uint8Array(val2):new Uint8Array(val2.buffer,val2.byteOffset,val2.byteLength);return typed1.every(((val,i)=>typed2[i]===val))}const keys1=Object.keys(val1),keys2=Object.keys(val2);return keys1.length===keys2.length&&keys1.every((key=>keys2.includes(key)))&&keys1.every((key=>valuesAreEqual(val1[key],val2[key])))}return false}exports.valuesAreEqual=valuesAreEqual;class ObjectDifferences{constructor(added,removed,changed){this.added=added;this.removed=removed;this.changed=changed}forChild(key){if(this.added.includes(key)){return"added"}if(this.removed.includes(key)){return"removed"}const changed=this.changed.find((ch=>ch.key===key));return changed?changed.change:"identical"}}exports.ObjectDifferences=ObjectDifferences;function compareValues(oldVal,newVal,sortedResults=false){const voids=[undefined,null];if(oldVal===newVal){return"identical"}else if(voids.indexOf(oldVal)>=0&&voids.indexOf(newVal)<0){return"added"}else if(voids.indexOf(oldVal)<0&&voids.indexOf(newVal)>=0){return"removed"}else if(typeof oldVal!==typeof newVal){return"changed"}else if(isTypedArray(oldVal)||isTypedArray(newVal)){if(!isTypedArray(oldVal)||!isTypedArray(newVal)){return"changed"}const typed1=oldVal instanceof Uint8Array?oldVal:oldVal instanceof ArrayBuffer?new Uint8Array(oldVal):new Uint8Array(oldVal.buffer,oldVal.byteOffset,oldVal.byteLength);const typed2=newVal instanceof Uint8Array?newVal:newVal instanceof ArrayBuffer?new Uint8Array(newVal):new Uint8Array(newVal.buffer,newVal.byteOffset,newVal.byteLength);return typed1.byteLength===typed2.byteLength&&typed1.every(((val,i)=>typed2[i]===val))?"identical":"changed"}else if(oldVal instanceof Date||newVal instanceof Date){return oldVal instanceof Date&&newVal instanceof Date&&oldVal.getTime()===newVal.getTime()?"identical":"changed"}else if(oldVal instanceof path_reference_1.PathReference||newVal instanceof path_reference_1.PathReference){return oldVal instanceof path_reference_1.PathReference&&newVal instanceof path_reference_1.PathReference&&oldVal.path===newVal.path?"identical":"changed"}else if(typeof oldVal==="object"){const isArray=oldVal instanceof Array;const getKeys=obj=>{let keys=Object.keys(obj).filter((key=>!voids.includes(obj[key])));if(isArray){keys=keys.map((v=>parseInt(v)))}return keys};const oldKeys=getKeys(oldVal);const newKeys=getKeys(newVal);const removedKeys=oldKeys.filter((key=>!newKeys.includes(key)));const addedKeys=newKeys.filter((key=>!oldKeys.includes(key)));const changedKeys=newKeys.reduce(((changed,key)=>{if(oldKeys.includes(key)){const val1=oldVal[key];const val2=newVal[key];const c=compareValues(val1,val2);if(c!=="identical"){changed.push({key:key,change:c})}}return changed}),[]);if(addedKeys.length===0&&removedKeys.length===0&&changedKeys.length===0){return"identical"}else{return new ObjectDifferences(addedKeys,removedKeys,sortedResults?changedKeys.sort(((a,b)=>a.key{switch(compareResult){case"identical":return[];case"changed":return[{target:target,prev:prev,val:val}];case"added":return[{target:target,prev:null,val:val}];case"removed":return[{target:target,prev:prev,val:null}];default:{let changes=[];compareResult.added.forEach((key=>changes.push({target:target.concat(key),prev:null,val:val[key]})));compareResult.removed.forEach((key=>changes.push({target:target.concat(key),prev:prev[key],val:null})));compareResult.changed.forEach((item=>{const childChanges=process(target.concat(item.key),item.change,prev[item.key],val[item.key]);changes=changes.concat(childChanges)}));return changes}}};const compareResult=compareValues(oldVal,newVal,sortedResults);return process([],compareResult,oldVal,newVal)}exports.getMutations=getMutations;function getChildValues(childKey,oldValue,newValue){oldValue=oldValue===null?null:oldValue[childKey];if(typeof oldValue==="undefined"){oldValue=null}newValue=newValue===null?null:newValue[childKey];if(typeof newValue==="undefined"){newValue=null}return{oldValue:oldValue,newValue:newValue}}exports.getChildValues=getChildValues;function defer(fn){process_1.default.nextTick(fn)}exports.defer=defer;function getGlobalObject(){var _a;if(typeof globalThis!=="undefined"){return globalThis}if(typeof global!=="undefined"){return global}if(typeof window!=="undefined"){return window}if(typeof self!=="undefined"){return self}return(_a=function(){return this}())!==null&&_a!==void 0?_a:Function("return this")()}exports.getGlobalObject=getGlobalObject}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./partial-array":28,"./path-reference":30,"./process":31,buffer:40}],40:[function(require,module,exports){},{}],41:[function(require,module,exports){(function(Buffer){(function(){ + */var acebase_client_1=require("./acebase-client");Object.defineProperty(exports,"AceBaseClient",{enumerable:true,get:function(){return acebase_client_1.AceBaseClient}});var auth_1=require("./auth");Object.defineProperty(exports,"AceBaseClientAuth",{enumerable:true,get:function(){return auth_1.AceBaseClientAuth}});var user_1=require("./user");Object.defineProperty(exports,"AceBaseUser",{enumerable:true,get:function(){return user_1.AceBaseUser}});var server_date_1=require("./server-date");Object.defineProperty(exports,"ServerDate",{enumerable:true,get:function(){return server_date_1.ServerDate}});var errors_1=require("./errors");Object.defineProperty(exports,"CachedValueUnavailableError",{enumerable:true,get:function(){return errors_1.CachedValueUnavailableError}});var acebase_core_1=require("acebase-core");Object.defineProperty(exports,"DataReference",{enumerable:true,get:function(){return acebase_core_1.DataReference}});Object.defineProperty(exports,"DataSnapshot",{enumerable:true,get:function(){return acebase_core_1.DataSnapshot}});Object.defineProperty(exports,"DataSnapshotsArray",{enumerable:true,get:function(){return acebase_core_1.DataSnapshotsArray}});Object.defineProperty(exports,"DataReferencesArray",{enumerable:true,get:function(){return acebase_core_1.DataReferencesArray}});Object.defineProperty(exports,"EventStream",{enumerable:true,get:function(){return acebase_core_1.EventStream}});Object.defineProperty(exports,"EventSubscription",{enumerable:true,get:function(){return acebase_core_1.EventSubscription}});Object.defineProperty(exports,"PathReference",{enumerable:true,get:function(){return acebase_core_1.PathReference}});Object.defineProperty(exports,"TypeMappings",{enumerable:true,get:function(){return acebase_core_1.TypeMappings}});Object.defineProperty(exports,"ObjectCollection",{enumerable:true,get:function(){return acebase_core_1.ObjectCollection}});Object.defineProperty(exports,"ID",{enumerable:true,get:function(){return acebase_core_1.ID}});Object.defineProperty(exports,"proxyAccess",{enumerable:true,get:function(){return acebase_core_1.proxyAccess}});Object.defineProperty(exports,"PartialArray",{enumerable:true,get:function(){return acebase_core_1.PartialArray}});Object.defineProperty(exports,"Transport",{enumerable:true,get:function(){return acebase_core_1.Transport}})},{"./acebase-client":1,"./auth":3,"./errors":6,"./server-date":12,"./user":13,"acebase-core":25}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=performance},{}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.promiseTimeout=exports.PromiseTimeoutError=void 0;class PromiseTimeoutError extends Error{}exports.PromiseTimeoutError=PromiseTimeoutError;function promiseTimeout(promise,ms,comment){return new Promise(((resolve,reject)=>{const timeout=setTimeout((()=>reject(new PromiseTimeoutError(`Promise ${comment?`"${comment}" `:""}timed out after ${ms}ms`))),ms);function success(result){clearTimeout(timeout);resolve(result)}promise.then(success).catch(reject)}))}exports.promiseTimeout=promiseTimeout},{}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const error_1=require("./error");async function request(method,url,options={accessToken:null,data:null,dataReceivedCallback:null,dataRequestCallback:null,context:null}){var _a;let postData=options.data;if(typeof postData==="undefined"||postData===null){postData=""}else if(typeof postData==="object"){postData=JSON.stringify(postData)}const headers={"AceBase-Context":JSON.stringify(options.context||null)};const init={method:method,headers:headers,body:undefined};if(typeof options.dataRequestCallback==="function"){headers["Content-Type"]="text/plain";const supportsStreaming=false;if(supportsStreaming){let canceled=false;init.body=new ReadableStream({async pull(controller){var _a;const chunkSize=controller.desiredSize||1024*16;const chunk=await((_a=options.dataRequestCallback)===null||_a===void 0?void 0:_a.call(options,chunkSize));if(canceled||[null,""].includes(chunk)){controller.close()}else{controller.enqueue(chunk)}},async start(controller){},cancel(){canceled=true}})}else{postData="";const chunkSize=1024*512;let chunk;while(chunk=await options.dataRequestCallback(chunkSize)){postData+=chunk}init.body=postData}}else if(postData.length>0){headers["Content-Type"]="application/json";init.body=postData}if(options.accessToken){headers["Authorization"]=`Bearer ${options.accessToken}`}const request={url:url,method:method,headers:headers,body:undefined};const res=await fetch(request.url,init).catch((err=>{throw new error_1.AceBaseRequestError(request,null,"fetch_failed",err.message)}));let data="";if(typeof options.dataReceivedCallback==="function"){const reader=(_a=res.body)===null||_a===void 0?void 0:_a.getReader();await new Promise(((resolve,reject)=>{(async function readNext(){var _a;try{const result=await(reader===null||reader===void 0?void 0:reader.read());(_a=options.dataReceivedCallback)===null||_a===void 0?void 0:_a.call(options,result===null||result===void 0?void 0:result.value);if(result===null||result===void 0?void 0:result.done){return resolve()}readNext()}catch(err){reader===null||reader===void 0?void 0:reader.cancel("error");reject(err)}})()}))}else{data=await res.text()}const isJSON=data[0]==="{"||data[0]==="[";if(res.status===200){const contextHeader=res.headers.get("AceBase-Context");let context;if(contextHeader&&contextHeader[0]==="{"){context=JSON.parse(contextHeader)}else{context={}}if(isJSON){data=JSON.parse(data)}return{context:context,data:data}}else{request.body=postData;const response={statusCode:res.status,statusMessage:res.statusText,headers:res.headers,body:data};let code=res.status,message=res.statusText;if(isJSON){const err=JSON.parse(data);if(err.code){code=err.code}if(err.message){message=err.message}}throw new error_1.AceBaseRequestError(request,response,code,message)}}exports.default=request},{"./error":11}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.NOT_CONNECTED_ERROR_MESSAGE=exports.AceBaseRequestError=void 0;class AceBaseRequestError extends Error{constructor(request,response,code,message="unknown error"){super(message);this.request=request;this.response=response;this.code=code;this.message=message}get isNetworkError(){return this.response===null}}exports.AceBaseRequestError=AceBaseRequestError;exports.NOT_CONNECTED_ERROR_MESSAGE="remote database is not connected"},{}],12:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ServerDate=exports.setServerBias=void 0;const acebase_core_1=require("acebase-core");const performance_1=require("./performance");const time={serverBias:0,localBias:0,lastTime:Date.now(),lastPerf:performance_1.default.now(),get bias(){return this.serverBias+this.localBias}};function biasChanged(){console.log(`Bias changed. server bias = ${time.serverBias}ms, local bias = ${time.localBias}ms`);acebase_core_1.ID.timeBias=time.bias}const interval=1e4;function checkLocalTime(){const now=Date.now(),perf=performance_1.default.now(),msPassed=perf-time.lastPerf,expected=time.lastTime+Math.round(msPassed),diff=expected-now;if(Math.abs(diff)>1){console.log(`Local time changed. diff = ${diff}ms`);time.localBias+=diff;biasChanged()}time.lastTime=now;time.lastPerf=perf;scheduleLocalTimeCheck()}function scheduleLocalTimeCheck(){const timeout=setTimeout(checkLocalTime,interval);timeout.unref&&timeout.unref()}scheduleLocalTimeCheck();function setServerBias(bias){if(typeof bias==="number"){time.serverBias=bias;time.localBias=0;biasChanged()}}exports.setServerBias=setServerBias;class ServerDate extends Date{constructor(){const biasedTime=Date.now()+time.bias;super(biasedTime)}}exports.ServerDate=ServerDate},{"./performance":8,"acebase-core":25}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AceBaseUser=void 0;class AceBaseUser{constructor(user){var _a,_b,_c;this.emailVerified=false;this.changePassword=false;Object.assign(this,user);if(!user.uid){throw new Error("User details is missing required uid field")}this.uid=user.uid;this.displayName=(_a=user.displayName)!==null&&_a!==void 0?_a:"unknown";this.created=(_b=user.created)!==null&&_b!==void 0?_b:new Date(0).toISOString();this.settings=(_c=user.settings)!==null&&_c!==void 0?_c:{}}}exports.AceBaseUser=AceBaseUser},{}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AceBaseBase=exports.AceBaseBaseSettings=void 0;const simple_event_emitter_1=require("./simple-event-emitter");const data_reference_1=require("./data-reference");const type_mappings_1=require("./type-mappings");const optional_observable_1=require("./optional-observable");const debug_1=require("./debug");const simple_colors_1=require("./simple-colors");class AceBaseBaseSettings{constructor(options){this.logLevel="log";this.logColors=true;this.info="realtime database";this.sponsor=false;if(typeof options!=="object"){options={}}if(typeof options.logLevel==="string"){this.logLevel=options.logLevel}if(typeof options.logColors==="boolean"){this.logColors=options.logColors}if(typeof options.info==="string"){this.info=options.info}if(typeof options.sponsor==="boolean"){this.sponsor=options.sponsor}}}exports.AceBaseBaseSettings=AceBaseBaseSettings;class AceBaseBase extends simple_event_emitter_1.SimpleEventEmitter{constructor(dbname,options={}){super();this._ready=false;options=new AceBaseBaseSettings(options);this.name=dbname;this.debug=new debug_1.DebugLogger(options.logLevel,`[${dbname}]`);(0,simple_colors_1.SetColorsEnabled)(options.logColors);const logoStyle=[simple_colors_1.ColorStyle.magenta,simple_colors_1.ColorStyle.bold];const logo=" ___ ______ "+"\n"+" / _ \\ | ___ \\ "+"\n"+" / /_\\ \\ ___ ___| |_/ / __ _ ___ ___ "+"\n"+" | _ |/ __/ _ \\ ___ \\/ _` / __|/ _ \\"+"\n"+" | | | | (_| __/ |_/ / (_| \\__ \\ __/"+"\n"+" \\_| |_/\\___\\___\\____/ \\__,_|___/\\___|";const info=options.info?"".padStart(40-options.info.length," ")+options.info+"\n":"";if(!options.sponsor){this.debug.write(logo.colorize(logoStyle));info&&this.debug.write(info.colorize(simple_colors_1.ColorStyle.magenta))}this.types=new type_mappings_1.TypeMappings(this);this.once("ready",(()=>{this._ready=true}))}async ready(callback){if(!this._ready){await new Promise((resolve=>this.on("ready",resolve)))}callback===null||callback===void 0?void 0:callback()}get isReady(){return this._ready}setObservable(ObservableImpl){(0,optional_observable_1.setObservable)(ObservableImpl)}ref(path){return new data_reference_1.DataReference(this,path)}get root(){return this.ref("")}query(path){const ref=new data_reference_1.DataReference(this,path);return new data_reference_1.DataReferenceQuery(ref)}get indexes(){return{get:()=>this.api.getIndexes(),create:(path,key,options)=>this.api.createIndex(path,key,options),delete:async filePath=>this.api.deleteIndex(filePath)}}get schema(){return{get:path=>this.api.getSchema(path),set:(path,schema)=>this.api.setSchema(path,schema),all:()=>this.api.getSchemas(),check:(path,value,isUpdate)=>this.api.validateSchema(path,value,isUpdate)}}}exports.AceBaseBase=AceBaseBase},{"./data-reference":21,"./debug":23,"./optional-observable":27,"./simple-colors":34,"./simple-event-emitter":35,"./type-mappings":38}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Api=void 0;class NotImplementedError extends Error{constructor(name){super(`${name} is not implemented`)}}class Api{constructor(){}stats(options){throw new NotImplementedError("stats")}subscribe(path,event,callback,settings){throw new NotImplementedError("subscribe")}unsubscribe(path,event,callback){throw new NotImplementedError("unsubscribe")}update(path,updates,options){throw new NotImplementedError("update")}set(path,value,options){throw new NotImplementedError("set")}get(path,options){throw new NotImplementedError("get")}transaction(path,callback,options){throw new NotImplementedError("transaction")}exists(path){throw new NotImplementedError("exists")}query(path,query,options){throw new NotImplementedError("query")}reflect(path,type,args){throw new NotImplementedError("reflect")}export(path,write,options){throw new NotImplementedError("export")}import(path,read,options){throw new NotImplementedError("import")}createIndex(path,key,options){throw new NotImplementedError("createIndex")}getIndexes(){throw new NotImplementedError("getIndexes")}deleteIndex(filePath){throw new NotImplementedError("deleteIndex")}setSchema(path,schema){throw new NotImplementedError("setSchema")}getSchema(path){throw new NotImplementedError("getSchema")}getSchemas(){throw new NotImplementedError("getSchemas")}validateSchema(path,value,isUpdate){throw new NotImplementedError("validateSchema")}getMutations(filter){throw new NotImplementedError("getMutations")}getChanges(filter){throw new NotImplementedError("getChanges")}}exports.Api=Api},{}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ascii85=void 0;function c(input,length,result){const b=[0,0,0,0,0];for(let i=0;i";return ret}exports.ascii85={encode:function(arr){if(arr instanceof ArrayBuffer){arr=new Uint8Array(arr,0,arr.byteLength)}return encode(arr)},decode:function(input){if(!input.startsWith("<~")||!input.endsWith("~>")){throw new Error("Invalid input string")}input=input.substr(2,input.length-4);const n=input.length,r=[],b=[0,0,0,0,0];let t,x,y,d;for(let i=0;i>>=8;y=t&255;t>>>=8;r.push(t>>>8,t&255,y,x);for(let j=d;j<5;++j,r.pop()){}i+=4}const data=new Uint8Array(r);return data.buffer.slice(data.byteOffset,data.byteOffset+data.byteLength)}}},{}],17:[function(require,module,exports){"use strict";var _a,_b;Object.defineProperty(exports,"__esModule",{value:true});const pad_1=require("../pad");const env=typeof window==="object"?window:self,globalCount=Object.keys(env).length,mimeTypesLength=(_b=(_a=navigator.mimeTypes)===null||_a===void 0?void 0:_a.length)!==null&&_b!==void 0?_b:0,clientId=(0,pad_1.default)((mimeTypesLength+navigator.userAgent.length).toString(36)+globalCount.toString(36),4);function fingerprint(){return clientId}exports.default=fingerprint},{"../pad":19}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const fingerprint_1=require("./fingerprint");const pad_1=require("./pad");let c=0;const blockSize=4,base=36,discreteValues=Math.pow(base,blockSize);function randomBlock(){return(0,pad_1.default)((Math.random()*discreteValues<<0).toString(base),blockSize)}function safeCounter(){c=ct2[i]===key))}static isAncestor(ancestor,other){return ancestor.lengthother[i]===key))}static isDescendant(descendant,other){return descendant.length>other.length&&other.every(((key,i)=>descendant[i]===key))}}const isProxy=Symbol("isProxy");class LiveDataProxy{static async create(ref,options){var _a;ref=new data_reference_1.DataReference(ref.db,ref.path);let cache,loaded=false;let latestCursor=options===null||options===void 0?void 0:options.cursor;let proxy;const proxyId=id_1.ID.generate();const clientSubscriptions=[];const clientEventEmitter=new simple_event_emitter_1.SimpleEventEmitter;clientEventEmitter.on("cursor",(cursor=>latestCursor=cursor));clientEventEmitter.on("error",(err=>{console.error(err.message,err.details)}));const applyChange=(keys,newValue)=>{if(keys.length===0){cache=newValue;return true}const allowCreation=false;if(allowCreation){cache=typeof keys[0]==="number"?[]:{}}let target=cache;const trailKeys=keys.slice();while(trailKeys.length>1){const key=trailKeys.shift();if(!(key in target)){if(allowCreation){target[key]=typeof key==="number"?[]:{}}else{return false}}target=target[key]}const prop=trailKeys.shift();if(newValue===null){target instanceof Array?target.splice(prop,1):delete target[prop]}else{target[prop]=newValue}return true};const syncFallback=async()=>{if(!loaded){return}await reload()};const subscription=ref.on("mutations",{syncFallback:syncFallback}).subscribe((async snap=>{var _a;if(!loaded){return}const context=snap.context();const isRemote=((_a=context.acebase_proxy)===null||_a===void 0?void 0:_a.id)!==proxyId;if(!isRemote){return}const mutations=snap.val(false);const proceed=mutations.every((mutation=>{if(!applyChange(mutation.target,mutation.val)){return false}const changeRef=mutation.target.reduce(((ref,key)=>ref.child(key)),ref);const changeSnap=new data_snapshot_1.DataSnapshot(changeRef,mutation.val,false,mutation.prev,snap.context());clientEventEmitter.emit("mutation",{snapshot:changeSnap,isRemote:isRemote});return true}));if(proceed){clientEventEmitter.emit("cursor",context.acebase_cursor);localMutationsEmitter.emit("mutations",{origin:"remote",snap:snap})}else{console.warn(`Cached value of live data proxy on "${ref.path}" appears outdated, will be reloaded`);await reload()}}));let processPromise=Promise.resolve();const mutationQueue=[];const transactions=[];const pushLocalMutations=async()=>{const mutations=[];for(let i=0,m=mutationQueue[0];iRelativeNodeTarget.areEqual(t.target,m.target)||RelativeNodeTarget.isAncestor(t.target,m.target)))){mutationQueue.splice(i,1);i--;mutations.push(m)}}if(mutations.length===0){return}mutations.forEach((mutation=>{mutation.value=(0,utils_1.cloneObject)(getTargetValue(cache,mutation.target))}));process_1.default.nextTick((()=>{const context={acebase_proxy:{id:proxyId,source:"update"}};mutations.forEach((mutation=>{const mutationRef=mutation.target.reduce(((ref,key)=>ref.child(key)),ref);const mutationSnap=new data_snapshot_1.DataSnapshot(mutationRef,mutation.value,false,mutation.previous,context);clientEventEmitter.emit("mutation",{snapshot:mutationSnap,isRemote:false})}));const snap=new data_snapshot_1.MutationsDataSnapshot(ref,mutations.map((m=>({target:m.target,val:m.value,prev:m.previous}))),context);localMutationsEmitter.emit("mutations",{origin:"local",snap:snap})}));processPromise=mutations.reduce(((mutations,m,i,arr)=>{if(!arr.some((other=>RelativeNodeTarget.isAncestor(other.target,m.target)))){mutations.push(m)}return mutations}),[]).reduce(((updates,m)=>{const target=m.target;if(target.length===0){updates.push({ref:ref,target:target,value:cache,type:"set",previous:m.previous})}else{const parentTarget=target.slice(0,-1);const key=target.slice(-1)[0];const parentRef=parentTarget.reduce(((ref,key)=>ref.child(key)),ref);const parentUpdate=updates.find((update=>update.ref.path===parentRef.path));const cacheValue=getTargetValue(cache,target);const prevValue=m.previous;if(parentUpdate){parentUpdate.value[key]=cacheValue;parentUpdate.previous[key]=prevValue}else{updates.push({ref:parentRef,target:parentTarget,value:{[key]:cacheValue},type:"update",previous:{[key]:prevValue}})}}return updates}),[]).reduce((async(promise,update)=>{const context={acebase_proxy:{id:proxyId,source:update.type}};await promise;await update.ref.context(context)[update.type](update.value).catch((err=>{clientEventEmitter.emit("error",{source:"update",message:`Error processing update of "/${ref.path}"`,details:err});const context={acebase_proxy:{id:proxyId,source:"update-rollback"}};const mutations=[];if(update.type==="set"){setTargetValue(cache,update.target,update.previous);const mutationSnap=new data_snapshot_1.DataSnapshot(update.ref,update.previous,false,update.value,context);clientEventEmitter.emit("mutation",{snapshot:mutationSnap,isRemote:false});mutations.push({target:update.target,val:update.previous,prev:update.value})}else{Object.keys(update.previous).forEach((key=>{setTargetValue(cache,update.target.concat(key),update.previous[key]);const mutationSnap=new data_snapshot_1.DataSnapshot(update.ref.child(key),update.previous[key],false,update.value[key],context);clientEventEmitter.emit("mutation",{snapshot:mutationSnap,isRemote:false});mutations.push({target:update.target.concat(key),val:update.previous[key],prev:update.value[key]})}))}mutations.forEach((m=>{const mutationRef=m.target.reduce(((ref,key)=>ref.child(key)),ref);const mutationSnap=new data_snapshot_1.DataSnapshot(mutationRef,m.val,false,m.prev,context);clientEventEmitter.emit("mutation",{snapshot:mutationSnap,isRemote:false})}));const snap=new data_snapshot_1.MutationsDataSnapshot(update.ref,mutations,context);localMutationsEmitter.emit("mutations",{origin:"local",snap:snap})}));if(update.ref.cursor){clientEventEmitter.emit("cursor",update.ref.cursor)}}),processPromise);await processPromise};let syncInProgress=false;const syncPromises=[];const syncCompleted=()=>{let resolve;const promise=new Promise((rs=>resolve=rs));syncPromises.push({resolve:resolve});return promise};let processQueueTimeout=null;const scheduleSync=()=>{if(!processQueueTimeout){processQueueTimeout=setTimeout((async()=>{syncInProgress=true;processQueueTimeout=null;await pushLocalMutations();syncInProgress=false;syncPromises.splice(0).forEach((p=>p.resolve()))}),0)}};const flagOverwritten=target=>{if(!mutationQueue.find((m=>RelativeNodeTarget.areEqual(m.target,target)))){mutationQueue.push({target:target,previous:(0,utils_1.cloneObject)(getTargetValue(cache,target))})}scheduleSync()};const localMutationsEmitter=new simple_event_emitter_1.SimpleEventEmitter;const addOnChangeHandler=(target,callback)=>{const isObject=val=>val!==null&&typeof val==="object";const mutationsHandler=async details=>{var _a;const{snap:snap,origin:origin}=details;const context=snap.context();const causedByOurProxy=((_a=context.acebase_proxy)===null||_a===void 0?void 0:_a.id)===proxyId;if(details.origin==="remote"&&causedByOurProxy){console.error("DEV ISSUE: mutationsHandler was called from remote event originating from our own proxy");return}const mutations=snap.val(false).filter((mutation=>mutation.target.slice(0,target.length).every(((key,i)=>target[i]===key))));if(mutations.length===0){return}let newValue,previousValue;const singleMutation=mutations.find((m=>m.target.length<=target.length));if(singleMutation){const trailKeys=target.slice(singleMutation.target.length);newValue=trailKeys.reduce(((val,key)=>!isObject(val)||!(key in val)?null:val[key]),singleMutation.val);previousValue=trailKeys.reduce(((val,key)=>!isObject(val)||!(key in val)?null:val[key]),singleMutation.prev)}else{const currentValue=getTargetValue(cache,target);newValue=(0,utils_1.cloneObject)(currentValue);previousValue=(0,utils_1.cloneObject)(newValue);mutations.forEach((mutation=>{const trailKeys=mutation.target.slice(target.length);for(let i=0,val=newValue,prev=previousValue;i{let keepSubscription=true;try{keepSubscription=false!==callback(Object.freeze(newValue),Object.freeze(previousValue),!causedByOurProxy,context)}catch(err){clientEventEmitter.emit("error",{source:origin==="remote"?"remote_update":"local_update",message:"Error running subscription callback",details:err})}if(keepSubscription===false){stop()}}))};localMutationsEmitter.on("mutations",mutationsHandler);const stop=()=>{localMutationsEmitter.off("mutations").off("mutations",mutationsHandler);clientSubscriptions.splice(clientSubscriptions.findIndex((cs=>cs.stop===stop)),1)};clientSubscriptions.push({target:target,stop:stop});return{stop:stop}};const handleFlag=(flag,target,args)=>{if(flag==="write"){return flagOverwritten(target)}else if(flag==="onChange"){return addOnChangeHandler(target,args.callback)}else if(flag==="subscribe"||flag==="observe"){const subscribe=subscriber=>{const currentValue=getTargetValue(cache,target);subscriber.next(currentValue);const subscription=addOnChangeHandler(target,(value=>{subscriber.next(value)}));return function unsubscribe(){subscription.stop()}};if(flag==="subscribe"){return subscribe}const Observable=(0,optional_observable_1.getObservable)();return new Observable(subscribe)}else if(flag==="transaction"){const hasConflictingTransaction=transactions.some((t=>RelativeNodeTarget.areEqual(target,t.target)||RelativeNodeTarget.isAncestor(target,t.target)||RelativeNodeTarget.isDescendant(target,t.target)));if(hasConflictingTransaction){return Promise.reject(new Error("Cannot start transaction because it conflicts with another transaction"))}return new Promise((async resolve=>{const hasPendingMutations=mutationQueue.some((m=>RelativeNodeTarget.areEqual(target,m.target)||RelativeNodeTarget.isAncestor(target,m.target)));if(hasPendingMutations){if(!syncInProgress){scheduleSync()}await syncCompleted()}const tx={target:target,status:"started",transaction:null};transactions.push(tx);tx.transaction={get status(){return tx.status},get completed(){return tx.status!=="started"},get mutations(){return mutationQueue.filter((m=>RelativeNodeTarget.areEqual(tx.target,m.target)||RelativeNodeTarget.isAncestor(tx.target,m.target)))},get hasMutations(){return this.mutations.length>0},async commit(){if(this.completed){throw new Error(`Transaction has completed already (status '${tx.status}')`)}tx.status="finished";transactions.splice(transactions.indexOf(tx),1);if(syncInProgress){await syncCompleted()}scheduleSync();await syncCompleted()},rollback(){if(this.completed){throw new Error(`Transaction has completed already (status '${tx.status}')`)}tx.status="canceled";const mutations=[];for(let i=0;i{if(m.target.length===0){cache=m.previous}else{setTargetValue(cache,m.target,m.previous)}}));transactions.splice(transactions.indexOf(tx),1)}};resolve(tx.transaction)}))}};const snap=await ref.get({cache_mode:"allow",cache_cursor:options===null||options===void 0?void 0:options.cursor});if(snap.context().acebase_origin!=="cache"){clientEventEmitter.emit("cursor",(_a=ref.cursor)!==null&&_a!==void 0?_a:null)}loaded=true;cache=snap.val();if(cache===null&&typeof(options===null||options===void 0?void 0:options.defaultValue)!=="undefined"){cache=options.defaultValue;const context={acebase_proxy:{id:proxyId,source:"default"}};await ref.context(context).set(cache)}proxy=createProxy({root:{ref:ref,get cache(){return cache}},target:[],id:proxyId,flag:handleFlag});const assertProxyAvailable=()=>{if(proxy===null){throw new Error("Proxy was destroyed")}};const reload=async()=>{assertProxyAvailable();mutationQueue.splice(0);const snap=await ref.get({allow_cache:false});const oldVal=cache,newVal=snap.val();cache=newVal;const mutations=(0,utils_1.getMutations)(oldVal,newVal);if(mutations.length===0){return}const context=snap.context();context.acebase_proxy={id:proxyId,source:"reload"};mutations.forEach((m=>{const targetRef=getTargetRef(ref,m.target);const newSnap=new data_snapshot_1.DataSnapshot(targetRef,m.val,m.val===null,m.prev,context);clientEventEmitter.emit("mutation",{snapshot:newSnap,isRemote:true})}));const mutationsSnap=new data_snapshot_1.MutationsDataSnapshot(ref,mutations,context);localMutationsEmitter.emit("mutations",{origin:"local",snap:mutationsSnap})};return{async destroy(){await processPromise;const promises=[subscription.stop(),...clientSubscriptions.map((cs=>cs.stop()))];await Promise.all(promises);["cursor","mutation","error"].forEach((event=>clientEventEmitter.off(event)));cache=null;proxy=null},stop(){this.destroy()},get value(){assertProxyAvailable();return proxy},get hasValue(){assertProxyAvailable();return cache!==null},set value(val){assertProxyAvailable();if(val!==null&&typeof val==="object"&&val[isProxy]){val=val.valueOf()}flagOverwritten([]);cache=val},get ref(){return ref},get cursor(){return latestCursor},reload:reload,onMutation(callback){assertProxyAvailable();clientEventEmitter.off("mutation");clientEventEmitter.on("mutation",(({snapshot:snapshot,isRemote:isRemote})=>{try{callback(snapshot,isRemote)}catch(err){clientEventEmitter.emit("error",{source:"mutation_callback",message:"Error in dataproxy onMutation callback",details:err})}}))},onError(callback){assertProxyAvailable();clientEventEmitter.off("error");clientEventEmitter.on("error",(err=>{try{callback(err)}catch(err){console.error(`Error in dataproxy onError callback: ${err.message}`)}}))},on(event,callback){clientEventEmitter.on(event,callback)},off(event,callback){clientEventEmitter.off(event,callback)}}}}exports.LiveDataProxy=LiveDataProxy;function getTargetValue(obj,target){let val=obj;for(const key of target){val=typeof val==="object"&&val!==null&&key in val?val[key]:null}return val}function setTargetValue(obj,target,value){if(target.length===0){throw new Error("Cannot update root target, caller must do that itself!")}const targetObject=target.slice(0,-1).reduce(((obj,key)=>obj[key]),obj);const prop=target.slice(-1)[0];if(value===null||typeof value==="undefined"){targetObject instanceof Array?targetObject.splice(prop,1):delete targetObject[prop]}else{targetObject[prop]=value}}function getTargetRef(ref,target){const path=path_info_1.PathInfo.get(ref.path).childPath(target);return new data_reference_1.DataReference(ref.db,path)}function createProxy(context){const targetRef=getTargetRef(context.root.ref,context.target);const childProxies=[];const handler={get(target,prop,receiver){target=getTargetValue(context.root.cache,context.target);if(typeof prop==="symbol"){if(prop.toString()===Symbol.iterator.toString()){prop="values"}else if(prop.toString()===isProxy.toString()){return true}else{return Reflect.get(target,prop,receiver)}}if(prop==="valueOf"){return function valueOf(){return target}}if(target===null||typeof target!=="object"){throw new Error(`Cannot read property "${prop}" of ${target}. Value of path "/${targetRef.path}" is not an object (anymore)`)}if(target instanceof Array&&typeof prop==="string"&&/^[0-9]+$/.test(prop)){prop=parseInt(prop)}const value=target[prop];if(value===null){delete target[prop];return}const childProxy=childProxies.find((proxy=>proxy.prop===prop));if(childProxy){if(childProxy.typeof===typeof value){return childProxy.value}childProxies.splice(childProxies.indexOf(childProxy),1)}const proxifyChildValue=prop=>{const value=target[prop];const childProxy=childProxies.find((child=>child.prop===prop));if(childProxy){if(childProxy.typeof===typeof value){return childProxy.value}childProxies.splice(childProxies.indexOf(childProxy),1)}if(typeof value!=="object"){return value}const newChildProxy=createProxy({root:context.root,target:context.target.concat(prop),id:context.id,flag:context.flag});childProxies.push({typeof:typeof value,prop:prop,value:newChildProxy});return newChildProxy};const unproxyValue=value=>value!==null&&typeof value==="object"&&value[isProxy]?value.getTarget():value;if(["string","number","boolean"].includes(typeof value)||value instanceof Date||value instanceof path_reference_1.PathReference||value instanceof ArrayBuffer||typeof value==="object"&&"buffer"in value){return value}const isArray=target instanceof Array;if(prop==="toString"){return function toString(){return`[LiveDataProxy for "${targetRef.path}"]`}}if(typeof value==="undefined"){if(prop==="push"){return function push(item){const childRef=targetRef.push();context.flag("write",context.target.concat(childRef.key));target[childRef.key]=item;return childRef.key}}if(prop==="getTarget"){return function(warn=true){warn&&console.warn("Use getTarget with caution - any changes will not be synchronized!");return target}}if(prop==="getRef"){return function getRef(){const ref=getTargetRef(context.root.ref,context.target);return ref}}if(prop==="forEach"){return function forEach(callback){const keys=Object.keys(target);let stop=false;for(let i=0;!stop&&iproxifyChildValue(key)));if(sortFn){arr.sort(sortFn)}return arr}}if(prop==="onChanged"){return function onChanged(callback){return context.flag("onChange",context.target,{callback:callback})}}if(prop==="subscribe"){return function subscribe(){return context.flag("subscribe",context.target)}}if(prop==="getObservable"){return function getObservable(){return context.flag("observe",context.target)}}if(prop==="getOrderedCollection"){return function getOrderedCollection(orderProperty,orderIncrement){return new OrderedCollectionProxy(this,orderProperty,orderIncrement)}}if(prop==="startTransaction"){return function startTransaction(){return context.flag("transaction",context.target)}}if(prop==="remove"&&!isArray){return function remove(){if(context.target.length===0){throw new Error("Can't remove proxy root value")}const parent=getTargetValue(context.root.cache,context.target.slice(0,-1));const key=context.target.slice(-1)[0];context.flag("write",context.target);delete parent[key]}}return}else if(typeof value==="function"){if(isArray){const writeArray=action=>{context.flag("write",context.target);return action()};const cleanArrayValues=values=>values.map((value=>{value=unproxyValue(value);removeVoidProperties(value);return value}));if(prop==="push"){return function push(...items){items=cleanArrayValues(items);return writeArray((()=>target.push(...items)))}}if(prop==="pop"){return function pop(){return writeArray((()=>target.pop()))}}if(prop==="splice"){return function splice(start,deleteCount,...items){items=cleanArrayValues(items);return writeArray((()=>target.splice(start,deleteCount,...items)))}}if(prop==="shift"){return function shift(){return writeArray((()=>target.shift()))}}if(prop==="unshift"){return function unshift(...items){items=cleanArrayValues(items);return writeArray((()=>target.unshift(...items)))}}if(prop==="sort"){return function sort(compareFn){return writeArray((()=>target.sort(compareFn)))}}if(prop==="reverse"){return function reverse(){return writeArray((()=>target.reverse()))}}if(["indexOf","lastIndexOf"].includes(prop)){return function indexOf(item,start){if(item!==null&&typeof item==="object"&&item[isProxy]){item=item.getTarget(false)}return target[prop](item,start)}}if(["forEach","every","some","filter","map"].includes(prop)){return function iterate(callback){return target[prop](((value,i)=>callback(proxifyChildValue(i),i,proxy)))}}if(["reduce","reduceRight"].includes(prop)){return function reduce(callback,initialValue){return target[prop](((prev,value,i)=>callback(prev,proxifyChildValue(i),i,proxy)),initialValue)}}if(["find","findIndex"].includes(prop)){return function find(callback){let value=target[prop](((value,i)=>callback(proxifyChildValue(i),i,proxy)));if(prop==="find"&&value){const index=target.indexOf(value);value=proxifyChildValue(index)}return value}}if(["values","entries","keys"].includes(prop)){return function*generator(){for(let i=0;itypeof key==="number"))){context.flag("write",context.target.slice(0,context.target.findIndex((key=>typeof key==="number"))))}else if(target instanceof Array){context.flag("write",context.target)}else{context.flag("write",context.target.concat(prop))}if(value===null){delete target[prop]}else{removeVoidProperties(value);target[prop]=value}return true},deleteProperty(target,prop){target=getTargetValue(context.root.cache,context.target);if(target===null){throw new Error(`Cannot delete property ${prop.toString()} of null`)}if(typeof prop==="symbol"){return Reflect.deleteProperty(target,prop)}if(!(prop in target)){return true}context.flag("write",context.target.concat(prop));delete target[prop];return true},ownKeys(target){target=getTargetValue(context.root.cache,context.target);return Reflect.ownKeys(target)},has(target,prop){target=getTargetValue(context.root.cache,context.target);return Reflect.has(target,prop)},getOwnPropertyDescriptor(target,prop){target=getTargetValue(context.root.cache,context.target);const descriptor=Reflect.getOwnPropertyDescriptor(target,prop);if(descriptor){descriptor.configurable=true}return descriptor},getPrototypeOf(target){target=getTargetValue(context.root.cache,context.target);return Reflect.getPrototypeOf(target)}};const proxy=new Proxy({},handler);return proxy}function removeVoidProperties(obj){if(typeof obj!=="object"){return}Object.keys(obj).forEach((key=>{const val=obj[key];if(val===null||typeof val==="undefined"){delete obj[key]}else if(typeof val==="object"){removeVoidProperties(val)}}))}function proxyAccess(proxiedValue){if(typeof proxiedValue!=="object"||!proxiedValue[isProxy]){throw new Error("Given value is not proxied. Make sure you are referencing the value through the live data proxy.")}return proxiedValue}exports.proxyAccess=proxyAccess;class OrderedCollectionProxy{constructor(collection,orderProperty="order",orderIncrement=10){this.collection=collection;this.orderProperty=orderProperty;this.orderIncrement=orderIncrement;if(typeof collection!=="object"||!collection[isProxy]){throw new Error("Collection is not proxied")}if(collection.valueOf()instanceof Array){throw new Error("Collection is an array, not an object collection")}if(!Object.keys(collection).every((key=>typeof collection[key]==="object"))){throw new Error("Collection has non-object children")}const ok=Object.keys(collection).every((key=>typeof collection[key][orderProperty]==="number"));if(!ok){const keys=Object.keys(collection);for(let i=0;i{const subscription=this.getObservable().subscribe((()=>{const newArray=this.getArray();subscriber.next(newArray)}));return function unsubscribe(){subscription.unsubscribe()}}))}getArray(){const arr=proxyAccess(this.collection).toArray(((a,b)=>a[this.orderProperty]-b[this.orderProperty]));return arr}add(item,index,from){const arr=this.getArray();let minOrder=Number.POSITIVE_INFINITY,maxOrder=Number.NEGATIVE_INFINITY;for(let i=0;ithis.collection[key]===item));if(!fromKey){throw new Error("item not found in collection")}if(from===index){return{key:fromKey,index:index}}if(Math.abs(from-index)===1){const otherItem=arr[index];const otherOrder=otherItem[this.orderProperty];otherItem[this.orderProperty]=item[this.orderProperty];item[this.orderProperty]=otherOrder;return{key:fromKey,index:index}}else{arr.splice(from,1)}}if(typeof index!=="number"||index>=arr.length){index=arr.length;item[this.orderProperty]=arr.length==0?0:maxOrder+this.orderIncrement}else if(index===0){item[this.orderProperty]=arr.length==0?0:minOrder-this.orderIncrement}else{const orders=arr.map((item=>item[this.orderProperty]));const gap=orders[index]-orders[index-1];if(gap>1){item[this.orderProperty]=orders[index]-Math.floor(gap/2)}else{arr.splice(index,0,item);for(let i=0;ithis.collection[key]===item));if(!key){throw new Error("Cannot find target object to delete")}this.collection[key]=null;return{key:key,index:index}}move(fromIndex,toIndex){const arr=this.getArray();return this.add(arr[fromIndex],toIndex,fromIndex)}sort(sortFn){const arr=this.getArray();arr.sort(sortFn);for(let i=0;i{newContext[key]=context[key]}))}this[_private].context=newContext;return this}else if(typeof context==="undefined"){console.warn("Use snap.context() instead of snap.ref.context() to get updating context in event callbacks");return currentContext}else{throw new Error("Invalid context argument")}}get cursor(){return this[_private].cursor}set cursor(value){var _a;this[_private].cursor=value;(_a=this.onCursor)===null||_a===void 0?void 0:_a.call(this,value)}get path(){return this[_private].path}get key(){const key=this[_private].key;return typeof key==="number"?`[${key}]`:key}get index(){const key=this[_private].key;if(typeof key!=="number"){throw new Error(`"${key}" is not a number`)}return key}get parent(){const currentPath=path_info_1.PathInfo.fillVariables2(this.path,this.vars);const info=path_info_1.PathInfo.get(currentPath);if(info.parentPath===null){return null}return new DataReference(this.db,info.parentPath).context(this[_private].context)}get vars(){return this[_private].vars}child(childPath){childPath=typeof childPath==="number"?childPath:childPath.replace(/^\/|\/$/g,"");const currentPath=path_info_1.PathInfo.fillVariables2(this.path,this.vars);const targetPath=path_info_1.PathInfo.getChildPath(currentPath,childPath);return new DataReference(this.db,targetPath).context(this[_private].context)}async set(value,onComplete){try{if(this.isWildcardPath){throw new Error(`Cannot set the value of wildcard path "/${this.path}"`)}if(this.parent===null){throw new Error("Cannot set the root object. Use update, or set individual child properties")}if(typeof value==="undefined"){throw new TypeError(`Cannot store undefined value in "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}value=this.db.types.serialize(this.path,value);const{cursor:cursor}=await this.db.api.set(this.path,value,{context:this[_private].context});this.cursor=cursor;if(typeof onComplete==="function"){try{onComplete(null,this)}catch(err){console.error("Error in onComplete callback:",err)}}}catch(err){if(typeof onComplete==="function"){try{onComplete(err,this)}catch(err){console.error("Error in onComplete callback:",err)}}else{throw err}}return this}async update(updates,onComplete){try{if(this.isWildcardPath){throw new Error(`Cannot update the value of wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}if(typeof updates!=="object"||updates instanceof Array||updates instanceof ArrayBuffer||updates instanceof Date){await this.set(updates)}else if(Object.keys(updates).length===0){console.warn(`update called on path "/${this.path}", but there is nothing to update`)}else{updates=this.db.types.serialize(this.path,updates);const{cursor:cursor}=await this.db.api.update(this.path,updates,{context:this[_private].context});this.cursor=cursor}if(typeof onComplete==="function"){try{onComplete(null,this)}catch(err){console.error("Error in onComplete callback:",err)}}}catch(err){if(typeof onComplete==="function"){try{onComplete(err,this)}catch(err){console.error("Error in onComplete callback:",err)}}else{throw err}}return this}async transaction(callback){if(this.isWildcardPath){throw new Error(`Cannot start a transaction on wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}let throwError;const cb=currentValue=>{currentValue=this.db.types.deserialize(this.path,currentValue);const snap=new data_snapshot_1.DataSnapshot(this,currentValue);let newValue;try{newValue=callback(snap)}catch(err){throwError=err;return}if(newValue instanceof Promise){return newValue.then((val=>this.db.types.serialize(this.path,val))).catch((err=>{throwError=err;return}))}else{return this.db.types.serialize(this.path,newValue)}};const{cursor:cursor}=await this.db.api.transaction(this.path,cb,{context:this[_private].context});this.cursor=cursor;if(throwError){throw throwError}return this}on(event,callback,cancelCallback){if(this.path===""&&["value","child_changed"].includes(event)){console.warn("WARNING: Listening for value and child_changed events on the root node is a bad practice. These events require loading of all data (value event), or potentially lots of data (child_changed event) each time they are fired")}let eventPublisher=null;const eventStream=new subscription_1.EventStream((publisher=>{eventPublisher=publisher}));const cb={event:event,stream:eventStream,userCallback:typeof callback==="function"&&callback,ourCallback:(err,path,newValue,oldValue,eventContext)=>{if(err){this.db.debug.error(`Error getting data for event ${event} on path "${path}"`,err);return}const ref=this.db.ref(path);ref[_private].vars=path_info_1.PathInfo.extractVariables(this.path,path);let callbackObject;if(event.startsWith("notify_")){callbackObject=ref.context(eventContext||{})}else{const values={previous:this.db.types.deserialize(path,oldValue),current:this.db.types.deserialize(path,newValue)};if(event==="child_removed"){callbackObject=new data_snapshot_1.DataSnapshot(ref,values.previous,true,values.previous,eventContext)}else if(event==="mutations"){callbackObject=new data_snapshot_1.MutationsDataSnapshot(ref,values.current,eventContext)}else{const isRemoved=event==="mutated"&&values.current===null;callbackObject=new data_snapshot_1.DataSnapshot(ref,values.current,isRemoved,values.previous,eventContext)}}eventPublisher.publish(callbackObject);if(eventContext===null||eventContext===void 0?void 0:eventContext.acebase_cursor){this.cursor=eventContext.acebase_cursor}}};this[_private].callbacks.push(cb);const subscribe=()=>{if(typeof callback==="function"){eventStream.subscribe(callback,((activated,cancelReason)=>{if(!activated){cancelCallback&&cancelCallback(cancelReason)}}))}const advancedOptions=typeof callback==="object"?callback:{newOnly:!callback};if(typeof advancedOptions.newOnly!=="boolean"){advancedOptions.newOnly=false}if(this.isWildcardPath){advancedOptions.newOnly=true}const cancelSubscription=err=>{const callbacks=this[_private].callbacks;callbacks.splice(callbacks.indexOf(cb),1);this.db.api.unsubscribe(this.path,event,cb.ourCallback);this.db.debug.error(`Subscription "${event}" on path "/${this.path}" canceled because of an error: ${err.message}`);eventPublisher.cancel(err.message)};const authorized=this.db.api.subscribe(this.path,event,cb.ourCallback,{newOnly:advancedOptions.newOnly,cancelCallback:cancelSubscription,syncFallback:advancedOptions.syncFallback});const allSubscriptionsStoppedCallback=()=>{const callbacks=this[_private].callbacks;callbacks.splice(callbacks.indexOf(cb),1);return this.db.api.unsubscribe(this.path,event,cb.ourCallback)};if(authorized instanceof Promise){authorized.then((()=>{eventPublisher.start(allSubscriptionsStoppedCallback)})).catch(cancelSubscription)}else{eventPublisher.start(allSubscriptionsStoppedCallback)}if(!advancedOptions.newOnly){if(event==="value"){this.get((snap=>{eventPublisher.publish(snap)}))}else if(event==="child_added"){this.get((snap=>{const val=snap.val();if(val===null||typeof val!=="object"){return}Object.keys(val).forEach((key=>{const childSnap=new data_snapshot_1.DataSnapshot(this.child(key),val[key]);eventPublisher.publish(childSnap)}))}))}else if(event==="notify_child_added"){const step=100,limit=step;let skip=0;const more=async()=>{const children=await this.db.api.reflect(this.path,"children",{limit:limit,skip:skip});children.list.forEach((child=>{const childRef=this.child(child.key);eventPublisher.publish(childRef)}));if(children.more){skip+=step;more()}};more()}}};if(this.db.isReady){subscribe()}else{this.db.ready(subscribe)}return eventStream}off(event,callback){const subscriptions=this[_private].callbacks;const stopSubs=subscriptions.filter((sub=>(!event||sub.event===event)&&(!callback||sub.userCallback===callback)));if(stopSubs.length===0){this.db.debug.warn(`Can't find event subscriptions to stop (path: "${this.path}", event: ${event||"(any)"}, callback: ${callback})`)}stopSubs.forEach((sub=>{sub.stream.stop()}));return this}get(optionsOrCallback,callback){if(!this.db.isReady){const promise=this.db.ready().then((()=>this.get(optionsOrCallback,callback)));return typeof optionsOrCallback!=="function"&&typeof callback!=="function"?promise:undefined}callback=typeof optionsOrCallback==="function"?optionsOrCallback:typeof callback==="function"?callback:undefined;if(this.isWildcardPath){const error=new Error(`Cannot get value of wildcard path "/${this.path}". Use .query() instead`);if(typeof callback==="function"){throw error}return Promise.reject(error)}const options=new DataRetrievalOptions(typeof optionsOrCallback==="object"?optionsOrCallback:{cache_mode:"allow"});const promise=this.db.api.get(this.path,options).then((result=>{var _a;const isNewApiResult="context"in result&&"value"in result;if(!isNewApiResult){console.warn("AceBase api.get method returned an old response value. Update your acebase or acebase-client package");result={value:result,context:{}}}const value=this.db.types.deserialize(this.path,result.value);const snapshot=new data_snapshot_1.DataSnapshot(this,value,undefined,undefined,result.context);if((_a=result.context)===null||_a===void 0?void 0:_a.acebase_cursor){this.cursor=result.context.acebase_cursor}return snapshot}));if(callback){promise.then(callback).catch((err=>{console.error("Uncaught error:",err)}));return}else{return promise}}once(event,options){if(event==="value"&&!this.isWildcardPath){return this.get(options)}return new Promise((resolve=>{const callback=snap=>{this.off(event,callback);resolve(snap)};this.on(event,callback)}))}push(value,onComplete){if(this.isWildcardPath){const error=new Error(`Cannot push to wildcard path "/${this.path}"`);if(typeof value==="undefined"||typeof onComplete==="function"){throw error}return Promise.reject(error)}const id=id_1.ID.generate();const ref=this.child(id);ref[_private].pushed=true;if(typeof value!=="undefined"){return ref.set(value,onComplete).then((()=>ref))}else{return ref}}async remove(){if(this.isWildcardPath){throw new Error(`Cannot remove wildcard path "/${this.path}". Use query().remove instead`)}if(this.parent===null){throw new Error("Cannot remove the root node")}return this.set(null)}async exists(){if(this.isWildcardPath){throw new Error(`Cannot check wildcard path "/${this.path}" existence`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.exists(this.path)}get isWildcardPath(){return this.path.indexOf("*")>=0||this.path.indexOf("$")>=0}query(){return new DataReferenceQuery(this)}async count(){const info=await this.reflect("info",{child_count:true});return info.children.count}async reflect(type,args){if(this.isWildcardPath){throw new Error(`Cannot reflect on wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.reflect(this.path,type,args)}async export(write,options={format:"json",type_safe:true}){if(this.isWildcardPath){throw new Error(`Cannot export wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}const writeFn=typeof write==="function"?write:write.write.bind(write);return this.db.api.export(this.path,writeFn,options)}async import(read,options={format:"json",suppress_events:false}){if(this.isWildcardPath){throw new Error(`Cannot import to wildcard path "/${this.path}"`)}if(!this.db.isReady){await this.db.ready()}return this.db.api.import(this.path,read,options)}proxy(options){const isOptionsArg=typeof options==="object"&&(typeof options.cursor!=="undefined"||typeof options.defaultValue!=="undefined");if(typeof options!=="undefined"&&!isOptionsArg){this.db.debug.warn("Warning: live data proxy is being initialized with a deprecated method signature. Use ref.proxy(options) instead of ref.proxy(defaultValue)");options={defaultValue:options}}return data_proxy_1.LiveDataProxy.create(this,options)}observe(options){if(options){throw new Error("observe does not support data retrieval options yet")}if(this.isWildcardPath){throw new Error(`Cannot observe wildcard path "/${this.path}"`)}const Observable=(0,optional_observable_1.getObservable)();return new Observable((observer=>{let cache,resolved=false;let promise=this.get(options).then((snap=>{resolved=true;cache=snap.val();observer.next(cache)}));const updateCache=snap=>{if(!resolved){promise=promise.then((()=>updateCache(snap)));return}const mutatedPath=snap.ref.path;if(mutatedPath===this.path){cache=snap.val();return observer.next(cache)}const trailKeys=path_info_1.PathInfo.getPathKeys(mutatedPath).slice(path_info_1.PathInfo.getPathKeys(this.path).length);let target=cache;while(trailKeys.length>1){const key=trailKeys.shift();if(!(key in target)){target[key]=typeof trailKeys[0]==="number"?[]:{}}target=target[key]}const prop=trailKeys.shift();const newValue=snap.val();if(newValue===null){target instanceof Array&&typeof prop==="number"?target.splice(prop,1):delete target[prop]}else{target[prop]=newValue}observer.next(cache)};this.on("mutated",updateCache);return()=>{this.off("mutated",updateCache)}}))}async forEach(callbackOrOptions,callback){let options;if(typeof callbackOrOptions==="function"){callback=callbackOrOptions}else{options=callbackOrOptions}if(typeof callback!=="function"){throw new TypeError("No callback function given")}const info=await this.reflect("children",{limit:0,skip:0});const summary={canceled:false,total:info.list.length,processed:0};for(let i=0;ithis.get(optionsOrCallback,callback)));return typeof optionsOrCallback!=="function"&&typeof callback!=="function"?promise:undefined}callback=typeof optionsOrCallback==="function"?optionsOrCallback:typeof callback==="function"?callback:undefined;const options=new QueryDataRetrievalOptions(typeof optionsOrCallback==="object"?optionsOrCallback:{snapshots:true,cache_mode:"allow"});options.allow_cache=options.cache_mode!=="bypass";options.eventHandler=ev=>{if(!this[_private].events[ev.name]){return false}const listeners=this[_private].events[ev.name];if(typeof listeners!=="object"||listeners.length===0){return false}if(["add","change","remove"].includes(ev.name)){const eventData={name:ev.name,ref:new DataReference(this.ref.db,ev.path)};if(options.snapshots&&ev.name!=="remove"){const val=db.types.deserialize(ev.path,ev.value);eventData.snapshot=new data_snapshot_1.DataSnapshot(eventData.ref,val,false)}ev=eventData}listeners.forEach((callback=>{try{callback(ev)}catch(e){}}))};options.monitor={add:false,change:false,remove:false};if(this[_private].events){if(this[_private].events["add"]&&this[_private].events["add"].length>0){options.monitor.add=true}if(this[_private].events["change"]&&this[_private].events["change"].length>0){options.monitor.change=true}if(this[_private].events["remove"]&&this[_private].events["remove"].length>0){options.monitor.remove=true}}this.stop();const db=this.ref.db;return db.api.query(this.ref.path,this[_private],options).catch((err=>{throw new Error(err)})).then((res=>{const{stop:stop}=res;let{results:results,context:context}=res;this.stop=async()=>{await stop()};if(!("results"in res&&"context"in res)){console.warn("Query results missing context. Update your acebase and/or acebase-client packages");results=res,context={}}if(options.snapshots){const snaps=results.map((result=>{const val=db.types.deserialize(result.path,result.val);return new data_snapshot_1.DataSnapshot(db.ref(result.path),val,false,undefined,context)}));return DataSnapshotsArray.from(snaps)}else{const refs=results.map((path=>db.ref(path)));return DataReferencesArray.from(refs)}})).then((results=>{callback&&callback(results);return results}))}async stop(){}getRefs(callback){return this.get({snapshots:false},callback)}find(){return this.get({snapshots:false})}async count(){const refs=await this.find();return refs.length}async exists(){const originalTake=this[_private].take;const p=this.take(1).find();this.take(originalTake);const refs=await p;return refs.length!==0}async remove(callback){const refs=await this.find();const parentUpdates=refs.reduce(((parents,ref)=>{const parent=parents[ref.parent.path];if(!parent){parents[ref.parent.path]=[ref]}else{parent.push(ref)}return parents}),{});const db=this.ref.db;const promises=Object.keys(parentUpdates).map((async parentPath=>{const updates=refs.reduce(((updates,ref)=>{updates[ref.key]=null;return updates}),{});const ref=db.ref(parentPath);try{await ref.update(updates);return{ref:ref,success:true}}catch(error){return{ref:ref,success:false,error:error}}}));const results=await Promise.all(promises);callback&&callback(results);return results}on(event,callback){if(!this[_private].events[event]){this[_private].events[event]=[]}this[_private].events[event].push(callback);return this}off(event,callback){if(typeof event==="undefined"){this[_private].events={};return this}if(!this[_private].events[event]){return this}if(typeof callback==="undefined"){delete this[_private].events[event];return this}const index=this[_private].events[event].indexOf(callback);if(!~index){return this}this[_private].events[event].splice(index,1);return this}async forEach(callbackOrOptions,callback){let options;if(typeof callbackOrOptions==="function"){callback=callbackOrOptions}else{options=callbackOrOptions}if(typeof callback!=="function"){throw new TypeError("No callback function given")}const refs=await this.find();const summary={canceled:false,total:refs.length,processed:0};for(let i=0;iarr[i]=snap));return arr}getValues(){return this.map((snap=>snap.val()))}}exports.DataSnapshotsArray=DataSnapshotsArray;class DataReferencesArray extends Array{static from(refs){const arr=new DataReferencesArray(refs.length);refs.forEach(((ref,i)=>arr[i]=ref));return arr}getPaths(){return this.map((ref=>ref.path))}}exports.DataReferencesArray=DataReferencesArray},{"./data-proxy":20,"./data-snapshot":22,"./id":24,"./optional-observable":27,"./path-info":29,"./subscription":36}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MutationsDataSnapshot=exports.DataSnapshot=void 0;const path_info_1=require("./path-info");function getChild(snapshot,path,previous=false){if(!snapshot.exists()){return null}let child=previous?snapshot.previous():snapshot.val();if(typeof path==="number"){return child[path]}path_info_1.PathInfo.getPathKeys(path).every((key=>{child=child[key];return typeof child!=="undefined"}));return child||null}function getChildren(snapshot){if(!snapshot.exists()){return[]}const value=snapshot.val();if(value instanceof Array){return new Array(value.length).map(((v,i)=>i))}if(typeof value==="object"){return Object.keys(value)}return[]}class DataSnapshot{constructor(ref,value,isRemoved=false,prevValue,context){this.ref=ref;this.val=()=>value;this.previous=()=>prevValue;this.exists=()=>{if(isRemoved){return false}return value!==null&&typeof value!=="undefined"};this.context=()=>context||{}}exists(){return false}static for(ref,value){return new DataSnapshot(ref,value)}child(path){const val=getChild(this,path,false);const prev=getChild(this,path,true);return new DataSnapshot(this.ref.child(path),val,false,prev)}hasChild(path){return getChild(this,path)!==null}hasChildren(){return getChildren(this).length>0}numChildren(){return getChildren(this).length}forEach(callback){const value=this.val();const prev=this.previous();return getChildren(this).every((key=>{const snap=new DataSnapshot(this.ref.child(key),value[key],false,prev[key]);return callback(snap)}))}get key(){return this.ref.key}}exports.DataSnapshot=DataSnapshot;class MutationsDataSnapshot extends DataSnapshot{constructor(ref,mutations,context){super(ref,mutations,false,undefined,context);this.previous=()=>{throw new Error("Iterate values to get previous values for each mutation")};this.val=(warn=true)=>{if(warn){console.warn("Unless you know what you are doing, it is best not to use the value of a mutations snapshot directly. Use child methods and forEach to iterate the mutations instead")}return mutations}}forEach(callback){const mutations=this.val();return mutations.every((mutation=>{const ref=mutation.target.reduce(((ref,key)=>ref.child(key)),this.ref);const snap=new DataSnapshot(ref,mutation.val,false,mutation.prev);return callback(snap)}))}child(index){if(typeof index!=="number"){throw new Error("child index must be a number")}const mutation=this.val()[index];const ref=mutation.target.reduce(((ref,key)=>ref.child(key)),this.ref);return new DataSnapshot(ref,mutation.val,false,mutation.prev)}}exports.MutationsDataSnapshot=MutationsDataSnapshot},{"./path-info":29}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.DebugLogger=void 0;const process_1=require("./process");const noop=()=>{};class DebugLogger{constructor(level="log",prefix=""){this.level=level;this.prefix=prefix;this.setLevel(level)}setLevel(level){const prefix=this.prefix?this.prefix+" %s":"";this.verbose=["verbose"].includes(level)?prefix?console.log.bind(console,prefix):console.log.bind(console):noop;this.log=["verbose","log"].includes(level)?prefix?console.log.bind(console,prefix):console.log.bind(console):noop;this.warn=["verbose","log","warn"].includes(level)?prefix?console.warn.bind(console,prefix):console.warn.bind(console):noop;this.error=["verbose","log","warn","error"].includes(level)?prefix?console.error.bind(console,prefix):console.error.bind(console):noop;this.write=text=>{const isRunKit=typeof process_1.default!=="undefined"&&process_1.default.env&&typeof process_1.default.env.RUNKIT_ENDPOINT_PATH==="string";if(text&&isRunKit){text.split("\n").forEach((line=>console.log(line)))}else{console.log(text)}}}}exports.DebugLogger=DebugLogger},{"./process":31}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ID=void 0;const cuid_1=require("./cuid");let timeBias=0;class ID{static set timeBias(bias){if(typeof bias!=="number"){return}timeBias=bias}static generate(){return(0,cuid_1.default)(timeBias).slice(1)}}exports.ID=ID},{"./cuid":18}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ObjectCollection=exports.PartialArray=exports.SimpleObservable=exports.SchemaDefinition=exports.Colorize=exports.ColorStyle=exports.SimpleEventEmitter=exports.SimpleCache=exports.ascii85=exports.PathInfo=exports.Utils=exports.TypeMappings=exports.Transport=exports.EventSubscription=exports.EventPublisher=exports.EventStream=exports.PathReference=exports.ID=exports.DebugLogger=exports.OrderedCollectionProxy=exports.proxyAccess=exports.MutationsDataSnapshot=exports.DataSnapshot=exports.DataReferencesArray=exports.DataSnapshotsArray=exports.QueryDataRetrievalOptions=exports.DataRetrievalOptions=exports.DataReferenceQuery=exports.DataReference=exports.Api=exports.AceBaseBaseSettings=exports.AceBaseBase=void 0;var acebase_base_1=require("./acebase-base");Object.defineProperty(exports,"AceBaseBase",{enumerable:true,get:function(){return acebase_base_1.AceBaseBase}});Object.defineProperty(exports,"AceBaseBaseSettings",{enumerable:true,get:function(){return acebase_base_1.AceBaseBaseSettings}});var api_1=require("./api");Object.defineProperty(exports,"Api",{enumerable:true,get:function(){return api_1.Api}});var data_reference_1=require("./data-reference");Object.defineProperty(exports,"DataReference",{enumerable:true,get:function(){return data_reference_1.DataReference}});Object.defineProperty(exports,"DataReferenceQuery",{enumerable:true,get:function(){return data_reference_1.DataReferenceQuery}});Object.defineProperty(exports,"DataRetrievalOptions",{enumerable:true,get:function(){return data_reference_1.DataRetrievalOptions}});Object.defineProperty(exports,"QueryDataRetrievalOptions",{enumerable:true,get:function(){return data_reference_1.QueryDataRetrievalOptions}});Object.defineProperty(exports,"DataSnapshotsArray",{enumerable:true,get:function(){return data_reference_1.DataSnapshotsArray}});Object.defineProperty(exports,"DataReferencesArray",{enumerable:true,get:function(){return data_reference_1.DataReferencesArray}});var data_snapshot_1=require("./data-snapshot");Object.defineProperty(exports,"DataSnapshot",{enumerable:true,get:function(){return data_snapshot_1.DataSnapshot}});Object.defineProperty(exports,"MutationsDataSnapshot",{enumerable:true,get:function(){return data_snapshot_1.MutationsDataSnapshot}});var data_proxy_1=require("./data-proxy");Object.defineProperty(exports,"proxyAccess",{enumerable:true,get:function(){return data_proxy_1.proxyAccess}});Object.defineProperty(exports,"OrderedCollectionProxy",{enumerable:true,get:function(){return data_proxy_1.OrderedCollectionProxy}});var debug_1=require("./debug");Object.defineProperty(exports,"DebugLogger",{enumerable:true,get:function(){return debug_1.DebugLogger}});var id_1=require("./id");Object.defineProperty(exports,"ID",{enumerable:true,get:function(){return id_1.ID}});var path_reference_1=require("./path-reference");Object.defineProperty(exports,"PathReference",{enumerable:true,get:function(){return path_reference_1.PathReference}});var subscription_1=require("./subscription");Object.defineProperty(exports,"EventStream",{enumerable:true,get:function(){return subscription_1.EventStream}});Object.defineProperty(exports,"EventPublisher",{enumerable:true,get:function(){return subscription_1.EventPublisher}});Object.defineProperty(exports,"EventSubscription",{enumerable:true,get:function(){return subscription_1.EventSubscription}});exports.Transport=require("./transport");var type_mappings_1=require("./type-mappings");Object.defineProperty(exports,"TypeMappings",{enumerable:true,get:function(){return type_mappings_1.TypeMappings}});exports.Utils=require("./utils");var path_info_1=require("./path-info");Object.defineProperty(exports,"PathInfo",{enumerable:true,get:function(){return path_info_1.PathInfo}});var ascii85_1=require("./ascii85");Object.defineProperty(exports,"ascii85",{enumerable:true,get:function(){return ascii85_1.ascii85}});var simple_cache_1=require("./simple-cache");Object.defineProperty(exports,"SimpleCache",{enumerable:true,get:function(){return simple_cache_1.SimpleCache}});var simple_event_emitter_1=require("./simple-event-emitter");Object.defineProperty(exports,"SimpleEventEmitter",{enumerable:true,get:function(){return simple_event_emitter_1.SimpleEventEmitter}});var simple_colors_1=require("./simple-colors");Object.defineProperty(exports,"ColorStyle",{enumerable:true,get:function(){return simple_colors_1.ColorStyle}});Object.defineProperty(exports,"Colorize",{enumerable:true,get:function(){return simple_colors_1.Colorize}});var schema_1=require("./schema");Object.defineProperty(exports,"SchemaDefinition",{enumerable:true,get:function(){return schema_1.SchemaDefinition}});var optional_observable_1=require("./optional-observable");Object.defineProperty(exports,"SimpleObservable",{enumerable:true,get:function(){return optional_observable_1.SimpleObservable}});var partial_array_1=require("./partial-array");Object.defineProperty(exports,"PartialArray",{enumerable:true,get:function(){return partial_array_1.PartialArray}});const object_collection_1=require("./object-collection");Object.defineProperty(exports,"ObjectCollection",{enumerable:true,get:function(){return object_collection_1.ObjectCollection}})},{"./acebase-base":14,"./api":15,"./ascii85":16,"./data-proxy":20,"./data-reference":21,"./data-snapshot":22,"./debug":23,"./id":24,"./object-collection":26,"./optional-observable":27,"./partial-array":28,"./path-info":29,"./path-reference":30,"./schema":32,"./simple-cache":33,"./simple-colors":34,"./simple-event-emitter":35,"./subscription":36,"./transport":37,"./type-mappings":38,"./utils":39}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ObjectCollection=void 0;const id_1=require("./id");class ObjectCollection{static from(array){const collection={};array.forEach((child=>{collection[id_1.ID.generate()]=child}));return collection}}exports.ObjectCollection=ObjectCollection},{"./id":24}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SimpleObservable=exports.setObservable=exports.getObservable=void 0;const utils_1=require("./utils");let _shimRequested=false;let _observable;(async()=>{const global=(0,utils_1.getGlobalObject)();if(typeof global.Observable!=="undefined"){_observable=global.Observable;return}try{const{Observable:Observable}=await Promise.resolve().then((()=>require("rxjs")));_observable=Observable}catch(_a){_observable=SimpleObservable}})();function getObservable(){if(_observable===SimpleObservable&&!_shimRequested){console.warn("Using AceBase's simple Observable implementation because rxjs is not available. "+'Add it to your project with "npm install rxjs", add it to AceBase using db.setObservable(Observable), '+'or call db.setObservable("shim") to suppress this warning')}if(_observable){return _observable}throw new Error("RxJS Observable could not be loaded. ")}exports.getObservable=getObservable;function setObservable(Observable){if(Observable==="shim"){_observable=SimpleObservable;_shimRequested=true}else{_observable=Observable}}exports.setObservable=setObservable;class SimpleObservable{constructor(create){this._active=false;this._subscribers=[];this._create=create}subscribe(subscriber){if(!this._active){const next=value=>{this._subscribers.forEach((s=>{try{s(value)}catch(err){console.error("Error in subscriber callback:",err)}}))};const observer={next:next};this._cleanup=this._create(observer);this._active=true}this._subscribers.push(subscriber);const unsubscribe=()=>{this._subscribers.splice(this._subscribers.indexOf(subscriber),1);if(this._subscribers.length===0){this._active=false;this._cleanup()}};const subscription={unsubscribe:unsubscribe};return subscription}}exports.SimpleObservable=SimpleObservable},{"./utils":39,rxjs:40}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PartialArray=void 0;class PartialArray{constructor(sparseArray){if(sparseArray instanceof Array){for(let i=0;ikey.startsWith("[")?parseInt(key.slice(1,-1)):key))}class PathInfo{constructor(path){if(typeof path==="string"){this.keys=getPathKeys(path)}else if(path instanceof Array){this.keys=path}this.path=this.keys.reduce(((path,key,i)=>i===0?`${key}`:typeof key==="string"?`${path}/${key}`:`${path}[${key}]`),"")}static get(path){return new PathInfo(path)}static getChildPath(path,childKey){return PathInfo.get(path).child(childKey).path}static getPathKeys(path){return getPathKeys(path)}get key(){return this.keys.length===0?null:this.keys.slice(-1)[0]}get parent(){if(this.keys.length==0){return null}const parentKeys=this.keys.slice(0,-1);return new PathInfo(parentKeys)}get parentPath(){return this.keys.length===0?null:this.parent.path}child(childKey){if(typeof childKey==="string"){if(childKey.length===0){throw new Error(`child key for path "${this.path}" cannot be empty`)}const keys=getPathKeys(childKey);keys.forEach((key=>{if(typeof key!=="string"){return}if(/[\x00-\x08\x0b\x0c\x0e-\x1f/[\]\\]/.test(key)){throw new Error(`Invalid child key "${key}" for path "${this.path}". Keys cannot contain control characters or any of the following characters: \\ / [ ]`)}if(key.length>128){throw new Error(`child key "${key}" for path "${this.path}" is too long. Max key length is 128`)}if(key.length===0){throw new Error(`child key for path "${this.path}" cannot be empty`)}}));childKey=keys}return new PathInfo(this.keys.concat(childKey))}childPath(childKey){return this.child(childKey).path}get pathKeys(){return this.keys}static extractVariables(varPath,fullPath){if(!varPath.includes("*")&&!varPath.includes("$")){return[]}const keys=getPathKeys(varPath);const pathKeys=getPathKeys(fullPath);let count=0;const variables={get length(){return count}};keys.forEach(((key,index)=>{const pathKey=pathKeys[index];if(key==="*"){variables[count++]=pathKey}else if(typeof key==="string"&&key[0]==="$"){variables[count++]=pathKey;variables[key]=pathKey;const varName=key.slice(1);if(typeof variables[varName]==="undefined"){variables[varName]=pathKey}}}));return variables}static fillVariables(varPath,fullPath){if(varPath.indexOf("*")<0&&varPath.indexOf("$")<0){return varPath}const keys=getPathKeys(varPath);const pathKeys=getPathKeys(fullPath);const merged=keys.map(((key,index)=>{if(key===pathKeys[index]||index>=pathKeys.length){return key}else if(typeof key==="string"&&(key==="*"||key[0]==="$")){return pathKeys[index]}else{throw new Error(`Path "${fullPath}" cannot be used to fill variables of path "${varPath}" because they do not match`)}}));let mergedPath="";merged.forEach((key=>{if(typeof key==="number"){mergedPath+=`[${key}]`}else{if(mergedPath.length>0){mergedPath+="/"}mergedPath+=key}}));return mergedPath}static fillVariables2(varPath,vars){if(typeof vars!=="object"||Object.keys(vars).length===0){return varPath}const pathKeys=getPathKeys(varPath);let n=0;const targetPath=pathKeys.reduce(((path,key)=>{if(typeof key==="string"&&(key==="*"||key.startsWith("$"))){return PathInfo.getChildPath(path,vars[n++])}else{return PathInfo.getChildPath(path,key)}}),"");return targetPath}equals(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(this.path===other.path){return true}if(this.keys.length!==other.keys.length){return false}return this.keys.every(((key,index)=>{const otherKey=other.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isAncestorOf(descendantPath){const descendant=descendantPath instanceof PathInfo?descendantPath:new PathInfo(descendantPath);if(descendant.path===""||this.path===descendant.path){return false}if(this.path===""){return true}if(this.keys.length>=descendant.keys.length){return false}return this.keys.every(((key,index)=>{const otherKey=descendant.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isDescendantOf(ancestorPath){const ancestor=ancestorPath instanceof PathInfo?ancestorPath:new PathInfo(ancestorPath);if(this.path===""||this.path===ancestor.path){return false}if(ancestorPath===""){return true}if(ancestor.keys.length>=this.keys.length){return false}return ancestor.keys.every(((key,index)=>{const otherKey=this.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isOnTrailOf(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(this.path.length===0||other.path.length===0){return true}if(this.path===other.path){return true}return this.pathKeys.every(((key,index)=>{if(index>=other.keys.length){return true}const otherKey=other.keys[index];return otherKey===key||typeof otherKey==="string"&&(otherKey==="*"||otherKey[0]==="$")||typeof key==="string"&&(key==="*"||key[0]==="$")}))}isChildOf(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(this.path===""){return false}return this.parent.equals(other)}isParentOf(otherPath){const other=otherPath instanceof PathInfo?otherPath:new PathInfo(otherPath);if(other.path===""){return false}return this.equals(other.parent)}}exports.PathInfo=PathInfo},{}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PathReference=void 0;class PathReference{constructor(path){this.path=path}}exports.PathReference=PathReference},{}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default={nextTick(fn){setTimeout(fn,0)}}},{}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SchemaDefinition=void 0;function parse(definition){let pos=0;function consumeSpaces(){let c;while(c=definition[pos],[" ","\r","\n","\t"].includes(c)){pos++}}function consumeCharacter(c){if(definition[pos]!==c){throw new Error(`Unexpected character at position ${pos}. Expected: '${c}', found '${definition[pos]}'`)}pos++}function readProperty(){consumeSpaces();const prop={name:"",optional:false,wildcard:false};let c;while(c=definition[pos],c==="_"||c==="$"||c>="a"&&c<="z"||c>="A"&&c<="Z"||prop.name.length>0&&c>="0"&&c<="9"||prop.name.length===0&&c==="*"){prop.name+=c;pos++}if(prop.name.length===0){throw new Error(`Property name expected at position ${pos}, found: ${definition.slice(pos,pos+10)}..`)}if(definition[pos]==="?"){prop.optional=true;pos++}if(prop.name==="*"||prop.name[0]==="$"){prop.optional=true;prop.wildcard=true}consumeSpaces();consumeCharacter(":");return prop}function readType(){consumeSpaces();let type={typeOf:"any"},c;let name="";while(c=definition[pos],c>="a"&&c<="z"||c>="A"&&c<="Z"){name+=c;pos++}if(name.length===0){if(definition[pos]==="*"){consumeCharacter("*");type.typeOf="any"}else if(["'",'"',"`"].includes(definition[pos])){type.typeOf="string";type.value="";const quote=definition[pos];consumeCharacter(quote);while(c=definition[pos],c&&c!==quote){type.value+=c;pos++}consumeCharacter(quote)}else if(definition[pos]>="0"&&definition[pos]<="9"){type.typeOf="number";let nr="";while(c=definition[pos],c==="."||c==="n"||c>="0"&&c<="9"){nr+=c;pos++}if(nr.endsWith("n")){type.value=BigInt(nr)}else if(nr.includes(".")){type.value=parseFloat(nr)}else{type.value=parseInt(nr)}}else if(definition[pos]==="{"){consumeCharacter("{");type.typeOf="object";type.instanceOf=Object;type.children=[];while(true){const prop=readProperty();const types=readTypes();type.children.push({name:prop.name,optional:prop.optional,wildcard:prop.wildcard,types:types});consumeSpaces();if(definition[pos]==="}"){break}consumeCharacter(",")}consumeCharacter("}")}else if(definition[pos]==="/"){consumeCharacter("/");let pattern="",flags="";while(c=definition[pos],c!=="/"||pattern.endsWith("\\")){pattern+=c;pos++}consumeCharacter("/");while(c=definition[pos],["g","i","m","s","u","y","d"].includes(c)){flags+=c;pos++}type.typeOf="string";type.matches=new RegExp(pattern,flags)}else{throw new Error(`Expected a type definition at position ${pos}, found character '${definition[pos]}'`)}}else if(["string","number","boolean","bigint","undefined","String","Number","Boolean","BigInt"].includes(name)){type.typeOf=name.toLowerCase()}else if(name==="Object"||name==="object"){type.typeOf="object";type.instanceOf=Object}else if(name==="Date"){type.typeOf="object";type.instanceOf=Date}else if(name==="Binary"||name==="binary"){type.typeOf="object";type.instanceOf=ArrayBuffer}else if(name==="any"){type.typeOf="any"}else if(name==="null"){type.typeOf="object";type.value=null}else if(name==="Array"){consumeCharacter("<");type.typeOf="object";type.instanceOf=Array;type.genericTypes=readTypes();consumeCharacter(">")}else if(["true","false"].includes(name)){type.typeOf="boolean";type.value=name==="true"}else{throw new Error(`Unknown type at position ${pos}: "${type}"`)}consumeSpaces();while(definition[pos]==="["){consumeCharacter("[");consumeCharacter("]");type={typeOf:"object",instanceOf:Array,genericTypes:[type]}}return type}function readTypes(){consumeSpaces();const types=[readType()];while(definition[pos]==="|"){consumeCharacter("|");types.push(readType());consumeSpaces()}return types}return readType()}function checkObject(path,properties,obj,partial){const invalidProperties=properties.find((prop=>prop.name==="*"||prop.name[0]==="$"))?[]:Object.keys(obj).filter((key=>![null,undefined].includes(obj[key])&&!properties.find((prop=>prop.name===key))));if(invalidProperties.length>0){return{ok:false,reason:`Object at path "${path}" cannot have propert${invalidProperties.length===1?"y":"ies"} ${invalidProperties.map((p=>`"${p}"`)).join(", ")}`}}function checkProperty(property){const hasValue=![null,undefined].includes(obj[property.name]);if(!property.optional&&(partial?obj[property.name]===null:!hasValue)){return{ok:false,reason:`Property at path "${path}/${property.name}" is not optional`}}if(hasValue&&property.types.length===1){return checkType(`${path}/${property.name}`,property.types[0],obj[property.name],false)}if(hasValue&&!property.types.some((type=>checkType(`${path}/${property.name}`,type,obj[property.name],false).ok))){return{ok:false,reason:`Property at path "${path}/${property.name}" does not match any of ${property.types.length} allowed types`}}return{ok:true}}const namedProperties=properties.filter((prop=>!prop.wildcard));const failedProperty=namedProperties.find((prop=>!checkProperty(prop).ok));if(failedProperty){const reason=checkProperty(failedProperty).reason;return{ok:false,reason:reason}}const wildcardProperty=properties.find((prop=>prop.wildcard));if(!wildcardProperty){return{ok:true}}const wildcardChildKeys=Object.keys(obj).filter((key=>!namedProperties.find((prop=>prop.name===key))));let result={ok:true};for(let i=0;i0){if(type.typeOf!=="object"){return{ok:false,reason:`path "${path}" must be typeof ${type.typeOf}`}}if(!type.children){return ok}const childKey=trailKeys[0];let property=type.children.find((prop=>prop.name===childKey));if(!property){property=type.children.find((prop=>prop.name==="*"||prop.name[0]==="$"))}if(!property){return{ok:false,reason:`Object at path "${path}" cannot have property "${childKey}"`}}if(property.optional&&value===null&&trailKeys.length===1){return ok}let result;property.types.some((type=>{const childPath=typeof childKey==="number"?`${path}[${childKey}]`:`${path}/${childKey}`;result=checkType(childPath,type,value,partial,trailKeys.slice(1));return result.ok}));return result}if(value===null){return ok}if(type.instanceOf===Object&&(typeof value!=="object"||value instanceof Array||value instanceof Date)){return{ok:false,reason:`path "${path}" must be an object collection`}}if(type.instanceOf&&(typeof value!=="object"||value.constructor!==type.instanceOf)){return{ok:false,reason:`path "${path}" must be an instance of ${type.instanceOf.name}`}}if("value"in type&&value!==type.value){return{ok:false,reason:`path "${path}" must be value: ${type.value}`}}if(typeof value!==type.typeOf){return{ok:false,reason:`path "${path}" must be typeof ${type.typeOf}`}}if(type.instanceOf===Array&&type.genericTypes&&!value.every((v=>type.genericTypes.some((t=>checkType(path,t,v,false).ok))))){return{ok:false,reason:`every array value of path "${path}" must match one of the specified types`}}if(type.typeOf==="object"&&type.children){return checkObject(path,type.children,value,partial)}if(type.matches&&!type.matches.test(value)){return{ok:false,reason:`path "${path}" must match regular expression /${type.matches.source}/${type.matches.flags}`}}return ok}function getConstructorType(val){switch(val){case String:return"string";case Number:return"number";case Boolean:return"boolean";case Date:return"Date";case BigInt:return"bigint";case Array:throw new Error("Schema error: Array cannot be used without a type. Use string[] or Array instead");default:throw new Error(`Schema error: unknown type used: ${val.name}`)}}class SchemaDefinition{constructor(definition){this.source=definition;if(typeof definition==="object"){const toTS=obj=>"{"+Object.keys(obj).map((key=>{let val=obj[key];if(val===undefined){val="undefined"}else if(val instanceof RegExp){val=`/${val.source}/${val.flags}`}else if(typeof val==="object"){val=toTS(val)}else if(typeof val==="function"){val=getConstructorType(val)}else if(!["string","number","boolean","bigint"].includes(typeof val)){throw new Error(`Type definition for key "${key}" must be a string, number, boolean, bigint, object, regular expression, or one of these classes: String, Number, Boolean, Date, BigInt`)}return`${key}:${val}`})).join(",")+"}";this.text=toTS(definition)}else if(typeof definition==="string"){this.text=definition}else{throw new Error("Type definiton must be a string or an object")}this.type=parse(this.text)}check(path,value,partial,trailKeys){return checkType(path,this.type,value,partial,trailKeys)}}exports.SchemaDefinition=SchemaDefinition},{}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SimpleCache=void 0;const utils_1=require("./utils");const calculateExpiryTime=expirySeconds=>expirySeconds>0?Date.now()+expirySeconds*1e3:Infinity;class SimpleCache{constructor(options){var _a;this.enabled=true;if(typeof options==="number"){options={expirySeconds:options}}options.cloneValues=options.cloneValues!==false;if(typeof options.expirySeconds!=="number"&&typeof options.maxEntries!=="number"){throw new Error("Either expirySeconds or maxEntries must be specified")}this.options=options;this.cache=new Map;const interval=setInterval((()=>{this.cleanUp()}),60*1e3);(_a=interval.unref)===null||_a===void 0?void 0:_a.call(interval)}get size(){return this.cache.size}has(key){if(!this.enabled){return false}return this.cache.has(key)}get(key){if(!this.enabled){return null}const entry=this.cache.get(key);if(!entry){return null}entry.expires=calculateExpiryTime(this.options.expirySeconds);entry.accessed=Date.now();return this.options.cloneValues?(0,utils_1.cloneObject)(entry.value):entry.value}set(key,value){if(this.options.maxEntries>0&&this.cache.size>=this.options.maxEntries&&!this.cache.has(key)){let oldest=null;const now=Date.now();for(const[key,entry]of this.cache.entries()){if(entry.expires<=now){this.cache.delete(key);oldest=null;break}if(!oldest||entry.accessed{if(entry.expires<=now){this.cache.delete(key)}}))}}exports.SimpleCache=SimpleCache},{"./utils":39}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.Colorize=exports.SetColorsEnabled=exports.ColorsSupported=exports.ColorStyle=void 0;const process_1=require("./process");const FontCode={bold:1,dim:2,italic:3,underline:4,inverse:7,hidden:8,strikethrough:94};const ColorCode={black:30,red:31,green:32,yellow:33,blue:34,magenta:35,cyan:36,white:37,grey:90,brightRed:91};const BgColorCode={bgBlack:40,bgRed:41,bgGreen:42,bgYellow:43,bgBlue:44,bgMagenta:45,bgCyan:46,bgWhite:47,bgGrey:100,bgBrightRed:101};const ResetCode={all:0,color:39,background:49,bold:22,dim:22,italic:23,underline:24,inverse:27,hidden:28,strikethrough:29};var ColorStyle;(function(ColorStyle){ColorStyle["reset"]="reset";ColorStyle["bold"]="bold";ColorStyle["dim"]="dim";ColorStyle["italic"]="italic";ColorStyle["underline"]="underline";ColorStyle["inverse"]="inverse";ColorStyle["hidden"]="hidden";ColorStyle["strikethrough"]="strikethrough";ColorStyle["black"]="black";ColorStyle["red"]="red";ColorStyle["green"]="green";ColorStyle["yellow"]="yellow";ColorStyle["blue"]="blue";ColorStyle["magenta"]="magenta";ColorStyle["cyan"]="cyan";ColorStyle["grey"]="grey";ColorStyle["bgBlack"]="bgBlack";ColorStyle["bgRed"]="bgRed";ColorStyle["bgGreen"]="bgGreen";ColorStyle["bgYellow"]="bgYellow";ColorStyle["bgBlue"]="bgBlue";ColorStyle["bgMagenta"]="bgMagenta";ColorStyle["bgCyan"]="bgCyan";ColorStyle["bgWhite"]="bgWhite";ColorStyle["bgGrey"]="bgGrey"})(ColorStyle=exports.ColorStyle||(exports.ColorStyle={}));function ColorsSupported(){if(typeof process_1.default==="undefined"||!process_1.default.stdout||!process_1.default.env||!process_1.default.platform||process_1.default.platform==="browser"){return false}if(process_1.default.platform==="win32"){return true}const env=process_1.default.env;if(env.COLORTERM){return true}if(env.TERM==="dumb"){return false}if(env.CI||env.TEAMCITY_VERSION){return!!env.TRAVIS}if(["iTerm.app","HyperTerm","Hyper","MacTerm","Apple_Terminal","vscode"].includes(env.TERM_PROGRAM)){return true}if(/^xterm-256|^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(env.TERM)){return true}return false}exports.ColorsSupported=ColorsSupported;let _enabled=ColorsSupported();function SetColorsEnabled(enabled){_enabled=ColorsSupported()&&enabled}exports.SetColorsEnabled=SetColorsEnabled;function Colorize(str,style){if(!_enabled){return str}const openCodes=[],closeCodes=[];const addStyle=style=>{if(style===ColorStyle.reset){openCodes.push(ResetCode.all)}else if(style in FontCode){openCodes.push(FontCode[style]);closeCodes.push(ResetCode[style])}else if(style in ColorCode){openCodes.push(ColorCode[style]);closeCodes.push(ResetCode.color)}else if(style in BgColorCode){openCodes.push(BgColorCode[style]);closeCodes.push(ResetCode.background)}};if(style instanceof Array){style.forEach(addStyle)}else{addStyle(style)}const open=openCodes.map((code=>"["+code+"m")).join("");const close=closeCodes.map((code=>"["+code+"m")).join("");return str.split("\n").map((line=>open+line+close)).join("\n")}exports.Colorize=Colorize;String.prototype.colorize=function(style){return Colorize(this,style)}},{"./process":31}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SimpleEventEmitter=void 0;function runCallback(callback,data){try{callback(data)}catch(err){console.error("Error in subscription callback",err)}}class SimpleEventEmitter{constructor(){this._subscriptions=[];this._oneTimeEvents=new Map}on(event,callback){if(this._oneTimeEvents.has(event)){return runCallback(callback,this._oneTimeEvents.get(event))}this._subscriptions.push({event:event,callback:callback,once:false});return this}off(event,callback){this._subscriptions=this._subscriptions.filter((s=>s.event!==event||callback&&s.callback!==callback));return this}once(event,callback){return new Promise((resolve=>{const ourCallback=data=>{resolve(data);callback===null||callback===void 0?void 0:callback(data)};if(this._oneTimeEvents.has(event)){runCallback(ourCallback,this._oneTimeEvents.get(event))}else{this._subscriptions.push({event:event,callback:ourCallback,once:true})}}))}emit(event,data){if(this._oneTimeEvents.has(event)){throw new Error(`Event "${event}" was supposed to be emitted only once`)}for(let i=0;i{if(this._internal.state==="active"){return resolve()}else if(this._internal.state==="canceled"&&!callback){return reject(new Error(this._internal.cancelReason))}const noop=()=>{};this._internal.activatePromises.push({resolve:resolve,reject:callback?noop:reject})}))}_setActivationState(activated,cancelReason){this._internal.cancelReason=cancelReason;this._internal.state=activated?"active":"canceled";while(this._internal.activatePromises.length>0){const p=this._internal.activatePromises.shift();if(activated){p.callback&&p.callback(true);p.resolve&&p.resolve()}else{p.callback&&p.callback(false,cancelReason);p.reject&&p.reject(cancelReason)}}}}exports.EventSubscription=EventSubscription;class EventPublisher{constructor(publish,start,cancel){this.publish=publish;this.start=start;this.cancel=cancel}}exports.EventPublisher=EventPublisher;class EventStream{constructor(eventPublisherCallback){const subscribers=[];let noMoreSubscribersCallback;let activationState;const STATE_STOPPED="stopped (no more subscribers)";this.subscribe=(callback,activationCallback)=>{if(typeof callback!=="function"){throw new TypeError("callback must be a function")}else if(activationState===STATE_STOPPED){throw new Error("stream can't be used anymore because all subscribers were stopped")}const sub={callback:callback,activationCallback:function(activated,cancelReason){activationCallback===null||activationCallback===void 0?void 0:activationCallback(activated,cancelReason);this.subscription._setActivationState(activated,cancelReason)},subscription:new EventSubscription((function stop(){subscribers.splice(subscribers.indexOf(this),1);return checkActiveSubscribers()}))};subscribers.push(sub);if(typeof activationState!=="undefined"){if(activationState===true){activationCallback===null||activationCallback===void 0?void 0:activationCallback(true);sub.subscription._setActivationState(true)}else if(typeof activationState==="string"){activationCallback===null||activationCallback===void 0?void 0:activationCallback(false,activationState);sub.subscription._setActivationState(false,activationState)}}return sub.subscription};const checkActiveSubscribers=()=>{let ret;if(subscribers.length===0){ret=noMoreSubscribersCallback===null||noMoreSubscribersCallback===void 0?void 0:noMoreSubscribersCallback();activationState=STATE_STOPPED}return Promise.resolve(ret)};this.unsubscribe=callback=>{const remove=callback?subscribers.filter((sub=>sub.callback===callback)):subscribers;remove.forEach((sub=>{const i=subscribers.indexOf(sub);subscribers.splice(i,1)}));checkActiveSubscribers()};this.stop=()=>{subscribers.splice(0);checkActiveSubscribers()};const publish=val=>{subscribers.forEach((sub=>{try{sub.callback(val)}catch(err){console.error(`Error running subscriber callback: ${err.message}`)}}));if(subscribers.length===0){checkActiveSubscribers()}return subscribers.length>0};const start=allSubscriptionsStoppedCallback=>{activationState=true;noMoreSubscribersCallback=allSubscriptionsStoppedCallback;subscribers.forEach((sub=>{var _a;(_a=sub.activationCallback)===null||_a===void 0?void 0:_a.call(sub,true)}))};const cancel=reason=>{activationState=reason;subscribers.forEach((sub=>{var _a;(_a=sub.activationCallback)===null||_a===void 0?void 0:_a.call(sub,false,reason||new Error("unknown reason"))}));subscribers.splice(0)};const publisher=new EventPublisher(publish,start,cancel);eventPublisherCallback(publisher)}}exports.EventStream=EventStream},{}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.deserialize2=exports.serialize2=exports.serialize=exports.detectSerializeVersion=exports.deserialize=void 0;const path_reference_1=require("./path-reference");const utils_1=require("./utils");const ascii85_1=require("./ascii85");const path_info_1=require("./path-info");const partial_array_1=require("./partial-array");const deserialize=data=>{if(data.map===null||typeof data.map==="undefined"){if(typeof data.val==="undefined"){throw new Error("serialized value must have a val property")}return data.val}const deserializeValue=(type,val)=>{if(type==="date"){return new Date(val)}else if(type==="binary"){return ascii85_1.ascii85.decode(val)}else if(type==="reference"){return new path_reference_1.PathReference(val)}else if(type==="regexp"){return new RegExp(val.pattern,val.flags)}else if(type==="array"){return new partial_array_1.PartialArray(val)}else if(type==="bigint"){return BigInt(val)}return val};if(typeof data.map==="string"){return deserializeValue(data.map,data.val)}Object.keys(data.map).forEach((path=>{const type=data.map[path];const keys=path_info_1.PathInfo.getPathKeys(path);let parent=data;let key="val";let val=data.val;keys.forEach((k=>{key=k;parent=val;val=val[key]}));parent[key]=deserializeValue(type,val)}));return data.val};exports.deserialize=deserialize;const detectSerializeVersion=data=>{if(typeof data!=="object"||data===null){return 2}if("map"in data&&"val"in data){return 1}else if("val"in data){if(Object.keys(data).length>1){return 2}return 1}return 2};exports.detectSerializeVersion=detectSerializeVersion;const serialize=obj=>{var _a;if(obj===null||typeof obj!=="object"||obj instanceof Date||obj instanceof ArrayBuffer||obj instanceof path_reference_1.PathReference||obj instanceof RegExp){const ser=(0,exports.serialize)({value:obj});return{map:(_a=ser.map)===null||_a===void 0?void 0:_a.value,val:ser.val.value}}obj=(0,utils_1.cloneObject)(obj);const process=(obj,mappings,prefix)=>{if(obj instanceof partial_array_1.PartialArray){mappings[prefix]="array"}Object.keys(obj).forEach((key=>{const val=obj[key];const path=prefix.length===0?key:`${prefix}/${key}`;if(typeof val==="bigint"){obj[key]=val.toString();mappings[path]="bigint"}else if(val instanceof Date){obj[key]=val.toISOString();mappings[path]="date"}else if(val instanceof ArrayBuffer){obj[key]=ascii85_1.ascii85.encode(val);mappings[path]="binary"}else if(val instanceof path_reference_1.PathReference){obj[key]=val.path;mappings[path]="reference"}else if(val instanceof RegExp){obj[key]={pattern:val.source,flags:val.flags};mappings[path]="regexp"}else if(typeof val==="object"&&val!==null){process(val,mappings,path)}}))};const mappings={};process(obj,mappings,"");const serialized={val:obj};if(Object.keys(mappings).length>0){serialized.map=mappings}return serialized};exports.serialize=serialize;const serialize2=obj=>{const getSerializedValue=val=>{if(typeof val==="bigint"){return{".type":"bigint",".val":val.toString()}}else if(val instanceof Date){return{".type":"date",".val":val.toISOString()}}else if(val instanceof ArrayBuffer){return{".type":"binary",".val":ascii85_1.ascii85.encode(val)}}else if(val instanceof path_reference_1.PathReference){return{".type":"reference",".val":val.path}}else if(val instanceof RegExp){return{".type":"regexp",".val":`/${val.source}/${val.flags}`}}else if(typeof val==="object"&&val!==null){if(val instanceof Array){const copy=[];for(let i=0;i{if(typeof data!=="object"||data===null){return data}if(typeof data[".type"]==="undefined"){if(data instanceof Array){const copy=[];const arr=data;for(let i=0;i{const mkeys=path_info_1.PathInfo.getPathKeys(mpath);if(mkeys.length!==keys.length){return false}return mkeys.every(((mkey,index)=>{if(mkey==="*"||typeof mkey==="string"&&mkey[0]==="$"){return true}return mkey===keys[index]}))}));const mapping=mappings[mappedPath];return mapping}function map(mappings,path){const targetPath=path_info_1.PathInfo.get(path).parentPath;if(targetPath===null){return}return get(mappings,targetPath)}function mapDeep(mappings,entryPath){entryPath=entryPath.replace(/^\/|\/$/g,"");const pathInfo=path_info_1.PathInfo.get(entryPath);const startPath=pathInfo.parentPath;const keys=startPath?path_info_1.PathInfo.getPathKeys(startPath):[];const matches=Object.keys(mappings).reduce(((m,mpath)=>{const mkeys=path_info_1.PathInfo.getPathKeys(mpath);if(mkeys.length{if(index>=keys.length){return false}else if(mkey==="*"||typeof mkey==="string"&&mkey[0]==="$"||mkey===keys[index]){return true}else{isMatch=false;return false}}))}if(isMatch){const mapping=mappings[mpath];m.push({path:mpath,type:mapping})}return m}),[]);return matches}function process(db,mappings,path,obj,action){if(obj===null||typeof obj!=="object"){return obj}const keys=path_info_1.PathInfo.getPathKeys(path);const m=mapDeep(mappings,path);const changes=[];m.sort(((a,b)=>path_info_1.PathInfo.getPathKeys(a.path).length>path_info_1.PathInfo.getPathKeys(b.path).length?-1:1));m.forEach((mapping=>{const mkeys=path_info_1.PathInfo.getPathKeys(mapping.path);mkeys.push("*");const mTrailKeys=mkeys.slice(keys.length);if(mTrailKeys.length===0){const vars=path_info_1.PathInfo.extractVariables(mapping.path,path);const ref=new data_reference_1.DataReference(db,path,vars);if(action==="serialize"){obj=mapping.type.serialize(obj,ref)}else if(action==="deserialize"){const snap=new data_snapshot_1.DataSnapshot(ref,obj);obj=mapping.type.deserialize(snap)}return}const process=(parentPath,parent,keys)=>{if(obj===null||typeof obj!=="object"){return obj}const key=keys[0];let children=[];if(key==="*"||typeof key==="string"&&key[0]==="$"){if(parent instanceof Array){children=parent.map(((val,index)=>({key:index,val:val})))}else{children=Object.keys(parent).map((k=>({key:k,val:parent[k]})))}}else{const child=parent[key];if(typeof child==="object"){children.push({key:key,val:child})}}children.forEach((child=>{const childPath=path_info_1.PathInfo.getChildPath(parentPath,child.key);const vars=path_info_1.PathInfo.extractVariables(mapping.path,childPath);const ref=new data_reference_1.DataReference(db,childPath,vars);if(keys.length===1){if(action==="serialize"){changes.push({parent:parent,key:child.key,original:parent[child.key]});parent[child.key]=mapping.type.serialize(child.val,ref)}else if(action==="deserialize"){const snap=new data_snapshot_1.DataSnapshot(ref,child.val);parent[child.key]=mapping.type.deserialize(snap)}}else{process(childPath,child.val,keys.slice(1))}}))};process(path,obj,mTrailKeys)}));if(action==="serialize"){obj=(0,utils_1.cloneObject)(obj);if(changes.length>0){changes.forEach((change=>{change.parent[change.key]=change.original}))}}return obj}const _mappings=Symbol("mappings");class TypeMappings{constructor(db){this.db=db;this[_mappings]={}}get mappings(){return this[_mappings]}map(path){return map(this[_mappings],path)}bind(path,type,options={}){if(typeof path!=="string"){throw new TypeError("path must be a string")}if(typeof type!=="function"){throw new TypeError("constructor must be a function")}if(typeof options.serializer==="undefined"){}else if(typeof options.serializer==="string"){if(typeof type.prototype[options.serializer]==="function"){options.serializer=type.prototype[options.serializer]}else{throw new TypeError(`${type.name}.prototype.${options.serializer} is not a function, cannot use it as serializer`)}}else if(typeof options.serializer!=="function"){throw new TypeError(`serializer for class ${type.name} must be a function, or the name of a prototype method`)}if(typeof options.creator==="undefined"){if(typeof type.create==="function"){options.creator=type.create}}else if(typeof options.creator==="string"){if(typeof type[options.creator]==="function"){options.creator=type[options.creator]}else{throw new TypeError(`${type.name}.${options.creator} is not a function, cannot use it as creator`)}}else if(typeof options.creator!=="function"){throw new TypeError(`creator for class ${type.name} must be a function, or the name of a static method`)}path=path.replace(/^\/|\/$/g,"");this[_mappings][path]={db:this.db,type:type,creator:options.creator,serializer:options.serializer,deserialize(snap){let obj;if(this.creator){obj=this.creator.call(this.type,snap)}else{obj=new this.type(snap)}return obj},serialize(obj,ref){if(this.serializer){obj=this.serializer.call(obj,ref,obj)}else if(obj&&typeof obj.serialize==="function"){obj=obj.serialize(ref,obj)}return obj}}}serialize(path,obj){return process(this.db,this[_mappings],path,obj,"serialize")}deserialize(path,obj){return process(this.db,this[_mappings],path,obj,"deserialize")}}exports.TypeMappings=TypeMappings},{"./data-reference":21,"./data-snapshot":22,"./path-info":29,"./utils":39}],39:[function(require,module,exports){(function(global,Buffer){(function(){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getGlobalObject=exports.defer=exports.getChildValues=exports.getMutations=exports.compareValues=exports.ObjectDifferences=exports.valuesAreEqual=exports.cloneObject=exports.concatTypedArrays=exports.decodeString=exports.encodeString=exports.bytesToBigint=exports.bigintToBytes=exports.bytesToNumber=exports.numberToBytes=void 0;const path_reference_1=require("./path-reference");const process_1=require("./process");const partial_array_1=require("./partial-array");function numberToBytes(number){const bytes=new Uint8Array(8);const view=new DataView(bytes.buffer);view.setFloat64(0,number);return new Array(...bytes)}exports.numberToBytes=numberToBytes;function bytesToNumber(bytes){const length=Array.isArray(bytes)?bytes.length:bytes.byteLength;if(length!==8){throw new TypeError("must be 8 bytes")}const bin=new Uint8Array(bytes);const view=new DataView(bin.buffer);const nr=view.getFloat64(0);return nr}exports.bytesToNumber=bytesToNumber;const big={zero:BigInt(0),one:BigInt(1),two:BigInt(2),eight:BigInt(8),ff:BigInt(255)};function bigintToBytes(number){if(typeof number!=="bigint"){throw new Error("number must be a bigint")}const bytes=[];const negative=number>big.eight}while(number!==(negative?-big.one:big.zero));bytes.reverse();if(negative?bytes[0]<128:bytes[0]>=128){bytes.unshift(negative?255:0)}return bytes}exports.bigintToBytes=bigintToBytes;function bytesToBigint(bytes){const negative=bytes[0]>=128;let number=big.zero;for(let b of bytes){if(negative){b=~b&255}number=(number<128){if((code&55296)===55296){const nextCode=str.charCodeAt(i+1);if((nextCode&56320)!==56320){throw new Error("follow-up utf-16 character does not start with 0xDC00")}i++;const p1=code&1023;const p2=nextCode&1023;code=65536|p1<<10|p2}if(code<2048){const b1=192|code>>6&31;const b2=128|code&63;arr.push(b1,b2)}else if(code<65536){const b1=224|code>>12&15;const b2=128|code>>6&63;const b3=128|code&63;arr.push(b1,b2,b3)}else if(code<2097152){const b1=240|code>>18&7;const b2=128|code>>12&63;const b3=128|code>>6&63;const b4=128|code&63;arr.push(b1,b2,b3,b4)}else{throw new Error(`Cannot convert character ${str.charAt(i)} (code ${code}) to utf-8`)}}else{arr.push(code<128?code:63)}}return new Uint8Array(arr)}}exports.encodeString=encodeString;function decodeString(buffer){if(typeof TextDecoder!=="undefined"){const decoder=new TextDecoder;if(buffer instanceof Uint8Array){return decoder.decode(buffer)}const buf=Uint8Array.from(buffer);return decoder.decode(buf)}else if(typeof Buffer==="function"){if(buffer instanceof Array){buffer=Uint8Array.from(buffer)}if(!(buffer instanceof Buffer)&&"buffer"in buffer&&buffer.buffer instanceof ArrayBuffer){const typedArray=buffer;buffer=Buffer.from(typedArray.buffer,typedArray.byteOffset,typedArray.byteLength)}if(!(buffer instanceof Buffer)){throw new Error("Unsupported buffer argument")}return buffer.toString("utf-8")}else{if(!(buffer instanceof Uint8Array)&&"buffer"in buffer&&buffer["buffer"]instanceof ArrayBuffer){const typedArray=buffer;buffer=new Uint8Array(typedArray.buffer,typedArray.byteOffset,typedArray.byteLength)}if(buffer instanceof Buffer||buffer instanceof Array||buffer instanceof Uint8Array){let str="";for(let i=0;i128){if((code&240)===240){const b1=code,b2=buffer[i+1],b3=buffer[i+2],b4=buffer[i+3];code=(b1&7)<<18|(b2&63)<<12|(b3&63)<<6|b4&63;i+=3}else if((code&224)===224){const b1=code,b2=buffer[i+1],b3=buffer[i+2];code=(b1&15)<<12|(b2&63)<<6|b3&63;i+=2}else if((code&192)===192){const b1=code,b2=buffer[i+1];code=(b1&31)<<6|b2&63;i++}else{throw new Error("invalid utf-8 data")}}if(code>=65536){code^=65536;const p1=55296|code>>10;const p2=56320|code&1023;str+=String.fromCharCode(p1);str+=String.fromCharCode(p2)}else{str+=String.fromCharCode(code)}}return str}else{throw new Error("Unsupported buffer argument")}}}exports.decodeString=decodeString;function concatTypedArrays(a,b){const c=new a.constructor(a.length+b.length);c.set(a);c.set(b,a.length);return c}exports.concatTypedArrays=concatTypedArrays;function cloneObject(original,stack){var _a;if(((_a=original===null||original===void 0?void 0:original.constructor)===null||_a===void 0?void 0:_a.name)==="DataSnapshot"){throw new TypeError(`Object to clone is a DataSnapshot (path "${original.ref.path}")`)}const checkAndFixTypedArray=obj=>{if(obj!==null&&typeof obj==="object"&&typeof obj.constructor==="function"&&typeof obj.constructor.name==="string"&&["Buffer","Uint8Array","Int8Array","Uint16Array","Int16Array","Uint32Array","Int32Array","BigUint64Array","BigInt64Array"].includes(obj.constructor.name)){obj=obj.buffer.slice(obj.byteOffset,obj.byteOffset+obj.byteLength)}return obj};original=checkAndFixTypedArray(original);if(typeof original!=="object"||original===null||original instanceof Date||original instanceof ArrayBuffer||original instanceof path_reference_1.PathReference||original instanceof RegExp){return original}const cloneValue=val=>{if(stack.indexOf(val)>=0){throw new ReferenceError("object contains a circular reference")}val=checkAndFixTypedArray(val);if(val===null||val instanceof Date||val instanceof ArrayBuffer||val instanceof path_reference_1.PathReference||val instanceof RegExp){return val}else if(typeof val==="object"){stack.push(val);val=cloneObject(val,stack);stack.pop();return val}else{return val}};if(typeof stack==="undefined"){stack=[original]}const clone=original instanceof Array?[]:original instanceof partial_array_1.PartialArray?new partial_array_1.PartialArray:{};Object.keys(original).forEach((key=>{const val=original[key];if(typeof val==="function"){return}clone[key]=cloneValue(val)}));return clone}exports.cloneObject=cloneObject;const isTypedArray=val=>typeof val==="object"&&["ArrayBuffer","Buffer","Uint8Array","Uint16Array","Uint32Array","Int8Array","Int16Array","Int32Array"].includes(val.constructor.name);function valuesAreEqual(val1,val2){if(val1===val2){return true}if(typeof val1!==typeof val2){return false}if(typeof val1==="object"||typeof val2==="object"){if(val1===null||val2===null){return false}if(val1 instanceof path_reference_1.PathReference||val2 instanceof path_reference_1.PathReference){return val1 instanceof path_reference_1.PathReference&&val2 instanceof path_reference_1.PathReference&&val1.path===val2.path}if(val1 instanceof Date||val2 instanceof Date){return val1 instanceof Date&&val2 instanceof Date&&val1.getTime()===val2.getTime()}if(val1 instanceof Array||val2 instanceof Array){return val1 instanceof Array&&val2 instanceof Array&&val1.length===val2.length&&val1.every(((item,i)=>valuesAreEqual(val1[i],val2[i])))}if(isTypedArray(val1)||isTypedArray(val2)){if(!isTypedArray(val1)||!isTypedArray(val2)||val1.byteLength===val2.byteLength){return false}const typed1=val1 instanceof ArrayBuffer?new Uint8Array(val1):new Uint8Array(val1.buffer,val1.byteOffset,val1.byteLength),typed2=val2 instanceof ArrayBuffer?new Uint8Array(val2):new Uint8Array(val2.buffer,val2.byteOffset,val2.byteLength);return typed1.every(((val,i)=>typed2[i]===val))}const keys1=Object.keys(val1),keys2=Object.keys(val2);return keys1.length===keys2.length&&keys1.every((key=>keys2.includes(key)))&&keys1.every((key=>valuesAreEqual(val1[key],val2[key])))}return false}exports.valuesAreEqual=valuesAreEqual;class ObjectDifferences{constructor(added,removed,changed){this.added=added;this.removed=removed;this.changed=changed}forChild(key){if(this.added.includes(key)){return"added"}if(this.removed.includes(key)){return"removed"}const changed=this.changed.find((ch=>ch.key===key));return changed?changed.change:"identical"}}exports.ObjectDifferences=ObjectDifferences;function compareValues(oldVal,newVal,sortedResults=false){const voids=[undefined,null];if(oldVal===newVal){return"identical"}else if(voids.indexOf(oldVal)>=0&&voids.indexOf(newVal)<0){return"added"}else if(voids.indexOf(oldVal)<0&&voids.indexOf(newVal)>=0){return"removed"}else if(typeof oldVal!==typeof newVal){return"changed"}else if(isTypedArray(oldVal)||isTypedArray(newVal)){if(!isTypedArray(oldVal)||!isTypedArray(newVal)){return"changed"}const typed1=oldVal instanceof Uint8Array?oldVal:oldVal instanceof ArrayBuffer?new Uint8Array(oldVal):new Uint8Array(oldVal.buffer,oldVal.byteOffset,oldVal.byteLength);const typed2=newVal instanceof Uint8Array?newVal:newVal instanceof ArrayBuffer?new Uint8Array(newVal):new Uint8Array(newVal.buffer,newVal.byteOffset,newVal.byteLength);return typed1.byteLength===typed2.byteLength&&typed1.every(((val,i)=>typed2[i]===val))?"identical":"changed"}else if(oldVal instanceof Date||newVal instanceof Date){return oldVal instanceof Date&&newVal instanceof Date&&oldVal.getTime()===newVal.getTime()?"identical":"changed"}else if(oldVal instanceof path_reference_1.PathReference||newVal instanceof path_reference_1.PathReference){return oldVal instanceof path_reference_1.PathReference&&newVal instanceof path_reference_1.PathReference&&oldVal.path===newVal.path?"identical":"changed"}else if(typeof oldVal==="object"){const isArray=oldVal instanceof Array;const getKeys=obj=>{let keys=Object.keys(obj).filter((key=>!voids.includes(obj[key])));if(isArray){keys=keys.map((v=>parseInt(v)))}return keys};const oldKeys=getKeys(oldVal);const newKeys=getKeys(newVal);const removedKeys=oldKeys.filter((key=>!newKeys.includes(key)));const addedKeys=newKeys.filter((key=>!oldKeys.includes(key)));const changedKeys=newKeys.reduce(((changed,key)=>{if(oldKeys.includes(key)){const val1=oldVal[key];const val2=newVal[key];const c=compareValues(val1,val2);if(c!=="identical"){changed.push({key:key,change:c})}}return changed}),[]);if(addedKeys.length===0&&removedKeys.length===0&&changedKeys.length===0){return"identical"}else{return new ObjectDifferences(addedKeys,removedKeys,sortedResults?changedKeys.sort(((a,b)=>a.key{switch(compareResult){case"identical":return[];case"changed":return[{target:target,prev:prev,val:val}];case"added":return[{target:target,prev:null,val:val}];case"removed":return[{target:target,prev:prev,val:null}];default:{let changes=[];compareResult.added.forEach((key=>changes.push({target:target.concat(key),prev:null,val:val[key]})));compareResult.removed.forEach((key=>changes.push({target:target.concat(key),prev:prev[key],val:null})));compareResult.changed.forEach((item=>{const childChanges=process(target.concat(item.key),item.change,prev[item.key],val[item.key]);changes=changes.concat(childChanges)}));return changes}}};const compareResult=compareValues(oldVal,newVal,sortedResults);return process([],compareResult,oldVal,newVal)}exports.getMutations=getMutations;function getChildValues(childKey,oldValue,newValue){oldValue=oldValue===null?null:oldValue[childKey];if(typeof oldValue==="undefined"){oldValue=null}newValue=newValue===null?null:newValue[childKey];if(typeof newValue==="undefined"){newValue=null}return{oldValue:oldValue,newValue:newValue}}exports.getChildValues=getChildValues;function defer(fn){process_1.default.nextTick(fn)}exports.defer=defer;function getGlobalObject(){var _a;if(typeof globalThis!=="undefined"){return globalThis}if(typeof global!=="undefined"){return global}if(typeof window!=="undefined"){return window}if(typeof self!=="undefined"){return self}return(_a=function(){return this}())!==null&&_a!==void 0?_a:Function("return this")()}exports.getGlobalObject=getGlobalObject}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer)},{"./partial-array":28,"./path-reference":30,"./process":31,buffer:40}],40:[function(require,module,exports){},{}],41:[function(require,module,exports){(function(Buffer){(function(){ /*! * Socket.IO v2.5.0 * (c) 2014-2021 Guillermo Rauch