@optimystic/db-core 0.5.1 → 0.6.0
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.
- package/dist/src/btree/btree.d.ts +2 -0
- package/dist/src/btree/btree.d.ts.map +1 -1
- package/dist/src/btree/btree.js +72 -52
- package/dist/src/btree/btree.js.map +1 -1
- package/dist/src/cluster/structs.d.ts +13 -0
- package/dist/src/cluster/structs.d.ts.map +1 -1
- package/dist/src/collection/collection.d.ts +3 -0
- package/dist/src/collection/collection.d.ts.map +1 -1
- package/dist/src/collection/collection.js +6 -0
- package/dist/src/collection/collection.js.map +1 -1
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +1 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/log/log.js +1 -1
- package/dist/src/log/log.js.map +1 -1
- package/dist/src/logger.d.ts +4 -0
- package/dist/src/logger.d.ts.map +1 -0
- package/dist/src/logger.js +8 -0
- package/dist/src/logger.js.map +1 -0
- package/dist/src/transaction/actions-engine.d.ts +1 -13
- package/dist/src/transaction/actions-engine.d.ts.map +1 -1
- package/dist/src/transaction/actions-engine.js +0 -7
- package/dist/src/transaction/actions-engine.js.map +1 -1
- package/dist/src/transaction/coordinator.d.ts +9 -1
- package/dist/src/transaction/coordinator.d.ts.map +1 -1
- package/dist/src/transaction/coordinator.js +77 -11
- package/dist/src/transaction/coordinator.js.map +1 -1
- package/dist/src/transaction/index.d.ts +4 -5
- package/dist/src/transaction/index.d.ts.map +1 -1
- package/dist/src/transaction/index.js +2 -2
- package/dist/src/transaction/index.js.map +1 -1
- package/dist/src/transaction/session.d.ts +7 -3
- package/dist/src/transaction/session.d.ts.map +1 -1
- package/dist/src/transaction/session.js +23 -10
- package/dist/src/transaction/session.js.map +1 -1
- package/dist/src/transaction/transaction.d.ts +21 -3
- package/dist/src/transaction/transaction.d.ts.map +1 -1
- package/dist/src/transaction/transaction.js +21 -7
- package/dist/src/transaction/transaction.js.map +1 -1
- package/dist/src/transaction/validator.d.ts +9 -2
- package/dist/src/transaction/validator.d.ts.map +1 -1
- package/dist/src/transaction/validator.js +26 -6
- package/dist/src/transaction/validator.js.map +1 -1
- package/dist/src/transactor/network-transactor.d.ts.map +1 -1
- package/dist/src/transactor/network-transactor.js +84 -9
- package/dist/src/transactor/network-transactor.js.map +1 -1
- package/dist/src/transactor/transactor-source.d.ts +4 -0
- package/dist/src/transactor/transactor-source.d.ts.map +1 -1
- package/dist/src/transactor/transactor-source.js +25 -9
- package/dist/src/transactor/transactor-source.js.map +1 -1
- package/dist/src/transform/atomic-proxy.d.ts +26 -0
- package/dist/src/transform/atomic-proxy.d.ts.map +1 -0
- package/dist/src/transform/atomic-proxy.js +47 -0
- package/dist/src/transform/atomic-proxy.js.map +1 -0
- package/dist/src/transform/cache-source.d.ts +3 -2
- package/dist/src/transform/cache-source.d.ts.map +1 -1
- package/dist/src/transform/cache-source.js +15 -3
- package/dist/src/transform/cache-source.js.map +1 -1
- package/dist/src/transform/index.d.ts +1 -0
- package/dist/src/transform/index.d.ts.map +1 -1
- package/dist/src/transform/index.js +1 -0
- package/dist/src/transform/index.js.map +1 -1
- package/dist/src/utility/batch-coordinator.d.ts.map +1 -1
- package/dist/src/utility/batch-coordinator.js +6 -1
- package/dist/src/utility/batch-coordinator.js.map +1 -1
- package/dist/src/utility/hash-string.d.ts +3 -6
- package/dist/src/utility/hash-string.d.ts.map +1 -1
- package/dist/src/utility/hash-string.js +8 -11
- package/dist/src/utility/hash-string.js.map +1 -1
- package/dist/src/utility/lru-map.d.ts +18 -0
- package/dist/src/utility/lru-map.d.ts.map +1 -0
- package/dist/src/utility/lru-map.js +52 -0
- package/dist/src/utility/lru-map.js.map +1 -0
- package/package.json +15 -8
- package/src/btree/btree.ts +71 -50
- package/src/cluster/structs.ts +11 -0
- package/src/collection/collection.ts +9 -0
- package/src/index.ts +1 -0
- package/src/log/log.ts +1 -1
- package/src/logger.ts +10 -0
- package/src/transaction/actions-engine.ts +0 -17
- package/src/transaction/coordinator.ts +87 -12
- package/src/transaction/index.ts +7 -6
- package/src/transaction/session.ts +34 -10
- package/src/transaction/transaction.ts +39 -10
- package/src/transaction/validator.ts +34 -7
- package/src/transactor/network-transactor.ts +92 -11
- package/src/transactor/transactor-source.ts +28 -9
- package/src/transform/atomic-proxy.ts +49 -0
- package/src/transform/cache-source.ts +18 -4
- package/src/transform/index.ts +1 -0
- package/src/utility/batch-coordinator.ts +7 -1
- package/src/utility/hash-string.ts +14 -17
- package/src/utility/lru-map.ts +55 -0
- package/dist/index.min.js +0 -9
- package/dist/index.min.js.map +0 -7
package/dist/index.min.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.OptimysticDbCore = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
|
-
"use strict";var OptimysticDbCore=(()=>{var Fe=Object.defineProperty;var Or=Object.getOwnPropertyDescriptor;var Pr=Object.getOwnPropertyNames;var Dr=Object.prototype.hasOwnProperty;var Nr=(s,e)=>()=>(s&&(e=s(s=0)),e);var B=(s,e)=>{for(var t in e)Fe(s,t,{get:e[t],enumerable:!0})},Lr=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Pr(e))!Dr.call(s,n)&&n!==t&&Fe(s,n,{get:()=>e[n],enumerable:!(r=Or(e,n))||r.enumerable});return s};var $r=s=>Lr(Fe({},"__esModule",{value:!0}),s);var Tr={};B(Tr,{ACTIONS_ENGINE_ID:()=>Ft,ActionsEngine:()=>ke,createActionsStatements:()=>Ie});function Ie(s){return s.map(e=>JSON.stringify(e))}var Ft,ke,Pe=Nr(()=>{"use strict";Ft="actions@1.0.0",ke=class{coordinator;constructor(e){this.coordinator=e}async execute(e){try{let t=[];for(let r of e.statements){let n=JSON.parse(r);if(!n.collectionId||typeof n.collectionId!="string")return{success:!1,error:"Invalid statement: missing collectionId"};if(!n.actions||!Array.isArray(n.actions))return{success:!1,error:`Invalid statement: collection ${n.collectionId} missing or invalid actions array`};t.push(n),await this.coordinator.applyActions([n],e.stamp.id)}return{success:!0,actions:t}}catch(t){return{success:!1,error:`Failed to execute transaction: ${t instanceof Error?t.message:String(t)}`}}}}});var ws={};B(ws,{ACTIONS_ENGINE_ID:()=>Ft,ActionsEngine:()=>ke,Atomic:()=>H,BTree:()=>G,CacheSource:()=>xe,Chain:()=>re,Collection:()=>Y,Diary:()=>It,DiaryHeaderBlockType:()=>vt,EntriesPerBlock:()=>Ye,KeyBound:()=>Ke,KeyRange:()=>Qe,Keyset:()=>_e,Latches:()=>K,Log:()=>E,LogDataBlockType:()=>Lt,LogHeaderBlockType:()=>$t,NetworkTransactor:()=>Rt,NodeCapacity:()=>A,Path:()=>X,PathBranch:()=>$,Pending:()=>ve,Tracker:()=>j,TransactionContext:()=>Ne,TransactionCoordinator:()=>De,TransactionSession:()=>Le,TransactionValidator:()=>$e,TransactorSource:()=>de,Tree:()=>Ct,TreeHeaderBlockType:()=>Bt,apply:()=>p,applyOperation:()=>U,applyOperations:()=>Vt,applyTransform:()=>Fr,applyTransformToStore:()=>Ve,blockIdToBytes:()=>C,blockIdsForTransforms:()=>L,concatTransform:()=>Ge,concatTransforms:()=>je,copyTransforms:()=>He,createActionsStatements:()=>Ie,createTransactionId:()=>fe,createTransactionStamp:()=>he,distinctBlockActionTransforms:()=>jt,emptyTransforms:()=>ue,ensured:()=>zt,ensuredMap:()=>gs,entryAt:()=>Z,get:()=>b,groupBy:()=>qt,hashString:()=>Q,isTransformsEmpty:()=>Re,mergeTransforms:()=>Gt,nameof:()=>I,pathValid:()=>Xt,peerIdFromString:()=>Mt,priorHash$:()=>ys,registerBlockType:()=>P,rootId$:()=>At,transformForBlockId:()=>qe,transformsFromTransform:()=>ze,withOperation:()=>Mr});var Ue=new Map;function P(s,e){if(Ue.has(s))throw new Error(`Block type ${s} (${e}) already registered (${Ue.get(s)})`);return Ue.set(s,e),s}function U(s,[e,t,r,n]){Array.isArray(n)?s[e].splice(t,r,...structuredClone(n)):s[e]=structuredClone(n)}function Vt(s,e){for(let t of e)U(s,t)}function Mr(s,[e,t,r,n]){if(Array.isArray(n)){let o=s[e];return{...s,[e]:[...o.slice(0,t),...structuredClone(n),...o.slice(t+r)]}}else return{...s,[e]:structuredClone(n)}}function L(s){if(!s)return[];let e=Object.keys(s.inserts??{}),t=Object.keys(s.updates??{}),r=s.deletes??[];return[...new Set([...e,...t,...r])]}function ue(){return{inserts:{},updates:{},deletes:[]}}function He(s){let e=s.updates?Object.fromEntries(Object.entries(s.updates).map(([t,r])=>[t,structuredClone(r)])):void 0;return{inserts:{...s.inserts},updates:e,deletes:s.deletes?[...s.deletes]:void 0}}function Gt(s,e){return{inserts:{...s.inserts,...e.inserts},updates:{...s.updates,...e.updates},deletes:[...s.deletes??[],...e.deletes??[]]}}function Re(s){return Object.keys(s.inserts??{}).length===0&&Object.keys(s.updates??{}).length===0&&(s.deletes?.length??0)===0}function je(...s){return s.reduce((e,t)=>Gt(e,t),ue())}function qe(s,e){return{...s.inserts&&e in s.inserts?{insert:s.inserts[e]}:{},...s.updates&&e in s.updates?{updates:structuredClone(s.updates[e])}:{},...s.deletes?.includes(e)?{delete:!0}:{}}}function ze(s,e){return{inserts:s.insert?{[e]:s.insert}:{},updates:s.updates?{[e]:s.updates}:{},deletes:s.delete?[e]:[]}}function Ve(s,e){for(let t of s.deletes??[])e.delete(t);for(let[,t]of Object.entries(s.inserts??{}))e.insert(t);for(let[t,r]of Object.entries(s.updates??{}))for(let n of r)e.update(t,n)}function Fr(s,e){if(e.insert&&(s=e.insert),s&&e.updates&&Vt(s,e.updates),!e.delete)return s}function Ge(s,e,t){return{inserts:{...s.inserts,...t.insert?{[e]:t.insert}:{}},updates:{...s.updates,...t.updates?{[e]:t.updates}:{}},deletes:[...s.deletes??[],...t.delete?[e]:[]]}}async function b(s,e){let t=await s.tryGet(e);if(!t)throw Error(`Missing block (${e})`);return t}function p(s,e,t){U(e,t),s.update(e.header.id,t)}function I(s,e){return e??s}var _=P("TL","TreeLeaf"),Je=P("TB","TreeBranch"),S=I("entries"),D=I("partitions"),V=I("nodes");var A=64,G=class s{store;trunk;keyFromEntry;compare;_version=0;constructor(e,t,r=o=>o,n=(o,i)=>o<i?-1:o>i?1:0){this.store=e,this.trunk=t,this.keyFromEntry=r,this.compare=n}static createRoot(e){return Jt(e,[])}static create(e,t,r=i=>i,n=(i,a)=>i<a?-1:i>a?1:0,o){let i=s.createRoot(e);e.insert(i);let a=t(e,i.header.id,o);return new s(e,a,r,n)}async first(){return await this.getFirst(await this.trunk.get())}async last(){return await this.getLast(await this.trunk.get())}async find(e){return await this.getPath(await this.trunk.get(),e)}async get(e){return this.at(await this.find(e))}at(e){return this.validatePath(e),e.on?this.getEntry(e):void 0}async*range(e){let t=e.first?await this.findFirst(e):e.isAscending?await this.first():await this.last(),r=e.last?await this.findLast(e):e.isAscending?await this.last():await this.first();if(!r.on)return;let n=this.keyFromPath(r),i=(e.isAscending?this.internalAscending(t):this.internalDescending(t))[Symbol.asyncIterator](),a=e.isAscending?1:-1;for await(let c of i){if(!c.on||this.compare(this.keyFromPath(c),n)*a>0)break;yield c}}isValid(e){return e.version===this._version}async insert(e){Object.freeze(e);let t=await this.internalInsert(e);return t.on&&(t.version=++this._version),t}async updateAt(e,t){this.validatePath(e),e.on&&Object.freeze(t);let r=await this.internalUpdate(e,t);return r[0].on&&(r[0].version=++this._version),r}async upsert(e){let t=await this.find(this.keyFromEntry(e));return Object.freeze(e),t.on?this.updateEntry(t,e):await this.internalInsertAt(t,e),t.version=++this._version,t}async merge(e,t){let r=await this.keyFromEntry(e),n=await this.find(r);return n.on?await this.updateAt(n,t(this.getEntry(n))):(await this.internalInsertAt(n,Object.freeze(e)),n.on=!0,n.version=++this._version,[n,!1])}async deleteAt(e){this.validatePath(e);let t=await this.internalDelete(e);return t&&++this._version,t}async drop(){let e=await this.trunk.get();for await(let t of this.nodeIds(e))this.store.delete(t)}ascending(e){return this.validatePath(e),this.internalAscending(e.clone())}descending(e){return this.validatePath(e),this.internalDescending(e.clone())}async getCount(e){let t=0,r=e?e.path.clone():await this.first();if(e?.ascending??!0)for(;r.on;)t+=r.leafNode.entries.length-r.leafIndex,r.leafIndex=r.leafNode.entries.length-1,await this.internalNext(r);else for(;r.on;)t+=r.leafIndex+1,r.leafIndex=0,await this.internalPrior(r);return t}async next(e){let t=e.clone();return await this.moveNext(t),t}async moveNext(e){this.validatePath(e),await this.internalNext(e)}async prior(e){let t=e.clone();return this.movePrior(t),t}async movePrior(e){this.validatePath(e),await this.internalPrior(e)}keyFromPath(e){return this.keyFromEntry(e.leafNode.entries[e.leafIndex])}async*internalAscending(e){for(this.validatePath(e);e.on;)yield e,await this.moveNext(e)}async*internalDescending(e){for(this.validatePath(e);e.on;)yield e,await this.movePrior(e)}async findFirst(e){let t=await this.find(e.first.key);return(!t.on||e.first&&!e.first.inclusive)&&(e.isAscending?await this.internalNext(t):await this.internalPrior(t)),t}async findLast(e){let t=await this.find(e.last.key);return(!t.on||e.last&&!e.last.inclusive)&&(e.isAscending?await this.internalPrior(t):await this.internalNext(t)),t}async getPath(e,t){if(e.header.type===_){let r=e,[n,o]=this.indexOfEntry(r.entries,t);return new X([],r,o,n,this._version)}else{let r=e,n=this.indexOfKey(r.partitions,t),o=await this.getPath(await b(this.store,r.nodes[n]),t);return o.branches.unshift(new $(r,n)),o}}indexOfEntry(e,t){let r=0,n=e.length-1,o=0,i=-1;for(;r<=n;){if(o=r+n>>>1,i=this.compare(t,this.keyFromEntry(e[o])),i===0)return[!0,o];i<0?n=o-1:r=o+1}return[!1,r]}indexOfKey(e,t){let r=0,n=e.length-1,o=0,i=-1;for(;r<=n;){if(o=r+n>>>1,i=this.compare(t,e[o]),i===0)return o+1;i<0?n=o-1:r=o+1}return r}async internalNext(e){if(e.on)if(e.leafIndex>=e.leafNode.entries.length-1){let t=0,r=!1,n=e.branches.length-1;for(;t<=n&&!r;){let o=e.branches[n-t];o.index===o.node.partitions.length?++t:r=!0}if(!r)e.leafIndex=e.leafNode.entries.length,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);++o.index,this.moveToFirst(await b(this.store,o.node.nodes[o.index]),e)}}else++e.leafIndex,e.on=!0;else if(e.on=e.branches.every(t=>t.index>=0&&t.index<t.node.nodes.length)&&e.leafIndex>=0&&e.leafIndex<e.leafNode.entries.length,e.on)return}async internalPrior(e){if(this.validatePath(e),e.leafIndex<=0){let t=0,r=!1,n=e.branches.length-1;for(;t<=n&&!r;)e.branches[n-t].index===0?++t:r=!0;if(!r)e.leafIndex=0,e.on=!1;else{e.branches.splice(-t,t);let o=e.branches.at(-1);--o.index,await this.moveToLast(await b(this.store,o.node.nodes[o.index]),e)}}else--e.leafIndex,e.on=!0}async internalUpdate(e,t){if(e.on){let r=this.keyFromPath(e),n=this.keyFromEntry(t);if(this.compare(r,n)!==0){let o=await this.internalInsert(t);return o.on&&(this.internalDelete(await this.find(r)),o=await this.find(n)),[o,!1]}else this.updateEntry(e,t)}return[e,!0]}async internalDelete(e){if(e.on){if(p(this.store,e.leafNode,[S,e.leafIndex,1,[]]),e.branches.length>0){if(e.leafIndex===0&&e.leafNode.entries.length>0){let r=e.branches.at(-1);this.updatePartition(r.index,e,e.branches.length-1,this.keyFromPath(e))}let t=await this.rebalanceLeaf(e,e.branches.length);t&&await this.trunk.set(t)}return e.on=!1,!0}else return!1}async internalInsert(e){let t=await this.find(this.keyFromEntry(e));return t.on?(t.on=!1,t):(await this.internalInsertAt(t,e),t.on=!0,t)}async internalInsertAt(e,t){let r=this.leafInsert(e,t),n=e.branches.length-1;for(;r&&n>=0;)r=await this.branchInsert(e,n,r),--n;if(r){let o=Kt(this.store,[r.key],[await this.trunk.getId(),r.right.header.id]);await this.store.insert(o),await this.trunk.set(o),e.branches.unshift(new $(o,r.indexDelta))}}async moveToFirst(e,t){if(e.header.type===_){let r=e;t.leafNode=r,t.leafIndex=0,t.on=r.entries.length>0}else t.branches.push(new $(e,0)),await this.moveToFirst(await b(this.store,e.nodes[0]),t)}async moveToLast(e,t){if(e.header.type===_){let r=e,n=r.entries.length;t.leafNode=r,t.on=n>0,t.leafIndex=n>0?n-1:0}else{let r=e,n=new $(r,r.partitions.length);t.branches.push(n),await this.moveToLast(await b(this.store,r.nodes[n.index]),t)}}async getFirst(e){if(e.header.type===_){let t=e;return new X([],t,0,t.entries.length>0,this._version)}else{let t=e,r=await this.getFirst(await b(this.store,t.nodes[0]));return r.branches.unshift(new $(t,0)),r}}async getLast(e){if(e.header.type===_){let t=e,r=t.entries.length;return new X([],t,r>0?r-1:0,r>0,this._version)}else{let t=e,r=t.nodes.length-1,n=await this.getLast(await b(this.store,t.nodes[r]));return n.branches.unshift(new $(t,r)),n}}leafInsert(e,t){let{leafNode:r,leafIndex:n}=e;if(r.entries.length<A){p(this.store,r,[S,n,0,[t]]);return}let o=r.entries.length+1>>>1,i=r.entries.slice(o);n>=o&&i.splice(n-o,0,t);let a=Jt(this.store,i);return this.store.insert(a),p(this.store,r,[S,o,r.entries.length-o,[]]),n<o?p(this.store,r,[S,n,0,[t]]):(e.leafNode=a,e.leafIndex-=o),new Ae(this.keyFromEntry(i[0]),a,n<o?0:1)}async branchInsert(e,t,r){let n=e.branches[t],{index:o,node:i}=n;if(n.index+=r.indexDelta,i.nodes.length<A){p(this.store,i,[D,o,0,[r.key]]),p(this.store,i,[V,o+1,0,[r.right.header.id]]);return}let a=i.nodes.length+1>>>1,c=i.partitions.slice(a),l=i.nodes.slice(a),f=n.index<a?0:1;f&&(n.index-=a,c.splice(n.index,0,r.key),l.splice(n.index+1,0,r.right.header.id));let d=Kt(this.store,c,l),h=i.partitions[a-1];return p(this.store,i,[D,a-1,c.length+1,[]]),p(this.store,i,[V,a,l.length,[]]),n.index<a&&(p(this.store,i,[D,o,0,[r.key]]),p(this.store,i,[V,o+1,0,[r.right.header.id]])),new Ae(h,d,f)}async rebalanceLeaf(e,t){if(t===0||e.leafNode.entries.length>=A>>>1)return;let r=e.leafNode,n=e.branches.at(t-1),o=n.index,i=n.node,a=i.nodes[o+1],c=a?await b(this.store,a):void 0;if(c&&c.entries.length>A>>>1){let d=c.entries[0];p(this.store,c,[S,0,1,[]]),p(this.store,r,[S,r.entries.length,0,[d]]),this.updatePartition(o+1,e,t-1,this.keyFromEntry(d));return}let l=i.nodes[o-1],f=l?await b(this.store,l):void 0;if(f&&f.entries.length>A>>>1){let d=f.entries[f.entries.length-1];p(this.store,f,[S,f.entries.length-1,1,[]]),p(this.store,r,[S,0,0,[d]]),this.updatePartition(o,e,t-1,this.keyFromEntry(d)),e.leafIndex+=1;return}if(c&&c.entries.length+r.entries.length<=A)return p(this.store,r,[S,r.entries.length,0,c.entries]),this.deletePartition(i,o),o===0&&this.updatePartition(o,e,t-1,this.keyFromEntry(r.entries[0])),this.store.delete(c.header.id),await this.rebalanceBranch(e,t-1);if(f&&f.entries.length+r.entries.length<=A)return e.leafNode=f,e.leafIndex+=f.entries.length,p(this.store,f,[S,f.entries.length,0,r.entries]),this.deletePartition(i,o-1),this.store.delete(r.header.id),await this.rebalanceBranch(e,t-1)}async rebalanceBranch(e,t){let r=e.branches[t],n=r.node;if(t===0&&n.partitions.length===0)return e.branches[t+1]?.node??e.leafNode;if(t===0||n.nodes.length>=A>>>1)return;let o=e.branches.at(t-1),i=o.index,a=o.node,c=a.nodes[i+1],l=c?await b(this.store,c):void 0;if(l&&l.nodes.length>A>>>1){let h=l.nodes[0],m=l.partitions[0];this.insertPartition(n,n.partitions.length,a.partitions[i],h),this.deletePartition(l,0,0),this.updatePartition(i+1,e,t-1,m);return}let f=a.nodes[i-1],d=f?await b(this.store,f):void 0;if(d&&d.nodes.length>A>>>1){let h=d.nodes[d.nodes.length-1],m=d.partitions[d.partitions.length-1];this.insertPartition(n,0,a.partitions[i-1],h,0),this.deletePartition(d,d.partitions.length-1),r.index+=1,this.updatePartition(i,e,t-1,m);return}if(l&&l.nodes.length+n.nodes.length<=A){let h=a.partitions[i];return this.deletePartition(a,i),p(this.store,n,[D,n.partitions.length,0,[h]]),p(this.store,n,[D,n.partitions.length,0,l.partitions]),p(this.store,n,[V,n.nodes.length,0,l.nodes]),i===0&&a.partitions.length>0&&this.updatePartition(i,e,t-1,a.partitions[0]),this.store.delete(l.header.id),this.rebalanceBranch(e,t-1)}if(d&&d.nodes.length+n.nodes.length<=A){let h=a.partitions[i-1];return this.deletePartition(a,i-1),p(this.store,d,[D,d.partitions.length,0,[h]]),p(this.store,d,[D,d.partitions.length,0,n.partitions]),p(this.store,d,[V,d.nodes.length,0,n.nodes]),r.node=d,r.index+=d.nodes.length,this.store.delete(n.header.id),this.rebalanceBranch(e,t-1)}}updatePartition(e,t,r,n){let o=t.branches[r];e>0?p(this.store,o.node,[D,e-1,1,[n]]):r!==0&&this.updatePartition(t.branches[r-1].index,t,r-1,n)}insertPartition(e,t,r,n,o=1){p(this.store,e,[D,t,0,[r]]),p(this.store,e,[V,t+o,0,[n]])}deletePartition(e,t,r=1){p(this.store,e,[D,t,1,[]]),p(this.store,e,[V,t+r,1,[]])}validatePath(e){if(!this.isValid(e))throw new Error("Path is invalid due to mutation of the tree")}async*nodeIds(e){if(e.header.type===Je){let t=await Promise.all(e.nodes.map(r=>b(this.store,r)));for(let r of t)yield*this.nodeIds(r)}yield e.header.id}getEntry(e){return e.leafNode.entries[e.leafIndex]}updateEntry(e,t){p(this.store,e.leafNode,[S,e.leafIndex,1,[t]])}},Ae=class{key;right;indexDelta;constructor(e,t,r){this.key=e,this.right=t,this.indexDelta=r}};function Jt(s,e){return{header:s.createBlockHeader(_),entries:e}}function Kt(s,e,t){return{header:s.createBlockHeader(Je),partitions:e,nodes:t}}var Ke=class{key;inclusive;constructor(e,t=!0){this.key=e,this.inclusive=t}},Qe=class{first;last;isAscending;constructor(e,t,r=!0){this.first=e,this.last=t,this.isAscending=r}};var _e=class extends G{};var $=class s{node;index;constructor(e,t){this.node=e,this.index=t}clone(){return new s(this.node,this.index)}},X=class s{branches;leafNode;leafIndex;on;version;constructor(e,t,r,n,o){this.branches=e,this.leafNode=t,this.leafIndex=r,this.on=n,this.version=o}isEqual(e){return this.leafNode===e.leafNode&&this.leafIndex===e.leafIndex&&this.on===e.on&&this.version===e.version}clone(){return new s(this.branches.map(e=>e.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var W=I("entries"),Qt=I("priorId"),Xe=I("nextId"),We=P("CHD","ChainDataBlock"),Ze=I("headId"),Ce=I("tailId"),_t=P("CHH","ChainHeaderBlock");var Ye=32,re=class s{store;id;options;constructor(e,t,r){this.store=e,this.id=t,this.options=r}static async create(e,t){let r=s.createTailBlock(e,t),n={...t?.createHeaderBlock?.(t?.newId)??{header:e.createBlockHeader(_t,t?.newId)},headId:r.header.id,tailId:r.header.id};return e.insert(n),e.insert(r),new s(e,n.header.id,t)}static createTailBlock(e,t){return{...t?.createDataBlock?.()??{header:e.createBlockHeader(We)},entries:[],priorId:void 0,nextId:void 0}}static async open(e,t,r){let n=await e.tryGet(t);if(!n)return;let o=n;if(!Object.hasOwn(o,"headId")||!Object.hasOwn(o,"tailId")){let i=s.createTailBlock(e,r);e.insert(i),p(e,n,[Ze,0,0,i.header.id]),p(e,n,[Ce,0,0,i.header.id])}return new s(e,t,r)}async add(...e){let t=await this.getTail();if(!t)throw new Error("Cannot add to non-existent chain");let{headerBlock:r,block:n}=t,o=n,i=new H(this.store),a=e.slice(0,Ye-o.entries.length);for(a.length>0&&(p(i,o,[W,o.entries.length,0,a]),e=e.slice(a.length));e.length>0;){let c={...this.options?.createDataBlock?.()??{header:this.store.createBlockHeader(We)},entries:e.splice(0,Math.min(Ye,e.length)),priorId:o.header.id,nextId:void 0};await this.options?.newBlock?.(c,n),i.insert(c),p(i,o,[Xe,0,0,c.header.id]),o=c}return o!==n&&p(i,r,[Ce,0,0,o.header.id]),i.commit(),{headerBlock:r,block:o,index:o.entries.length-1}}updateAt(e,t){if(!Xt(e))throw new Error("Invalid path");let{index:r,block:n}=e;p(this.store,n,[W,r,1,[t]])}async pop(e=1){if(e<=0)return[];let t=await this.getTail();if(!t)return[];let{headerBlock:r,block:n}=t,o=n,i=[],a=new H(this.store);for(;e>0;)if(o.entries.length>e){let c=o.entries.slice(-e);i.unshift(...c),p(a,o,[W,o.entries.length-e,e,[]]);break}else if(i.unshift(...o.entries),e-=o.entries.length,o.priorId)a.delete(o.header.id),o=await a.tryGet(o.priorId),p(a,o,[Xe,0,0,void 0]);else{p(a,o,[W,0,o.entries.length,[]]);break}return o!==n&&p(a,r,[Ce,0,0,o.header.id]),a.commit(),i}async dequeue(e=1){if(e<=0)return[];let t=new H(this.store),r=await this.getHead();if(!r)return[];let{headerBlock:n,block:o}=r,i=o,a=[];for(;e>0;)if(i.entries.length>e){a.push(...i.entries.slice(0,e)),p(t,i,[W,0,e,[]]);break}else if(a.push(...i.entries),e-=i.entries.length,i.nextId)t.delete(i.header.id),i=await t.tryGet(i.nextId),p(t,i,[Qt,0,0,void 0]);else{p(t,i,[W,0,i.entries.length,[]]);break}return i!==o&&p(t,n,[Ze,0,0,i.header.id]),t.commit(),a}async*select(e,t=!0){let r=e??(t?await this.getHead():await this.getTail());if(!r)return;let n=r.block,o=r.index;if(t)for(;n;){for(;o<n.entries.length;++o)yield{headerBlock:r.headerBlock,block:n,index:o};n=n.nextId?await this.store.tryGet(n.nextId):void 0,o=0}else for(;n;){for(;o>=0;--o)yield{headerBlock:r.headerBlock,block:n,index:o};n=n.priorId?await this.store.tryGet(n.priorId):void 0,o=(n?.entries.length??0)-1}}async next(e){let{headerBlock:t,block:r,index:n}=e;return n<r.entries.length-1||!r.nextId?{headerBlock:t,block:r,index:n+1}:{headerBlock:t,block:await this.store.tryGet(r.nextId),index:0}}async prev(e){let{headerBlock:t,block:r,index:n}=e;if(n>0||!r.priorId)return{headerBlock:t,block:r,index:n-1};let o=await this.store.tryGet(r.priorId);return{headerBlock:t,block:o,index:o.entries.length-1}}async getTail(e){let t=e??await this.getHeader(),r=t?await this.store.tryGet(t.tailId):void 0;for(;r?.nextId;)r=await this.store.tryGet(r.nextId);return r?{headerBlock:t,block:r,index:r.entries.length-1}:void 0}async getHead(e){let t=e??await this.getHeader(),r=t?await this.store.tryGet(t.headId):void 0;for(;r?.priorId;)r=await this.store.tryGet(r.priorId);return r?{headerBlock:t,block:r,index:0}:void 0}async getHeader(){return await this.store.tryGet(this.id)}};function Xt(s){return s.block.entries.length>s.index&&s.index>=0}function Z(s){return s.block.entries[s.index]}function Te(s=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}var st={};B(st,{base10:()=>Vr});var oo=new Uint8Array(0);function Wt(s,e){if(s===e)return!0;if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.byteLength;t++)if(s[t]!==e[t])return!1;return!0}function R(s){if(s instanceof Uint8Array&&s.constructor.name==="Uint8Array")return s;if(s instanceof ArrayBuffer)return new Uint8Array(s);if(ArrayBuffer.isView(s))return new Uint8Array(s.buffer,s.byteOffset,s.byteLength);throw new Error("Unknown type, must be binary type")}function Zt(s){return new TextEncoder().encode(s)}function Yt(s){return new TextDecoder().decode(s)}function Ur(s,e){if(s.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<s.length;n++){var o=s.charAt(n),i=o.charCodeAt(0);if(t[i]!==255)throw new TypeError(o+" is ambiguous");t[i]=n}var a=s.length,c=s.charAt(0),l=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function d(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";for(var y=0,g=0,x=0,k=u.length;x!==k&&u[x]===0;)x++,y++;for(var v=(k-x)*f+1>>>0,T=new Uint8Array(v);x!==k;){for(var N=u[x],z=0,O=v-1;(N!==0||z<g)&&O!==-1;O--,z++)N+=256*T[O]>>>0,T[O]=N%a>>>0,N=N/a>>>0;if(N!==0)throw new Error("Non-zero carry");g=z,x++}for(var F=v-g;F!==v&&T[F]===0;)F++;for(var Be=c.repeat(y);F<v;++F)Be+=s.charAt(T[F]);return Be}function h(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;var y=0;if(u[y]!==" "){for(var g=0,x=0;u[y]===c;)g++,y++;for(var k=(u.length-y)*l+1>>>0,v=new Uint8Array(k);u[y];){var T=t[u.charCodeAt(y)];if(T===255)return;for(var N=0,z=k-1;(T!==0||N<x)&&z!==-1;z--,N++)T+=a*v[z]>>>0,v[z]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");x=N,y++}if(u[y]!==" "){for(var O=k-x;O!==k&&v[O]===0;)O++;for(var F=new Uint8Array(g+(k-O)),Be=g;O!==k;)F[Be++]=v[O++];return F}}}function m(u){var y=h(u);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:m}}var Hr=Ur,Rr=Hr,tr=Rr;var et=class{name;prefix;baseEncode;constructor(e,t,r){this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},tt=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,r){this.name=e,this.prefix=t;let n=t.codePointAt(0);if(n===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return rr(this,e)}},rt=class{decoders;constructor(e){this.decoders=e}or(e){return rr(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function rr(s,e){return new rt({...s.decoders??{[s.prefix]:s},...e.decoders??{[e.prefix]:e}})}var nt=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new et(e,t,r),this.decoder=new tt(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function ne({name:s,prefix:e,encode:t,decode:r}){return new nt(s,e,t,r)}function J({name:s,prefix:e,alphabet:t}){let{encode:r,decode:n}=tr(t,s);return ne({prefix:e,name:s,encode:r,decode:o=>R(n(o))})}function jr(s,e,t,r){let n=s.length;for(;s[n-1]==="=";)--n;let o=new Uint8Array(n*t/8|0),i=0,a=0,c=0;for(let l=0;l<n;++l){let f=e[s[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<t|f,i+=t,i>=8&&(i-=8,o[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function qr(s,e,t){let r=e[e.length-1]==="=",n=(1<<t)-1,o="",i=0,a=0;for(let c=0;c<s.length;++c)for(a=a<<8|s[c],i+=8;i>t;)i-=t,o+=e[n&a>>i];if(i!==0&&(o+=e[n&a<<t-i]),r)for(;(o.length*t&7)!==0;)o+="=";return o}function zr(s){let e={};for(let t=0;t<s.length;++t)e[s[t]]=t;return e}function w({name:s,prefix:e,bitsPerChar:t,alphabet:r}){let n=zr(r);return ne({prefix:e,name:s,encode(o){return qr(o,r,t)},decode(o){return jr(o,n,t,s)}})}var Vr=J({prefix:"9",name:"base10",alphabet:"0123456789"});var ot={};B(ot,{base16:()=>Gr,base16upper:()=>Jr});var Gr=w({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Jr=w({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var it={};B(it,{base2:()=>Kr});var Kr=w({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var at={};B(at,{base256emoji:()=>Zr});var nr=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Qr=nr.reduce((s,e,t)=>(s[t]=e,s),[]),_r=nr.reduce((s,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return s[r]=t,s},[]);function Xr(s){return s.reduce((e,t)=>(e+=Qr[t],e),"")}function Wr(s){let e=[];for(let t of s){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let n=_r[r];if(n==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(n)}return new Uint8Array(e)}var Zr=ne({prefix:"\u{1F680}",name:"base256emoji",encode:Xr,decode:Wr});var ct={};B(ct,{base32:()=>se,base32hex:()=>rn,base32hexpad:()=>sn,base32hexpadupper:()=>on,base32hexupper:()=>nn,base32pad:()=>en,base32padupper:()=>tn,base32upper:()=>Yr,base32z:()=>an});var se=w({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Yr=w({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),en=w({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),tn=w({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rn=w({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),nn=w({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sn=w({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),on=w({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),an=w({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var lt={};B(lt,{base36:()=>pe,base36upper:()=>cn});var pe=J({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),cn=J({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var dt={};B(dt,{base58btc:()=>M,base58flickr:()=>ln});var M=J({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ln=J({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ht={};B(ht,{base64:()=>dn,base64pad:()=>hn,base64url:()=>fn,base64urlpad:()=>un});var dn=w({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),hn=w({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),fn=w({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),un=w({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var ft={};B(ft,{base8:()=>pn});var pn=w({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ut={};B(ut,{identity:()=>mn});var mn=ne({prefix:"\0",name:"identity",encode:s=>Yt(s),decode:s=>Zt(s)});var Io=new TextEncoder,vo=new TextDecoder;var mt={};B(mt,{identity:()=>Un});var wn=ir,sr=128,xn=127,bn=~xn,kn=Math.pow(2,31);function ir(s,e,t){e=e||[],t=t||0;for(var r=t;s>=kn;)e[t++]=s&255|sr,s/=128;for(;s&bn;)e[t++]=s&255|sr,s>>>=7;return e[t]=s|0,ir.bytes=t-r+1,e}var In=pt,vn=128,or=127;function pt(s,r){var t=0,r=r||0,n=0,o=r,i,a=s.length;do{if(o>=a)throw pt.bytes=0,new RangeError("Could not decode varint");i=s[o++],t+=n<28?(i&or)<<n:(i&or)*Math.pow(2,n),n+=7}while(i>=vn);return pt.bytes=o-r,t}var Bn=Math.pow(2,7),An=Math.pow(2,14),Cn=Math.pow(2,21),Tn=Math.pow(2,28),Sn=Math.pow(2,35),En=Math.pow(2,42),On=Math.pow(2,49),Pn=Math.pow(2,56),Dn=Math.pow(2,63),Nn=function(s){return s<Bn?1:s<An?2:s<Cn?3:s<Tn?4:s<Sn?5:s<En?6:s<On?7:s<Pn?8:s<Dn?9:10},Ln={encode:wn,decode:In,encodingLength:Nn},$n=Ln,me=$n;function ye(s,e=0){return[me.decode(s,e),me.decode.bytes]}function oe(s,e,t=0){return me.encode(s,e,t),e}function ie(s){return me.encodingLength(s)}function ce(s,e){let t=e.byteLength,r=ie(s),n=r+ie(t),o=new Uint8Array(n+t);return oe(s,o,0),oe(t,o,r),o.set(e,n),new ae(s,t,e,o)}function ar(s){let e=R(s),[t,r]=ye(e),[n,o]=ye(e.subarray(r)),i=e.subarray(r+o);if(i.byteLength!==n)throw new Error("Incorrect length");return new ae(t,n,i,e)}function cr(s,e){if(s===e)return!0;{let t=e;return s.code===t.code&&s.size===t.size&&t.bytes instanceof Uint8Array&&Wt(s.bytes,t.bytes)}}var ae=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};var lr=0,Mn="identity",dr=R;function Fn(s,e){if(e?.truncate!=null&&e.truncate!==s.byteLength){if(e.truncate<0||e.truncate>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,e.truncate)}return ce(lr,dr(s))}var Un={code:lr,name:Mn,encode:dr,digest:Fn};var wt={};B(wt,{sha256:()=>Rn,sha512:()=>jn});var Hn=20;function gt({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new yt(s,e,t,r,n)}var yt=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,o){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??Hn,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?hr(r,this.code,t?.truncate):r.then(n=>hr(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function hr(s,e,t){if(t!=null&&t!==s.byteLength){if(t>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,t)}return ce(e,s)}function ur(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var Rn=gt({name:"sha2-256",code:18,encode:ur("SHA-256")}),jn=gt({name:"sha2-512",code:19,encode:ur("SHA-512")});function pr(s,e){let{bytes:t,version:r}=s;switch(r){case 0:return zn(t,xt(s),e??M.encoder);default:return Vn(t,xt(s),e??se.encoder)}}var mr=new WeakMap;function xt(s){let e=mr.get(s);if(e==null){let t=new Map;return mr.set(s,t),t}return e}var Ee=class s{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==we)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Gn)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return s.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,r=ce(e,t);return s.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return s.equals(this,e)}static equals(e,t){let r=t;return r!=null&&e.code===r.code&&e.version===r.version&&cr(e.multihash,r.multihash)}toString(e){return pr(this,e)}toJSON(){return{"/":pr(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof s)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:r,code:n,multihash:o,bytes:i}=t;return new s(r,n,o,i??yr(r,n,o.bytes))}else if(t[Jn]===!0){let{version:r,multihash:n,code:o}=t,i=ar(n);return s.create(r,o,i)}else return null}static create(e,t,r){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==we)throw new Error(`Version 0 CID must use dag-pb (code: ${we}) block encoding`);return new s(e,t,r,r.bytes)}case 1:{let n=yr(e,t,r.bytes);return new s(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return s.create(0,we,e)}static createV1(e,t){return s.create(1,e,t)}static decode(e){let[t,r]=s.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=s.inspectBytes(e),r=t.size-t.multihashSize,n=R(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=n.subarray(t.multihashSize-t.digestSize),i=new ae(t.multihashCode,t.digestSize,o,n);return[t.version===0?s.createV0(i):s.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[d,h]=ye(e.subarray(t));return t+=h,d},n=r(),o=we;if(n===18?(n=0,t=0):o=r(),n!==0&&n!==1)throw new RangeError(`Invalid CID version ${n}`);let i=t,a=r(),c=r(),l=t+c,f=l-i;return{version:n,codec:o,multihashCode:a,digestSize:c,multihashSize:f,size:l}}static parse(e,t){let[r,n]=qn(e,t),o=s.decode(n);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xt(o).set(r,e),o}};function qn(s,e){switch(s[0]){case"Q":{let t=e??M;return[M.prefix,t.decode(`${M.prefix}${s}`)]}case M.prefix:{let t=e??M;return[M.prefix,t.decode(s)]}case se.prefix:{let t=e??se;return[se.prefix,t.decode(s)]}case pe.prefix:{let t=e??pe;return[pe.prefix,t.decode(s)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[s[0],e.decode(s)]}}}function zn(s,e,t){let{prefix:r}=t;if(r!==M.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let n=e.get(r);if(n==null){let o=t.encode(s).slice(1);return e.set(r,o),o}else return n}function Vn(s,e,t){let{prefix:r}=t,n=e.get(r);if(n==null){let o=t.encode(s);return e.set(r,o),o}else return n}var we=112,Gn=18;function yr(s,e,t){let r=ie(s),n=r+ie(e),o=new Uint8Array(n+t.byteLength);return oe(s,o,0),oe(e,o,r),o.set(t,n),o}var Jn=Symbol.for("@ipld/js-cid/CID");var bt={...ut,...it,...ft,...st,...ot,...ct,...lt,...dt,...ht,...at},Go={...wt,...mt};function gr(s=0){return new Uint8Array(s)}function xr(s,e,t,r){return{name:s,prefix:e,encoder:{name:s,prefix:e,encode:t},decoder:{decode:r}}}var wr=xr("utf8","u",s=>"u"+new TextDecoder("utf8").decode(s),s=>new TextEncoder().encode(s.substring(1))),kt=xr("ascii","a",s=>{let e="a";for(let t=0;t<s.length;t++)e+=String.fromCharCode(s[t]);return e},s=>{s=s.substring(1);let e=gr(s.length);for(let t=0;t<s.length;t++)e[t]=s.charCodeAt(t);return e}),Kn={utf8:wr,"utf-8":wr,hex:bt.base16,latin1:kt,ascii:kt,binary:kt,...bt},br=Kn;function le(s,e="utf8"){let t=br[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(s).substring(1)}var K=class{static lockQueues=new Map;static async acquire(e){let t=this.lockQueues.get(e)??Promise.resolve(),r,n=new Promise(i=>{r=i});return this.lockQueues.set(e,n),await t,()=>{r(),this.lockQueues.get(e)===n&&this.lockQueues.delete(e)}}};var Qn=100,Y=class s{id;transactor;handlers;source;sourceCache;tracker;filterConflict;pending=[];latchId;constructor(e,t,r,n,o,i,a){this.id=e,this.transactor=t,this.handlers=r,this.source=n,this.sourceCache=o,this.tracker=i,this.filterConflict=a,this.latchId=`Collection:${this.id}`}static async createOrOpen(e,t,r){let n=new de(t,e,void 0),o=new xe(n),i=new j(o);if(await n.tryGet(t)){let c=await E.open(i,t);n.actionContext=await c.getActionContext()}else{let c=r.createHeaderBlock(t,i);i.insert(c),n.actionContext=void 0,await E.open(i,t)}return new s(t,e,r.modules,n,o,i,r.filterConflict)}async act(...e){let t=await K.acquire(this.latchId);try{await this.actInternal(...e)}finally{t()}}async actInternal(...e){await this.internalTransact(...e),this.pending.push(...e)}async internalTransact(...e){let t=new H(this.tracker);for(let r of e){let n=this.handlers[r.type];if(!n)throw new Error(`No handler for action type ${r.type}`);await n(r,t)}t.commit()}async update(){let e=await K.acquire(this.latchId);try{await this.updateInternal()}finally{e()}}async updateInternal(){let e=new de(this.id,this.transactor,void 0),t=new j(e),r=this.source.actionContext,n=await E.open(t,this.id),o=n?await n.getFrom(r?.rev??0):void 0,i=!1;for(let a of o?.entries??[])this.pending=this.pending.map(c=>this.doFilterConflict(c,a.actions)?c:void 0).filter(Boolean),this.sourceCache.clear(a.blockIds),i=i||this.tracker.conflicts(new Set(a.blockIds)).length>0;i&&await this.replayActions(),this.source.actionContext=o?.context}async sync(){let e=await K.acquire(this.latchId);try{await this.syncInternal()}finally{e()}}async syncInternal(){let e=Te(16),t=le(e,"base64url");for(;this.pending.length||!Re(this.tracker.transforms);){let r=[...this.pending],n=He(this.tracker.transforms),o=new j(this.sourceCache,n),i=await E.open(o,this.id);if(!i)throw new Error(`Log not found for collection ${this.id}`);let a=(this.source.actionContext?.rev??0)+1,c=await i.addActions(r,t,a,()=>o.transformedBlockIds()),l=await this.source.transact(o.transforms,t,a,this.id,c.tailPath.block.header.id);if(l)l.pending&&await new Promise(f=>setTimeout(f,Qn)),await this.updateInternal();else{this.pending=this.pending.slice(r.length);let f=o.reset();await this.replayActions(),this.sourceCache.transformCache(f),this.source.actionContext=this.source.actionContext?{committed:[...this.source.actionContext.committed,{actionId:t,rev:a}],rev:a}:{committed:[{actionId:t,rev:a}],rev:a}}}}async updateAndSync(){let e=await K.acquire(this.latchId);try{await this.updateInternal(),await this.syncInternal()}finally{e()}}async*selectLog(e=!0){let t=await E.open(this.tracker,this.id);if(!t)throw new Error(`Log not found for collection ${this.id}`);for await(let r of t.select(void 0,e))r.action&&(yield*e?r.action.actions:r.action.actions.reverse())}async replayActions(){this.tracker.reset();for(let e of this.pending)await this.internalTransact(e)}doFilterConflict(e,t){if(this.filterConflict){let r=this.filterConflict(e,t);if(r)r!==e&&this.pending.push(r);else return!1}return!0}};var It=class s{collection;constructor(e){this.collection=e}static async create(e,t){let r={modules:{append:async(o,i)=>{}},createHeaderBlock:(o,i)=>({header:i.createBlockHeader(vt,o)})},n=await Y.createOrOpen(e,t,r);return new s(n)}async append(e){let t={type:"append",data:e};await this.collection.act(t),await this.collection.updateAndSync()}async update(){await this.collection.update()}async*select(e=!0){for await(let t of this.collection.selectLog(e))yield t.data}};var vt=P("DIH","DiaryHeaderBlock");var Bt=P("TRE","TreeHeaderBlock"),At=I("rootId");var be=class{store;collectionId;constructor(e,t){this.store=e,this.collectionId=t}async get(){return await b(this.store,await this.getId())}async set(e){let t=await b(this.store,this.collectionId);p(this.store,t,[At,0,1,e.header.id])}async getId(){return(await b(this.store,this.collectionId)).rootId}};var Ct=class s{collection;btree;constructor(e,t){this.collection=e,this.btree=t}static async createOrOpen(e,t,r=o=>o,n=(o,i)=>o<i?-1:o>i?1:0){let o,i={modules:{replace:async({data:c},l)=>{for(let[f,d]of c)d?await o.upsert(d):await o.deleteAt(await o.find(f))}},createHeaderBlock:(c,l)=>{let f;return o=G.create(l,(d,h)=>(f=h,new be(l,c)),r,n),{header:l.createBlockHeader(Bt,c),rootId:f}}},a=await Y.createOrOpen(e,t,i);return o=o??new G(a.tracker,new be(a.tracker,a.id),r,n),new s(a,o)}async replace(e){await this.collection.act({type:"replace",data:e}),await this.collection.updateAndSync()}async update(){await this.collection.update()}async first(){return await this.btree.first()}async last(){return await this.btree.last()}async find(e){return await this.btree.find(e)}async get(e){return await this.btree.get(e)}at(e){return this.btree.at(e)}range(e){return this.btree.range(e)}ascending(e){return this.btree.ascending(e)}descending(e){return this.btree.descending(e)}async getCount(e){return await this.btree.getCount(e)}async next(e){return await this.btree.next(e)}async moveNext(e){await this.btree.moveNext(e)}async prior(e){return await this.btree.prior(e)}async movePrior(e){await this.btree.movePrior(e)}isValid(e){return this.btree.isValid(e)}};var Li=new Uint8Array(0);var _n=vr,kr=128,Xn=127,Wn=~Xn,Zn=Math.pow(2,31);function vr(s,e,t){e=e||[],t=t||0;for(var r=t;s>=Zn;)e[t++]=s&255|kr,s/=128;for(;s&Wn;)e[t++]=s&255|kr,s>>>=7;return e[t]=s|0,vr.bytes=t-r+1,e}var Yn=Tt,es=128,Ir=127;function Tt(s,r){var t=0,r=r||0,n=0,o=r,i,a=s.length;do{if(o>=a)throw Tt.bytes=0,new RangeError("Could not decode varint");i=s[o++],t+=n<28?(i&Ir)<<n:(i&Ir)*Math.pow(2,n),n+=7}while(i>=es);return Tt.bytes=o-r,t}var ts=Math.pow(2,7),rs=Math.pow(2,14),ns=Math.pow(2,21),ss=Math.pow(2,28),os=Math.pow(2,35),is=Math.pow(2,42),as=Math.pow(2,49),cs=Math.pow(2,56),ls=Math.pow(2,63),ds=function(s){return s<ts?1:s<rs?2:s<ns?3:s<ss?4:s<os?5:s<is?6:s<as?7:s<cs?8:s<ls?9:10},hs={encode:_n,decode:Yn,encodingLength:ds},fs=hs,St=fs;function Et(s,e,t=0){return St.encode(s,e,t),e}function Ot(s){return St.encodingLength(s)}function Br(s,e){let t=e.byteLength,r=Ot(s),n=r+Ot(t),o=new Uint8Array(n+t);return Et(s,o,0),Et(t,o,r),o.set(e,n),new Pt(s,t,e,o)}var Pt=class{code;size;digest;bytes;constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}};var ms=20;function Nt({name:s,code:e,encode:t,minDigestLength:r,maxDigestLength:n}){return new Dt(s,e,t,r,n)}var Dt=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,r,n,o){this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??ms,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?Ar(r,this.code,t?.truncate):r.then(n=>Ar(n,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ar(s,e,t){if(t!=null&&t!==s.byteLength){if(t>s.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${s.byteLength}`);s=s.subarray(0,t)}return Br(e,s)}function Cr(s){return async e=>new Uint8Array(await crypto.subtle.digest(s,e))}var Oe=Nt({name:"sha2-256",code:18,encode:Cr("SHA-256")}),Vi=Nt({name:"sha2-512",code:19,encode:Cr("SHA-512")});var ys=I("priorHash"),E=class s{chain;constructor(e){this.chain=e}get id(){return this.chain.id}static async open(e,t){let r=await re.open(e,t,s.getChainOptions(e));return r?new s(r):void 0}static async create(e,t){return new s(await re.create(e,{...s.getChainOptions(e),newId:t}))}async addActions(e,t,r,n,o=[],i=Date.now()){let a={timestamp:i,rev:r,action:{actionId:t,actions:e,blockIds:[],collectionIds:o}},c=await this.chain.add(a),l={...a,action:{...a.action,blockIds:n()}};return this.chain.updateAt(c,l),{entry:l,tailPath:c}}async addCheckpoint(e,t,r=Date.now()){let n={timestamp:r,rev:t,checkpoint:{pendings:e}},o=await this.chain.add(n);return{entry:n,tailPath:o}}async getActionContext(){let e=await this.chain.getTail();if(!e)return;let t=await this.findCheckpoint(e);return{committed:t?[...t.pendings,...await this.pendingFrom(t.path)]:[],rev:t?.rev??0}}async getFrom(e){let t=[],r=[],n,o;for await(let i of this.chain.select(void 0,!1)){let a=Z(i);if(n=n??a.rev,a.checkpoint){o=i,r.unshift(...a.checkpoint.pendings);break}r.unshift({actionId:a.action.actionId,rev:a.rev}),e!==void 0&&a.rev>e&&t.unshift(a.action)}if(o)for await(let i of this.chain.select(o,!1)){let a=Z(i);if(e!==void 0&&a.rev>e)a.action&&t.unshift(a.action);else break}return{context:n?{committed:r,rev:n}:void 0,entries:t}}async*select(e,t=!0){for await(let r of this.chain.select(e,t))yield Z(r)}async findCheckpoint(e){let t,r;for await(let n of this.chain.select(e,!1)){let o=Z(n);if(r=r??o.rev,o.checkpoint)return{path:n,pendings:o.checkpoint.pendings,rev:r};t=n}return t?{path:t,pendings:[],rev:r}:void 0}async pendingFrom(e){let t=[];for await(let r of this.chain.select(e)){let n=Z(r);n?.action&&t.push({actionId:n.action.actionId,rev:n.rev})}return t}static getChainOptions(e){return{createDataBlock:()=>({header:e.createBlockHeader("LGD")}),createHeaderBlock:t=>({header:e.createBlockHeader("LGH",t)}),newBlock:async(t,r)=>{if(r){let n=await Oe.digest(new TextEncoder().encode(JSON.stringify(r)));t.priorHash=le(n.digest,"base64url")}}}}};var Lt="LGD",$t="LGH";function Mt(s){return{toString:()=>s,equals:e=>e!=null&&typeof e=="object"&&"toString"in e&&typeof e.toString=="function"&&e.toString()===s}}function Q(s){let e=5381;for(let t=0;t<s.length;t++)e=(e<<5)+e+s.charCodeAt(t)|0;return Math.abs(e).toString(36)}function he(s,e,t,r){let n=JSON.stringify({peerId:s,timestamp:e,schemaHash:t,engineId:r}),o=`stamp:${Q(n)}`;return{peerId:s,timestamp:e,schemaHash:t,engineId:r,id:o}}function fe(s,e,t){let r=JSON.stringify({stampId:s,statements:e,reads:t});return`tx:${Q(r)}`}Pe();Pe();var De=class{transactor;collections;constructor(e,t){this.transactor=e,this.collections=t}async applyActions(e,t){for(let{collectionId:r,actions:n}of e){let o=this.collections.get(r);if(!o)throw new Error(`Collection not found: ${r}`);for(let i of n){let a={...i,transaction:t};await o.act(a)}}}async commit(e){let t=Array.from(this.collections.entries()).map(([c,l])=>({collectionId:c,collection:l,transforms:l.tracker.transforms})).filter(({transforms:c})=>Object.keys(c.inserts??{}).length+Object.keys(c.updates??{}).length+(c.deletes?.length??0)>0);if(t.length===0)return;let r=new Map,n=new Map;for(let{collectionId:c,collection:l,transforms:f}of t){r.set(c,f);let d=await E.open(l.tracker,c);if(!d)throw new Error(`Log not found for collection ${c}`);let h=await d.chain.getTail();h&&n.set(c,h.block.header.id)}let o=t.flatMap(({collectionId:c,transforms:l})=>[...Object.entries(l.inserts??{}).map(([f,d])=>({type:"insert",collectionId:c,blockId:f,block:d})),...Object.entries(l.updates??{}).map(([f,d])=>({type:"update",collectionId:c,blockId:f,operations:d})),...(l.deletes??[]).map(f=>({type:"delete",collectionId:c,blockId:f}))]),i=this.hashOperations(o),a=await this.coordinateTransaction(e,i,r,n);if(!a.success)throw new Error(`Transaction commit failed: ${a.error}`)}async rollback(e){for(let t of this.collections.values())t.tracker.reset()}getTransforms(){let e=new Map;for(let[t,r]of this.collections.entries()){let n=r.tracker.transforms;(Object.keys(n.inserts??{}).length>0||Object.keys(n.updates??{}).length>0||(n.deletes?.length??0)>0)&&e.set(t,n)}return e}resetTransforms(){for(let e of this.collections.values())e.tracker.reset()}hashOperations(e){let t=JSON.stringify(e);return`ops:${Q(t)}`}async commitTransaction(e){let t=Array.from(e.getCollectionActions().entries()).map(([l,f])=>({collectionId:l,actions:f}));if(t.length===0)return{success:!0};let r=Ie(t),n=e.getReads(),o=he("local",Date.now(),"",e.engine),i={stamp:o,statements:r,reads:n,id:fe(o.id,r,n)},{ActionsEngine:a}=await Promise.resolve().then(()=>(Pe(),Tr)),c=new a(this);return await this.execute(i,c)}async execute(e,t){let r=await t.execute(e);if(!r.success)return r;if(!r.actions||r.actions.length===0)return{success:!0};let n=new Map,o=new Map,i=new Map,a=r.actions.map(d=>d.collectionId);for(let d of r.actions){let h=await this.applyActionsToCollection(d,e,a);if(!h.success)return{success:!1,error:h.error};n.set(d.collectionId,h.transforms),o.set(d.collectionId,h.logTailBlockId),i.set(d.collectionId,h.results)}let c=Array.from(n.entries()).flatMap(([d,h])=>[...Object.entries(h.inserts??{}).map(([m,u])=>({type:"insert",collectionId:d,blockId:m,block:u})),...Object.entries(h.updates??{}).map(([m,u])=>({type:"update",collectionId:d,blockId:m,operations:u})),...(h.deletes??[]).map(m=>({type:"delete",collectionId:d,blockId:m}))]),l=this.hashOperations(c),f=await this.coordinateTransaction(e,l,n,o);return f.success?{success:!0,actions:r.actions,results:i}:f}async applyActionsToCollection(e,t,r){let n=this.collections.get(e.collectionId);if(!n)return{success:!1,error:`Collection not found: ${e.collectionId}`};let o=n.tracker.transforms,i=await E.open(n.tracker,e.collectionId);if(!i)return{success:!1,error:`Log not found for collection ${e.collectionId}`};let a=t.id,c=(n.source.actionContext?.rev??0)+1,l=await i.addActions(e.actions,a,c,()=>L(o),r);return{success:!0,transforms:o,logTailBlockId:l.tailPath.block.header.id,results:[]}}async coordinateTransaction(e,t,r,n){let o=Array.from(n.values()),i=await this.gatherPhase(o),a=await this.pendPhase(e,t,r,i);if(!a.success)return a;let c=await this.commitPhase(e.id,o,a.pendedBlockIds);return c.success?{success:!0}:(await this.cancelPhase(e.id,r),c)}async gatherPhase(e){if(e.length===1||!this.transactor.queryClusterNominees)return null;let t=e.map(o=>this.transactor.queryClusterNominees(o));return(await Promise.all(t)).reduce((o,i)=>(i.nominees.forEach(a=>o.add(a)),o),new Set)}async pendPhase(e,t,r,n){if(r.size===0)return{success:!1,error:"No transforms to pend"};let o=new Map,i=e.id,a=n?Array.from(n):void 0;for(let[c,l]of r.entries()){let f=this.collections.get(c);if(!f)return{success:!1,error:`Collection not found: ${c}`};let d=(f.source.actionContext?.rev??0)+1,h={actionId:i,rev:d,transforms:l,policy:"r",transaction:e,operationsHash:t,superclusterNominees:a},m=await this.transactor.pend(h);if(!m.success)return{success:!1,error:`Pend failed for collection ${c}: ${m.reason}`};o.set(c,m.blockIds)}return{success:!0,pendedBlockIds:o}}async commitPhase(e,t,r){for(let[n,o]of r.entries()){let i=this.collections.get(n);if(!i)return{success:!1,error:`Collection not found: ${n}`};let a=(i.source.actionContext?.rev??0)+1,c=t.find(d=>o.includes(d));if(!c)return{success:!1,error:`Log tail block not found for collection ${n}`};let l={actionId:e,blockIds:o,tailId:c,rev:a};if(!(await this.transactor.commit(l)).success)return{success:!1,error:`Commit failed for collection ${n}`}}return{success:!0}}async cancelPhase(e,t){for(let[r,n]of t.entries()){if(!this.collections.get(r))continue;let i=L(n);await this.transactor.cancel({actionId:e,blockIds:i})}}};var Ne=class{coordinator;transactionId;engine;collectionActions=new Map;reads=[];constructor(e,t,r){this.coordinator=e,this.transactionId=t,this.engine=r}async addAction(e,t){let r={...t,transaction:this.transactionId},n=this.coordinator.collections.get(e);n&&await n.act(r),this.collectionActions.has(e)||this.collectionActions.set(e,[]),this.collectionActions.get(e).push(r)}addRead(e){this.reads.push(e)}async commit(){return await this.coordinator.commitTransaction(this)}rollback(){this.collectionActions.clear(),this.reads.length=0}getCollectionActions(){return this.collectionActions}getReads(){return this.reads}getAffectedCollections(){return new Set(this.collectionActions.keys())}};var Le=class{coordinator;engine;statements=[];stamp;committed=!1;rolledBack=!1;constructor(e,t,r="local",n=""){this.coordinator=e,this.engine=t,this.stamp=he(r,Date.now(),n,"unknown")}async execute(e,t){if(this.committed)return{success:!1,error:"Transaction already committed"};if(this.rolledBack)return{success:!1,error:"Transaction already rolled back"};try{let r;if(t)r=t;else{let n={stamp:this.stamp,statements:[e],reads:[],id:"temp"},o=await this.engine.execute(n);if(!o.success||!o.actions)return{success:!1,error:o.error||"Failed to translate statement"};r=o.actions}return await this.coordinator.applyActions(r,this.stamp.id),this.statements.push(e),{success:!0}}catch(r){return{success:!1,error:`Failed to execute statement: ${r instanceof Error?r.message:String(r)}`}}}async commit(){if(this.committed)return{success:!1,error:"Transaction already committed"};if(this.rolledBack)return{success:!1,error:"Transaction already rolled back"};let e={stamp:this.stamp,statements:this.statements,reads:[],id:fe(this.stamp.id,this.statements,[])};return await this.coordinator.commit(e),this.committed=!0,{success:!0}}async rollback(){if(this.committed)throw new Error("Cannot rollback: transaction already committed");if(this.rolledBack)throw new Error("Transaction already rolled back");await this.coordinator.rollback(this.stamp.id),this.rolledBack=!0,this.statements.length=0}getStampId(){return this.stamp.id}getStamp(){return this.stamp}getStatements(){return this.statements}isCommitted(){return this.committed}isRolledBack(){return this.rolledBack}};var $e=class{engines;createValidationCoordinator;constructor(e,t){this.engines=e,this.createValidationCoordinator=t}async validate(e,t){let{stamp:r,statements:n}=e,o=this.engines.get(r.engineId);if(!o)return{valid:!1,reason:`Unknown engine: ${r.engineId}`};let i=await o.getSchemaHash();if(i!==r.schemaHash)return{valid:!1,reason:`Schema mismatch: local=${i}, sender=${r.schemaHash}`};let a=this.createValidationCoordinator();try{let c=await o.engine.execute(e);if(!c.success)return{valid:!1,reason:`Re-execution failed: ${c.error}`};c.actions&&c.actions.length>0&&await a.applyActions(c.actions,r.id);let l=a.getTransforms(),f=this.collectOperations(l),d=this.hashOperations(f);return d!==t?{valid:!1,reason:"Operations hash mismatch",computedHash:d}:{valid:!0,computedHash:d}}finally{a.dispose()}}async getSchemaHash(e){let t=this.engines.get(e);return t?await t.getSchemaHash():void 0}collectOperations(e){return Array.from(e.entries()).flatMap(([t,r])=>[...Object.entries(r.inserts??{}).map(([n,o])=>({type:"insert",collectionId:t,blockId:n,block:o})),...Object.entries(r.updates??{}).map(([n,o])=>({type:"update",collectionId:t,blockId:n,operations:o})),...(r.deletes??[]).map(n=>({type:"delete",collectionId:t,blockId:n}))])}hashOperations(e){let t=JSON.stringify(e);return`ops:${Q(t)}`}};async function C(s){let e=new TextEncoder().encode(s);return(await Oe.digest(e)).digest}function Sr(s){for(let e in s)return!1;return!0}var ve=class{promise;response;error;t1=Date.now();duration;get isResponse(){return this.response!==void 0}get isError(){return this.error!==void 0}get isComplete(){return this.isResponse||this.isError}async result(){if(this.isResponse)return this.response;if(this.isError)throw this.error;return await this.promise}constructor(e){this.promise=e,e.then(t=>(this.duration=Date.now()-this.t1,this.response=t,t),t=>{this.duration=Date.now()-this.t1,this.error=t})}};function Ut(s,e,t,r){let n=s.reduce((o,[i,a])=>{let c=a.toString(),l=o.get(c)??{peerId:a,blockId:i,excludedPeers:r};return o.set(c,{...l,payload:t(e,i,l.payload)}),o},new Map);return Array.from(n.values())}function*Er(s){let e=[...s];for(;e.length>0;){let t=e.pop();(!t.request||!t.request.isResponse)&&(yield t),t.subsumedBy&&t.subsumedBy.length&&e.push(...t.subsumedBy)}}function Ht(s,e){for(let t of s){let r=!1,n=[t];for(;n.length>0;){let o=n.pop();if(e(o)){r=!0;break}if(o.subsumedBy&&o.subsumedBy.length)for(let i=0;i<o.subsumedBy.length;i++)n.push(o.subsumedBy[i])}if(!r)return!1}return!0}function*q(s,e){let t=[...s];for(;t.length>0;){let r=t.pop();(!e||e(r))&&(yield r),r.subsumedBy&&r.subsumedBy.length&&t.push(...r.subsumedBy)}}function ee(s,e,t){return[...t??[],e]}async function te(s,e,t,r,n,o){let i=new WeakMap;for(let c of s)i.set(c,c);let a=async c=>{await Promise.all(c.map(async l=>{l.request=new ve(e(l).catch(async f=>{if(n>Date.now()){let d=[l.peerId,...l.excludedPeers??[]],h=await Me(t(l),l.payload,r,d,o);if(h.length>0&&n>Date.now()){let m=i.get(l)??l;m.subsumedBy=[...m.subsumedBy??[],...h];for(let u of h)i.set(u,m);await a(h)}}throw f}))})),await Promise.all(c.map(l=>l.request?.result().catch(()=>{})))};await a(s)}async function Me(s,e,t,r,n){let o=new Set(s),i=await Promise.all(Array.from(o).map(async a=>[a,await n(a,{excludedPeers:r})]));return Ut(i,e,t,r)}var Rt=class{keyNetwork;timeoutMs;abortOrCancelTimeoutMs;getRepo;constructor(e){this.keyNetwork=e.keyNetwork,this.timeoutMs=e.timeoutMs,this.abortOrCancelTimeoutMs=e.abortOrCancelTimeoutMs,this.getRepo=e.getRepo}async get(e){let t=Array.from(new Set(e.blockIds)),r=await this.batchesForPayload(t,t,(h,m,u)=>[...u??[],...h.filter(y=>y===m)],[]),n=Date.now()+this.timeoutMs,o;try{await te(r,h=>this.getRepo(h.peerId).get({blockIds:h.payload,context:e.context},{expiration:n}),h=>h.payload,(h,m,u)=>[...u??[],...h.filter(y=>y===m)],n,async(h,m)=>this.keyNetwork.findCoordinator(await C(h),m))}catch(h){o=h}let i=h=>h.request?.isResponse===!0&&h.request.response!=null,a=h=>{if(!i(h))return!1;let m=h.request.response;return h.payload.some(u=>{let y=m[u];return y&&typeof y=="object"&&"block"in y&&y.block!=null})},c=Array.from(q(r)).filter(h=>!i(h)||!a(h));if(c.length>0&&Date.now()<n)try{let h=new Map;for(let m of c){let u=new Set([m.peerId,...m.excludedPeers??[]]);h.set(m,u);let y=await Me(m.payload,m.payload,(g,x,k)=>[...k??[],...g.filter(v=>v===x)],Array.from(u),async(g,x)=>this.keyNetwork.findCoordinator(await C(g),x));y.length>0&&(m.subsumedBy=[...m.subsumedBy??[],...y],await te(y,g=>this.getRepo(g.peerId).get({blockIds:g.payload,context:e.context},{expiration:n}),g=>g.payload,(g,x,k)=>[...k??[],...g.filter(v=>v===x)],n,async(g,x)=>this.keyNetwork.findCoordinator(await C(g),x)))}}catch(h){o||(o=h)}let l=Array.from(q(r,h=>h.request?.isResponse&&!Sr(h.request.response))),f=new Map;for(let h of l){let m=h.request.response;for(let[u,y]of Object.entries(m)){let g=f.get(u),x=y&&typeof y=="object"&&"block"in y&&y.block!=null,k=g&&typeof g=="object"&&"block"in g&&g.block!=null;(!g||x&&!k)&&f.set(u,y)}}if(t.filter(h=>!f.has(h)).length>0){let h=this.formatBatchStatuses(r,u=>u.request?.isResponse??!1,u=>{let y=u.request==null?"no-response":u.request.isResponse?"response":"in-flight";return`${u.peerId.toString()}[block:${u.blockId}](${y})`}),m=new Error(`Some peers did not complete: ${h}${o?`; root: ${o.message}`:""}`);throw m.cause=o,m}return Object.fromEntries(f)}async getStatus(e){let t=[...new Set(e.flatMap(n=>n.blockIds))];if(t.length===0)return e.map(n=>({...n,statuses:[]}));let r=await this.get({blockIds:t});return e.map(n=>({...n,statuses:n.blockIds.map(o=>{let i=r[o];if(!i)return"aborted";let{state:a}=i;return a.pendings?.includes(n.actionId)?"pending":a.latest?.actionId===n.actionId?"committed":"aborted"})}))}async consolidateCoordinators(e,t,r){let n=await Promise.all(e.map(async a=>({blockId:a,coordinator:await this.keyNetwork.findCoordinator(await C(a),{excludedPeers:[]})}))),o=new Map;for(let{blockId:a,coordinator:c}of n){let l=c.toString(),f=o.get(l)??[];f.push(a),o.set(l,f)}let i=[];for(let[a,c]of o){let l=n.find(d=>d.coordinator.toString()===a).coordinator,f={inserts:{},updates:{},deletes:[]};for(let d of c)f=r(t,d,f);i.push({peerId:l,payload:f,blockId:c[0],coordinatingBlockIds:c,excludedPeers:[]})}return i}async pend(e){let t=(c,l,f)=>{let d=qe(c,l);return f?Ge(f,l,d):ze(d,l)},r=L(e.transforms),n=await this.consolidateCoordinators(r,e.transforms,t),o=Date.now()+this.timeoutMs,i;try{await te(n,c=>this.getRepo(c.peerId).pend({...e,transforms:c.payload},{expiration:o,coordinatingBlockIds:c.coordinatingBlockIds}),c=>L(c.payload),t,o,async(c,l)=>this.keyNetwork.findCoordinator(await C(c),l));try{let c=this.keyNetwork;if(typeof c?.recordCoordinator=="function")for(let l of Array.from(q(n)))c.recordCoordinator(await C(l.blockId),l.peerId)}catch(c){console.warn("Failed to record coordinator hint",c)}}catch(c){i=c}if(!Ht(n,c=>c.request?.isResponse&&c.request.response.success)){let c=this.formatBatchStatuses(n,d=>(d.request?.isResponse&&d.request.response?.success)??!1,d=>{let h=d.request==null?"no-response":d.request.isResponse?"non-success":"in-flight";return`${d.peerId.toString()}[block:${d.blockId}](${h})`}),l=new Error(`Some peers did not complete: ${c}${i?`; root: ${i.message}`:""}`),f=i;l.cause=f,l.errors=f?[f]:[],i=l}if(i){Promise.resolve().then(()=>this.cancelBatch(n,{blockIds:r,actionId:e.actionId}));let c=Array.from(q(n,l=>l.request?.isResponse&&!l.request.response.success));if(c.length>0)return{success:!1,missing:jt(c.flatMap(l=>l.request.response.missing).filter(l=>l!==void 0))};throw i}return{success:!0,pending:Array.from(q(n,c=>c.request?.isResponse&&c.request.response.success)).flatMap(c=>c.request.response.pending),blockIds:L(e.transforms)}}async cancel(e){let t=await this.batchesForPayload(e.blockIds,e.blockIds,ee,[]),r=Date.now()+this.abortOrCancelTimeoutMs;await te(t,n=>this.getRepo(n.peerId).cancel({actionId:e.actionId,blockIds:n.payload},{expiration:r}),n=>n.payload,ee,r,async(n,o)=>this.keyNetwork.findCoordinator(await C(n),o))}async queryClusterNominees(e){let t=await C(e),r=await this.keyNetwork.findCluster(t);return{nominees:Object.keys(r).map(o=>Mt(o))}}async commit(e){let t=[...new Set([...e.blockIds,e.tailId])];if(e.headerId&&!e.blockIds.includes(e.headerId)){let o=await this.commitBlock(e.headerId,t,e.actionId,e.rev);if(!o.success)return o}let r=await this.commitBlock(e.tailId,t,e.actionId,e.rev);if(!r.success)return r;let n=e.blockIds.filter(o=>o!==e.tailId&&!(e.headerId&&o===e.headerId&&!e.blockIds.includes(e.headerId)));if(n.length>0){let{batches:o,error:i}=await this.commitBlocks({blockIds:n,actionId:e.actionId,rev:e.rev});if(i)try{console.warn("[NetworkTransactor] non-tail commit had errors; proceeding after tail commit:",i.message)}catch{}}return{success:!0}}async commitBlock(e,t,r,n){let{batches:o,error:i}=await this.commitBlocks({blockIds:[e],actionId:r,rev:n});if(i){Promise.resolve().then(()=>this.cancel({blockIds:t,actionId:r}));let a=Array.from(q(o,c=>c.request?.isResponse&&!c.request.response.success));if(a.length>0)return{missing:jt(a.flatMap(c=>c.request.response.missing)),success:!1};throw i}return{success:!0}}async commitBlocks({blockIds:e,actionId:t,rev:r}){let n=Date.now()+this.timeoutMs,o=await this.batchesForPayload(e,e,ee,[]),i;try{await te(o,a=>this.getRepo(a.peerId).commit({actionId:t,blockIds:a.payload,rev:r},{expiration:n}),a=>a.payload,ee,n,async(a,c)=>this.keyNetwork.findCoordinator(await C(a),c))}catch(a){i=a}if(!Ht(o,a=>a.request?.isResponse&&a.request.response.success)){let a=this.formatBatchStatuses(o,l=>(l.request?.isResponse&&l.request.response?.success)??!1,l=>{let f=l.request==null?"no-response":l.request.isResponse?"non-success":"in-flight",d=l.request?.response,h=d&&d.success===!1?Array.isArray(d.missing)?` missing=${d.missing.length}`:" success=false":"";return`${l.peerId.toString()}[blocks:${l.payload instanceof Array?l.payload.length:1}](${f})${h?" "+h:""}`}),c=new Error(`Some peers did not complete: ${a}${i?`; root: ${i.message}`:""}`);c.cause=i,i=c}return{batches:o,error:i}}async batchesForPayload(e,t,r,n){return Me(e,t,r,n,async(o,i)=>this.keyNetwork.findCoordinator(await C(o),i))}async cancelBatch(e,t){let r=Date.now()+this.abortOrCancelTimeoutMs,n=Ut(Array.from(q(e)).map(o=>[o.blockId,o.peerId]),t.blockIds,ee,[]);await te(n,o=>this.getRepo(o.peerId).cancel({actionId:t.actionId,blockIds:o.payload},{expiration:r}),o=>o.payload,ee,r,async(o,i)=>this.keyNetwork.findCoordinator(await C(o),i))}formatBatchStatuses(e,t,r){let o=Array.from(Er(e)).map(r).join(", ");return o.length===0&&(o=Array.from(q(e)).map(r).join(", ")),o}};function jt(s){let e=qt(s,({actionId:t})=>t);return Object.entries(e).map(([t,r])=>({actionId:t,transforms:je(...r.map(n=>n.transforms))}))}var de=class{collectionId;transactor;actionContext;constructor(e,t,r){this.collectionId=e,this.transactor=t,this.actionContext=r}createBlockHeader(e,t){return{type:e,id:t??this.generateId(),collectionId:this.collectionId}}generateId(){return le(Te(32),"base64url")}async tryGet(e){let t=await this.transactor.get({blockIds:[e],context:this.actionContext});if(t){let{block:r,state:n}=t[e];return r}}async transact(e,t,r,n,o){let i=await this.transactor.pend({transforms:e,actionId:t,rev:r,policy:"r"});if(!i.success)return i;let a=e.inserts&&Object.hasOwn(e.inserts,n),c=await this.transactor.commit({headerId:a?n:void 0,tailId:o,blockIds:i.blockIds,actionId:t,rev:r});if(!c.success)return c}};var j=class{source;transforms;constructor(e,t=ue()){this.source=e,this.transforms=t}async tryGet(e){let t=await this.source.tryGet(e);if(t){if((this.transforms.updates?.[e]??[]).forEach(n=>U(t,n)),this.transforms.deletes?.includes(e))return}else if(this.transforms.inserts&&Object.hasOwn(this.transforms.inserts,e))return structuredClone(this.transforms.inserts[e]);return t}generateId(){return this.source.generateId()}createBlockHeader(e,t){return this.source.createBlockHeader(e,t)}insert(e){let t=this.transforms.inserts??={};t[e.header.id]=structuredClone(e);let r=this.transforms.deletes,n=r?.indexOf(e.header.id)??-1;n>=0&&r.splice(n,1)}update(e,t){let r=this.transforms.inserts?.[e];if(r)U(r,t);else{let n=this.transforms.updates??={};zt(n,e,()=>[]).push(structuredClone(t))}}delete(e){this.transforms.inserts&&delete this.transforms.inserts[e],this.transforms.updates&&delete this.transforms.updates[e],(this.transforms.deletes??=[]).push(e)}reset(e=ue()){let t=this.transforms;return this.transforms=e,t}transformedBlockIds(){return Array.from(new Set(L(this.transforms)))}conflicts(e){return this.transformedBlockIds().filter(t=>e.has(t))}};var H=class extends j{store;constructor(e){super(e),this.store=e}commit(){let e=this.reset();Ve(e,this.store)}};var xe=class{source;cache=new Map;constructor(e){this.source=e}async tryGet(e){let t=this.cache.get(e);return t||(t=await this.source.tryGet(e),t&&this.cache.set(e,t)),structuredClone(t)}generateId(){return this.source.generateId()}createBlockHeader(e,t){return this.source.createBlockHeader(e,t)}clear(e=void 0){if(e)for(let t of e)this.cache.delete(t);else this.cache.clear()}transformCache(e){for(let t of e.deletes??[])this.cache.delete(t);for(let[,t]of Object.entries(e.inserts??{}))this.cache.set(t.header.id,structuredClone(t));for(let[t,r]of Object.entries(e.updates??{}))for(let n of r){let o=this.cache.get(t);o&&U(o,n)}}};function qt(s,e){return s.reduce((t,r)=>{let n=e(r);return(t[n]??=[]).push(r),t},{})}function zt(s,e,t,r){let n=s[e];return typeof n>"u"?(n=t(),s[e]=n):r&&r(n),n}function gs(s,e,t,r){let n=s.get(e);return typeof n>"u"?(n=t(),s.set(e,n)):r&&r(n),n}return $r(ws);})();
|
|
3
|
-
/*! Bundled license information:
|
|
4
|
-
|
|
5
|
-
@noble/hashes/utils.js:
|
|
6
|
-
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
7
|
-
*/
|
|
8
|
-
return OptimysticDbCore}));
|
|
9
|
-
//# sourceMappingURL=index.min.js.map
|