@verdant-web/store 2.5.6 → 2.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,6 +7,6 @@
7
7
  - Changed collections: ${o.changedCollections.join(", ")}
8
8
  - New indexes: ${Object.keys(o.addedIndexes).map(d=>o.addedIndexes[d].map(p=>`${d}.${p.name}`)).flatMap(d=>d).join(", ")}
9
9
  - Removed indexes: ${Object.keys(o.removedIndexes).map(d=>o.removedIndexes[d].map(p=>`${d}.${p.name}`)).flatMap(d=>d).join(", ")}
10
- `)}}),De(t,r.namespace,i)):De(t,r.namespace,i)}function ri({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,s)=>(r[s]={put:async a=>{Z(i.newSchema.collections[s],a);let o=a[i.newSchema.collections[s].primaryKey],c=T(s,o);return n.push(c),await t.insertLocalOperation(H(a,c,e)),a},delete:a=>{let o=T(s,a);return t.insertLocalOperation([{oid:o,timestamp:e(),data:{op:"delete"}}])}},r),{})}function or({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async s=>{let a=T(r,s);return await e.getDocumentSnapshot(a)},findOne:async s=>{let a=await lt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a):null},findAll:async s=>{let a=await dt({collection:r,index:s,context:t});return await Promise.all(a.map(c=>e.getDocumentSnapshot(c)))}},n),{})}function cr({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=or({migration:t,context:e,meta:i}),a=ri({migration:t,getMigrationNow:n,newOids:r,meta:i}),o=new Array;return{log:e.log,newOids:r,migrate:async(l,u)=>{let d=await s[l].findAll();await Promise.all(d.map(async p=>{y(xe(p),`Document is missing an OID: ${JSON.stringify(p)}`);let g=_(p),I=await u(p);if(I){Se(g),Se(I),re(I);let h=Oe(g,I,n,void 0,[],{mergeUnknownObjects:!0});h.length>0&&await i.insertLocalOperation(h)}}))},queries:s,mutations:a,awaitables:o}}function lr({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),a=ri({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:s,mutations:a,awaitables:[]}}async function dr(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function ur(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function pr(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function hr({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>w(r.oid))))}var pt=class extends b{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();return e?(this._undone.push(await e()),this.emit("change"),!0):!1};this.redo=async()=>{let e=this._undone.pop();return e?(this._undoable.push(await e()),this.emit("change"),!0):!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var ht=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return y(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),T(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return Z(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),s=this.getOid(t,r);return this.entities.create(r,s,n)};this.delete=async(t,e,n={})=>{let r=T(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>T(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>T(t,r)),n)}};var ce=Symbol("entity-file-update"),Te=Symbol("entity-file-mark-failed"),mr,fr,ne=class extends b{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._disposed=!1;this._downloadRemote=!1;this[mr]=e=>{this._loading=!1,this._failed=!1,this._disposed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[fr]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{mr=ce,fr=Te}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}};var si=jt(Ae(),1);function yr(i){return{id:(0,si.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function ie(i,t){if(typeof window<"u"&&i instanceof File){let e=yr(i);return t(e),Rn(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=ie(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=ie(i[e],t);return i}return i}function ai(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var mt=class extends N{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let s=e.file?await ai(e.file):void 0;if(!s&&r&&e.url)try{s=await fetch(e.url,{method:"GET",credentials:"include"}).then(a=>a.arrayBuffer())}catch(a){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",a)}return this.run("files",a=>a.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:s}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?gr(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",s=>s.get(e),"readonly",n);if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,deletedAt:Date.now()}),"readwrite",n)};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),"readonly")).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function gr(i,t){return new Blob([i],{type:t})}function br(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var ft=class{constructor({db:t,sync:e,context:n,meta:r,config:s={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[ce](e);else{let n=new ne(e.id);n[ce](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=t=>{if(this.files.has(t))return this.files.get(t);let e=new ne(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[Te]();return}let n=await this.storage.getFile(t.id);if(n)t[ce](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[ce](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[Te](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[Te](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],"readwrite");await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new mt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:br,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var le=class{constructor(t){this.value=t}deref(){return this.value}};var oi="@@refresh",yt="@@deepChange";function Ee(i,t){return i[oi](t)}var vr,Sr,K=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:s,onAllUnsubscribed:a}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[vr]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let s=this._deleted&&!n;this._deleted=n,this.cachedDestructure=null,this._updatedAt=r||null,this.cachedDeepUpdatedAt=null,this._deleted?this.events.emit("delete",t):(this.events.emit("change",t),this[yt](this,t)),s&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[Sr]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[yt](t,e)};this.getChildFieldSchema=t=>{if(this.fieldSchema.type==="object")return this.fieldSchema.properties[t];if(this.fieldSchema.type==="array")return this.fieldSchema.items;if(this.fieldSchema.type==="map")return this.fieldSchema.values;if(this.fieldSchema.type==="any")return this.fieldSchema;throw new Error("Invalid field schema")};this.dispose=()=>{this.events.dispose()};this.subscribe=(t,e)=>this.events.subscribe(t,e);this.addPatches=t=>{this.store.addLocalOperations(t)};this.cloneCurrent=()=>{if(this._current!==void 0)return _(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity(t,n,this)};this.wrapValue=(t,e)=>{if(E(t)){let n=t.id,r=this.getSubObject(n,e);if(r)return r;throw new Error(`CACHE MISS: Subobject ${n} does not exist on ${this.oid}`)}else if(V(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[yt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{let n=this.getChildFieldSchema(e);return n&&Y(t,n),ie(t,this.store.addFile)};this.get=t=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");let e=this.value[t];return this.wrapValue(e,t)};this.getAll=()=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");if(this.cachedDestructure)return this.cachedDestructure;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>this.wrapValue(e,n));else{t={};for(let e in this.value)t[e]=this.get(e)}return this.cachedDestructure=t,t};this.getSnapshot=()=>{if(!this.value||this.deleted)return null;if(this.cachedSnapshot)return this.cachedSnapshot;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>E(e)?this.getSubObject(e.id,n)?.getSnapshot():e);else{t={...this.value};for(let[e,n]of Object.entries(t))E(n)&&(t[e]=this.getSubObject(n.id,e)?.getSnapshot())}return x(t,this.oid),this.cachedSnapshot=t,t};this.keys=()=>Object.keys(this.value||{});this.entries=()=>Object.entries(this.getAll());this.values=()=>Object.values(this.getAll());this.set=(t,e)=>{this.addPatches(this.store.patchCreator.createSet(this.oid,t,this.processInputValue(e,t)))};this.delete=t=>{if(Array.isArray(this.value))this.addPatches(this.store.patchCreator.createListDelete(this.oid,t,1));else{let e=this.getDeleteMode(t);if(!e)throw new Error(`Cannot delete key ${t} - the property is not marked as optional in the schema`);e==="delete"?this.addPatches(this.store.patchCreator.createRemove(this.oid,t)):this.addPatches(this.store.patchCreator.createSet(this.oid,t,null))}};this.getDeleteMode=t=>{if(this.fieldSchema.type==="any"||this.fieldSchema.type==="map")return"delete";if(this.fieldSchema.type==="object"){let e=this.fieldSchema.properties[t];if(!e||e.type==="any")return"delete";if(e.type==="map")return!1;if(e.nullable)return"null"}return!1};this.remove=this.delete.bind(this);this.update=(t,{replaceSubObjects:e=!1,merge:n=!0}={replaceSubObjects:!1,merge:!0})=>{if(!n&&this.fieldSchema.type!=="any"&&this.fieldSchema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');for(let[s,a]of Object.entries(t)){let o=this.getChildFieldSchema(s);o&&Y(a,o)}let r=ie(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),x(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=F(t);if(!e||!this.cache.hasOid(e))throw new Error(`Cannot move object ${JSON.stringify(t)} which does not exist in this list`);return e}else return t};this.push=t=>{this.addPatches(this.store.patchCreator.createListPush(this.oid,this.processInputValue(t,this.value.length)))};this.insert=(t,e)=>{this.addPatches(this.store.patchCreator.createListInsert(this.oid,t,this.processInputValue(e,t)))};this.move=(t,e)=>{this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,t,e))};this.moveItem=(t,e)=>{let n=this.getItemRefValue(t);if(E(n))this.addPatches(this.store.patchCreator.createListMoveByRef(this.oid,n,e));else{let r=this.value.indexOf(n);this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,r,e))}};this.removeAll=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t)))};this.removeFirst=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"first"))};this.removeLast=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"last"))};this.add=t=>{this.addPatches(this.store.patchCreator.createListAdd(this.oid,this.processInputValue(t,this.value.length)))};this.has=t=>typeof t=="object"?this.value.some(e=>E(e)?e.id===F(t):(V(e),!1)):this.value.includes(t);this.getAsWrapped=()=>{if(!this.isList)throw new Error("Cannot map items of a non-list");return this.value.map(this.wrapValue)};this.map=t=>this.getAsWrapped().map(t);this.filter=t=>this.getAsWrapped().filter((e,n)=>t(e,n));this.forEach=t=>{this.getAsWrapped().forEach(t)};this.some=t=>this.getAsWrapped().some(t);this.every=t=>this.getAsWrapped().every(t);this.find=t=>this.getAsWrapped().find(t);this.oid=t;let{collection:o}=M(t);this.collection=o,this.parent=s&&new le(s),this.store=e,this.fieldSchema=n,this.cache=r;let{view:c,deleted:l,lastTimestamp:u}=this.cache.computeView(t);if(this._current=c,this._deleted=l,this._updatedAt=u||null,this.cachedDeepUpdatedAt=null,this.events=new b(()=>{this.hasSubscribers||a?.()}),this.oid.includes(".")&&!this.parent)throw new Error("Parent must be provided for sub entities");y(!!n,"Field schema must be provided")}hasSubscribersToDeepChanges(){return this.events.subscriberCount("changeDeep")>0}get hasSubscribers(){if(this.events.totalSubscriberCount()>0)return!0;let t=this.parent?.deref();for(;t;){if(t.hasSubscribersToDeepChanges())return!0;t=t.parent?.deref()}return!1}get deleted(){return this._deleted}get value(){return this._current}get isList(){return Array.isArray(this._current)}get updatedAt(){return this._updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let t=this._updatedAt;return this.isList?this.forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}):this.values().forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}),this.cachedDeepUpdatedAt=t,t}get uid(){return this.oid}get length(){return this.value.length}[(vr=oi,Sr=yt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var gt=class extends b{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:s}=r;n.add(s);let a=this.localOperationsMap.get(s)||[];a.push(r),this.localOperationsMap.set(s,a)}for(let r of n){let a=this.entities.get(r)?.deref();a&&(Ee(a,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:s}=r;n.affectedOids?.add(s);let a=this.operationsMap.get(s)||[],o=a.findIndex(l=>l.timestamp>=r.timestamp);if(o!==-1){if(a[o].timestamp===r.timestamp)continue;a.splice(o,0,r)}else a.push(r);this.operationsMap.set(s,a);let c=this.localOperationsMap.get(s);c&&this.localOperationsMap.set(s,c.filter(l=>l.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:s}=r,a=this.baselinesMap.get(s);if(a?.timestamp&&a.timestamp>=r.timestamp)continue;n?.add(s),this.baselinesMap.set(s,r);let o=this.operationsMap.get(s)||[];for(;o[0]?.timestamp<r.timestamp;)o.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:s})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let a={isLocal:s||!1,affectedOids:new Set};if(this.insertBaselines(n,a),this.insertOperations(e,a),r)for(let o of this.entities.values()){let c=o.deref();c&&Ee(c,a)}else for(let o of a.affectedOids){let l=this.entities.get(o)?.deref();l&&(Ee(l,a),this.emit(`change:${o}`),this.emit("change:*",o))}};this.applyOperations=(e,n,r,s)=>{let a,o=this.storeTools.now;for(let c of r)if(!(s&&c.timestamp<=s)){if(En(c.timestamp,o)>0){a=c.timestamp;continue}c.data.op==="delete"?n=!0:(e=X(e,c.data),c.data.op==="initialize"&&(n=!1))}return a&&this.context.globalEvents.emit("futureSeen",a),{view:e,deleted:n,empty:!e&&!r.length}};this.computeView=e=>{let n=this.computeConfirmedView(e),r=this.localOperationsMap.get(e)||[];if(n.empty&&!r.length)return this.context.log("debug",`Entity ${e} accessed with no local data at all`),{view:null,deleted:!0,lastTimestamp:null};let{view:s,deleted:a}=this.applyOperations(n.view,n.deleted,r);return s&&x(s,e),{view:s,deleted:a,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],s=_(n?.snapshot||void 0),a=this.applyOperations(s,!s,r,n?.timestamp);return a.view&&x(a.view,e),a.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),a};this.getLastTimestamp=e=>{let n=this.localOperationsMap.get(e);n?.length||(n=this.operationsMap.get(e)||[]);let r=null;return n.length?r=n[n.length-1]?.timestamp:r=this.baselinesMap.get(e)?.timestamp??null,r?this.storeTools.time.getWallClockTime(r):null};this.getEntity=(e,n,r)=>{let a=this.entities.get(e)?.deref();return a||(a=new K({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r}),this.entities.set(e,new le(a))),a};this.hasOid=e=>this.operationsMap.has(e)||this.baselinesMap.has(e);this.dispose=()=>{this.entities.forEach(e=>e.deref()?.dispose()),this.entities.clear()};this.reset=(e,n,r=!1)=>{let s={isLocal:!1,affectedOids:new Set};if(this.baselinesMap=new Map(n.map(a=>[a.oid,a])),r)this.operationsMap=new Map;else for(let a of this.operationsMap.keys())this.operationsMap.set(a,this.operationsMap.get(a)?.filter(o=>!o.confirmed)??[]);this.insertOperations(e,s);for(let a of this.entities.keys()){let c=this.entities.get(a)?.deref();c&&(Ee(c,s),this.emit(`change:${a}`),this.emit("change:*",a))}};this.oid=e,this.operationsMap=new Map,this.localOperationsMap=new Map,this.baselinesMap=new Map,this.storeTools={addLocalOperations:n.addLocalOperations,patchCreator:n.meta.patchCreator,addFile:n.files.add,getFile:n.files.get,time:n.meta.time,now:n.meta.now},this.context=r}};var bt="@@default",vt=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=bt;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=M(t);return this.schema.collections[e]?{type:"object",properties:this.schema.collections[e].fields}:(this.log("warn",`Missing schema for collection: ${e}`),null)};this.refreshFamilyCache=async(t,e=!1)=>{if(this._disposed)return;let n=this.meta.createTransaction(["baselines","operations"]),r=[],s=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,a=>{r.push(a)},{transaction:n,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,a=>{a.confirmed=!0,s.push(a)},{transaction:n,mode:"readwrite"})]),t.reset(s,r,e)};this.openFamilyCache=async t=>{let e=w(t),n=this.documentFamilyCaches.get(e);return n||(n=new gt({oid:e,store:this,context:this.context}),this.documentFamilyCaches.set(e,n),await this.refreshFamilyCache(n)),n};this.onEntityChange=async t=>{};this.writeDocumentToStorage=async t=>{if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let e=w(t),{id:n,collection:r}=M(e),s=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let a=s?.getSnapshot();if(a){let o=_(a);Xe(this.schema.collections[r],o),se(o);try{let l=this.db.transaction(r,"readwrite").objectStore(r);await k(l.put(o)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",o)}catch{this.log("\u26A0\uFE0F CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues",`
10
+ `)}}),De(t,r.namespace,i)):De(t,r.namespace,i)}function ri({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,s)=>(r[s]={put:async a=>{Z(i.newSchema.collections[s],a);let o=a[i.newSchema.collections[s].primaryKey],c=T(s,o);return n.push(c),await t.insertLocalOperation(H(a,c,e)),a},delete:a=>{let o=T(s,a);return t.insertLocalOperation([{oid:o,timestamp:e(),data:{op:"delete"}}])}},r),{})}function or({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async s=>{let a=T(r,s);return await e.getDocumentSnapshot(a)},findOne:async s=>{let a=await lt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a):null},findAll:async s=>{let a=await dt({collection:r,index:s,context:t});return await Promise.all(a.map(c=>e.getDocumentSnapshot(c)))}},n),{})}function cr({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=or({migration:t,context:e,meta:i}),a=ri({migration:t,getMigrationNow:n,newOids:r,meta:i}),o=new Array;return{log:e.log,newOids:r,migrate:async(l,u)=>{let d=await s[l].findAll();await Promise.all(d.filter(Boolean).map(async p=>{y(xe(p),`Document is missing an OID: ${JSON.stringify(p)}`);let g=_(p),I=await u(p);if(I){Se(g),Se(I),re(I);let h=Oe(g,I,n,void 0,[],{mergeUnknownObjects:!0});h.length>0&&await i.insertLocalOperation(h)}}))},queries:s,mutations:a,awaitables:o}}function lr({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),a=ri({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:s,mutations:a,awaitables:[]}}async function dr(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function ur(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function pr(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function hr({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>w(r.oid))))}var pt=class extends b{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();return e?(this._undone.push(await e()),this.emit("change"),!0):!1};this.redo=async()=>{let e=this._undone.pop();return e?(this._undoable.push(await e()),this.emit("change"),!0):!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var ht=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return y(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),T(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return Z(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),s=this.getOid(t,r);return this.entities.create(r,s,n)};this.delete=async(t,e,n={})=>{let r=T(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>T(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>T(t,r)),n)}};var ce=Symbol("entity-file-update"),Te=Symbol("entity-file-mark-failed"),mr,fr,ne=class extends b{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._disposed=!1;this._downloadRemote=!1;this[mr]=e=>{this._loading=!1,this._failed=!1,this._disposed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[fr]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{mr=ce,fr=Te}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}};var si=jt(Ae(),1);function yr(i){return{id:(0,si.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function ie(i,t){if(typeof window<"u"&&i instanceof File){let e=yr(i);return t(e),Rn(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=ie(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=ie(i[e],t);return i}return i}function ai(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var mt=class extends N{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let s=e.file?await ai(e.file):void 0;if(!s&&r&&e.url)try{s=await fetch(e.url,{method:"GET",credentials:"include"}).then(a=>a.arrayBuffer())}catch(a){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",a)}return this.run("files",a=>a.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:s}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?gr(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",s=>s.get(e),"readonly",n);if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,deletedAt:Date.now()}),"readwrite",n)};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),"readonly")).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function gr(i,t){return new Blob([i],{type:t})}function br(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var ft=class{constructor({db:t,sync:e,context:n,meta:r,config:s={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[ce](e);else{let n=new ne(e.id);n[ce](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=t=>{if(this.files.has(t))return this.files.get(t);let e=new ne(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[Te]();return}let n=await this.storage.getFile(t.id);if(n)t[ce](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[ce](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[Te](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[Te](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],"readwrite");await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new mt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:br,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var le=class{constructor(t){this.value=t}deref(){return this.value}};var oi="@@refresh",yt="@@deepChange";function Ee(i,t){return i[oi](t)}var vr,Sr,K=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:s,onAllUnsubscribed:a}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[vr]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let s=this._deleted&&!n;this._deleted=n,this.cachedDestructure=null,this._updatedAt=r||null,this.cachedDeepUpdatedAt=null,this._deleted?this.events.emit("delete",t):(this.events.emit("change",t),this[yt](this,t)),s&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[Sr]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[yt](t,e)};this.getChildFieldSchema=t=>{if(this.fieldSchema.type==="object")return this.fieldSchema.properties[t];if(this.fieldSchema.type==="array")return this.fieldSchema.items;if(this.fieldSchema.type==="map")return this.fieldSchema.values;if(this.fieldSchema.type==="any")return this.fieldSchema;throw new Error("Invalid field schema")};this.dispose=()=>{this.events.dispose()};this.subscribe=(t,e)=>this.events.subscribe(t,e);this.addPatches=t=>{this.store.addLocalOperations(t)};this.cloneCurrent=()=>{if(this._current!==void 0)return _(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity(t,n,this)};this.wrapValue=(t,e)=>{if(E(t)){let n=t.id,r=this.getSubObject(n,e);if(r)return r;throw new Error(`CACHE MISS: Subobject ${n} does not exist on ${this.oid}`)}else if(V(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[yt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{let n=this.getChildFieldSchema(e);return n&&Y(t,n),ie(t,this.store.addFile)};this.get=t=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");let e=this.value[t];return this.wrapValue(e,t)};this.getAll=()=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");if(this.cachedDestructure)return this.cachedDestructure;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>this.wrapValue(e,n));else{t={};for(let e in this.value)t[e]=this.get(e)}return this.cachedDestructure=t,t};this.getSnapshot=()=>{if(!this.value||this.deleted)return null;if(this.cachedSnapshot)return this.cachedSnapshot;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>E(e)?this.getSubObject(e.id,n)?.getSnapshot():e);else{t={...this.value};for(let[e,n]of Object.entries(t))E(n)&&(t[e]=this.getSubObject(n.id,e)?.getSnapshot())}return x(t,this.oid),this.cachedSnapshot=t,t};this.keys=()=>Object.keys(this.value||{});this.entries=()=>Object.entries(this.getAll());this.values=()=>Object.values(this.getAll());this.set=(t,e)=>{this.addPatches(this.store.patchCreator.createSet(this.oid,t,this.processInputValue(e,t)))};this.delete=t=>{if(Array.isArray(this.value))this.addPatches(this.store.patchCreator.createListDelete(this.oid,t,1));else{let e=this.getDeleteMode(t);if(!e)throw new Error(`Cannot delete key ${t} - the property is not marked as optional in the schema`);e==="delete"?this.addPatches(this.store.patchCreator.createRemove(this.oid,t)):this.addPatches(this.store.patchCreator.createSet(this.oid,t,null))}};this.getDeleteMode=t=>{if(this.fieldSchema.type==="any"||this.fieldSchema.type==="map")return"delete";if(this.fieldSchema.type==="object"){let e=this.fieldSchema.properties[t];if(!e||e.type==="any")return"delete";if(e.type==="map")return!1;if(e.nullable)return"null"}return!1};this.remove=this.delete.bind(this);this.update=(t,{replaceSubObjects:e=!1,merge:n=!0}={replaceSubObjects:!1,merge:!0})=>{if(!n&&this.fieldSchema.type!=="any"&&this.fieldSchema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');for(let[s,a]of Object.entries(t)){let o=this.getChildFieldSchema(s);o&&Y(a,o)}let r=ie(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),x(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=F(t);if(!e||!this.cache.hasOid(e))throw new Error(`Cannot move object ${JSON.stringify(t)} which does not exist in this list`);return e}else return t};this.push=t=>{this.addPatches(this.store.patchCreator.createListPush(this.oid,this.processInputValue(t,this.value.length)))};this.insert=(t,e)=>{this.addPatches(this.store.patchCreator.createListInsert(this.oid,t,this.processInputValue(e,t)))};this.move=(t,e)=>{this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,t,e))};this.moveItem=(t,e)=>{let n=this.getItemRefValue(t);if(E(n))this.addPatches(this.store.patchCreator.createListMoveByRef(this.oid,n,e));else{let r=this.value.indexOf(n);this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,r,e))}};this.removeAll=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t)))};this.removeFirst=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"first"))};this.removeLast=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"last"))};this.add=t=>{this.addPatches(this.store.patchCreator.createListAdd(this.oid,this.processInputValue(t,this.value.length)))};this.has=t=>typeof t=="object"?this.value.some(e=>E(e)?e.id===F(t):(V(e),!1)):this.value.includes(t);this.getAsWrapped=()=>{if(!this.isList)throw new Error("Cannot map items of a non-list");return this.value.map(this.wrapValue)};this.map=t=>this.getAsWrapped().map(t);this.filter=t=>this.getAsWrapped().filter((e,n)=>t(e,n));this.forEach=t=>{this.getAsWrapped().forEach(t)};this.some=t=>this.getAsWrapped().some(t);this.every=t=>this.getAsWrapped().every(t);this.find=t=>this.getAsWrapped().find(t);this.oid=t;let{collection:o}=M(t);this.collection=o,this.parent=s&&new le(s),this.store=e,this.fieldSchema=n,this.cache=r;let{view:c,deleted:l,lastTimestamp:u}=this.cache.computeView(t);if(this._current=c,this._deleted=l,this._updatedAt=u||null,this.cachedDeepUpdatedAt=null,this.events=new b(()=>{this.hasSubscribers||a?.()}),this.oid.includes(".")&&!this.parent)throw new Error("Parent must be provided for sub entities");y(!!n,"Field schema must be provided")}hasSubscribersToDeepChanges(){return this.events.subscriberCount("changeDeep")>0}get hasSubscribers(){if(this.events.totalSubscriberCount()>0)return!0;let t=this.parent?.deref();for(;t;){if(t.hasSubscribersToDeepChanges())return!0;t=t.parent?.deref()}return!1}get deleted(){return this._deleted}get value(){return this._current}get isList(){return Array.isArray(this._current)}get updatedAt(){return this._updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let t=this._updatedAt;return this.isList?this.forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}):this.values().forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}),this.cachedDeepUpdatedAt=t,t}get uid(){return this.oid}get length(){return this.value.length}[(vr=oi,Sr=yt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var gt=class extends b{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:s}=r;n.add(s);let a=this.localOperationsMap.get(s)||[];a.push(r),this.localOperationsMap.set(s,a)}for(let r of n){let a=this.entities.get(r)?.deref();a&&(Ee(a,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:s}=r;n.affectedOids?.add(s);let a=this.operationsMap.get(s)||[],o=a.findIndex(l=>l.timestamp>=r.timestamp);if(o!==-1){if(a[o].timestamp===r.timestamp)continue;a.splice(o,0,r)}else a.push(r);this.operationsMap.set(s,a);let c=this.localOperationsMap.get(s);c&&this.localOperationsMap.set(s,c.filter(l=>l.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:s}=r,a=this.baselinesMap.get(s);if(a?.timestamp&&a.timestamp>=r.timestamp)continue;n?.add(s),this.baselinesMap.set(s,r);let o=this.operationsMap.get(s)||[];for(;o[0]?.timestamp<r.timestamp;)o.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:s})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let a={isLocal:s||!1,affectedOids:new Set};if(this.insertBaselines(n,a),this.insertOperations(e,a),r)for(let o of this.entities.values()){let c=o.deref();c&&Ee(c,a)}else for(let o of a.affectedOids){let l=this.entities.get(o)?.deref();l&&(Ee(l,a),this.emit(`change:${o}`),this.emit("change:*",o))}};this.applyOperations=(e,n,r,s)=>{let a,o=this.storeTools.now;for(let c of r)if(!(s&&c.timestamp<=s)){if(En(c.timestamp,o)>0){a=c.timestamp;continue}c.data.op==="delete"?n=!0:(e=X(e,c.data),c.data.op==="initialize"&&(n=!1))}return a&&this.context.globalEvents.emit("futureSeen",a),{view:e,deleted:n,empty:!e&&!r.length}};this.computeView=e=>{let n=this.computeConfirmedView(e),r=this.localOperationsMap.get(e)||[];if(n.empty&&!r.length)return this.context.log("debug",`Entity ${e} accessed with no local data at all`),{view:null,deleted:!0,lastTimestamp:null};let{view:s,deleted:a}=this.applyOperations(n.view,n.deleted,r);return s&&x(s,e),{view:s,deleted:a,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],s=_(n?.snapshot||void 0),a=this.applyOperations(s,!s,r,n?.timestamp);return a.view&&x(a.view,e),a.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),a};this.getLastTimestamp=e=>{let n=this.localOperationsMap.get(e);n?.length||(n=this.operationsMap.get(e)||[]);let r=null;return n.length?r=n[n.length-1]?.timestamp:r=this.baselinesMap.get(e)?.timestamp??null,r?this.storeTools.time.getWallClockTime(r):null};this.getEntity=(e,n,r)=>{let a=this.entities.get(e)?.deref();return a||(a=new K({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r}),this.entities.set(e,new le(a))),a};this.hasOid=e=>this.operationsMap.has(e)||this.baselinesMap.has(e);this.dispose=()=>{this.entities.forEach(e=>e.deref()?.dispose()),this.entities.clear()};this.reset=(e,n,r=!1)=>{let s={isLocal:!1,affectedOids:new Set};if(this.baselinesMap=new Map(n.map(a=>[a.oid,a])),r)this.operationsMap=new Map;else for(let a of this.operationsMap.keys())this.operationsMap.set(a,this.operationsMap.get(a)?.filter(o=>!o.confirmed)??[]);this.insertOperations(e,s);for(let a of this.entities.keys()){let c=this.entities.get(a)?.deref();c&&(Ee(c,s),this.emit(`change:${a}`),this.emit("change:*",a))}};this.oid=e,this.operationsMap=new Map,this.localOperationsMap=new Map,this.baselinesMap=new Map,this.storeTools={addLocalOperations:n.addLocalOperations,patchCreator:n.meta.patchCreator,addFile:n.files.add,getFile:n.files.get,time:n.meta.time,now:n.meta.now},this.context=r}};var bt="@@default",vt=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=bt;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=M(t);return this.schema.collections[e]?{type:"object",properties:this.schema.collections[e].fields}:(this.log("warn",`Missing schema for collection: ${e}`),null)};this.refreshFamilyCache=async(t,e=!1)=>{if(this._disposed)return;let n=this.meta.createTransaction(["baselines","operations"]),r=[],s=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,a=>{r.push(a)},{transaction:n,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,a=>{a.confirmed=!0,s.push(a)},{transaction:n,mode:"readwrite"})]),t.reset(s,r,e)};this.openFamilyCache=async t=>{let e=w(t),n=this.documentFamilyCaches.get(e);return n||(n=new gt({oid:e,store:this,context:this.context}),this.documentFamilyCaches.set(e,n),await this.refreshFamilyCache(n)),n};this.onEntityChange=async t=>{};this.writeDocumentToStorage=async t=>{if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let e=w(t),{id:n,collection:r}=M(e),s=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let a=s?.getSnapshot();if(a){let o=_(a);Xe(this.schema.collections[r],o),se(o);try{let l=this.db.transaction(r,"readwrite").objectStore(r);await k(l.put(o)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",o)}catch{this.log("\u26A0\uFE0F CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues",`
11
11
  `,"Invalid data:",JSON.stringify(o))}}else{let c=this.db.transaction(r,"readwrite").objectStore(r);await k(c.delete(n)),this.log("info","\u274C","deleted",r,n,"from storage")}};this.get=async t=>{let e=await this.openFamilyCache(t),n=this.getDocumentSchema(t);return n?e.getEntity(t,n):null};this.getCached=t=>{let e=this.documentFamilyCaches.get(t);if(e){let n=this.getDocumentSchema(t);return n?e.getEntity(t,n):null}return null};this.create=async(t,e,n)=>{$e(t);let r=ie(t,this.files.add);x(r,e);let s=this.meta.patchCreator.createInitialize(r,e),a=await this.openFamilyCache(e);a.insertLocalOperations(s),await this.submitOperations(s,n);let o=this.getDocumentSchema(e);if(!o)throw new Error(`Cannot create a document in the ${M(e).collection} collection; it is not defined in the current schema version.`);return a.getEntity(e,o)};this.addOperationsToOpenCaches=async(t,e)=>{let n=Xt(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding",e.confirmed?"confirmed":"unconfirmed","operations to cache",s,n[s].length),e.isLocal?a.insertLocalOperations(n[s]):a.insertOperations(n[s],e))})};this.addBaselinesToOpenCaches=async(t,e)=>{let n=Yt(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding","baselines to cache",s,n[s].length),a.insertBaselines(n[s],e))})};this.addDataToOpenCaches=({baselines:t,operations:e,reset:n,isLocal:r})=>{let s=Yt(t),a=Xt(e),o=Array.from(new Set(Object.keys(s).concat(Object.keys(a))));for(let c of o){let l=this.documentFamilyCaches.get(c);l?(l.addData({operations:a[c]||[],baselines:s[c]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",c,a[c]?.length??0,"operations",s[c]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",c,"because it is not open")}return o};this.addData=async({operations:t,baselines:e,reset:n})=>{let r=t;for(let o of r)o.confirmed=!1;let s=[];n?(this.log("Resetting local store to replicate remote synced data",e.length,"baselines, and",t.length,"operations"),await this.meta.reset(),await this.resetStoredDocuments(),s=Array.from(new Set(e.map(o=>w(o.oid)).concat(t.map(o=>w(o.oid)))))):s=this.addDataToOpenCaches({operations:r,baselines:e,reset:n}),await this.meta.insertRemoteBaselines(e),await this.meta.insertRemoteOperations(t),n&&await this.refreshAllCaches(!0);for(let o of s)await this.writeDocumentToStorage(o);let a=Array.from(new Set(s.map(o=>M(o).collection)));this.context.log("changes to collections",a),this.context.entityEvents.emit("collectionsChanged",a)};this.addLocalOperations=async t=>{this.log("Adding local operations",t.length),this.addOperationsToOpenCaches(t,{isLocal:!0,confirmed:!1}),this.operationBatcher.add({key:this.currentBatchKey,items:t})};this.batch=({undoable:t=!0,batchName:e=ze(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),a={run:o=>(this.currentBatchKey=e,o(),this.currentBatchKey=bt,a),flush:async()=>(await this.operationBatcher.flush(bt),s.flush()),discard:()=>{this.operationBatcher.discard(e)}};return a};this.flushPatches=async()=>{await this.operationBatcher.flush(this.currentBatchKey)};this.flushOperations=async(t,e,n)=>{if(t.length){this.log("Flushing operations",t.length,"to storage / sync");for(let r of t)r.timestamp=this.meta.now;await this.submitOperations(t,n)}};this.submitOperations=async(t,{undoable:e=!0}={})=>{e&&this.undoHistory.addUndo(await this.createUndo(t)),await this.meta.insertLocalOperation(t),this.addDataToOpenCaches({operations:t,baselines:[]});let n=Array.from(new Set(t.map(s=>w(s.oid))));for(let s of n)await this.writeDocumentToStorage(s);let r=new Set(t.map(({oid:s})=>M(s).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Kn(t),n=[],r=()=>this.meta.now;for(let[s,a]of Object.entries(e)){let o=await this.openFamilyCache(s),{view:c,deleted:l}=o.computeConfirmedView(s),u=Jn(s,c,a,r);n.unshift(...u)}return n};this.createUndo=async t=>{let e=await this.getInverseOperations(t);return async()=>{let n=await this.createUndo(e);return await this.submitOperations(e.map(r=>(r.timestamp=this.meta.now,r)),{undoable:!1}),n}};this.delete=async(t,e)=>{y(t===w(t),"Only root documents may be deleted via client methods");let n=await this.meta.getAllDocumentRelatedOids(t),r=this.meta.patchCreator.createDeleteAll(n);await this.submitOperations(r,e)};this.deleteAll=async(t,e)=>{let n=await Promise.all(t.map(s=>this.meta.getAllDocumentRelatedOids(s))),r=this.meta.patchCreator.createDeleteAll(n.flat());await this.submitOperations(r,e)};this.reset=async()=>{this.context.log("warn","Resetting local database"),await this.resetStoredDocuments(),await this.refreshAllCaches(!0)};this.destroy=()=>{this._disposed=!0;for(let t of this.unsubscribes)t();for(let t of this.documentFamilyCaches.values())t.dispose();this.documentFamilyCaches.clear()};this.handleRebase=t=>{this.log("debug","Reacting to rebases",t.length),this.addBaselinesToOpenCaches(t,{isLocal:!0})};this.resetStoredDocuments=async()=>{let t=this.db.transaction(Object.keys(this.schema.collections),"readwrite");for(let e of Object.keys(this.schema.collections)){let n=t.objectStore(e);await k(n.clear())}};this.refreshAllCaches=async(t=!1)=>{for(let[e,n]of this.documentFamilyCaches)await this.refreshFamilyCache(n,t)};this.context=t,this.defaultBatchTimeout=n,this.meta=e,this.files=r,this.operationBatcher=new ae(this.flushOperations),this.operationBatcher.add({key:bt,items:[],max:100,timeout:n,userData:{undoable:!0}}),this.unsubscribes.push(this.meta.subscribe("rebase",this.handleRebase))}get log(){return this.context.log}get db(){return this.context.documentDb}get undoHistory(){return this.context.undoHistory}get schema(){return this.context.schema}};var on=Symbol("handleMessage"),xr,Re=class extends b{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[xr]=async(e,n)=>{let r=!1,s=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(s.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},s.clear();for(let[a,o]of Object.entries(n.peerPresence))this.isSelf(e,o)?(this._self=o,this._selfReplicaIds.add(o.replicaId),this.emit("selfChanged",o)):(r=!0,s.add(a),this._peers[a]=o,this.emit("peerChanged",a,o))}else if(n.type==="presence-offline"){s.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let a=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,a)}r&&(this._peerIds=Array.from(s),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,s)=>({...r,...s}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this._updateBatcher=new ae(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{xr=on}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var St=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),s=new window.FormData;s.append("file",e);try{let a=await fetch(n+`/${t.id}`,{method:"POST",body:s,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return a.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",a.status,await a.text()),{success:!1,retry:a.status>=500})}catch(a){return this.log("error","File upload failed",a),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,retry:!0}}};this.endpointProvider=t,this.log=e}};var de=class extends b{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&window.addEventListener("pageshow",()=>this.start(!0))}get interval(){return this._interval}};var xt=class extends b{constructor({endpointProvider:e,meta:n,presence:r,interval:s=15*1e3,log:a=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let a=await s.json();for(let o of a.messages)this.handleServerMessage(o);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else this.log("Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),s.status>=500&&this.heartbeat.keepAlive()}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.dispose=()=>{};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=a,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new de({interval:s}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}get isConnected(){return this._isConnected}get status(){return this._status}};function cn(i){this.message=i}cn.prototype=new Error,cn.prototype.name="InvalidCharacterError";var ci=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new cn("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,s=0,a="";n=t.charAt(s++);~n&&(e=r%4?64*e+n:n,r++%4)?a+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return a};function Or(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(ci(e).replace(/(.)/g,function(n,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch{return ci(t)}}function Ot(i){this.message=i}function wr(i,t){if(typeof i!="string")throw new Ot("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(Or(i.split(".")[e]))}catch(n){throw new Ot("Invalid token specified: "+n.message)}}Ot.prototype=new Error,Ot.prototype.name="InvalidTokenError";var li=wr;var wt=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(o=>{if(o.ok)return o.json();throw new Error(`Auth endpoint returned non-200 response: ${o.status}`)}),y(t.accessToken,"No access token provided from auth endpoint");let e=li(t.accessToken);y(e.url,"No sync endpoint provided from auth endpoint"),y(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let s=n.toString(),a=e.file;if(!a){let o=new URL(r);o.pathname=o.pathname+"/files",a=o.toString()}return this.cached={http:r,websocket:s,files:a,token:t.accessToken},this.cached};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var It=class extends b{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Ct=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var Dt=class extends b{constructor({endpointProvider:e,meta:n,presence:r,log:s}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new de;this.reconnectScheduler=new It(new Ct(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e)};this.onMessage=async e=>{let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length){for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.hasStartedSync){this.log("Skipping op-re message because sync hasn't started yet",n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.dispose=()=>{this.socket?.removeEventListener("close",this.onClose),this.socket?.close()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.dispose(),this.socket=null,this._status="paused"};this.log=s||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Pt=class extends b{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new Re({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},ue=class extends b{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:s=!0,autoStart:a,initialTransport:o,pullInterval:c,presenceUpdateBatchTimeout:l,defaultProfile:u,useBroadcastChannel:d},{meta:p,log:g,onData:I}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message)};this.handleMessage=async e=>{if(e.type==="op-re"||e.type==="sync-resp")for(let n of e.operations)this.meta.time.update(n.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[on](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1};this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.dispose=()=>{this.webSocketSync.dispose(),this.pushPullSync.dispose()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=p,this.onData=I,this.log=g||(()=>{}),this.presence=new Re({initialPresence:r,defaultProfile:u,updateBatchTimeout:l}),this.endpointProvider=new wt({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new Dt({endpointProvider:this.endpointProvider,meta:p,presence:this.presence,log:this.log}),this.pushPullSync=new xt({endpointProvider:this.endpointProvider,meta:p,presence:this.presence,log:this.log,interval:c}),this.fileSync=new St({endpointProvider:this.endpointProvider,log:this.log}),d&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),o==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let h=()=>{m&&clearTimeout(m);let v=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;v&&this.mode==="pull"?this.setMode("realtime"):!v&&this.mode==="realtime"&&(m=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},m;this.presence.subscribe("peersChanged",h),s!=="peers-only"&&this.presence.subscribe("selfChanged",h)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var pe=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};function Cr(i){return i!==null}function ln(i){return Array.isArray(i)?i.map(ln).filter(Cr):i instanceof K&&i.deleted?null:i}function W(i,t){return!i&&!t||i&&t&&ve(i)===ve(t)}var dn=Symbol("ON_ALL_UNSUBSCRIBED"),j=Symbol("UPDATE"),Dr,U=class extends pe{constructor({initial:e,context:n,collection:r,key:s,shouldUpdate:a}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=ln(e),this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof K&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof K&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value),this._executionPromise);this[Dr]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new b(c=>{c==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=s,this.collection=r;let o=a||(c=>c.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",c=>{o(c)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Dr=dn}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var Tt=class extends U{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=T(r.collection,e),this.hydrate=n}};var Pr,Et=class extends U{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await lt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Pr]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Pr=j}};var Tr,Rt=class extends U{constructor({index:e,hydrate:n,pageSize:r,page:s,...a}){super({initial:[],...a});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await Ce({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Tr]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=s}static{Tr=j}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Er,_t=class extends U{constructor({hydrate:e,pageSize:n,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await Ce({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await Ce({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Er]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Er=j}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Rr,kt=class extends U{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await dt({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[Rr]=e=>{W(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Rr=j}};var Ft=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:s}){this.serializeIndex=t=>t?ve(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new Tt({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Et({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[j](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new kt({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[j](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(s,()=>new Rt({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:n}),a=>{a[j](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new _t({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[j](t)})};this.cache=e,this.collection=t,this.hydrate=n.get,this.context=r,this.documentManager=s,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var At=class extends pe{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[dn](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let s=this.get(e);return s?(r?.(s),s):this.set(n())}};var he=class extends b{constructor(e,n,r){super();this.config=e;this.context=n;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let l of e)n[l]=await we(this.documentDb,l);let r=await this.meta.stats(),s=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,a=Object.values(n).reduce((l,{size:u})=>l+u,0),o=r.baselinesSize.size+r.operationsSize.size,c=o/a;return{collections:n,meta:r,storage:s,totalMetaSize:o,totalCollectionsSize:a,metaToDataRatio:c,quotaUsage:s?.usage&&s?.quota?s.usage/s.quota:void 0}};this.close=async()=>{await this.entities.flushPatches(),this.sync.stop(),this.sync.dispose(),this.meta.close(),this._entities.destroy(),await Ie(this.documentDb),await Ie(this.metaDb),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await et(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ie(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,s=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((o,c)=>{s.onsuccess=o,s.onerror=c});let a=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await Pe({meta:this.meta,migrations:this.config.migrations,context:this.context,version:r}),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ie(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=a,this.context.documentDb=await Pe({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a.version})};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig?new ue(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new Pt,this._fileManager=new ft({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new vt({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new At({context:n}),this._documentManager=new ht(this.meta,this.schema,this._entities);let s=jn(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",s),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[a,o]of Object.entries(n.schema.collections)){let c=o,l=c.pluralName??c.name+"s";y(l===a,`The key of the collection in the schema must be the plural of the name (expected: "${l}")`),this[l]=new Ft({collection:l,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var Mt=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e=[t.namespace,"meta"].join("_"),{db:n}=await Yn(this._namespace,{indexedDB:t.indexedDb,log:t.log,databaseName:e}),r={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new pt,entityEvents:new b,globalEvents:new b},s=new ot({context:r,disableRebasing:t.disableRebasing});await s.updateSchema(t.schema,t.overrideSchemaConflict);let a=await Pe({context:r,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb}),o=Object.assign(r,{documentDb:a}),c=new he({syncConfig:t.sync,migrations:t.migrations,files:t.files},o,{meta:s});return this.resolveReady(c),this._resolvedValue=c,c}catch(e){throw this.rejectReady(e),e}finally{this._initializing=!1}};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await et(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=un;
12
12
  //# sourceMappingURL=index.js.map