@optimystic/db-core 0.1.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +8 -0
  2. package/dist/index.min.js +1 -1
  3. package/dist/index.min.js.map +4 -4
  4. package/dist/src/blocks/block-types.d.ts +1 -1
  5. package/dist/src/blocks/block-types.d.ts.map +1 -1
  6. package/dist/src/btree/btree.d.ts.map +1 -1
  7. package/dist/src/btree/btree.js +3 -5
  8. package/dist/src/btree/btree.js.map +1 -1
  9. package/dist/src/btree/independent-trunk.d.ts +4 -4
  10. package/dist/src/btree/independent-trunk.d.ts.map +1 -1
  11. package/dist/src/btree/independent-trunk.js +2 -2
  12. package/dist/src/btree/independent-trunk.js.map +1 -1
  13. package/dist/src/btree/path.d.ts +1 -1
  14. package/dist/src/btree/path.d.ts.map +1 -1
  15. package/dist/src/btree/tree-block.d.ts +1 -1
  16. package/dist/src/btree/tree-block.d.ts.map +1 -1
  17. package/dist/src/btree/tree-block.js +2 -2
  18. package/dist/src/btree/tree-block.js.map +1 -1
  19. package/dist/src/btree/trunk.d.ts +3 -3
  20. package/dist/src/btree/trunk.d.ts.map +1 -1
  21. package/dist/src/collection/collection.d.ts +5 -1
  22. package/dist/src/collection/collection.d.ts.map +1 -1
  23. package/dist/src/collection/collection.js +77 -50
  24. package/dist/src/collection/collection.js.map +1 -1
  25. package/dist/src/collections/diary/diary.d.ts +2 -0
  26. package/dist/src/collections/diary/diary.d.ts.map +1 -1
  27. package/dist/src/collections/diary/diary.js +4 -0
  28. package/dist/src/collections/diary/diary.js.map +1 -1
  29. package/dist/src/collections/tree/struct.d.ts.map +1 -1
  30. package/dist/src/collections/tree/struct.js +2 -1
  31. package/dist/src/collections/tree/struct.js.map +1 -1
  32. package/dist/src/index.d.ts +1 -0
  33. package/dist/src/index.d.ts.map +1 -1
  34. package/dist/src/index.js +1 -0
  35. package/dist/src/index.js.map +1 -1
  36. package/dist/src/transaction/coordinator.d.ts.map +1 -1
  37. package/dist/src/transaction/coordinator.js +14 -19
  38. package/dist/src/transaction/coordinator.js.map +1 -1
  39. package/dist/src/transaction/transaction.d.ts.map +1 -1
  40. package/dist/src/transaction/transaction.js +1 -13
  41. package/dist/src/transaction/transaction.js.map +1 -1
  42. package/dist/src/transaction/validator.d.ts.map +1 -1
  43. package/dist/src/transaction/validator.js +5 -9
  44. package/dist/src/transaction/validator.js.map +1 -1
  45. package/dist/src/transactor/network-transactor.d.ts.map +1 -1
  46. package/dist/src/transactor/network-transactor.js +29 -3
  47. package/dist/src/transactor/network-transactor.js.map +1 -1
  48. package/dist/src/transactor/transactor-source.js +1 -1
  49. package/dist/src/transactor/transactor-source.js.map +1 -1
  50. package/dist/src/transform/cache-source.js +3 -3
  51. package/dist/src/transform/cache-source.js.map +1 -1
  52. package/dist/src/transform/helpers.d.ts +27 -2
  53. package/dist/src/transform/helpers.d.ts.map +1 -1
  54. package/dist/src/transform/helpers.js +44 -14
  55. package/dist/src/transform/helpers.js.map +1 -1
  56. package/dist/src/transform/struct.d.ts +5 -4
  57. package/dist/src/transform/struct.d.ts.map +1 -1
  58. package/dist/src/transform/tracker.d.ts.map +1 -1
  59. package/dist/src/transform/tracker.js +18 -9
  60. package/dist/src/transform/tracker.js.map +1 -1
  61. package/dist/src/utility/batch-coordinator.js +0 -1
  62. package/dist/src/utility/batch-coordinator.js.map +1 -1
  63. package/dist/src/utility/hash-string.d.ts +11 -0
  64. package/dist/src/utility/hash-string.d.ts.map +1 -0
  65. package/dist/src/utility/hash-string.js +17 -0
  66. package/dist/src/utility/hash-string.js.map +1 -0
  67. package/package.json +14 -8
  68. package/src/blocks/block-types.ts +1 -1
  69. package/src/blocks/structs.ts +1 -1
  70. package/src/btree/btree.ts +3 -5
  71. package/src/btree/independent-trunk.ts +6 -6
  72. package/src/btree/path.ts +1 -1
  73. package/src/btree/tree-block.ts +3 -3
  74. package/src/btree/trunk.ts +3 -3
  75. package/src/collection/collection.ts +78 -51
  76. package/src/collections/diary/diary.ts +5 -0
  77. package/src/collections/tree/struct.ts +2 -1
  78. package/src/index.ts +1 -0
  79. package/src/transaction/coordinator.ts +14 -18
  80. package/src/transaction/session.ts +182 -182
  81. package/src/transaction/transaction.ts +2 -13
  82. package/src/transaction/validator.ts +147 -150
  83. package/src/transactor/network-transactor.ts +32 -2
  84. package/src/transactor/transactor-source.ts +1 -1
  85. package/src/transform/cache-source.ts +3 -3
  86. package/src/transform/helpers.ts +44 -14
  87. package/src/transform/struct.ts +5 -6
  88. package/src/transform/tracker.ts +16 -9
  89. package/src/utility/hash-string.ts +17 -0
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
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 cn=Object.defineProperty;var ma=Object.getOwnPropertyDescriptor;var ya=Object.getOwnPropertyNames;var xa=Object.prototype.hasOwnProperty;var ga=(n,t)=>()=>(n&&(t=n(n=0)),t);var ct=(n,t)=>{for(var e in t)cn(n,e,{get:t[e],enumerable:!0})},wa=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ya(t))!xa.call(n,s)&&s!==e&&cn(n,s,{get:()=>t[s],enumerable:!(r=ma(t,s))||r.enumerable});return n};var ba=n=>wa(cn({},"__esModule",{value:!0}),n);var ca={};ct(ca,{ACTIONS_ENGINE_ID:()=>Xs,ActionsEngine:()=>dr,createActionsStatements:()=>hr});function hr(n){return n.map(t=>JSON.stringify(t))}var Xs,dr,Yr=ga(()=>{"use strict";Xs="actions@1.0.0",dr=class{coordinator;constructor(t){this.coordinator=t}async execute(t){try{let e=[];for(let r of t.statements){let s=JSON.parse(r);if(!s.collectionId||typeof s.collectionId!="string")return{success:!1,error:"Invalid statement: missing collectionId"};if(!s.actions||!Array.isArray(s.actions))return{success:!1,error:`Invalid statement: collection ${s.collectionId} missing or invalid actions array`};e.push(s),await this.coordinator.applyActions([s],t.stamp.id)}return{success:!0,actions:e}}catch(e){return{success:!1,error:`Failed to execute transaction: ${e instanceof Error?e.message:String(e)}`}}}}});var Yf={};ct(Yf,{ACTIONS_ENGINE_ID:()=>Xs,ActionsEngine:()=>dr,Atomic:()=>Dt,BTree:()=>jt,CacheSource:()=>lr,Chain:()=>we,Collection:()=>ye,Diary:()=>Fs,DiaryHeaderBlockType:()=>$s,EntriesPerBlock:()=>Sn,KeyBound:()=>gn,KeyRange:()=>wn,Keyset:()=>bn,Latches:()=>fr,Log:()=>xt,LogDataBlockType:()=>zs,LogHeaderBlockType:()=>Ys,NetworkTransactor:()=>eo,NodeCapacity:()=>lt,Path:()=>se,PathBranch:()=>vt,Pending:()=>yr,Tracker:()=>Vt,TransactionContext:()=>Xr,TransactionCoordinator:()=>Wr,TransactionSession:()=>Jr,TransactionValidator:()=>Qr,TransactorSource:()=>Me,Tree:()=>Zs,TreeHeaderBlockType:()=>js,apply:()=>_,applyOperation:()=>Lt,applyOperations:()=>io,applyTransform:()=>Ia,applyTransformToStore:()=>mn,blockIdToBytes:()=>mt,blockIdsForTransforms:()=>At,concatTransform:()=>yn,concatTransforms:()=>dn,copyTransforms:()=>ln,createActionsStatements:()=>hr,createTransactionId:()=>qe,createTransactionStamp:()=>He,distinctBlockActionTransforms:()=>ro,emptyTransforms:()=>Ve,ensured:()=>Ws,ensuredMap:()=>zf,entryAt:()=>ie,get:()=>W,groupBy:()=>no,isTransformsEmpty:()=>un,mergeTransforms:()=>ao,nameof:()=>st,pathValid:()=>ho,priorHash$:()=>qf,registerBlockType:()=>gt,rootId$:()=>Gs,transformForBlockId:()=>hn,transformsFromTransform:()=>pn,withOperation:()=>Ea});var fn=new Map;function gt(n,t){if(fn.has(n))throw new Error(`Block type ${n} (${t}) already registered (${fn.get(n)})`);return fn.set(n,t),n}function Lt(n,[t,e,r,s]){Array.isArray(s)?n[t].splice(e,r,...structuredClone(s)):n[t]=structuredClone(s)}function io(n,t){for(let e of t)Lt(n,e)}function Ea(n,[t,e,r,s]){if(Array.isArray(s)){let o=n[t];return{...n,[t]:[...o.slice(0,e),...structuredClone(s),...o.slice(e+r)]}}else return{...n,[t]:structuredClone(s)}}function At(n){if(!n)return[];let t=Object.keys(n.inserts??{}),e=Object.keys(n.updates??{}),r=n.deletes??[];return[...new Set([...t,...e,...r])]}function Ve(){return{inserts:{},updates:{},deletes:[]}}function ln(n){return{inserts:{...n.inserts},updates:{...n.updates},deletes:n.deletes}}function ao(n,t){return{inserts:{...n.inserts,...t.inserts},updates:{...n.updates,...t.updates},deletes:[...n.deletes,...t.deletes]}}function un(n){return Object.keys(n.inserts).length===0&&Object.keys(n.updates).length===0&&n.deletes.length===0}function dn(...n){return n.reduce((t,e)=>ao(t,e),Ve())}function hn(n,t){return{...t in n.inserts?{insert:n.inserts[t]}:{},...t in n.updates?{updates:n.updates[t]}:{},...t in n.deletes?{delete:!0}:{}}}function pn(n,t){return{inserts:n.insert?{[t]:n.insert}:{},updates:n.updates?{[t]:n.updates}:{},deletes:n.delete?[t]:[]}}function mn(n,t){for(let e of n.deletes)t.delete(e);for(let[,e]of Object.entries(n.inserts))t.insert(e);for(let[e,r]of Object.entries(n.updates))for(let s of r)t.update(e,s)}function Ia(n,t){if(t.insert&&(n=t.insert),n&&t.updates&&io(n,t.updates),!t.delete)return n}function yn(n,t,e){return{inserts:{...n.inserts,...e.insert?{[t]:e.insert}:{}},updates:{...n.updates,...e.updates?{[t]:e.updates}:{}},deletes:[...n.deletes,...e.delete?[t]:[]]}}async function W(n,t){let e=await n.tryGet(t);if(!e)throw Error(`Missing block (${t})`);return e}function _(n,t,e){Lt(t,e),n.update(t.header.id,e)}function st(n,t){return t??n}var ne=gt("TL","TreeLeaf"),xn=gt("TB","TreeBranch"),yt=st("entries"),wt=st("partitions"),$t=st("nodes");var lt=64,jt=class n{store;trunk;keyFromEntry;compare;_version=0;constructor(t,e,r=o=>o,s=(o,i)=>o<i?-1:o>i?1:0){this.store=t,this.trunk=e,this.keyFromEntry=r,this.compare=s}static createRoot(t){return co(t,[])}static create(t,e,r=i=>i,s=(i,c)=>i<c?-1:i>c?1:0,o){let i=n.createRoot(t);t.insert(i);let c=e(t,i.header.id,o);return new n(t,c,r,s)}async first(){return await this.getFirst(await this.trunk.get())}async last(){return await this.getLast(await this.trunk.get())}async find(t){return await this.getPath(await this.trunk.get(),t)}async get(t){return this.at(await this.find(t))}at(t){return this.validatePath(t),t.on?this.getEntry(t):void 0}async*range(t){let e=t.first?await this.findFirst(t):t.isAscending?await this.first():await this.last(),r=t.last?await this.findLast(t):t.isAscending?await this.last():await this.first();if(!r.on)return;let s=this.keyFromPath(r),i=(t.isAscending?this.internalAscending(e):this.internalDescending(e))[Symbol.asyncIterator](),c=t.isAscending?1:-1;for await(let a of i){if(!a.on||this.compare(this.keyFromPath(a),s)*c>0)break;yield a}}isValid(t){return t.version===this._version}async insert(t){Object.freeze(t);let e=await this.internalInsert(t);return e.on&&(e.version=++this._version),e}async updateAt(t,e){this.validatePath(t),t.on&&Object.freeze(e);let r=await this.internalUpdate(t,e);return r[0].on&&(r[0].version=++this._version),r}async upsert(t){let e=await this.find(this.keyFromEntry(t));return Object.freeze(t),e.on?this.updateEntry(e,t):await this.internalInsertAt(e,t),e.version=++this._version,e}async merge(t,e){let r=await this.keyFromEntry(t),s=await this.find(r);if(s.on){let o=await this.updateAt(s,e(this.getEntry(s)));return o[0].on&&(o[0].version=++this._version),o}else return await this.internalInsertAt(s,Object.freeze(t)),s.on=!0,s.version=++this._version,[s,!1]}async deleteAt(t){this.validatePath(t);let e=await this.internalDelete(t);return e&&++this._version,e}async drop(){let t=await this.trunk.get();for await(let e of this.nodeIds(t))this.store.delete(e)}ascending(t){return this.validatePath(t),this.internalAscending(t.clone())}descending(t){return this.validatePath(t),this.internalDescending(t.clone())}async getCount(t){let e=0,r=t?t.path.clone():await this.first();if(t?.ascending??!0)for(;r.on;)e+=r.leafNode.entries.length-r.leafIndex,r.leafIndex=r.leafNode.entries.length-1,await this.internalNext(r);else for(;r.on;)e+=r.leafIndex+1,r.leafIndex=0,await this.internalPrior(r);return e}async next(t){let e=t.clone();return await this.moveNext(e),e}async moveNext(t){this.validatePath(t),await this.internalNext(t)}async prior(t){let e=t.clone();return this.movePrior(e),e}async movePrior(t){this.validatePath(t),await this.internalPrior(t)}keyFromPath(t){return this.keyFromEntry(t.leafNode.entries[t.leafIndex])}async*internalAscending(t){for(this.validatePath(t);t.on;)yield t,await this.moveNext(t)}async*internalDescending(t){for(this.validatePath(t);t.on;)yield t,await this.movePrior(t)}async findFirst(t){let e=await this.find(t.first.key);return(!e.on||t.first&&!t.first.inclusive)&&(t.isAscending?await this.internalNext(e):await this.internalPrior(e)),e}async findLast(t){let e=await this.find(t.last.key);return(!e.on||t.last&&!t.last.inclusive)&&(t.isAscending?await this.internalPrior(e):await this.internalNext(e)),e}async getPath(t,e){if(t.header.type===ne){let r=t,[s,o]=this.indexOfEntry(r.entries,e);return new se([],r,o,s,this._version)}else{let r=t,s=this.indexOfKey(r.partitions,e),o=await this.getPath(await W(this.store,r.nodes[s]),e);return o.branches.unshift(new vt(r,s)),o}}indexOfEntry(t,e){let r=0,s=t.length-1,o=0,i=-1;for(;r<=s;){if(o=r+s>>>1,i=this.compare(e,this.keyFromEntry(t[o])),i===0)return[!0,o];i<0?s=o-1:r=o+1}return[!1,r]}indexOfKey(t,e){let r=0,s=t.length-1,o=0,i=-1;for(;r<=s;){if(o=r+s>>>1,i=this.compare(e,t[o]),i===0)return o+1;i<0?s=o-1:r=o+1}return r}async internalNext(t){if(t.on)if(t.leafIndex>=t.leafNode.entries.length-1){let e=0,r=!1,s=t.branches.length-1;for(;e<=s&&!r;){let o=t.branches[s-e];o.index===o.node.partitions.length?++e:r=!0}if(!r)t.leafIndex=t.leafNode.entries.length,t.on=!1;else{t.branches.splice(-e,e);let o=t.branches.at(-1);++o.index,this.moveToFirst(await W(this.store,o.node.nodes[o.index]),t)}}else++t.leafIndex,t.on=!0;else if(t.on=t.branches.every(e=>e.index>=0&&e.index<e.node.nodes.length)&&t.leafIndex>=0&&t.leafIndex<t.leafNode.entries.length,t.on)return}async internalPrior(t){if(this.validatePath(t),t.leafIndex<=0){let e=0,r=!1,s=t.branches.length-1;for(;e<=s&&!r;)t.branches[s-e].index===0?++e:r=!0;if(!r)t.leafIndex=0,t.on=!1;else{t.branches.splice(-e,e);let o=t.branches.at(-1);--o.index,await this.moveToLast(await W(this.store,o.node.nodes[o.index]),t)}}else--t.leafIndex,t.on=!0}async internalUpdate(t,e){if(t.on){let r=this.keyFromPath(t),s=this.keyFromEntry(e);if(this.compare(r,s)!==0){let o=await this.internalInsert(e);return o.on&&(this.internalDelete(await this.find(r)),o=await this.find(s)),[o,!1]}else this.updateEntry(t,e)}return[t,!0]}async internalDelete(t){if(t.on){if(_(this.store,t.leafNode,[yt,t.leafIndex,1,[]]),t.branches.length>0){if(t.leafIndex===0){let r=t.branches.at(-1);this.updatePartition(r.index,t,t.branches.length-1,this.keyFromPath(t))}let e=await this.rebalanceLeaf(t,t.branches.length);e&&await this.trunk.set(e)}return t.on=!1,!0}else return!1}async internalInsert(t){let e=await this.find(this.keyFromEntry(t));return e.on?(e.on=!1,e):(await this.internalInsertAt(e,t),e.on=!0,e)}async internalInsertAt(t,e){let r=this.leafInsert(t,e),s=t.branches.length-1;for(;r&&s>=0;)r=await this.branchInsert(t,s,r),--s;if(r){let o=fo(this.store,[r.key],[await this.trunk.getId(),r.right.header.id]);await this.store.insert(o),await this.trunk.set(o),t.branches.unshift(new vt(o,r.indexDelta))}}async moveToFirst(t,e){if(t.header.type===ne){let r=t;e.leafNode=r,e.leafIndex=0,e.on=r.entries.length>0}else e.branches.push(new vt(t,0)),await this.moveToFirst(await W(this.store,t.nodes[0]),e)}async moveToLast(t,e){if(t.header.type===ne){let r=t,s=r.entries.length;e.leafNode=r,e.on=s>0,e.leafIndex=s>0?s-1:0}else{let r=t,s=new vt(r,r.partitions.length);e.branches.push(s),await this.moveToLast(await W(this.store,r.nodes[s.index]),e)}}async getFirst(t){if(t.header.type===ne){let e=t;return new se([],e,0,e.entries.length>0,this._version)}else{let e=t,r=await this.getFirst(await W(this.store,e.nodes[0]));return r.branches.unshift(new vt(e,0)),r}}async getLast(t){if(t.header.type===ne){let e=t,r=e.entries.length;return new se([],e,r>0?r-1:0,r>0,this._version)}else{let e=t,r=e.nodes.length-1,s=await this.getLast(await W(this.store,e.nodes[r]));return s.branches.unshift(new vt(e,r)),s}}leafInsert(t,e){let{leafNode:r,leafIndex:s}=t;if(r.entries.length<lt){_(this.store,r,[yt,s,0,[e]]);return}let o=r.entries.length+1>>>1,i=r.entries.slice(o);s>=o&&i.splice(s-o,0,e);let c=co(this.store,i);return this.store.insert(c),_(this.store,r,[yt,o,r.entries.length-o,[]]),s<o?_(this.store,r,[yt,s,0,[e]]):(t.leafNode=c,t.leafIndex-=o),new gr(this.keyFromEntry(i[0]),c,s<o?0:1)}async branchInsert(t,e,r){let s=t.branches[e],{index:o,node:i}=s;if(s.index+=r.indexDelta,i.nodes.length<lt){_(this.store,i,[wt,o,0,[r.key]]),_(this.store,i,[$t,o+1,0,[r.right.header.id]]);return}let c=i.nodes.length+1>>>1,a=i.partitions.slice(c),f=i.nodes.slice(c),u=s.index<c?0:1;u&&(s.index-=c,a.splice(s.index,0,r.key),f.splice(s.index+1,0,r.right.header.id));let l=fo(this.store,a,f),d=i.partitions[c-1];return _(this.store,i,[wt,c-1,a.length+1,[]]),_(this.store,i,[$t,c,f.length,[]]),s.index<c&&(_(this.store,i,[wt,o,0,[r.key]]),_(this.store,i,[$t,o+1,0,[r.right.header.id]])),new gr(d,l,u)}async rebalanceLeaf(t,e){if(e===0||t.leafNode.entries.length>=lt>>>1)return;let r=t.leafNode,s=t.branches.at(e-1),o=s.index,i=s.node,c=i.nodes[o+1],a=c?await W(this.store,c):void 0;if(a&&a.entries.length>lt>>>1){let l=a.entries[0];_(this.store,a,[yt,0,1,[]]),_(this.store,r,[yt,r.entries.length,0,[l]]),this.updatePartition(o+1,t,e-1,this.keyFromEntry(l));return}let f=i.nodes[o-1],u=f?await W(this.store,f):void 0;if(u&&u.entries.length>lt>>>1){let l=u.entries[u.entries.length-1];_(this.store,u,[yt,u.entries.length-1,1,[]]),_(this.store,r,[yt,0,0,[l]]),this.updatePartition(o,t,e-1,this.keyFromEntry(l)),t.leafIndex+=1;return}if(a&&a.entries.length+r.entries.length<=lt)return _(this.store,r,[yt,r.entries.length,0,a.entries]),this.deletePartition(i,o),o===0&&this.updatePartition(o,t,e-1,this.keyFromEntry(r.entries[0])),this.store.delete(a.header.id),await this.rebalanceBranch(t,e-1);if(u&&u.entries.length+r.entries.length<=lt)return t.leafNode=u,t.leafIndex+=u.entries.length,_(this.store,u,[yt,u.entries.length,0,r.entries]),this.deletePartition(i,o-1),this.store.delete(r.header.id),await this.rebalanceBranch(t,e-1)}async rebalanceBranch(t,e){let r=t.branches[e],s=r.node;if(e===0&&s.partitions.length===0)return t.branches[e+1]?.node??t.leafNode;if(e===0||s.nodes.length>=lt<<1)return;let o=t.branches.at(e-1),i=o.index,c=o.node,a=c.nodes[i+1],f=a?await W(this.store,a):void 0;if(f&&f.nodes.length>lt>>>1){let d=f.nodes[0],p=f.partitions[0];this.insertPartition(s,s.partitions.length,c.partitions[i],d),this.deletePartition(f,0,0),this.updatePartition(i+1,t,e-1,p);return}let u=c.nodes[i-1],l=u?await W(this.store,u):void 0;if(l&&l.nodes.length>lt>>>1){let d=l.nodes[l.nodes.length-1],p=l.partitions[l.partitions.length-1];this.insertPartition(s,0,c.partitions[i-1],d,0),this.deletePartition(l,l.partitions.length-1),r.index+=1,this.updatePartition(i,t,e-1,p);return}if(f&&f.nodes.length+s.nodes.length<=lt){let d=c.partitions[i];return this.deletePartition(c,i),_(this.store,s,[wt,s.partitions.length,0,[d]]),_(this.store,s,[wt,s.partitions.length,0,f.partitions]),_(this.store,s,[$t,s.nodes.length,0,f.nodes]),i===0&&c.partitions.length>0&&this.updatePartition(i,t,e-1,c.partitions[0]),this.store.delete(f.header.id),this.rebalanceBranch(t,e-1)}if(l&&l.nodes.length+s.nodes.length<=lt){let d=c.partitions[i-1];return this.deletePartition(c,i-1),_(this.store,l,[wt,l.partitions.length,0,[d]]),_(this.store,l,[wt,l.partitions.length,0,s.partitions]),_(this.store,l,[$t,l.nodes.length,0,s.nodes]),r.node=l,r.index+=l.nodes.length,this.store.delete(s.header.id),this.rebalanceBranch(t,e-1)}}updatePartition(t,e,r,s){let o=e.branches[r];t>0?_(this.store,o.node,[wt,t-1,1,[s]]):r!==0&&this.updatePartition(e.branches[r-1].index,e,r-1,s)}insertPartition(t,e,r,s,o=1){_(this.store,t,[wt,e,0,[r]]),_(this.store,t,[$t,e+o,0,[s]])}deletePartition(t,e,r=1){_(this.store,t,[wt,e,1,[]]),_(this.store,t,[$t,e+r,1,[]])}validatePath(t){if(!this.isValid(t))throw new Error("Path is invalid due to mutation of the tree")}async*nodeIds(t){if(t.header.type===xn){let e=await Promise.all(t.nodes.map(r=>W(this.store,r)));for(let r of e)yield*this.nodeIds(r)}yield t.header.id}getEntry(t){return t.leafNode.entries[t.leafIndex]}updateEntry(t,e){_(this.store,t.leafNode,[yt,t.leafIndex,1,[e]])}},gr=class{key;right;indexDelta;constructor(t,e,r){this.key=t,this.right=e,this.indexDelta=r}};function co(n,t){return{header:n.createBlockHeader(ne),entries:t}}function fo(n,t,e){return{header:n.createBlockHeader(xn),partitions:t,nodes:e}}var gn=class{key;inclusive;constructor(t,e=!0){this.key=t,this.inclusive=e}},wn=class{first;last;isAscending;constructor(t,e,r=!0){this.first=t,this.last=e,this.isAscending=r}};var bn=class extends jt{};var vt=class n{node;index;constructor(t,e){this.node=t,this.index=e}clone(){return new n(this.node,this.index)}},se=class n{branches;leafNode;leafIndex;on;version;constructor(t,e,r,s,o){this.branches=t,this.leafNode=e,this.leafIndex=r,this.on=s,this.version=o}isEqual(t){return this.leafNode===t.leafNode&&this.leafIndex===t.leafIndex&&this.on===t.on&&this.version===t.version}clone(){return new n(this.branches.map(t=>t.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var oe=st("entries"),lo=st("priorId"),En=st("nextId"),In=gt("CHD","ChainDataBlock"),Bn=st("headId"),wr=st("tailId"),uo=gt("CHH","ChainHeaderBlock");var Sn=32,we=class n{store;id;options;constructor(t,e,r){this.store=t,this.id=e,this.options=r}static async create(t,e){let r=n.createTailBlock(t,e),s={...e?.createHeaderBlock?.(e?.newId)??{header:t.createBlockHeader(uo,e?.newId)},headId:r.header.id,tailId:r.header.id};return t.insert(s),t.insert(r),new n(t,s.header.id,e)}static createTailBlock(t,e){return{...e?.createDataBlock?.()??{header:t.createBlockHeader(In)},entries:[],priorId:void 0,nextId:void 0}}static async open(t,e,r){let s=await t.tryGet(e);if(!s)return;let o=s;if(!Object.hasOwn(o,"headId")||!Object.hasOwn(o,"tailId")){let i=n.createTailBlock(t,r);t.insert(i),_(t,s,[Bn,0,0,i.header.id]),_(t,s,[wr,0,0,i.header.id])}return new n(t,e,r)}async add(...t){let e=await this.getTail();if(!e)throw new Error("Cannot add to non-existent chain");let{headerBlock:r,block:s}=e,o=s,i=new Dt(this.store),c=t.slice(0,Sn-o.entries.length);for(c.length>0&&(_(i,o,[oe,o.entries.length,0,c]),t=t.slice(c.length));t.length>0;){let a={...this.options?.createDataBlock?.()??{header:this.store.createBlockHeader(In)},entries:t.splice(0,Math.min(Sn,t.length)),priorId:o.header.id,nextId:void 0};await this.options?.newBlock?.(a,s),i.insert(a),_(i,o,[En,0,0,a.header.id]),o=a}return o!==s&&_(i,r,[wr,0,0,o.header.id]),i.commit(),{headerBlock:r,block:o,index:o.entries.length-1}}updateAt(t,e){if(!ho(t))throw new Error("Invalid path");let{index:r,block:s}=t;_(this.store,s,[oe,r,1,[e]])}async pop(t=1){if(t<=0)return[];let e=await this.getTail();if(!e)return[];let{headerBlock:r,block:s}=e,o=s,i=[],c=new Dt(this.store);for(;t>0;)if(o.entries.length>t){let a=o.entries.slice(-t);i.unshift(...a),_(c,o,[oe,o.entries.length-t,t,[]]);break}else if(i.unshift(...o.entries),t-=o.entries.length,o.priorId)c.delete(o.header.id),o=await c.tryGet(o.priorId),_(c,o,[En,0,0,void 0]);else{_(c,o,[oe,0,o.entries.length,[]]);break}return o!==s&&_(c,r,[wr,0,0,o.header.id]),c.commit(),i}async dequeue(t=1){if(t<=0)return[];let e=new Dt(this.store),r=await this.getHead();if(!r)return[];let{headerBlock:s,block:o}=r,i=o,c=[];for(;t>0;)if(i.entries.length>t){c.push(...i.entries.slice(0,t)),_(e,i,[oe,0,t,[]]);break}else if(c.push(...i.entries),t-=i.entries.length,i.nextId)e.delete(i.header.id),i=await e.tryGet(i.nextId),_(e,i,[lo,0,0,void 0]);else{_(e,i,[oe,0,i.entries.length,[]]);break}return i!==o&&_(e,s,[Bn,0,0,i.header.id]),e.commit(),c}async*select(t,e=!0){let r=t??(e?await this.getHead():await this.getTail());if(!r)return;let s=r.block,o=r.index;if(e)for(;s;){for(;o<s.entries.length;++o)yield{headerBlock:r.headerBlock,block:s,index:o};s=s.nextId?await this.store.tryGet(s.nextId):void 0,o=0}else for(;s;){for(;o>=0;--o)yield{headerBlock:r.headerBlock,block:s,index:o};s=s.priorId?await this.store.tryGet(s.priorId):void 0,o=(s?.entries.length??0)-1}}async next(t){let{headerBlock:e,block:r,index:s}=t;return s<r.entries.length-1||!r.nextId?{headerBlock:e,block:r,index:s+1}:{headerBlock:e,block:await this.store.tryGet(r.nextId),index:0}}async prev(t){let{headerBlock:e,block:r,index:s}=t;if(s>0||!r.priorId)return{headerBlock:e,block:r,index:s-1};let o=await this.store.tryGet(r.priorId);return{headerBlock:e,block:o,index:o.entries.length-1}}async getTail(t){let e=t??await this.getHeader(),r=e?await this.store.tryGet(e.tailId):void 0;for(;r?.nextId;)r=await this.store.tryGet(r.nextId);return r?{headerBlock:e,block:r,index:r.entries.length-1}:void 0}async getHead(t){let e=t??await this.getHeader(),r=e?await this.store.tryGet(e.headId):void 0;for(;r?.priorId;)r=await this.store.tryGet(r.priorId);return r?{headerBlock:e,block:r,index:0}:void 0}async getHeader(){return await this.store.tryGet(this.id)}};function ho(n){return n.block.entries.length>n.index&&n.index>=0}function ie(n){return n.block.entries[n.index]}var Fe=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},br=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var po={get(n=globalThis){let t=n.crypto;if(t?.subtle==null)throw new br("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Er=po;var kt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Ir=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Br=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Cn={};ct(Cn,{base58btc:()=>Y,base58flickr:()=>Ca});var ql=new Uint8Array(0);function mo(n,t){if(n===t)return!0;if(n.byteLength!==t.byteLength)return!1;for(let e=0;e<n.byteLength;e++)if(n[e]!==t[e])return!1;return!0}function Rt(n){if(n instanceof Uint8Array&&n.constructor.name==="Uint8Array")return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);throw new Error("Unknown type, must be binary type")}function yo(n){return new TextEncoder().encode(n)}function xo(n){return new TextDecoder().decode(n)}function Ba(n,t){if(n.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),r=0;r<e.length;r++)e[r]=255;for(var s=0;s<n.length;s++){var o=n.charAt(s),i=o.charCodeAt(0);if(e[i]!==255)throw new TypeError(o+" is ambiguous");e[i]=s}var c=n.length,a=n.charAt(0),f=Math.log(c)/Math.log(256),u=Math.log(256)/Math.log(c);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var I=0,b=0,x=0,S=h.length;x!==S&&h[x]===0;)x++,I++;for(var w=(S-x)*u+1>>>0,v=new Uint8Array(w);x!==S;){for(var N=h[x],K=0,M=w-1;(N!==0||K<b)&&M!==-1;M--,K++)N+=256*v[M]>>>0,v[M]=N%c>>>0,N=N/c>>>0;if(N!==0)throw new Error("Non-zero carry");b=K,x++}for(var B=w-b;B!==w&&v[B]===0;)B++;for(var E=a.repeat(I);B<w;++B)E+=n.charAt(v[B]);return E}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var I=0;if(h[I]!==" "){for(var b=0,x=0;h[I]===a;)b++,I++;for(var S=(h.length-I)*f+1>>>0,w=new Uint8Array(S);h[I];){var v=e[h.charCodeAt(I)];if(v===255)return;for(var N=0,K=S-1;(v!==0||N<x)&&K!==-1;K--,N++)v+=c*w[K]>>>0,w[K]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");x=N,I++}if(h[I]!==" "){for(var M=S-x;M!==S&&w[M]===0;)M++;for(var B=new Uint8Array(b+(S-M)),E=b;M!==S;)B[E++]=w[M++];return B}}}function p(h){var I=d(h);if(I)return I;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:p}}var Sa=Ba,Aa=Sa,wo=Aa;var An=class{name;prefix;baseEncode;constructor(t,e,r){this.name=t,this.prefix=e,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},vn=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,r){this.name=t,this.prefix=e;let s=e.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return bo(this,t)}},kn=class{decoders;constructor(t){this.decoders=t}or(t){return bo(this,t)}decode(t){let e=t[0],r=this.decoders[e];if(r!=null)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function bo(n,t){return new kn({...n.decoders??{[n.prefix]:n},...t.decoders??{[t.prefix]:t}})}var Tn=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,r,s){this.name=t,this.prefix=e,this.baseEncode=r,this.baseDecode=s,this.encoder=new An(t,e,r),this.decoder=new vn(t,e,s)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function be({name:n,prefix:t,encode:e,decode:r}){return new Tn(n,t,e,r)}function Gt({name:n,prefix:t,alphabet:e}){let{encode:r,decode:s}=wo(e,n);return be({prefix:t,name:n,encode:r,decode:o=>Rt(s(o))})}function va(n,t,e,r){let s=n.length;for(;n[s-1]==="=";)--s;let o=new Uint8Array(s*e/8|0),i=0,c=0,a=0;for(let f=0;f<s;++f){let u=t[n[f]];if(u===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<e|u,i+=e,i>=8&&(i-=8,o[a++]=255&c>>i)}if(i>=e||(255&c<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return o}function ka(n,t,e){let r=t[t.length-1]==="=",s=(1<<e)-1,o="",i=0,c=0;for(let a=0;a<n.length;++a)for(c=c<<8|n[a],i+=8;i>e;)i-=e,o+=t[s&c>>i];if(i!==0&&(o+=t[s&c<<e-i]),r)for(;(o.length*e&7)!==0;)o+="=";return o}function Ta(n){let t={};for(let e=0;e<n.length;++e)t[n[e]]=e;return t}function Z({name:n,prefix:t,bitsPerChar:e,alphabet:r}){let s=Ta(r);return be({prefix:t,name:n,encode(o){return ka(o,r,e)},decode(o){return va(o,s,e,n)}})}var Y=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ca=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ln={};ct(Ln,{base32:()=>Ee,base32hex:()=>_a,base32hexpad:()=>Oa,base32hexpadupper:()=>Pa,base32hexupper:()=>Na,base32pad:()=>Da,base32padupper:()=>Ra,base32upper:()=>La,base32z:()=>Ua});var Ee=Z({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),La=Z({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Da=Z({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ra=Z({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_a=Z({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Na=Z({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Oa=Z({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pa=Z({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ua=Z({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Dn={};ct(Dn,{base36:()=>$e,base36upper:()=>Ka});var $e=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ka=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ma=Bo,Eo=128,Ha=127,qa=~Ha,Va=Math.pow(2,31);function Bo(n,t,e){t=t||[],e=e||0;for(var r=e;n>=Va;)t[e++]=n&255|Eo,n/=128;for(;n&qa;)t[e++]=n&255|Eo,n>>>=7;return t[e]=n|0,Bo.bytes=e-r+1,t}var Fa=Rn,$a=128,Io=127;function Rn(n,r){var e=0,r=r||0,s=0,o=r,i,c=n.length;do{if(o>=c)throw Rn.bytes=0,new RangeError("Could not decode varint");i=n[o++],e+=s<28?(i&Io)<<s:(i&Io)*Math.pow(2,s),s+=7}while(i>=$a);return Rn.bytes=o-r,e}var ja=Math.pow(2,7),Ga=Math.pow(2,14),Za=Math.pow(2,21),za=Math.pow(2,28),Ya=Math.pow(2,35),Xa=Math.pow(2,42),Wa=Math.pow(2,49),Ja=Math.pow(2,56),Qa=Math.pow(2,63),tc=function(n){return n<ja?1:n<Ga?2:n<Za?3:n<za?4:n<Ya?5:n<Xa?6:n<Wa?7:n<Ja?8:n<Qa?9:10},ec={encode:Ma,decode:Fa,encodingLength:tc},rc=ec,je=rc;function Ge(n,t=0){return[je.decode(n,t),je.decode.bytes]}function Ie(n,t,e=0){return je.encode(n,t,e),t}function Be(n){return je.encodingLength(n)}function Ae(n,t){let e=t.byteLength,r=Be(n),s=r+Be(e),o=new Uint8Array(s+e);return Ie(n,o,0),Ie(e,o,r),o.set(t,s),new Se(n,e,t,o)}function Ze(n){let t=Rt(n),[e,r]=Ge(t),[s,o]=Ge(t.subarray(r)),i=t.subarray(r+o);if(i.byteLength!==s)throw new Error("Incorrect length");return new Se(e,s,i,t)}function So(n,t){if(n===t)return!0;{let e=t;return n.code===e.code&&n.size===e.size&&e.bytes instanceof Uint8Array&&mo(n.bytes,e.bytes)}}var Se=class{code;size;digest;bytes;constructor(t,e,r,s){this.code=t,this.size=e,this.digest=r,this.bytes=s}};function Ao(n,t){let{bytes:e,version:r}=n;switch(r){case 0:return sc(e,_n(n),t??Y.encoder);default:return oc(e,_n(n),t??Ee.encoder)}}var vo=new WeakMap;function _n(n){let t=vo.get(n);if(t==null){let e=new Map;return vo.set(n,e),e}return t}var ot=class n{code;version;multihash;bytes;"/";constructor(t,e,r,s){this.code=e,this.version=t,this.multihash=r,this.bytes=s,this["/"]=s}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:t,multihash:e}=this;if(t!==ze)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==ic)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return n.createV0(e)}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:t,digest:e}=this.multihash,r=Ae(t,e);return n.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(t){return n.equals(this,t)}static equals(t,e){let r=e;return r!=null&&t.code===r.code&&t.version===r.version&&So(t.multihash,r.multihash)}toString(t){return Ao(this,t)}toJSON(){return{"/":Ao(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof n)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:r,code:s,multihash:o,bytes:i}=e;return new n(r,s,o,i??ko(r,s,o.bytes))}else if(e[ac]===!0){let{version:r,multihash:s,code:o}=e,i=Ze(s);return n.create(r,o,i)}else return null}static create(t,e,r){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==ze)throw new Error(`Version 0 CID must use dag-pb (code: ${ze}) block encoding`);return new n(t,e,r,r.bytes)}case 1:{let s=ko(t,e,r.bytes);return new n(t,e,r,s)}default:throw new Error("Invalid version")}}static createV0(t){return n.create(0,ze,t)}static createV1(t,e){return n.create(1,t,e)}static decode(t){let[e,r]=n.decodeFirst(t);if(r.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=n.inspectBytes(t),r=e.size-e.multihashSize,s=Rt(t.subarray(r,r+e.multihashSize));if(s.byteLength!==e.multihashSize)throw new Error("Incorrect length");let o=s.subarray(e.multihashSize-e.digestSize),i=new Se(e.multihashCode,e.digestSize,o,s);return[e.version===0?n.createV0(i):n.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,r=()=>{let[l,d]=Ge(t.subarray(e));return e+=d,l},s=r(),o=ze;if(s===18?(s=0,e=0):o=r(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let i=e,c=r(),a=r(),f=e+a,u=f-i;return{version:s,codec:o,multihashCode:c,digestSize:a,multihashSize:u,size:f}}static parse(t,e){let[r,s]=nc(t,e),o=n.decode(s);if(o.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return _n(o).set(r,t),o}};function nc(n,t){switch(n[0]){case"Q":{let e=t??Y;return[Y.prefix,e.decode(`${Y.prefix}${n}`)]}case Y.prefix:{let e=t??Y;return[Y.prefix,e.decode(n)]}case Ee.prefix:{let e=t??Ee;return[Ee.prefix,e.decode(n)]}case $e.prefix:{let e=t??$e;return[$e.prefix,e.decode(n)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[n[0],t.decode(n)]}}}function sc(n,t,e){let{prefix:r}=e;if(r!==Y.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let s=t.get(r);if(s==null){let o=e.encode(n).slice(1);return t.set(r,o),o}else return s}function oc(n,t,e){let{prefix:r}=e,s=t.get(r);if(s==null){let o=e.encode(n);return t.set(r,o),o}else return s}var ze=112,ic=18;function ko(n,t,e){let r=Be(n),s=r+Be(t),o=new Uint8Array(s+e.byteLength);return Ie(n,o,0),Ie(t,o,r),o.set(e,s),o}var ac=Symbol.for("@ipld/js-cid/CID");var Nn={};ct(Nn,{identity:()=>bt});var To=0,cc="identity",Co=Rt;function fc(n,t){if(t?.truncate!=null&&t.truncate!==n.byteLength){if(t.truncate<0||t.truncate>n.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${n.byteLength}`);n=n.subarray(0,t.truncate)}return Ae(To,Co(n))}var bt={code:To,name:cc,encode:Co,digest:fc};function Et(n,t){if(n===t)return!0;if(n.byteLength!==t.byteLength)return!1;for(let e=0;e<n.byteLength;e++)if(n[e]!==t[e])return!1;return!0}function _t(n=0){return new Uint8Array(n)}function ut(n=0){return new Uint8Array(n)}function Ar(n,t){t==null&&(t=n.reduce((s,o)=>s+o.length,0));let e=ut(t),r=0;for(let s of n)e.set(s,r),r+=s.length;return e}var Do=Symbol.for("@achingbrain/uint8arraylist");function Lo(n,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let r of n){let s=e+r.byteLength;if(t<s)return{buf:r,index:t-e};e=s}throw new RangeError("index is out of bounds")}function vr(n){return!!n?.[Do]}var dt=class n{bufs;length;[Do]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let r of t)if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.push(r);else if(vr(r))e+=r.byteLength,this.bufs.push(...r.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let r of t.reverse())if(r instanceof Uint8Array)e+=r.byteLength,this.bufs.unshift(r);else if(vr(r))e+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Lo(this.bufs,t);return e.buf[e.index]}set(t,e){let r=Lo(this.bufs,t);r.buf[r.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let r=0;r<t.length;r++)this.set(e+r,t[r]);else if(vr(t))for(let r=0;r<t.length;r++)this.set(e+r,t.get(r));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:r,length:s}=this._subList(t,e);return Ar(r,s)}subarray(t,e){let{bufs:r,length:s}=this._subList(t,e);return r.length===1?r[0]:Ar(r,s)}sublist(t,e){let{bufs:r,length:s}=this._subList(t,e),o=new n;return o.length=s,o.bufs=[...r],o}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let r=[],s=0;for(let o=0;o<this.bufs.length;o++){let i=this.bufs[o],c=s,a=c+i.byteLength;if(s=a,t>=a)continue;let f=t>=c&&t<a,u=e>c&&e<=a;if(f&&u){if(t===c&&e===a){r.push(i);break}let l=t-c;r.push(i.subarray(l,l+(e-t)));break}if(f){if(t===0){r.push(i);continue}r.push(i.subarray(t-c));continue}if(u){if(e===a){r.push(i);break}r.push(i.subarray(0,e-c));break}r.push(i)}return{bufs:r,length:e-t}}indexOf(t,e=0){if(!vr(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let s=r.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let o=256,i=new Int32Array(o);for(let l=0;l<o;l++)i[l]=-1;for(let l=0;l<s;l++)i[r[l]]=l;let c=i,a=this.byteLength-r.byteLength,f=r.byteLength-1,u;for(let l=e;l<=a;l+=u){u=0;for(let d=f;d>=0;d--){let p=this.get(l+d);if(r[d]!==p){u=Math.max(1,d-c[p]);break}}if(u===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let r=ut(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,e),this.write(r,t)}getInt16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,e)}setInt16(t,e,r){let s=_t(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,e,r),this.write(s,t)}getInt32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,e)}setInt32(t,e,r){let s=_t(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,e,r),this.write(s,t)}getBigInt64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,e)}setBigInt64(t,e,r){let s=_t(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,e,r),this.write(s,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let r=ut(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,e),this.write(r,t)}getUint16(t,e){let r=this.subarray(t,t+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,e)}setUint16(t,e,r){let s=_t(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,e,r),this.write(s,t)}getUint32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,e)}setUint32(t,e,r){let s=_t(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,e,r),this.write(s,t)}getBigUint64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,e)}setBigUint64(t,e,r){let s=_t(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,e,r),this.write(s,t)}getFloat32(t,e){let r=this.subarray(t,t+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,e)}setFloat32(t,e,r){let s=_t(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,e,r),this.write(s,t)}getFloat64(t,e){let r=this.subarray(t,t+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,e)}setFloat64(t,e,r){let s=_t(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,e,r),this.write(s,t)}equals(t){if(t==null||!(t instanceof n)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let r=new n;return r.bufs=t,e==null&&(e=t.reduce((s,o)=>s+o.byteLength,0)),r.length=e,r}};var On={};ct(On,{base10:()=>lc});var lc=Gt({prefix:"9",name:"base10",alphabet:"0123456789"});var Pn={};ct(Pn,{base16:()=>uc,base16upper:()=>dc});var uc=Z({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),dc=Z({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Un={};ct(Un,{base2:()=>hc});var hc=Z({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Kn={};ct(Kn,{base256emoji:()=>gc});var Ro=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}"),pc=Ro.reduce((n,t,e)=>(n[e]=t,n),[]),mc=Ro.reduce((n,t,e)=>{let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);return n[r]=e,n},[]);function yc(n){return n.reduce((t,e)=>(t+=pc[e],t),"")}function xc(n){let t=[];for(let e of n){let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);let s=mc[r];if(s==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(s)}return new Uint8Array(t)}var gc=be({prefix:"\u{1F680}",name:"base256emoji",encode:yc,decode:xc});var Mn={};ct(Mn,{base64:()=>wc,base64pad:()=>bc,base64url:()=>Ec,base64urlpad:()=>Ic});var wc=Z({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),bc=Z({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ec=Z({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ic=Z({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Hn={};ct(Hn,{base8:()=>Bc});var Bc=Z({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var qn={};ct(qn,{identity:()=>Sc});var Sc=be({prefix:"\0",name:"identity",encode:n=>xo(n),decode:n=>yo(n)});var Su=new TextEncoder,Au=new TextDecoder;var $n={};ct($n,{sha256:()=>Nt,sha512:()=>Tc});var kc=20;function Fn({name:n,code:t,encode:e,minDigestLength:r,maxDigestLength:s}){return new Vn(n,t,e,r,s)}var Vn=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,r,s,o){this.name=t,this.code=e,this.encode=r,this.minDigestLength=s??kc,this.maxDigestLength=o}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let r=this.encode(t);return r instanceof Uint8Array?_o(r,this.code,e?.truncate):r.then(s=>_o(s,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function _o(n,t,e){if(e!=null&&e!==n.byteLength){if(e>n.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${n.byteLength}`);n=n.subarray(0,e)}return Ae(t,n)}function Oo(n){return async t=>new Uint8Array(await crypto.subtle.digest(n,t))}var Nt=Fn({name:"sha2-256",code:18,encode:Oo("SHA-256")}),Tc=Fn({name:"sha2-512",code:19,encode:Oo("SHA-512")});var jn={...qn,...Un,...Hn,...On,...Pn,...Ln,...Dn,...Cn,...Mn,...Kn},Uu={...$n,...Nn};function Uo(n,t,e,r){return{name:n,prefix:t,encoder:{name:n,prefix:t,encode:e},decoder:{decode:r}}}var Po=Uo("utf8","u",n=>"u"+new TextDecoder("utf8").decode(n),n=>new TextEncoder().encode(n.substring(1))),Gn=Uo("ascii","a",n=>{let t="a";for(let e=0;e<n.length;e++)t+=String.fromCharCode(n[e]);return t},n=>{n=n.substring(1);let t=ut(n.length);for(let e=0;e<n.length;e++)t[e]=n.charCodeAt(e);return t}),Cc={utf8:Po,"utf-8":Po,hex:jn.base16,latin1:Gn,ascii:Gn,binary:Gn,...jn},kr=Cc;function Zt(n,t="utf8"){let e=kr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${n}`)}function X(n,t="utf8"){let e=kr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(n).substring(1)}var Lc=parseInt("11111",2),Zn=parseInt("10000000",2),Dc=parseInt("01111111",2),Ko={0:Ye,1:Ye,2:Rc,3:Oc,4:Pc,5:Nc,6:_c,16:Ye,22:Ye,48:Ye};function zn(n,t={offset:0}){let e=n[t.offset]&Lc;if(t.offset++,Ko[e]!=null)return Ko[e](n,t);throw new Error("No decoder for tag "+e)}function Xe(n,t){let e=0;if((n[t.offset]&Zn)===Zn){let r=n[t.offset]&Dc,s="0x";t.offset++;for(let o=0;o<r;o++,t.offset++)s+=n[t.offset].toString(16).padStart(2,"0");e=parseInt(s,16)}else e=n[t.offset],t.offset++;return e}function Ye(n,t){Xe(n,t);let e=[];for(;!(t.offset>=n.byteLength);){let r=zn(n,t);if(r===null)break;e.push(r)}return e}function Rc(n,t){let e=Xe(n,t),r=t.offset,s=t.offset+e,o=[];for(let i=r;i<s;i++)i===r&&n[i]===0||o.push(n[i]);return t.offset+=e,Uint8Array.from(o)}function _c(n,t){let e=Xe(n,t),r=t.offset+e,s=n[t.offset];t.offset++;let o=0,i=0;s<40?(o=0,i=s):s<80?(o=1,i=s-40):(o=2,i=s-80);let c=`${o}.${i}`,a=[];for(;t.offset<r;){let f=n[t.offset];if(t.offset++,a.push(f&127),f<128){a.reverse();let u=0;for(let l=0;l<a.length;l++)u+=a[l]<<l*7;c+=`.${u}`,a=[]}}return c}function Nc(n,t){return t.offset++,null}function Oc(n,t){let e=Xe(n,t),r=n[t.offset];t.offset++;let s=n.subarray(t.offset,t.offset+e-1);if(t.offset+=e,r!==0)throw new Error("Unused bits in bit string is unimplemented");return s}function Pc(n,t){let e=Xe(n,t),r=n.subarray(t.offset,t.offset+e);return t.offset+=e,r}function Uc(n){let t=n.toString(16);t.length%2===1&&(t="0"+t);let e=new dt;for(let r=0;r<t.length;r+=2)e.append(Uint8Array.from([parseInt(`${t[r]}${t[r+1]}`,16)]));return e}function Yn(n){if(n.byteLength<128)return Uint8Array.from([n.byteLength]);let t=Uc(n.byteLength);return new dt(Uint8Array.from([t.byteLength|Zn]),t)}function Mo(n){let t=new dt,e=128;return(n.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(n),new dt(Uint8Array.from([2]),Yn(t),t)}function Ho(n){let t=Uint8Array.from([0]),e=new dt(t,n);return new dt(Uint8Array.from([3]),Yn(e),e)}function Tr(n,t=48){let e=new dt;for(let r of n)e.append(r);return new dt(Uint8Array.from([t]),Yn(e),e)}async function qo(n,t,e,r){let s=await crypto.subtle.importKey("jwk",n,{name:"ECDSA",namedCurve:n.crv??"P-256"},!1,["verify"]);r?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},s,t,e.subarray());return r?.signal?.throwIfAborted(),o}var Kc=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Mc=Uint8Array.from([6,5,43,129,4,0,34]),Hc=Uint8Array.from([6,5,43,129,4,0,35]),qc={ext:!0,kty:"EC",crv:"P-256"},Vc={ext:!0,kty:"EC",crv:"P-384"},Fc={ext:!0,kty:"EC",crv:"P-521"},Xn=32,Wn=48,Jn=66;function Vo(n){let t=zn(n);return Fo(t)}function Fo(n){let t=n[1][1][0],e=1,r,s;if(t.byteLength===Xn*2+1)return r=X(t.subarray(e,e+Xn),"base64url"),s=X(t.subarray(e+Xn),"base64url"),new ke({...qc,key_ops:["verify"],x:r,y:s});if(t.byteLength===Wn*2+1)return r=X(t.subarray(e,e+Wn),"base64url"),s=X(t.subarray(e+Wn),"base64url"),new ke({...Vc,key_ops:["verify"],x:r,y:s});if(t.byteLength===Jn*2+1)return r=X(t.subarray(e,e+Jn),"base64url"),s=X(t.subarray(e+Jn),"base64url"),new ke({...Fc,key_ops:["verify"],x:r,y:s});throw new kt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function $o(n){return Tr([Mo(Uint8Array.from([1])),Tr([$c(n.crv)],160),Tr([Ho(new dt(Uint8Array.from([4]),Zt(n.x??"","base64url"),Zt(n.y??"","base64url")))],161)]).subarray()}function $c(n){if(n==="P-256")return Kc;if(n==="P-384")return Mc;if(n==="P-521")return Hc;throw new kt(`Invalid curve ${n}`)}var ke=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=$o(this.jwk)),this._raw}toMultihash(){return bt.digest(Te(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,e,r){return qo(this.jwk,e,t,r)}};function ae(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function Tt(n,t=""){if(!Number.isSafeInteger(n)||n<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${n}`)}}function U(n,t,e=""){let r=ae(n),s=n?.length,o=t!==void 0;if(!r||o&&s!==t){let i=e&&`"${e}" `,c=o?` of length ${t}`:"",a=r?`length=${s}`:`type=${typeof n}`;throw new Error(i+"expected Uint8Array"+c+", got "+a)}return n}function Cr(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Tt(n.outputLen),Tt(n.blockLen)}function Ce(n,t=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(t&&n.finished)throw new Error("Hash#digest() has already been called")}function Go(n,t){U(n,void 0,"digestInto() output");let e=t.outputLen;if(n.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Pt(...n){for(let t=0;t<n.length;t++)n[t].fill(0)}function Lr(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function It(n,t){return n<<32-t|n>>>t}var Zo=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jc=Array.from({length:256},(n,t)=>t.toString(16).padStart(2,"0"));function Ut(n){if(U(n),Zo)return n.toHex();let t="";for(let e=0;e<n.length;e++)t+=jc[n[e]];return t}var Ot={_0:48,_9:57,A:65,F:70,a:97,f:102};function jo(n){if(n>=Ot._0&&n<=Ot._9)return n-Ot._0;if(n>=Ot.A&&n<=Ot.F)return n-(Ot.A-10);if(n>=Ot.a&&n<=Ot.f)return n-(Ot.a-10)}function Kt(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(Zo)return Uint8Array.fromHex(n);let t=n.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let r=new Uint8Array(e);for(let s=0,o=0;s<e;s++,o+=2){let i=jo(n.charCodeAt(o)),c=jo(n.charCodeAt(o+1));if(i===void 0||c===void 0){let a=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}r[s]=i*16+c}return r}function ft(...n){let t=0;for(let r=0;r<n.length;r++){let s=n[r];U(s),t+=s.length}let e=new Uint8Array(t);for(let r=0,s=0;r<n.length;r++){let o=n[r];e.set(o,s),s+=o.length}return e}function Qn(n,t={}){let e=(s,o)=>n(o).update(s).digest(),r=n(void 0);return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=s=>n(s),Object.assign(e,t),Object.freeze(e)}function zt(n=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(n))}var ts=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function zo(n,t,e){return n&t^~n&e}function Yo(n,t,e){return n&t^n&e^t&e}var We=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,r,s){this.blockLen=t,this.outputLen=e,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(t),this.view=Lr(this.buffer)}update(t){Ce(this),U(t);let{view:e,buffer:r,blockLen:s}=this,o=t.length;for(let i=0;i<o;){let c=Math.min(s-this.pos,o-i);if(c===s){let a=Lr(t);for(;s<=o-i;i+=s)this.process(a,i);continue}r.set(t.subarray(i,i+c),this.pos),this.pos+=c,i+=c,this.pos===s&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Ce(this),Go(t,this),this.finished=!0;let{buffer:e,view:r,blockLen:s,isLE:o}=this,{pos:i}=this;e[i++]=128,Pt(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let l=i;l<s;l++)e[l]=0;r.setBigUint64(s-8,BigInt(this.length*8),o),this.process(r,0);let c=Lr(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=a/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<f;l++)c.setUint32(4*l,u[l],o)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let r=t.slice(0,e);return this.destroy(),r}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:r,length:s,finished:o,destroyed:i,pos:c}=this;return t.destroyed=i,t.finished=o,t.length=s,t.pos=c,s%e&&t.buffer.set(r),t}clone(){return this._cloneInto()}},Mt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var et=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Dr=BigInt(4294967295),Xo=BigInt(32);function Gc(n,t=!1){return t?{h:Number(n&Dr),l:Number(n>>Xo&Dr)}:{h:Number(n>>Xo&Dr)|0,l:Number(n&Dr)|0}}function Wo(n,t=!1){let e=n.length,r=new Uint32Array(e),s=new Uint32Array(e);for(let o=0;o<e;o++){let{h:i,l:c}=Gc(n[o],t);[r[o],s[o]]=[i,c]}return[r,s]}var es=(n,t,e)=>n>>>e,rs=(n,t,e)=>n<<32-e|t>>>e,ce=(n,t,e)=>n>>>e|t<<32-e,fe=(n,t,e)=>n<<32-e|t>>>e,Je=(n,t,e)=>n<<64-e|t>>>e-32,Qe=(n,t,e)=>n>>>e-32|t<<64-e;function Ct(n,t,e,r){let s=(t>>>0)+(r>>>0);return{h:n+e+(s/2**32|0)|0,l:s|0}}var Jo=(n,t,e)=>(n>>>0)+(t>>>0)+(e>>>0),Qo=(n,t,e,r)=>t+e+r+(n/2**32|0)|0,ti=(n,t,e,r)=>(n>>>0)+(t>>>0)+(e>>>0)+(r>>>0),ei=(n,t,e,r,s)=>t+e+r+s+(n/2**32|0)|0,ri=(n,t,e,r,s)=>(n>>>0)+(t>>>0)+(e>>>0)+(r>>>0)+(s>>>0),ni=(n,t,e,r,s,o)=>t+e+r+s+o+(n/2**32|0)|0;var zc=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Yt=new Uint32Array(64),ns=class extends We{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:r,D:s,E:o,F:i,G:c,H:a}=this;return[t,e,r,s,o,i,c,a]}set(t,e,r,s,o,i,c,a){this.A=t|0,this.B=e|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=c|0,this.H=a|0}process(t,e){for(let l=0;l<16;l++,e+=4)Yt[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=Yt[l-15],p=Yt[l-2],h=It(d,7)^It(d,18)^d>>>3,I=It(p,17)^It(p,19)^p>>>10;Yt[l]=I+Yt[l-7]+h+Yt[l-16]|0}let{A:r,B:s,C:o,D:i,E:c,F:a,G:f,H:u}=this;for(let l=0;l<64;l++){let d=It(c,6)^It(c,11)^It(c,25),p=u+d+zo(c,a,f)+zc[l]+Yt[l]|0,I=(It(r,2)^It(r,13)^It(r,22))+Yo(r,s,o)|0;u=f,f=a,a=c,c=i+p|0,i=o,o=s,s=r,r=p+I|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,c=c+this.E|0,a=a+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(r,s,o,i,c,a,f,u)}roundClean(){Pt(Yt)}destroy(){this.set(0,0,0,0,0,0,0,0),Pt(this.buffer)}},ss=class extends ns{A=Mt[0]|0;B=Mt[1]|0;C=Mt[2]|0;D=Mt[3]|0;E=Mt[4]|0;F=Mt[5]|0;G=Mt[6]|0;H=Mt[7]|0;constructor(){super(32)}};var si=Wo(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),Yc=si[0],Xc=si[1],Xt=new Uint32Array(80),Wt=new Uint32Array(80),os=class extends We{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:r,Bl:s,Ch:o,Cl:i,Dh:c,Dl:a,Eh:f,El:u,Fh:l,Fl:d,Gh:p,Gl:h,Hh:I,Hl:b}=this;return[t,e,r,s,o,i,c,a,f,u,l,d,p,h,I,b]}set(t,e,r,s,o,i,c,a,f,u,l,d,p,h,I,b){this.Ah=t|0,this.Al=e|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=c|0,this.Dl=a|0,this.Eh=f|0,this.El=u|0,this.Fh=l|0,this.Fl=d|0,this.Gh=p|0,this.Gl=h|0,this.Hh=I|0,this.Hl=b|0}process(t,e){for(let w=0;w<16;w++,e+=4)Xt[w]=t.getUint32(e),Wt[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let v=Xt[w-15]|0,N=Wt[w-15]|0,K=ce(v,N,1)^ce(v,N,8)^es(v,N,7),M=fe(v,N,1)^fe(v,N,8)^rs(v,N,7),B=Xt[w-2]|0,E=Wt[w-2]|0,O=ce(B,E,19)^Je(B,E,61)^es(B,E,6),H=fe(B,E,19)^Qe(B,E,61)^rs(B,E,6),L=ti(M,H,Wt[w-7],Wt[w-16]),y=ei(L,K,O,Xt[w-7],Xt[w-16]);Xt[w]=y|0,Wt[w]=L|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:c,Cl:a,Dh:f,Dl:u,Eh:l,El:d,Fh:p,Fl:h,Gh:I,Gl:b,Hh:x,Hl:S}=this;for(let w=0;w<80;w++){let v=ce(l,d,14)^ce(l,d,18)^Je(l,d,41),N=fe(l,d,14)^fe(l,d,18)^Qe(l,d,41),K=l&p^~l&I,M=d&h^~d&b,B=ri(S,N,M,Xc[w],Wt[w]),E=ni(B,x,v,K,Yc[w],Xt[w]),O=B|0,H=ce(r,s,28)^Je(r,s,34)^Je(r,s,39),L=fe(r,s,28)^Qe(r,s,34)^Qe(r,s,39),y=r&o^r&c^o&c,g=s&i^s&a^i&a;x=I|0,S=b|0,I=p|0,b=h|0,p=l|0,h=d|0,{h:l,l:d}=Ct(f|0,u|0,E|0,O|0),f=c|0,u=a|0,c=o|0,a=i|0,o=r|0,i=s|0;let m=Jo(O,L,g);r=Qo(m,E,H,y),s=m|0}({h:r,l:s}=Ct(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=Ct(this.Bh|0,this.Bl|0,o|0,i|0),{h:c,l:a}=Ct(this.Ch|0,this.Cl|0,c|0,a|0),{h:f,l:u}=Ct(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:d}=Ct(this.Eh|0,this.El|0,l|0,d|0),{h:p,l:h}=Ct(this.Fh|0,this.Fl|0,p|0,h|0),{h:I,l:b}=Ct(this.Gh|0,this.Gl|0,I|0,b|0),{h:x,l:S}=Ct(this.Hh|0,this.Hl|0,x|0,S|0),this.set(r,s,o,i,c,a,f,u,l,d,p,h,I,b,x,S)}roundClean(){Pt(Xt,Wt)}destroy(){Pt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},is=class extends os{Ah=et[0]|0;Al=et[1]|0;Bh=et[2]|0;Bl=et[3]|0;Ch=et[4]|0;Cl=et[5]|0;Dh=et[6]|0;Dl=et[7]|0;Eh=et[8]|0;El=et[9]|0;Fh=et[10]|0;Fl=et[11]|0;Gh=et[12]|0;Gl=et[13]|0;Hh=et[14]|0;Hl=et[15]|0;constructor(){super(64)}};var oi=Qn(()=>new ss,ts(1));var ii=Qn(()=>new is,ts(3));var cs=BigInt(0),as=BigInt(1);function Ht(n,t=""){if(typeof n!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof n)}return n}function ai(n){if(typeof n=="bigint"){if(!Rr(n))throw new Error("positive bigint expected, got "+n)}else Tt(n);return n}function tr(n){let t=ai(n).toString(16);return t.length&1?"0"+t:t}function ci(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?cs:BigInt("0x"+n)}function Le(n){return ci(Ut(n))}function le(n){return ci(Ut(Nr(U(n)).reverse()))}function _r(n,t){Tt(t),n=ai(n);let e=Kt(n.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function fs(n,t){return _r(n,t).reverse()}function Nr(n){return Uint8Array.from(n)}var Rr=n=>typeof n=="bigint"&&cs<=n;function Wc(n,t,e){return Rr(n)&&Rr(t)&&Rr(e)&&t<=n&&n<e}function er(n,t,e,r){if(!Wc(t,e,r))throw new Error("expected valid "+n+": "+e+" <= n < "+r+", got "+t)}function ls(n){let t;for(t=0;n>cs;n>>=as,t+=1);return t}var rr=n=>(as<<BigInt(n))-as;function fi(n,t,e){if(Tt(n,"hashLen"),Tt(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let r=b=>new Uint8Array(b),s=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),c=1e3,a=r(n),f=r(n),u=0,l=()=>{a.fill(1),f.fill(0),u=0},d=(...b)=>e(f,ft(a,...b)),p=(b=s)=>{f=d(o,b),a=d(),b.length!==0&&(f=d(i,b),a=d())},h=()=>{if(u++>=c)throw new Error("drbg: tried max amount of iterations");let b=0,x=[];for(;b<t;){a=d();let S=a.slice();x.push(S),b+=a.length}return ft(...x)};return(b,x)=>{l(),p(b);let S;for(;!(S=x(h()));)p();return l(),S}}function Jt(n,t={},e={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(o,i,c){let a=n[o];if(c&&a===void 0)return;let f=typeof a;if(f!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${f}`)}let s=(o,i)=>Object.entries(o).forEach(([c,a])=>r(c,a,i));s(t,!1),s(e,!0)}function De(n){let t=new WeakMap;return(e,...r)=>{let s=t.get(e);if(s!==void 0)return s;let o=n(e,...r);return t.set(e,o),o}}var it=BigInt(0),J=BigInt(1),ue=BigInt(2),di=BigInt(3),hi=BigInt(4),pi=BigInt(5),Jc=BigInt(7),mi=BigInt(8),Qc=BigInt(9),yi=BigInt(16);function z(n,t){let e=n%t;return e>=it?e:t+e}function F(n,t,e){let r=n;for(;t-- >it;)r*=r,r%=e;return r}function li(n,t){if(n===it)throw new Error("invert: expected non-zero number");if(t<=it)throw new Error("invert: expected positive modulus, got "+t);let e=z(n,t),r=t,s=it,o=J,i=J,c=it;for(;e!==it;){let f=r/e,u=r%e,l=s-i*f,d=o-c*f;r=e,e=u,s=i,o=c,i=l,c=d}if(r!==J)throw new Error("invert: does not exist");return z(s,t)}function ds(n,t,e){if(!n.eql(n.sqr(t),e))throw new Error("Cannot find square root")}function xi(n,t){let e=(n.ORDER+J)/hi,r=n.pow(t,e);return ds(n,r,t),r}function tf(n,t){let e=(n.ORDER-pi)/mi,r=n.mul(t,ue),s=n.pow(r,e),o=n.mul(t,s),i=n.mul(n.mul(o,ue),s),c=n.mul(o,n.sub(i,n.ONE));return ds(n,c,t),c}function ef(n){let t=Re(n),e=gi(n),r=e(t,t.neg(t.ONE)),s=e(t,r),o=e(t,t.neg(r)),i=(n+Jc)/yi;return(c,a)=>{let f=c.pow(a,i),u=c.mul(f,r),l=c.mul(f,s),d=c.mul(f,o),p=c.eql(c.sqr(u),a),h=c.eql(c.sqr(l),a);f=c.cmov(f,u,p),u=c.cmov(d,l,h);let I=c.eql(c.sqr(u),a),b=c.cmov(f,u,I);return ds(c,b,a),b}}function gi(n){if(n<di)throw new Error("sqrt is not defined for small field");let t=n-J,e=0;for(;t%ue===it;)t/=ue,e++;let r=ue,s=Re(n);for(;ui(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return xi;let o=s.pow(r,t),i=(t+J)/ue;return function(a,f){if(a.is0(f))return f;if(ui(a,f)!==1)throw new Error("Cannot find square root");let u=e,l=a.mul(a.ONE,o),d=a.pow(f,t),p=a.pow(f,i);for(;!a.eql(d,a.ONE);){if(a.is0(d))return a.ZERO;let h=1,I=a.sqr(d);for(;!a.eql(I,a.ONE);)if(h++,I=a.sqr(I),h===u)throw new Error("Cannot find square root");let b=J<<BigInt(u-h-1),x=a.pow(l,b);u=h,l=a.sqr(x),d=a.mul(d,l),p=a.mul(p,x)}return p}}function rf(n){return n%hi===di?xi:n%mi===pi?tf:n%yi===Qc?ef(n):gi(n)}var wi=(n,t)=>(z(n,t)&J)===J,nf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function hs(n){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=nf.reduce((r,s)=>(r[s]="function",r),t);return Jt(n,e),n}function sf(n,t,e){if(e<it)throw new Error("invalid exponent, negatives unsupported");if(e===it)return n.ONE;if(e===J)return t;let r=n.ONE,s=t;for(;e>it;)e&J&&(r=n.mul(r,s)),s=n.sqr(s),e>>=J;return r}function nr(n,t,e=!1){let r=new Array(t.length).fill(e?n.ZERO:void 0),s=t.reduce((i,c,a)=>n.is0(c)?i:(r[a]=i,n.mul(i,c)),n.ONE),o=n.inv(s);return t.reduceRight((i,c,a)=>n.is0(c)?i:(r[a]=n.mul(i,r[a]),n.mul(i,c)),o),r}function ui(n,t){let e=(n.ORDER-J)/ue,r=n.pow(t,e),s=n.eql(r,n.ONE),o=n.eql(r,n.ZERO),i=n.eql(r,n.neg(n.ONE));if(!s&&!o&&!i)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function of(n,t){t!==void 0&&Tt(t);let e=t!==void 0?t:n.toString(2).length,r=Math.ceil(e/8);return{nBitLength:e,nByteLength:r}}var us=class{ORDER;BITS;BYTES;isLE;ZERO=it;ONE=J;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=it)throw new Error("invalid field: expected ORDER > 0, got "+t);let r;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(r=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:s,nByteLength:o}=of(t,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=s,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return z(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return it<=t&&t<this.ORDER}is0(t){return t===it}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&J)===J}neg(t){return z(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return z(t*t,this.ORDER)}add(t,e){return z(t+e,this.ORDER)}sub(t,e){return z(t-e,this.ORDER)}mul(t,e){return z(t*e,this.ORDER)}pow(t,e){return sf(this,t,e)}div(t,e){return z(t*li(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return li(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=rf(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?fs(t,this.BYTES):_r(t,this.BYTES)}fromBytes(t,e=!1){U(t);let{_lengths:r,BYTES:s,isLE:o,ORDER:i,_mod:c}=this;if(r){if(!r.includes(t.length)||t.length>s)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+t.length);let f=new Uint8Array(s);f.set(t,o?0:f.length-t.length),t=f}if(t.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+t.length);let a=o?le(t):Le(t);if(c&&(a=z(a,i)),!e&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(t){return nr(this,t)}cmov(t,e,r){return r?e:t}};function Re(n,t={}){return new us(n,t)}function bi(n){if(typeof n!="bigint")throw new Error("field order must be bigint");let t=n.toString(2).length;return Math.ceil(t/8)}function ps(n){let t=bi(n);return t+Math.ceil(t/2)}function ms(n,t,e=!1){U(n);let r=n.length,s=bi(t),o=ps(t);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let i=e?le(n):Le(n),c=z(i,t-J)+J;return e?fs(c,s):_r(c,s)}var _e=BigInt(0),de=BigInt(1);function sr(n,t){let e=t.negate();return n?e:t}function he(n,t){let e=nr(n.Fp,t.map(r=>r.Z));return t.map((r,s)=>n.fromAffine(r.toAffine(e[s])))}function Si(n,t){if(!Number.isSafeInteger(n)||n<=0||n>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+n)}function ys(n,t){Si(n,t);let e=Math.ceil(t/n)+1,r=2**(n-1),s=2**n,o=rr(n),i=BigInt(n);return{windows:e,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function Ei(n,t,e){let{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=e,c=Number(n&s),a=n>>i;c>r&&(c-=o,a+=de);let f=t*r,u=f+Math.abs(c)-1,l=c===0,d=c<0,p=t%2!==0;return{nextN:a,offset:u,isZero:l,isNeg:d,isNegF:p,offsetF:f}}var xs=new WeakMap,Ai=new WeakMap;function gs(n){return Ai.get(n)||1}function Ii(n){if(n!==_e)throw new Error("invalid wNAF")}var Ne=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,r=this.ZERO){let s=t;for(;e>_e;)e&de&&(r=r.add(s)),s=s.double(),e>>=de;return r}precomputeWindow(t,e){let{windows:r,windowSize:s}=ys(e,this.bits),o=[],i=t,c=i;for(let a=0;a<r;a++){c=i,o.push(c);for(let f=1;f<s;f++)c=c.add(i),o.push(c);i=c.double()}return o}wNAF(t,e,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=ys(t,this.bits);for(let c=0;c<i.windows;c++){let{nextN:a,offset:f,isZero:u,isNeg:l,isNegF:d,offsetF:p}=Ei(r,c,i);r=a,u?o=o.add(sr(d,e[p])):s=s.add(sr(l,e[f]))}return Ii(r),{p:s,f:o}}wNAFUnsafe(t,e,r,s=this.ZERO){let o=ys(t,this.bits);for(let i=0;i<o.windows&&r!==_e;i++){let{nextN:c,offset:a,isZero:f,isNeg:u}=Ei(r,i,o);if(r=c,!f){let l=e[a];s=s.add(u?l.negate():l)}}return Ii(r),s}getPrecomputes(t,e,r){let s=xs.get(e);return s||(s=this.precomputeWindow(e,t),t!==1&&(typeof r=="function"&&(s=r(s)),xs.set(e,s))),s}cached(t,e,r){let s=gs(t);return this.wNAF(s,this.getPrecomputes(s,t,r),e)}unsafe(t,e,r,s){let o=gs(t);return o===1?this._unsafeLadder(t,e,s):this.wNAFUnsafe(o,this.getPrecomputes(o,t,r),e,s)}createCache(t,e){Si(e,this.bits),Ai.set(t,e),xs.delete(t)}hasCache(t){return gs(t)!==1}};function vi(n,t,e,r){let s=t,o=n.ZERO,i=n.ZERO;for(;e>_e||r>_e;)e&de&&(o=o.add(s)),r&de&&(i=i.add(s)),s=s.double(),e>>=de,r>>=de;return{p1:o,p2:i}}function Bi(n,t,e){if(t){if(t.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return hs(t),t}else return Re(n,{isLE:e})}function Or(n,t,e={},r){if(r===void 0&&(r=n==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${n} CURVE object`);for(let a of["p","n","h"]){let f=t[a];if(!(typeof f=="bigint"&&f>_e))throw new Error(`CURVE.${a} must be positive bigint`)}let s=Bi(t.p,e.Fp,r),o=Bi(t.n,e.Fn,r),c=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let a of c)if(!s.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:s,Fn:o}}function Pr(n,t){return function(r){let s=n(r);return{secretKey:s,publicKey:t(s)}}}var Qt=BigInt(0),Q=BigInt(1),ws=BigInt(2),af=BigInt(8);function cf(n,t,e,r){let s=n.sqr(e),o=n.sqr(r),i=n.add(n.mul(t.a,s),o),c=n.add(n.ONE,n.mul(t.d,n.mul(s,o)));return n.eql(i,c)}function ki(n,t={}){let e=Or("edwards",n,t,t.FpFnLE),{Fp:r,Fn:s}=e,o=e.CURVE,{h:i}=o;Jt(t,{},{uvRatio:"function"});let c=ws<<BigInt(s.BYTES*8)-Q,a=b=>r.create(b),f=t.uvRatio||((b,x)=>{try{return{isValid:!0,value:r.sqrt(r.div(b,x))}}catch{return{isValid:!1,value:Qt}}});if(!cf(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(b,x,S=!1){let w=S?Q:Qt;return er("coordinate "+b,x,w,c),x}function l(b){if(!(b instanceof h))throw new Error("EdwardsPoint expected")}let d=De((b,x)=>{let{X:S,Y:w,Z:v}=b,N=b.is0();x==null&&(x=N?af:r.inv(v));let K=a(S*x),M=a(w*x),B=r.mul(v,x);if(N)return{x:Qt,y:Q};if(B!==Q)throw new Error("invZ was invalid");return{x:K,y:M}}),p=De(b=>{let{a:x,d:S}=o;if(b.is0())throw new Error("bad point: ZERO");let{X:w,Y:v,Z:N,T:K}=b,M=a(w*w),B=a(v*v),E=a(N*N),O=a(E*E),H=a(M*x),L=a(E*a(H+B)),y=a(O+a(S*a(M*B)));if(L!==y)throw new Error("bad point: equation left != right (1)");let g=a(w*v),m=a(N*K);if(g!==m)throw new Error("bad point: equation left != right (2)");return!0});class h{static BASE=new h(o.Gx,o.Gy,Q,a(o.Gx*o.Gy));static ZERO=new h(Qt,Q,Q,Qt);static Fp=r;static Fn=s;X;Y;Z;T;constructor(x,S,w,v){this.X=u("x",x),this.Y=u("y",S),this.Z=u("z",w,!0),this.T=u("t",v),Object.freeze(this)}static CURVE(){return o}static fromAffine(x){if(x instanceof h)throw new Error("extended point not allowed");let{x:S,y:w}=x||{};return u("x",S),u("y",w),new h(S,w,Q,a(S*w))}static fromBytes(x,S=!1){let w=r.BYTES,{a:v,d:N}=o;x=Nr(U(x,w,"point")),Ht(S,"zip215");let K=Nr(x),M=x[w-1];K[w-1]=M&-129;let B=le(K),E=S?c:r.ORDER;er("point.y",B,Qt,E);let O=a(B*B),H=a(O-Q),L=a(N*O-v),{isValid:y,value:g}=f(H,L);if(!y)throw new Error("bad point: invalid y coordinate");let m=(g&Q)===Q,A=(M&128)!==0;if(!S&&g===Qt&&A)throw new Error("bad point: x=0 and x_0=1");return A!==m&&(g=a(-g)),h.fromAffine({x:g,y:B})}static fromHex(x,S=!1){return h.fromBytes(Kt(x),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,S=!0){return I.createCache(this,x),S||this.multiply(ws),this}assertValidity(){p(this)}equals(x){l(x);let{X:S,Y:w,Z:v}=this,{X:N,Y:K,Z:M}=x,B=a(S*M),E=a(N*v),O=a(w*M),H=a(K*v);return B===E&&O===H}is0(){return this.equals(h.ZERO)}negate(){return new h(a(-this.X),this.Y,this.Z,a(-this.T))}double(){let{a:x}=o,{X:S,Y:w,Z:v}=this,N=a(S*S),K=a(w*w),M=a(ws*a(v*v)),B=a(x*N),E=S+w,O=a(a(E*E)-N-K),H=B+K,L=H-M,y=B-K,g=a(O*L),m=a(H*y),A=a(O*y),k=a(L*H);return new h(g,m,k,A)}add(x){l(x);let{a:S,d:w}=o,{X:v,Y:N,Z:K,T:M}=this,{X:B,Y:E,Z:O,T:H}=x,L=a(v*B),y=a(N*E),g=a(M*w*H),m=a(K*O),A=a((v+N)*(B+E)-L-y),k=m-g,C=m+g,D=a(y-S*L),T=a(A*k),R=a(C*D),P=a(A*D),$=a(k*C);return new h(T,R,$,P)}subtract(x){return this.add(x.negate())}multiply(x){if(!s.isValidNot0(x))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:w}=I.cached(this,x,v=>he(h,v));return he(h,[S,w])[0]}multiplyUnsafe(x,S=h.ZERO){if(!s.isValid(x))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return x===Qt?h.ZERO:this.is0()||x===Q?this:I.unsafe(this,x,w=>he(h,w),S)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return I.unsafe(this,o.n).is0()}toAffine(x){return d(this,x)}clearCofactor(){return i===Q?this:this.multiplyUnsafe(i)}toBytes(){let{x,y:S}=this.toAffine(),w=r.toBytes(S);return w[w.length-1]|=x&Q?128:0,w}toHex(){return Ut(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let I=new Ne(h,s.BITS);return h.BASE.precompute(8),h}function Ti(n,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');Jt(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:r}=e,{BASE:s,Fp:o,Fn:i}=n,c=e.randomBytes||zt,a=e.adjustScalarBytes||(B=>B),f=e.domain||((B,E,O)=>{if(Ht(O,"phflag"),E.length||O)throw new Error("Contexts/pre-hash are not supported");return B});function u(B){return i.create(le(B))}function l(B){let E=w.secretKey;U(B,w.secretKey,"secretKey");let O=U(t(B),2*E,"hashedSecretKey"),H=a(O.slice(0,E)),L=O.slice(E,2*E),y=u(H);return{head:H,prefix:L,scalar:y}}function d(B){let{head:E,prefix:O,scalar:H}=l(B),L=s.multiply(H),y=L.toBytes();return{head:E,prefix:O,scalar:H,point:L,pointBytes:y}}function p(B){return d(B).pointBytes}function h(B=Uint8Array.of(),...E){let O=ft(...E);return u(t(f(O,U(B,void 0,"context"),!!r)))}function I(B,E,O={}){B=U(B,void 0,"message"),r&&(B=r(B));let{prefix:H,scalar:L,pointBytes:y}=d(E),g=h(O.context,H,B),m=s.multiply(g).toBytes(),A=h(O.context,m,y,B),k=i.create(g+A*L);if(!i.isValid(k))throw new Error("sign failed: invalid s");let C=ft(m,i.toBytes(k));return U(C,w.signature,"result")}let b={zip215:!0};function x(B,E,O,H=b){let{context:L,zip215:y}=H,g=w.signature;B=U(B,g,"signature"),E=U(E,void 0,"message"),O=U(O,w.publicKey,"publicKey"),y!==void 0&&Ht(y,"zip215"),r&&(E=r(E));let m=g/2,A=B.subarray(0,m),k=le(B.subarray(m,g)),C,D,T;try{C=n.fromBytes(O,y),D=n.fromBytes(A,y),T=s.multiplyUnsafe(k)}catch{return!1}if(!y&&C.isSmallOrder())return!1;let R=h(L,D.toBytes(),C.toBytes(),E);return D.add(C.multiplyUnsafe(R)).subtract(T).clearCofactor().is0()}let S=o.BYTES,w={secretKey:S,publicKey:S,signature:2*S,seed:S};function v(B=c(w.seed)){return U(B,w.seed,"seed")}function N(B){return ae(B)&&B.length===i.BYTES}function K(B,E){try{return!!n.fromBytes(B,E)}catch{return!1}}let M={getExtendedPublicKey:d,randomSecretKey:v,isValidSecretKey:N,isValidPublicKey:K,toMontgomery(B){let{y:E}=n.fromBytes(B),O=w.publicKey,H=O===32;if(!H&&O!==57)throw new Error("only defined for 25519 and 448");let L=H?o.div(Q+E,Q-E):o.div(E-Q,E+Q);return o.toBytes(L)},toMontgomerySecret(B){let E=w.secretKey;U(B,E);let O=t(B.subarray(0,E));return a(O).subarray(0,E)}};return Object.freeze({keygen:Pr(v,p),getPublicKey:p,sign:I,verify:x,utils:M,Point:n,lengths:w})}var ff=BigInt(1),Ci=BigInt(2);var lf=BigInt(5),uf=BigInt(8),bs=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),df={p:bs,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:uf,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function hf(n){let t=BigInt(10),e=BigInt(20),r=BigInt(40),s=BigInt(80),o=bs,c=n*n%o*n%o,a=F(c,Ci,o)*c%o,f=F(a,ff,o)*n%o,u=F(f,lf,o)*f%o,l=F(u,t,o)*u%o,d=F(l,e,o)*l%o,p=F(d,r,o)*d%o,h=F(p,s,o)*p%o,I=F(h,s,o)*p%o,b=F(I,t,o)*u%o;return{pow_p_5_8:F(b,Ci,o)*n%o,b2:c}}function pf(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}var Li=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function mf(n,t){let e=bs,r=z(t*t*t,e),s=z(r*r*t,e),o=hf(n*s).pow_p_5_8,i=z(n*r*o,e),c=z(t*i*i,e),a=i,f=z(i*Li,e),u=c===n,l=c===z(-n,e),d=c===z(-n*Li,e);return u&&(i=a),(l||d)&&(i=f),wi(i,e)&&(i=z(-i,e)),{isValid:u||l,value:i}}var yf=ki(df,{uvRatio:mf});function xf(n){return Ti(yf,ii,Object.assign({adjustScalarBytes:pf},n))}var Di=xf({});var Ur=32;var Es,gf=(async()=>{try{return await Er.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function wf(n,t,e){if(n.buffer instanceof ArrayBuffer){let r=await Er.get().subtle.importKey("raw",n.buffer,{name:"Ed25519"},!1,["verify"]);return await Er.get().subtle.verify({name:"Ed25519"},r,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function bf(n,t,e){return Di.verify(t,e instanceof Uint8Array?e:e.subarray(),n)}async function Ri(n,t,e){return Es==null&&(Es=await gf),Es?wf(n,t,e):bf(n,t,e)}function Kr(n){return n==null?!1:typeof n.then=="function"&&typeof n.catch=="function"&&typeof n.finally=="function"}var Mr=class{type="Ed25519";raw;constructor(t){this.raw=Is(t,Ur)}toMultihash(){return bt.digest(Te(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,r){r?.signal?.throwIfAborted();let s=Ri(this.raw,e,t);return Kr(s)?s.then(o=>(r?.signal?.throwIfAborted(),o)):s}};function Ni(n){return n=Is(n,Ur),new Mr(n)}function Is(n,t){if(n=Uint8Array.from(n??[]),n.length!==t)throw new kt(`Key must be a Uint8Array of length ${t}, got ${n.length}`);return n}var If=Math.pow(2,7),Bf=Math.pow(2,14),Sf=Math.pow(2,21),Oi=Math.pow(2,28),Pi=Math.pow(2,35),Ui=Math.pow(2,42),Ki=Math.pow(2,49),at=128,te=127;function or(n){if(n<If)return 1;if(n<Bf)return 2;if(n<Sf)return 3;if(n<Oi)return 4;if(n<Pi)return 5;if(n<Ui)return 6;if(n<Ki)return 7;if(Number.MAX_SAFE_INTEGER!=null&&n>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mi(n,t,e=0){switch(or(n)){case 8:t[e++]=n&255|at,n/=128;case 7:t[e++]=n&255|at,n/=128;case 6:t[e++]=n&255|at,n/=128;case 5:t[e++]=n&255|at,n/=128;case 4:t[e++]=n&255|at,n>>>=7;case 3:t[e++]=n&255|at,n>>>=7;case 2:t[e++]=n&255|at,n>>>=7;case 1:{t[e++]=n&255,n>>>=7;break}default:throw new Error("unreachable")}return t}function Hi(n,t){let e=n[t],r=0;if(r+=e&te,e<at||(e=n[t+1],r+=(e&te)<<7,e<at)||(e=n[t+2],r+=(e&te)<<14,e<at)||(e=n[t+3],r+=(e&te)<<21,e<at)||(e=n[t+4],r+=(e&te)*Oi,e<at)||(e=n[t+5],r+=(e&te)*Pi,e<at)||(e=n[t+6],r+=(e&te)*Ui,e<at)||(e=n[t+7],r+=(e&te)*Ki,e<at))return r;throw new RangeError("Could not decode varint")}var Bs=new Float32Array([-0]),ee=new Uint8Array(Bs.buffer);function qi(n,t,e){Bs[0]=n,t[e]=ee[0],t[e+1]=ee[1],t[e+2]=ee[2],t[e+3]=ee[3]}function Vi(n,t){return ee[0]=n[t],ee[1]=n[t+1],ee[2]=n[t+2],ee[3]=n[t+3],Bs[0]}var Ss=new Float64Array([-0]),nt=new Uint8Array(Ss.buffer);function Fi(n,t,e){Ss[0]=n,t[e]=nt[0],t[e+1]=nt[1],t[e+2]=nt[2],t[e+3]=nt[3],t[e+4]=nt[4],t[e+5]=nt[5],t[e+6]=nt[6],t[e+7]=nt[7]}function $i(n,t){return nt[0]=n[t],nt[1]=n[t+1],nt[2]=n[t+2],nt[3]=n[t+3],nt[4]=n[t+4],nt[5]=n[t+5],nt[6]=n[t+6],nt[7]=n[t+7],Ss[0]}var Af=BigInt(Number.MAX_SAFE_INTEGER),vf=BigInt(Number.MIN_SAFE_INTEGER),ht=class n{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,r=~this.hi>>>0;return e===0&&(r=r+1>>>0),-(e+r*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,r=~this.hi>>>0;return e===0&&(r=r+1>>>0),-(BigInt(e)+(BigInt(r)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:r<128?9:10}static fromBigInt(t){if(t===0n)return pe;if(t<Af&&t>vf)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let r=t>>32n,s=t-(r<<32n);return e&&(r=~r|0n,s=~s|0n,++s>ji&&(s=0n,++r>ji&&(r=0n))),new n(Number(s),Number(r))}static fromNumber(t){if(t===0)return pe;let e=t<0;e&&(t=-t);let r=t>>>0,s=(t-r)/4294967296>>>0;return e&&(s=~s>>>0,r=~r>>>0,++r>4294967295&&(r=0,++s>4294967295&&(s=0))),new n(r,s)}static from(t){return typeof t=="number"?n.fromNumber(t):typeof t=="bigint"?n.fromBigInt(t):typeof t=="string"?n.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new n(t.low>>>0,t.high>>>0):pe}},pe=new ht(0,0);pe.toBigInt=function(){return 0n};pe.zzEncode=pe.zzDecode=function(){return this};pe.length=function(){return 1};var ji=4294967296n;function Gi(n){let t=0,e=0;for(let r=0;r<n.length;++r)e=n.charCodeAt(r),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(n.charCodeAt(r+1)&64512)===56320?(++r,t+=4):t+=3;return t}function Zi(n,t,e){if(e-t<1)return"";let s,o=[],i=0,c;for(;t<e;)c=n[t++],c<128?o[i++]=c:c>191&&c<224?o[i++]=(c&31)<<6|n[t++]&63:c>239&&c<365?(c=((c&7)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,o[i++]=55296+(c>>10),o[i++]=56320+(c&1023)):o[i++]=(c&15)<<12|(n[t++]&63)<<6|n[t++]&63,i>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s!=null?(i>0&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))}function As(n,t,e){let r=e,s,o;for(let i=0;i<n.length;++i)s=n.charCodeAt(i),s<128?t[e++]=s:s<2048?(t[e++]=s>>6|192,t[e++]=s&63|128):(s&64512)===55296&&((o=n.charCodeAt(i+1))&64512)===56320?(s=65536+((s&1023)<<10)+(o&1023),++i,t[e++]=s>>18|240,t[e++]=s>>12&63|128,t[e++]=s>>6&63|128,t[e++]=s&63|128):(t[e++]=s>>12|224,t[e++]=s>>6&63|128,t[e++]=s&63|128);return e-r}function Bt(n,t){return RangeError(`index out of range: ${n.pos} + ${t??1} > ${n.len}`)}function Hr(n,t){return(n[t-4]|n[t-3]<<8|n[t-2]<<16|n[t-1]<<24)>>>0}var vs=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,Bt(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw Bt(this,4);return Hr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Bt(this,4);return Hr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Bt(this,4);let t=Vi(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw Bt(this,4);let t=$i(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,r=this.pos+t;if(r>this.len)throw Bt(this,t);return this.pos+=t,e===r?new Uint8Array(0):this.buf.subarray(e,r)}string(){let t=this.bytes();return Zi(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw Bt(this,t);this.pos+=t}else do if(this.pos>=this.len)throw Bt(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new ht(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw Bt(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw Bt(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Bt(this,8);let t=Hr(this.buf,this.pos+=4),e=Hr(this.buf,this.pos+=4);return new ht(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Hi(this.buf,this.pos);return this.pos+=or(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ks(n){return new vs(n instanceof Uint8Array?n:n.subarray())}function qr(n,t,e){let r=ks(n);return t.decode(r,void 0,e)}function Ts(n){let t=n??8192,e=t>>>1,r,s=t;return function(i){if(i<1||i>e)return ut(i);s+i>t&&(r=ut(t),s=0);let c=r.subarray(s,s+=i);return(s&7)!==0&&(s=(s|7)+1),c}}var me=class{fn;len;next;val;constructor(t,e,r){this.fn=t,this.len=e,this.next=void 0,this.val=r}};function Cs(){}var Ds=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},kf=Ts();function Tf(n){return globalThis.Buffer!=null?ut(n):kf(n)}var ar=class{len;head;tail;states;constructor(){this.len=0,this.head=new me(Cs,0,0),this.tail=this.head,this.states=null}_push(t,e,r){return this.tail=this.tail.next=new me(t,e,r),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Rs((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Vr,10,ht.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=ht.fromBigInt(t);return this._push(Vr,e.length(),e)}uint64Number(t){return this._push(Mi,or(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=ht.fromBigInt(t).zzEncode();return this._push(Vr,e.length(),e)}sint64Number(t){let e=ht.fromNumber(t).zzEncode();return this._push(Vr,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ls,1,t?1:0)}fixed32(t){return this._push(ir,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=ht.fromBigInt(t);return this._push(ir,4,e.lo)._push(ir,4,e.hi)}fixed64Number(t){let e=ht.fromNumber(t);return this._push(ir,4,e.lo)._push(ir,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(qi,4,t)}double(t){return this._push(Fi,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ls,1,0):this.uint32(e)._push(Lf,e,t)}string(t){let e=Gi(t);return e!==0?this.uint32(e)._push(As,e,t):this._push(Ls,1,0)}fork(){return this.states=new Ds(this),this.head=this.tail=new me(Cs,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new me(Cs,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=t.next,this.tail=e,this.len+=r),this}finish(){let t=this.head.next,e=Tf(this.len),r=0;for(;t!=null;)t.fn(t.val,e,r),r+=t.len,t=t.next;return e}};function Ls(n,t,e){t[e]=n&255}function Cf(n,t,e){for(;n>127;)t[e++]=n&127|128,n>>>=7;t[e]=n}var Rs=class extends me{next;constructor(t,e){super(Cf,t,e),this.next=void 0}};function Vr(n,t,e){for(;n.hi!==0;)t[e++]=n.lo&127|128,n.lo=(n.lo>>>7|n.hi<<25)>>>0,n.hi>>>=7;for(;n.lo>127;)t[e++]=n.lo&127|128,n.lo=n.lo>>>7;t[e++]=n.lo}function ir(n,t,e){t[e]=n&255,t[e+1]=n>>>8&255,t[e+2]=n>>>16&255,t[e+3]=n>>>24}function Lf(n,t,e){t.set(n,e)}globalThis.Buffer!=null&&(ar.prototype.bytes=function(n){let t=n.length>>>0;return this.uint32(t),t>0&&this._push(Df,t,n),this},ar.prototype.string=function(n){let t=globalThis.Buffer.byteLength(n);return this.uint32(t),t>0&&this._push(Rf,t,n),this});function Df(n,t,e){t.set(n,e)}function Rf(n,t,e){n.length<40?As(n,t,e):t.utf8Write!=null?t.utf8Write(n,e):t.set(Zt(n),e)}function _s(){return new ar}function Fr(n,t){let e=_s();return t.encode(n,e,{lengthDelimited:!1}),e.finish()}var Oe;(function(n){n[n.VARINT=0]="VARINT",n[n.BIT64=1]="BIT64",n[n.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",n[n.START_GROUP=3]="START_GROUP",n[n.END_GROUP=4]="END_GROUP",n[n.BIT32=5]="BIT32"})(Oe||(Oe={}));function $r(n,t,e,r){return{name:n,type:t,encode:e,decode:r}}function Ns(n){function t(s){if(n[s.toString()]==null)throw new Error("Invalid enum value");return n[s]}let e=function(o,i){let c=t(o);i.int32(c)},r=function(o){let i=o.int32();return t(i)};return $r("enum",Oe.VARINT,e,r)}function jr(n,t){return $r("message",Oe.LENGTH_DELIMITED,n,t)}var pt;(function(n){n.RSA="RSA",n.Ed25519="Ed25519",n.secp256k1="secp256k1",n.ECDSA="ECDSA"})(pt||(pt={}));var Os;(function(n){n[n.RSA=0]="RSA",n[n.Ed25519=1]="Ed25519",n[n.secp256k1=2]="secp256k1",n[n.ECDSA=3]="ECDSA"})(Os||(Os={}));(function(n){n.codec=()=>Ns(Os)})(pt||(pt={}));var cr;(function(n){let t;n.codec=()=>(t==null&&(t=jr((e,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),e.Type!=null&&(r.uint32(8),pt.codec().encode(e.Type,r)),e.Data!=null&&(r.uint32(18),r.bytes(e.Data)),s.lengthDelimited!==!1&&r.ldelim()},(e,r,s={})=>{let o={},i=r==null?e.len:e.pos+r;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.Type=pt.codec().decode(e);break}case 2:{o.Data=e.bytes();break}default:{e.skipType(c&7);break}}}return o})),t),n.encode=e=>Fr(e,n.codec()),n.decode=(e,r)=>qr(e,n.codec(),r)})(cr||(cr={}));var Ps;(function(n){let t;n.codec=()=>(t==null&&(t=jr((e,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),e.Type!=null&&(r.uint32(8),pt.codec().encode(e.Type,r)),e.Data!=null&&(r.uint32(18),r.bytes(e.Data)),s.lengthDelimited!==!1&&r.ldelim()},(e,r,s={})=>{let o={},i=r==null?e.len:e.pos+r;for(;e.pos<i;){let c=e.uint32();switch(c>>>3){case 1:{o.Type=pt.codec().decode(e);break}case 2:{o.Data=e.bytes();break}default:{e.skipType(c&7);break}}}return o})),t),n.encode=e=>Fr(e,n.codec()),n.decode=(e,r)=>qr(e,n.codec(),r)})(Ps||(Ps={}));function Pe(n){if(isNaN(n)||n<=0)throw new kt("random bytes length must be a Number bigger than 0");return zt(n)}var Gr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(Cr(t),U(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,s=new Uint8Array(r);s.set(e.length>r?t.create().update(e).digest():e);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Pt(s)}update(t){return Ce(this),this.iHash.update(t),this}digestInto(t){Ce(this),U(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:r,finished:s,destroyed:o,blockLen:i,outputLen:c}=this;return t=t,t.finished=s,t.destroyed=o,t.blockLen=i,t.outputLen=c,t.oHash=e._cloneInto(t.oHash),t.iHash=r._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Us=(n,t,e)=>new Gr(n,t).update(e).digest();Us.create=(n,t)=>new Gr(n,t);var Yi=(n,t)=>(n+(n>=0?t:-t)/Xi)/t;function Nf(n,t,e){let[[r,s],[o,i]]=t,c=Yi(i*n,e),a=Yi(-s*n,e),f=n-c*r-a*o,u=-c*s-a*i,l=f<qt,d=u<qt;l&&(f=-f),d&&(u=-u);let p=rr(Math.ceil(ls(e)/2))+Ue;if(f<qt||f>=p||u<qt||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:l,k1:f,k2neg:d,k2:u}}function Ms(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function Ks(n,t){let e={};for(let r of Object.keys(t))e[r]=n[r]===void 0?t[r]:n[r];return Ht(e.lowS,"lowS"),Ht(e.prehash,"prehash"),e.format!==void 0&&Ms(e.format),e}var Hs=class extends Error{constructor(t=""){super(t)}},re={Err:Hs,_tlv:{encode:(n,t)=>{let{Err:e}=re;if(n<0||n>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let r=t.length/2,s=tr(r);if(s.length/2&128)throw new e("tlv.encode: long form length too big");let o=r>127?tr(s.length/2|128):"";return tr(n)+o+s+t},decode(n,t){let{Err:e}=re,r=0;if(n<0||n>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[r++]!==n)throw new e("tlv.decode: wrong tlv");let s=t[r++],o=!!(s&128),i=0;if(!o)i=s;else{let a=s&127;if(!a)throw new e("tlv.decode(long): indefinite length not supported");if(a>4)throw new e("tlv.decode(long): byte length is too big");let f=t.subarray(r,r+a);if(f.length!==a)throw new e("tlv.decode: length bytes not complete");if(f[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of f)i=i<<8|u;if(r+=a,i<128)throw new e("tlv.decode(long): not minimal encoding")}let c=t.subarray(r,r+i);if(c.length!==i)throw new e("tlv.decode: wrong value length");return{v:c,l:t.subarray(r+i)}}},_int:{encode(n){let{Err:t}=re;if(n<qt)throw new t("integer: negative integers are not allowed");let e=tr(n);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(n){let{Err:t}=re;if(n[0]&128)throw new t("invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Le(n)}},toSig(n){let{Err:t,_int:e,_tlv:r}=re,s=U(n,void 0,"signature"),{v:o,l:i}=r.decode(48,s);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:c,l:a}=r.decode(2,o),{v:f,l:u}=r.decode(2,a);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(c),s:e.decode(f)}},hexFromSig(n){let{_tlv:t,_int:e}=re,r=t.encode(2,e.encode(n.r)),s=t.encode(2,e.encode(n.s)),o=r+s;return t.encode(48,o)}},qt=BigInt(0),Ue=BigInt(1),Xi=BigInt(2),Zr=BigInt(3),Of=BigInt(4);function Wi(n,t={}){let e=Or("weierstrass",n,t),{Fp:r,Fn:s}=e,o=e.CURVE,{h:i,n:c}=o;Jt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:a}=t;if(a&&(!r.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=Qi(r,s);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(L,y,g){let{x:m,y:A}=y.toAffine(),k=r.toBytes(m);if(Ht(g,"isCompressed"),g){u();let C=!r.isOdd(A);return ft(Ji(C),k)}else return ft(Uint8Array.of(4),k,r.toBytes(A))}function d(L){U(L,void 0,"Point");let{publicKey:y,publicKeyUncompressed:g}=f,m=L.length,A=L[0],k=L.subarray(1);if(m===y&&(A===2||A===3)){let C=r.fromBytes(k);if(!r.isValid(C))throw new Error("bad point: is not on curve, wrong x");let D=I(C),T;try{T=r.sqrt(D)}catch($){let V=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}u();let R=r.isOdd(T);return(A&1)===1!==R&&(T=r.neg(T)),{x:C,y:T}}else if(m===g&&A===4){let C=r.BYTES,D=r.fromBytes(k.subarray(0,C)),T=r.fromBytes(k.subarray(C,C*2));if(!b(D,T))throw new Error("bad point: is not on curve");return{x:D,y:T}}else throw new Error(`bad point: got length ${m}, expected compressed=${y} or uncompressed=${g}`)}let p=t.toBytes||l,h=t.fromBytes||d;function I(L){let y=r.sqr(L),g=r.mul(y,L);return r.add(r.add(g,r.mul(L,o.a)),o.b)}function b(L,y){let g=r.sqr(y),m=I(L);return r.eql(g,m)}if(!b(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let x=r.mul(r.pow(o.a,Zr),Of),S=r.mul(r.sqr(o.b),BigInt(27));if(r.is0(r.add(x,S)))throw new Error("bad curve params: a or b");function w(L,y,g=!1){if(!r.isValid(y)||g&&r.is0(y))throw new Error(`bad point coordinate ${L}`);return y}function v(L){if(!(L instanceof E))throw new Error("Weierstrass Point expected")}function N(L){if(!a||!a.basises)throw new Error("no endo");return Nf(L,a.basises,s.ORDER)}let K=De((L,y)=>{let{X:g,Y:m,Z:A}=L;if(r.eql(A,r.ONE))return{x:g,y:m};let k=L.is0();y==null&&(y=k?r.ONE:r.inv(A));let C=r.mul(g,y),D=r.mul(m,y),T=r.mul(A,y);if(k)return{x:r.ZERO,y:r.ZERO};if(!r.eql(T,r.ONE))throw new Error("invZ was invalid");return{x:C,y:D}}),M=De(L=>{if(L.is0()){if(t.allowInfinityPoint&&!r.is0(L.Y))return;throw new Error("bad point: ZERO")}let{x:y,y:g}=L.toAffine();if(!r.isValid(y)||!r.isValid(g))throw new Error("bad point: x or y not field elements");if(!b(y,g))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function B(L,y,g,m,A){return g=new E(r.mul(g.X,L),g.Y,g.Z),y=sr(m,y),g=sr(A,g),y.add(g)}class E{static BASE=new E(o.Gx,o.Gy,r.ONE);static ZERO=new E(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=s;X;Y;Z;constructor(y,g,m){this.X=w("x",y),this.Y=w("y",g,!0),this.Z=w("z",m),Object.freeze(this)}static CURVE(){return o}static fromAffine(y){let{x:g,y:m}=y||{};if(!y||!r.isValid(g)||!r.isValid(m))throw new Error("invalid affine point");if(y instanceof E)throw new Error("projective point not allowed");return r.is0(g)&&r.is0(m)?E.ZERO:new E(g,m,r.ONE)}static fromBytes(y){let g=E.fromAffine(h(U(y,void 0,"point")));return g.assertValidity(),g}static fromHex(y){return E.fromBytes(Kt(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,g=!0){return H.createCache(this,y),g||this.multiply(Zr),this}assertValidity(){M(this)}hasEvenY(){let{y}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(y)}equals(y){v(y);let{X:g,Y:m,Z:A}=this,{X:k,Y:C,Z:D}=y,T=r.eql(r.mul(g,D),r.mul(k,A)),R=r.eql(r.mul(m,D),r.mul(C,A));return T&&R}negate(){return new E(this.X,r.neg(this.Y),this.Z)}double(){let{a:y,b:g}=o,m=r.mul(g,Zr),{X:A,Y:k,Z:C}=this,D=r.ZERO,T=r.ZERO,R=r.ZERO,P=r.mul(A,A),$=r.mul(k,k),V=r.mul(C,C),q=r.mul(A,k);return q=r.add(q,q),R=r.mul(A,C),R=r.add(R,R),D=r.mul(y,R),T=r.mul(m,V),T=r.add(D,T),D=r.sub($,T),T=r.add($,T),T=r.mul(D,T),D=r.mul(q,D),R=r.mul(m,R),V=r.mul(y,V),q=r.sub(P,V),q=r.mul(y,q),q=r.add(q,R),R=r.add(P,P),P=r.add(R,P),P=r.add(P,V),P=r.mul(P,q),T=r.add(T,P),V=r.mul(k,C),V=r.add(V,V),P=r.mul(V,q),D=r.sub(D,P),R=r.mul(V,$),R=r.add(R,R),R=r.add(R,R),new E(D,T,R)}add(y){v(y);let{X:g,Y:m,Z:A}=this,{X:k,Y:C,Z:D}=y,T=r.ZERO,R=r.ZERO,P=r.ZERO,$=o.a,V=r.mul(o.b,Zr),q=r.mul(g,k),j=r.mul(m,C),tt=r.mul(A,D),St=r.add(g,m),G=r.add(k,C);St=r.mul(St,G),G=r.add(q,j),St=r.sub(St,G),G=r.add(g,A);let rt=r.add(k,D);return G=r.mul(G,rt),rt=r.add(q,tt),G=r.sub(G,rt),rt=r.add(m,A),T=r.add(C,D),rt=r.mul(rt,T),T=r.add(j,tt),rt=r.sub(rt,T),P=r.mul($,G),T=r.mul(V,tt),P=r.add(T,P),T=r.sub(j,P),P=r.add(j,P),R=r.mul(T,P),j=r.add(q,q),j=r.add(j,q),tt=r.mul($,tt),G=r.mul(V,G),j=r.add(j,tt),tt=r.sub(q,tt),tt=r.mul($,tt),G=r.add(G,tt),q=r.mul(j,G),R=r.add(R,q),q=r.mul(rt,G),T=r.mul(St,T),T=r.sub(T,q),q=r.mul(St,j),P=r.mul(rt,P),P=r.add(P,q),new E(T,R,P)}subtract(y){return this.add(y.negate())}is0(){return this.equals(E.ZERO)}multiply(y){let{endo:g}=t;if(!s.isValidNot0(y))throw new Error("invalid scalar: out of range");let m,A,k=C=>H.cached(this,C,D=>he(E,D));if(g){let{k1neg:C,k1:D,k2neg:T,k2:R}=N(y),{p:P,f:$}=k(D),{p:V,f:q}=k(R);A=$.add(q),m=B(g.beta,P,V,C,T)}else{let{p:C,f:D}=k(y);m=C,A=D}return he(E,[m,A])[0]}multiplyUnsafe(y){let{endo:g}=t,m=this;if(!s.isValid(y))throw new Error("invalid scalar: out of range");if(y===qt||m.is0())return E.ZERO;if(y===Ue)return m;if(H.hasCache(this))return this.multiply(y);if(g){let{k1neg:A,k1:k,k2neg:C,k2:D}=N(y),{p1:T,p2:R}=vi(E,m,k,D);return B(g.beta,T,R,A,C)}else return H.unsafe(m,y)}toAffine(y){return K(this,y)}isTorsionFree(){let{isTorsionFree:y}=t;return i===Ue?!0:y?y(E,this):H.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:y}=t;return i===Ue?this:y?y(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(y=!0){return Ht(y,"isCompressed"),this.assertValidity(),p(E,this,y)}toHex(y=!0){return Ut(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let O=s.BITS,H=new Ne(E,t.endo?Math.ceil(O/2):O);return E.BASE.precompute(8),E}function Ji(n){return Uint8Array.of(n?2:3)}function Qi(n,t){return{secretKey:t.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Pf(n,t={}){let{Fn:e}=n,r=t.randomBytes||zt,s=Object.assign(Qi(n.Fp,e),{seed:ps(e.ORDER)});function o(p){try{let h=e.fromBytes(p);return e.isValidNot0(h)}catch{return!1}}function i(p,h){let{publicKey:I,publicKeyUncompressed:b}=s;try{let x=p.length;return h===!0&&x!==I||h===!1&&x!==b?!1:!!n.fromBytes(p)}catch{return!1}}function c(p=r(s.seed)){return ms(U(p,s.seed,"seed"),e.ORDER)}function a(p,h=!0){return n.BASE.multiply(e.fromBytes(p)).toBytes(h)}function f(p){let{secretKey:h,publicKey:I,publicKeyUncompressed:b}=s;if(!ae(p)||"_lengths"in e&&e._lengths||h===I)return;let x=U(p,void 0,"key").length;return x===I||x===b}function u(p,h,I=!0){if(f(p)===!0)throw new Error("first arg must be private key");if(f(h)===!1)throw new Error("second arg must be public key");let b=e.fromBytes(p);return n.fromBytes(h).multiply(b).toBytes(I)}let l={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:c},d=Pr(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:u,keygen:d,Point:n,utils:l,lengths:s})}function ta(n,t,e={}){Cr(t),Jt(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let r=e.randomBytes||zt,s=e.hmac||((g,m)=>Us(t,g,m)),{Fp:o,Fn:i}=n,{ORDER:c,BITS:a}=i,{keygen:f,getPublicKey:u,getSharedSecret:l,utils:d,lengths:p}=Pf(n,e),h={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},I=c*Xi<o.ORDER;function b(g){let m=c>>Ue;return g>m}function x(g,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return m}function S(){if(I)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function w(g,m){Ms(m);let A=p.signature,k=m==="compact"?A:m==="recovered"?A+1:void 0;return U(g,k)}class v{r;s;recovery;constructor(m,A,k){if(this.r=x("r",m),this.s=x("s",A),k!=null){if(S(),![0,1,2,3].includes(k))throw new Error("invalid recovery id");this.recovery=k}Object.freeze(this)}static fromBytes(m,A=h.format){w(m,A);let k;if(A==="der"){let{r:R,s:P}=re.toSig(U(m));return new v(R,P)}A==="recovered"&&(k=m[0],A="compact",m=m.subarray(1));let C=p.signature/2,D=m.subarray(0,C),T=m.subarray(C,C*2);return new v(i.fromBytes(D),i.fromBytes(T),k)}static fromHex(m,A){return this.fromBytes(Kt(m),A)}assertRecovery(){let{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new v(this.r,this.s,m)}recoverPublicKey(m){let{r:A,s:k}=this,C=this.assertRecovery(),D=C===2||C===3?A+c:A;if(!o.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let T=o.toBytes(D),R=n.fromBytes(ft(Ji((C&1)===0),T)),P=i.inv(D),$=K(U(m,void 0,"msgHash")),V=i.create(-$*P),q=i.create(k*P),j=n.BASE.multiplyUnsafe(V).add(R.multiplyUnsafe(q));if(j.is0())throw new Error("invalid recovery: point at infinify");return j.assertValidity(),j}hasHighS(){return b(this.s)}toBytes(m=h.format){if(Ms(m),m==="der")return Kt(re.hexFromSig(this));let{r:A,s:k}=this,C=i.toBytes(A),D=i.toBytes(k);return m==="recovered"?(S(),ft(Uint8Array.of(this.assertRecovery()),C,D)):ft(C,D)}toHex(m){return Ut(this.toBytes(m))}}let N=e.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");let A=Le(m),k=m.length*8-a;return k>0?A>>BigInt(k):A},K=e.bits2int_modN||function(m){return i.create(N(m))},M=rr(a);function B(g){return er("num < 2^"+a,g,qt,M),i.toBytes(g)}function E(g,m){return U(g,void 0,"message"),m?U(t(g),void 0,"prehashed message"):g}function O(g,m,A){let{lowS:k,prehash:C,extraEntropy:D}=Ks(A,h);g=E(g,C);let T=K(g),R=i.fromBytes(m);if(!i.isValidNot0(R))throw new Error("invalid private key");let P=[B(R),B(T)];if(D!=null&&D!==!1){let j=D===!0?r(p.secretKey):D;P.push(U(j,void 0,"extraEntropy"))}let $=ft(...P),V=T;function q(j){let tt=N(j);if(!i.isValidNot0(tt))return;let St=i.inv(tt),G=n.BASE.multiply(tt).toAffine(),rt=i.create(G.x);if(rt===qt)return;let xr=i.create(St*i.create(V+rt*R));if(xr===qt)return;let so=(G.x===rt?0:2)|Number(G.y&Ue),oo=xr;return k&&b(xr)&&(oo=i.neg(xr),so^=1),new v(rt,oo,I?void 0:so)}return{seed:$,k2sig:q}}function H(g,m,A={}){let{seed:k,k2sig:C}=O(g,m,A);return fi(t.outputLen,i.BYTES,s)(k,C).toBytes(A.format)}function L(g,m,A,k={}){let{lowS:C,prehash:D,format:T}=Ks(k,h);if(A=U(A,void 0,"publicKey"),m=E(m,D),!ae(g)){let R=g instanceof v?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}w(g,T);try{let R=v.fromBytes(g,T),P=n.fromBytes(A);if(C&&R.hasHighS())return!1;let{r:$,s:V}=R,q=K(m),j=i.inv(V),tt=i.create(q*j),St=i.create($*j),G=n.BASE.multiplyUnsafe(tt).add(P.multiplyUnsafe(St));return G.is0()?!1:i.create(G.x)===$}catch{return!1}}function y(g,m,A={}){let{prehash:k}=Ks(A,h);return m=E(m,k),v.fromBytes(g,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:f,getPublicKey:u,getSharedSecret:l,utils:d,lengths:p,Point:n,sign:H,verify:L,recoverPublicKey:y,Signature:v,hash:t})}var Vs={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Uf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var ea=BigInt(2);function Kf(n){let t=Vs.p,e=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),c=BigInt(44),a=BigInt(88),f=n*n*n%t,u=f*f*n%t,l=F(u,e,t)*u%t,d=F(l,e,t)*u%t,p=F(d,ea,t)*f%t,h=F(p,s,t)*p%t,I=F(h,o,t)*h%t,b=F(I,c,t)*I%t,x=F(b,a,t)*b%t,S=F(x,c,t)*I%t,w=F(S,e,t)*u%t,v=F(w,i,t)*h%t,N=F(v,r,t)*f%t,K=F(N,ea,t);if(!qs.eql(qs.sqr(K),n))throw new Error("Cannot find square root");return K}var qs=Re(Vs.p,{sqrt:Kf}),Mf=Wi(Vs,{Fp:qs,endo:Uf}),Ke=ta(Mf,oi);function ra(n,t,e,r){let s=Nt.digest(e instanceof Uint8Array?e:e.subarray());if(Kr(s))return s.then(({digest:o})=>(r?.signal?.throwIfAborted(),Ke.verify(t,o,n,{prehash:!1,format:"der"}))).catch(o=>{throw o.name==="AbortError"?o:new Fe(String(o))});try{return r?.signal?.throwIfAborted(),Ke.verify(t,s.digest,n,{prehash:!1,format:"der"})}catch(o){throw new Fe(String(o))}}var zr=class{type="secp256k1";raw;_key;constructor(t){this._key=sa(t),this.raw=na(this._key)}toMultihash(){return bt.digest(Te(this))}toCID(){return ot.createV1(114,this.toMultihash())}toString(){return Y.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,r){return ra(this._key,e,t,r)}};function oa(n){return new zr(n)}function na(n){return Ke.Point.fromBytes(n).toBytes()}function sa(n){try{return Ke.Point.fromBytes(n),n}catch(t){throw new Ir(String(t))}}function ia(n){let{Type:t,Data:e}=cr.decode(n.digest),r=e??new Uint8Array;switch(t){case pt.Ed25519:return Ni(r);case pt.secp256k1:return oa(r);case pt.ECDSA:return Vo(r);default:throw new Br}}function Te(n){return cr.encode({Type:pt[n.type],Data:n.raw})}var fr=class{static lockQueues=new Map;static async acquire(t){let e=this.lockQueues.get(t)??Promise.resolve(),r,s=new Promise(i=>{r=i});return this.lockQueues.set(t,s),await e,()=>{r(),this.lockQueues.get(t)===s&&this.lockQueues.delete(t)}}};var Hf=100,ye=class n{id;transactor;handlers;source;sourceCache;tracker;filterConflict;pending=[];constructor(t,e,r,s,o,i,c){this.id=t,this.transactor=e,this.handlers=r,this.source=s,this.sourceCache=o,this.tracker=i,this.filterConflict=c}static async createOrOpen(t,e,r){let s=new Me(e,t,void 0),o=new lr(s),i=new Vt(o);if(await s.tryGet(e)){let a=await xt.open(i,e);s.actionContext=await a.getActionContext()}else{let a=r.createHeaderBlock(e,i);i.insert(a),s.actionContext=void 0,await xt.open(i,e)}return new n(e,t,r.modules,s,o,i,r.filterConflict)}async act(...t){await this.internalTransact(...t),this.pending.push(...t)}async internalTransact(...t){let e=new Dt(this.tracker);for(let r of t){let s=this.handlers[r.type];if(!s)throw new Error(`No handler for action type ${r.type}`);await s(r,e)}e.commit()}async update(){let t=new Me(this.id,this.transactor,void 0),e=new Vt(t),r=this.source.actionContext,s=await xt.open(e,this.id),o=s?await s.getFrom(r?.rev??0):void 0,i=!1;for(let c of o?.entries??[])this.pending=this.pending.map(a=>this.doFilterConflict(a,c.actions)?a:void 0).filter(Boolean),this.sourceCache.clear(c.blockIds),i=i||e.conflicts(new Set(c.blockIds)).length>0;i&&await this.replayActions(),this.source.actionContext=o?.context}async sync(){let t=`Collection.sync:${this.id}`,e=await fr.acquire(t);try{let r=Pe(16),s=X(r,"base64url");for(;this.pending.length||!un(this.tracker.transforms);){let o=[...this.pending],i=ln(this.tracker.transforms),c=new Vt(this.sourceCache,i),a=await xt.open(c,this.id);if(!a)throw new Error(`Log not found for collection ${this.id}`);let f=(this.source.actionContext?.rev??0)+1,u=await a.addActions(o,s,f,()=>c.transformedBlockIds()),l=await this.source.transact(c.transforms,s,f,this.id,u.tailPath.block.header.id);if(l)l.pending&&await new Promise(d=>setTimeout(d,Hf)),await this.update();else{this.pending=this.pending.slice(o.length);let d=c.reset();await this.replayActions(),this.sourceCache.transformCache(d),this.source.actionContext=this.source.actionContext?{committed:[...this.source.actionContext.committed,{actionId:s,rev:f}],rev:f}:{committed:[{actionId:s,rev:f}],rev:f}}}}finally{e()}}async updateAndSync(){await this.update(),await this.sync()}async*selectLog(t=!0){let e=await xt.open(this.tracker,this.id);if(!e)throw new Error(`Log not found for collection ${this.id}`);for await(let r of e.select(void 0,t))r.action&&(yield*t?r.action.actions:r.action.actions.reverse())}async replayActions(){for(this.tracker.reset();this.pending.length;){let t=[...this.pending];this.pending=[],await this.internalTransact(...t)}}doFilterConflict(t,e){if(this.filterConflict){let r=this.filterConflict(t,e);if(r)r!==t&&this.act(r);else return!1}return!0}};var Fs=class n{collection;constructor(t){this.collection=t}static async create(t,e){let r={modules:{append:async(o,i)=>{}},createHeaderBlock:(o,i)=>({header:i.createBlockHeader($s,o)})},s=await ye.createOrOpen(t,e,r);return new n(s)}async append(t){let e={type:"append",data:t};await this.collection.act(e),await this.collection.updateAndSync()}async*select(t=!0){for await(let e of this.collection.selectLog(t))yield e.data}};var $s=gt("DIH","DiaryHeaderBlock");var js=gt("TRE","TreeHeaderBlock"),Gs=st("rootId");var ur=class{store;collectionId;constructor(t,e){this.store=t,this.collectionId=e}async get(){return await W(this.store,await this.getId())}async set(t){let e=await W(this.store,this.collectionId);_(this.store,e,[Gs,0,1,t.header.id])}async getId(){return(await W(this.store,this.collectionId)).rootId}};var Zs=class n{collection;btree;constructor(t,e){this.collection=t,this.btree=e}static async createOrOpen(t,e,r=o=>o,s=(o,i)=>o<i?-1:o>i?1:0){let o,i={modules:{replace:async({data:a},f)=>{for(let[u,l]of a)l?await o.upsert(l):await o.deleteAt(await o.find(u))}},createHeaderBlock:(a,f)=>{let u;return o=jt.create(f,(l,d)=>(u=d,new ur(f,a)),r,s),{header:f.createBlockHeader(js,a),rootId:u}}},c=await ye.createOrOpen(t,e,i);return o=o??new jt(c.tracker,new ur(c.tracker,c.id),r,s),new n(c,o)}async replace(t){await this.collection.act({type:"replace",data:t}),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(t){return await this.btree.find(t)}async get(t){return await this.btree.get(t)}at(t){return this.btree.at(t)}range(t){return this.btree.range(t)}ascending(t){return this.btree.ascending(t)}descending(t){return this.btree.descending(t)}async getCount(t){return await this.btree.getCount(t)}async next(t){return await this.btree.next(t)}async moveNext(t){await this.btree.moveNext(t)}async prior(t){return await this.btree.prior(t)}async movePrior(t){await this.btree.movePrior(t)}isValid(t){return this.btree.isValid(t)}};var qf=st("priorHash"),xt=class n{chain;constructor(t){this.chain=t}get id(){return this.chain.id}static async open(t,e){let r=await we.open(t,e,n.getChainOptions(t));return r?new n(r):void 0}static async create(t,e){return new n(await we.create(t,{...n.getChainOptions(t),newId:e}))}async addActions(t,e,r,s,o=[],i=Date.now()){let c={timestamp:i,rev:r,action:{actionId:e,actions:t,blockIds:[],collectionIds:o}},a=await this.chain.add(c),f={...c,action:{...c.action,blockIds:s()}};return this.chain.updateAt(a,f),{entry:f,tailPath:a}}async addCheckpoint(t,e,r=Date.now()){let s={timestamp:r,rev:e,checkpoint:{pendings:t}},o=await this.chain.add(s);return{entry:s,tailPath:o}}async getActionContext(){let t=await this.chain.getTail();if(!t)return;let e=await this.findCheckpoint(t);return{committed:e?[...e.pendings,...await this.pendingFrom(e.path)]:[],rev:e?.rev??0}}async getFrom(t){let e=[],r=[],s,o;for await(let i of this.chain.select(void 0,!1)){let c=ie(i);if(s=s??c.rev,c.checkpoint){o=i,r.unshift(...c.checkpoint.pendings);break}r.unshift({actionId:c.action.actionId,rev:c.rev}),t!==void 0&&c.rev>t&&e.unshift(c.action)}if(o)for await(let i of this.chain.select(o,!1)){let c=ie(i);if(t!==void 0&&c.rev>t)c.action&&e.unshift(c.action);else break}return{context:s?{committed:r,rev:s}:void 0,entries:e}}async*select(t,e=!0){for await(let r of this.chain.select(t,e))yield ie(r)}async findCheckpoint(t){let e,r;for await(let s of this.chain.select(t,!1)){let o=ie(s);if(r=r??o.rev,o.checkpoint)return{path:s,pendings:o.checkpoint.pendings,rev:r};e=s}return e?{path:e,pendings:[],rev:r}:void 0}async pendingFrom(t){let e=[];for await(let r of this.chain.select(t)){let s=ie(r);s?.action&&e.push({actionId:s.action.actionId,rev:s.rev})}return e}static getChainOptions(t){return{createDataBlock:()=>({header:t.createBlockHeader("LGD")}),createHeaderBlock:e=>({header:t.createBlockHeader("LGH",e)}),newBlock:async(e,r)=>{if(r){let s=await Nt.digest(new TextEncoder().encode(JSON.stringify(r)));e.priorHash=X(s.digest,"base64url")}}}}};var zs="LGD",Ys="LGH";function He(n,t,e,r){let s=JSON.stringify({peerId:n,timestamp:t,schemaHash:e,engineId:r}),o=`stamp:${aa(s)}`;return{peerId:n,timestamp:t,schemaHash:e,engineId:r,id:o}}function qe(n,t,e){let r=JSON.stringify({stampId:n,statements:t,reads:e});return`tx:${aa(r)}`}function aa(n){let t=0;for(let e=0;e<n.length;e++){let r=n.charCodeAt(e);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}Yr();var Xr=class{coordinator;transactionId;engine;collectionActions=new Map;reads=[];constructor(t,e,r){this.coordinator=t,this.transactionId=e,this.engine=r}async addAction(t,e){let r={...e,transaction:this.transactionId},s=this.coordinator.collections.get(t);s&&await s.act(r),this.collectionActions.has(t)||this.collectionActions.set(t,[]),this.collectionActions.get(t).push(r)}addRead(t){this.reads.push(t)}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())}};Yr();var Wr=class{transactor;collections;constructor(t,e){this.transactor=t,this.collections=e}async applyActions(t,e){for(let{collectionId:r,actions:s}of t){let o=this.collections.get(r);if(!o)throw new Error(`Collection not found: ${r}`);for(let i of s){let c={...i,transaction:e};await o.act(c)}}}async commit(t){let e=Array.from(this.collections.entries()).map(([a,f])=>({collectionId:a,collection:f,transforms:f.tracker.transforms})).filter(({transforms:a})=>Object.keys(a.inserts).length+Object.keys(a.updates).length+a.deletes.length>0);if(e.length===0)return;let r=new Map,s=new Map;for(let{collectionId:a,collection:f,transforms:u}of e){r.set(a,u);let l=await xt.open(f.tracker,a);if(!l)throw new Error(`Log not found for collection ${a}`);let d=await l.chain.getTail();d&&s.set(a,d.block.header.id)}let o=e.flatMap(({collectionId:a,transforms:f})=>[...Object.entries(f.inserts).map(([u,l])=>({type:"insert",collectionId:a,blockId:u,block:l})),...Object.entries(f.updates).map(([u,l])=>({type:"update",collectionId:a,blockId:u,operations:l})),...f.deletes.map(u=>({type:"delete",collectionId:a,blockId:u}))]),i=this.hashOperations(o),c=await this.coordinateTransaction(t,i,r,s);if(!c.success)throw new Error(`Transaction commit failed: ${c.error}`)}async rollback(t){for(let e of this.collections.values())e.tracker.reset()}getTransforms(){let t=new Map;for(let[e,r]of this.collections.entries()){let s=r.tracker.transforms;(Object.keys(s.inserts).length>0||Object.keys(s.updates).length>0||s.deletes.length>0)&&t.set(e,s)}return t}resetTransforms(){for(let t of this.collections.values())t.tracker.reset()}hashOperations(t){let e=JSON.stringify(t),r=Array.from(e).reduce((s,o)=>{let i=o.charCodeAt(0);return(s<<5)-s+i&s},0);return`ops:${Math.abs(r).toString(36)}`}async commitTransaction(t){let e=Array.from(t.getCollectionActions().entries()).map(([f,u])=>({collectionId:f,actions:u}));if(e.length===0)return{success:!0};let r=hr(e),s=t.getReads(),o=He("local",Date.now(),"",t.engine),i={stamp:o,statements:r,reads:s,id:qe(o.id,r,s)},{ActionsEngine:c}=await Promise.resolve().then(()=>(Yr(),ca)),a=new c(this);return await this.execute(i,a)}async execute(t,e){let r=await e.execute(t);if(!r.success)return r;if(!r.actions||r.actions.length===0)return{success:!0};let s=new Map,o=new Map,i=new Map,c=r.actions.map(l=>l.collectionId);for(let l of r.actions){let d=await this.applyActionsToCollection(l,t,c);if(!d.success)return{success:!1,error:d.error};s.set(l.collectionId,d.transforms),o.set(l.collectionId,d.logTailBlockId),i.set(l.collectionId,d.results)}let a=Array.from(s.entries()).flatMap(([l,d])=>[...Object.entries(d.inserts).map(([p,h])=>({type:"insert",collectionId:l,blockId:p,block:h})),...Object.entries(d.updates).map(([p,h])=>({type:"update",collectionId:l,blockId:p,operations:h})),...d.deletes.map(p=>({type:"delete",collectionId:l,blockId:p}))]),f=this.hashOperations(a),u=await this.coordinateTransaction(t,f,s,o);return u.success?{success:!0,actions:r.actions,results:i}:u}async applyActionsToCollection(t,e,r){let s=this.collections.get(t.collectionId);if(!s)return{success:!1,error:`Collection not found: ${t.collectionId}`};let o=s.tracker.transforms,i=await xt.open(s.tracker,t.collectionId);if(!i)return{success:!1,error:`Log not found for collection ${t.collectionId}`};let c=e.id,a=(s.source.actionContext?.rev??0)+1,f=await i.addActions(t.actions,c,a,()=>At(o),r);return{success:!0,transforms:o,logTailBlockId:f.tailPath.block.header.id,results:[]}}async coordinateTransaction(t,e,r,s){let o=Array.from(s.values()),i=await this.gatherPhase(o),c=await this.pendPhase(t,e,r,i);if(!c.success)return c;let a=await this.commitPhase(t.id,o,c.pendedBlockIds);return a.success?{success:!0}:(await this.cancelPhase(t.id,r),a)}async gatherPhase(t){if(t.length===1||!this.transactor.queryClusterNominees)return null;let e=t.map(o=>this.transactor.queryClusterNominees(o));return(await Promise.all(e)).reduce((o,i)=>(i.nominees.forEach(c=>o.add(c)),o),new Set)}async pendPhase(t,e,r,s){if(r.size===0)return{success:!1,error:"No transforms to pend"};let o=new Map,i=t.id,c=s?Array.from(s):void 0;for(let[a,f]of r.entries()){let u=this.collections.get(a);if(!u)return{success:!1,error:`Collection not found: ${a}`};let l=(u.source.actionContext?.rev??0)+1,d={actionId:i,rev:l,transforms:f,policy:"r",transaction:t,operationsHash:e,superclusterNominees:c},p=await this.transactor.pend(d);if(!p.success)return{success:!1,error:`Pend failed for collection ${a}: ${p.reason}`};o.set(a,p.blockIds)}return{success:!0,pendedBlockIds:o}}async commitPhase(t,e,r){for(let[s,o]of r.entries()){let i=this.collections.get(s);if(!i)return{success:!1,error:`Collection not found: ${s}`};let c=(i.source.actionContext?.rev??0)+1,a=e.find(l=>o.includes(l));if(!a)return{success:!1,error:`Log tail block not found for collection ${s}`};let f={actionId:t,blockIds:o,tailId:a,rev:c};if(!(await this.transactor.commit(f)).success)return{success:!1,error:`Commit failed for collection ${s}`}}return{success:!0}}async cancelPhase(t,e){for(let[r,s]of e.entries()){if(!this.collections.get(r))continue;let i=At(s);await this.transactor.cancel({actionId:t,blockIds:i})}}};var Jr=class{coordinator;engine;statements=[];stamp;committed=!1;rolledBack=!1;constructor(t,e,r="local",s=""){this.coordinator=t,this.engine=e,this.stamp=He(r,Date.now(),s,"unknown")}async execute(t,e){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(e)r=e;else{let s={stamp:this.stamp,statements:[t],reads:[],id:"temp"},o=await this.engine.execute(s);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(t),{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 t={stamp:this.stamp,statements:this.statements,reads:[],id:qe(this.stamp.id,this.statements,[])};return await this.coordinator.commit(t),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 Vt=class{source;transforms;constructor(t,e=Ve()){this.source=t,this.transforms=e}async tryGet(t){let e=await this.source.tryGet(t);if(e){if((this.transforms.updates[t]??[]).forEach(s=>Lt(e,s)),this.transforms.deletes?.includes(t))return}else if(Object.hasOwn(this.transforms.inserts,t))return structuredClone(this.transforms.inserts[t]);return e}generateId(){return this.source.generateId()}createBlockHeader(t,e){return this.source.createBlockHeader(t,e)}insert(t){this.transforms.inserts[t.header.id]=structuredClone(t),this.transforms.deletes.splice(this.transforms.deletes.indexOf(t.header.id),1)}update(t,e){let r=this.transforms.inserts[t];r?Lt(r,e):Ws(this.transforms.updates,t,()=>[]).push(structuredClone(e))}delete(t){delete this.transforms.inserts[t],delete this.transforms.updates[t],this.transforms.deletes.push(t)}reset(t=Ve()){let e=this.transforms;return this.transforms=t,e}transformedBlockIds(){return Array.from(new Set(At(this.transforms)))}conflicts(t){return this.transformedBlockIds().filter(e=>t.has(e))}};var Qr=class{engines;createValidationCoordinator;constructor(t,e){this.engines=t,this.createValidationCoordinator=e}async validate(t,e){let{stamp:r,statements:s}=t,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 c=this.createValidationCoordinator();try{let a=await o.engine.execute(t);if(!a.success)return{valid:!1,reason:`Re-execution failed: ${a.error}`};a.actions&&a.actions.length>0&&await c.applyActions(a.actions,r.id);let f=c.getTransforms(),u=this.collectOperations(f),l=this.hashOperations(u);return l!==e?{valid:!1,reason:"Operations hash mismatch",computedHash:l}:{valid:!0,computedHash:l}}finally{c.dispose()}}async getSchemaHash(t){let e=this.engines.get(t);return e?await e.getSchemaHash():void 0}collectOperations(t){return Array.from(t.entries()).flatMap(([e,r])=>[...Object.entries(r.inserts).map(([s,o])=>({type:"insert",collectionId:e,blockId:s,block:o})),...Object.entries(r.updates).map(([s,o])=>({type:"update",collectionId:e,blockId:s,operations:o})),...r.deletes.map(s=>({type:"delete",collectionId:e,blockId:s}))])}hashOperations(t){let e=JSON.stringify(t),r=Array.from(e).reduce((s,o)=>{let i=o.charCodeAt(0);return(s<<5)-s+i&s},0);return`ops:${Math.abs(r).toString(36)}`}};var Js=Symbol.for("@libp2p/peer-id");var tn=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var en=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},rn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var fa=Symbol.for("nodejs.util.inspect.custom"),Vf=114,pr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Js]=!0;toString(){return this.string==null&&(this.string=Y.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return ot.createV1(Vf,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[fa](){return`PeerId(${this.toString()})`}},nn=class extends pr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},sn=class extends pr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},on=class extends pr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Ff=2336,mr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=bt.digest(Zt(this.url))}[fa](){return`PeerId(${this.url})`}[Js]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return ot.createV1(Ff,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=X(t)),t.toString()===this.toString())}};var $f=114,la=2336;function ua(n,t){let e;if(n.charAt(0)==="1"||n.charAt(0)==="Q")e=Ze(Y.decode(`z${n}`));else{if(n.startsWith("k51qzi5uqu5")||n.startsWith("kzwfwjn5ji4")||n.startsWith("k2k4r8")||n.startsWith("bafz"))return jf(ot.parse(n));if(t==null)throw new tn('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Ze(t.decode(n))}return da(e)}function da(n){if(Zf(n))return new nn({multihash:n});if(Gf(n))try{let t=ia(n);if(t.type==="Ed25519")return new sn({multihash:n,publicKey:t});if(t.type==="secp256k1")return new on({multihash:n,publicKey:t})}catch{let e=X(n.digest);return new mr(new URL(e))}throw new rn("Supplied PeerID Multihash is invalid")}function jf(n){if(n?.multihash==null||n.version==null||n.version===1&&n.code!==$f&&n.code!==la)throw new en("Supplied PeerID CID is invalid");if(n.code===la){let t=X(n.multihash.digest);return new mr(new URL(t))}return da(n.multihash)}function Gf(n){return n.code===bt.code}function Zf(n){return n.code===Nt.code}async function mt(n){let t=new TextEncoder().encode(n);return(await Nt.digest(t)).digest}function ha(n){for(let t in n)return!1;return!0}var yr=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(t){this.promise=t,t.then(e=>(this.duration=Date.now()-this.t1,this.response=e,e),e=>{this.duration=Date.now()-this.t1,this.error=e})}};function Qs(n,t,e,r){let s=n.reduce((o,[i,c])=>{let a=c.toString(),f=o.get(a)??{peerId:c,blockId:i,excludedPeers:r};return o.set(a,{...f,payload:e(t,i,f.payload)}),o},new Map);return Array.from(s.values())}function*pa(n){let t=[...n];for(;t.length>0;){let e=t.pop();(!e.request||!e.request.isResponse)&&(yield e),e.subsumedBy&&e.subsumedBy.length&&t.push(...e.subsumedBy)}}function to(n,t){for(let e of n){let r=!1,s=[e];for(;s.length>0;){let o=s.pop();if(t(o)){r=!0;break}if(o.subsumedBy&&o.subsumedBy.length)for(let i=0;i<o.subsumedBy.length;i++)s.push(o.subsumedBy[i])}if(!r)return!1}return!0}function*Ft(n,t){let e=[...n];for(;e.length>0;){let r=e.pop();(!t||t(r))&&(yield r),r.subsumedBy&&r.subsumedBy.length&&e.push(...r.subsumedBy)}}function xe(n,t,e){return[...e??[],t]}async function ge(n,t,e,r,s,o){let i=new WeakMap;for(let a of n)i.set(a,a);let c=async a=>{await Promise.all(a.map(async f=>{f.request=new yr(t(f).catch(async u=>{if(s>Date.now()){let l=[f.peerId,...f.excludedPeers??[]],d=await an(e(f),f.payload,r,l,o);if(d.length>0&&s>Date.now()){let p=i.get(f)??f;p.subsumedBy=[...p.subsumedBy??[],...d];for(let h of d)i.set(h,p);await c(d)}}throw u}))})),await Promise.all(a.map(f=>f.request?.result().catch(()=>{})))};await c(n)}async function an(n,t,e,r,s){let o=new Set(n),i=await Promise.all(Array.from(o).map(async c=>[c,await s(c,{excludedPeers:r})]));return Qs(i,t,e,r)}var eo=class{keyNetwork;timeoutMs;abortOrCancelTimeoutMs;getRepo;constructor(t){this.keyNetwork=t.keyNetwork,this.timeoutMs=t.timeoutMs,this.abortOrCancelTimeoutMs=t.abortOrCancelTimeoutMs,this.getRepo=t.getRepo}async get(t){let e=Array.from(new Set(t.blockIds)),r=await this.batchesForPayload(e,e,(d,p,h)=>[...h??[],...d.filter(I=>I===p)],[]),s=Date.now()+this.timeoutMs,o;try{await ge(r,d=>this.getRepo(d.peerId).get({blockIds:d.payload,context:t.context},{expiration:s}),d=>d.payload,(d,p,h)=>[...h??[],...d.filter(I=>I===p)],s,async(d,p)=>this.keyNetwork.findCoordinator(await mt(d),p))}catch(d){o=d}let i=d=>d.request?.isResponse===!0&&d.request.response!=null,c=d=>{if(!i(d))return!1;let p=d.request.response;return d.payload.some(h=>{let I=p[h];return I&&typeof I=="object"&&"block"in I&&I.block!=null})},a=Array.from(Ft(r)).filter(d=>!i(d)||!c(d));if(a.length>0&&Date.now()<s)try{let d=new Map;for(let p of a){let h=new Set([p.peerId,...p.excludedPeers??[]]);d.set(p,h);let I=await an(p.payload,p.payload,(b,x,S)=>[...S??[],...b.filter(w=>w===x)],Array.from(h),async(b,x)=>this.keyNetwork.findCoordinator(await mt(b),x));I.length>0&&(p.subsumedBy=[...p.subsumedBy??[],...I],await ge(I,b=>this.getRepo(b.peerId).get({blockIds:b.payload,context:t.context},{expiration:s}),b=>b.payload,(b,x,S)=>[...S??[],...b.filter(w=>w===x)],s,async(b,x)=>this.keyNetwork.findCoordinator(await mt(b),x)))}}catch(d){o||(o=d)}let f=Array.from(Ft(r,d=>d.request?.isResponse&&!ha(d.request.response))),u=new Map;for(let d of f){let p=d.request.response;for(let[h,I]of Object.entries(p)){let b=u.get(h),x=I&&typeof I=="object"&&"block"in I&&I.block!=null,S=b&&typeof b=="object"&&"block"in b&&b.block!=null;(!b||x&&!S)&&u.set(h,I)}}if(e.filter(d=>!u.has(d)).length>0){let d=this.formatBatchStatuses(r,h=>h.request?.isResponse??!1,h=>{let I=h.request==null?"no-response":h.request.isResponse?"response":"in-flight";return`${h.peerId.toString()}[block:${h.blockId}](${I})`}),p=new Error(`Some peers did not complete: ${d}${o?`; root: ${o.message}`:""}`);throw p.cause=o,p}return Object.fromEntries(u)}async getStatus(t){throw new Error("Method not implemented.")}async consolidateCoordinators(t,e,r){let s=await Promise.all(t.map(async c=>({blockId:c,coordinator:await this.keyNetwork.findCoordinator(await mt(c),{excludedPeers:[]})}))),o=new Map;for(let{blockId:c,coordinator:a}of s){let f=a.toString(),u=o.get(f)??[];u.push(c),o.set(f,u)}let i=[];for(let[c,a]of o){let f=s.find(l=>l.coordinator.toString()===c).coordinator,u={inserts:{},updates:{},deletes:[]};for(let l of a)u=r(e,l,u);i.push({peerId:f,payload:u,blockId:a[0],coordinatingBlockIds:a,excludedPeers:[]})}return i}async pend(t){let e=(a,f,u)=>{let l=hn(a,f);return u?yn(u,f,l):pn(l,f)},r=At(t.transforms),s=await this.consolidateCoordinators(r,t.transforms,e),o=Date.now()+this.timeoutMs,i;try{await ge(s,a=>this.getRepo(a.peerId).pend({...t,transforms:a.payload},{expiration:o,coordinatingBlockIds:a.coordinatingBlockIds}),a=>At(a.payload),e,o,async(a,f)=>this.keyNetwork.findCoordinator(await mt(a),f));try{let a=this.keyNetwork;if(typeof a?.recordCoordinator=="function")for(let f of Array.from(Ft(s)))a.recordCoordinator(await mt(f.blockId),f.peerId)}catch(a){console.warn("Failed to record coordinator hint",a)}}catch(a){i=a}if(!to(s,a=>a.request?.isResponse&&a.request.response.success)){let a=this.formatBatchStatuses(s,l=>(l.request?.isResponse&&l.request.response?.success)??!1,l=>{let d=l.request==null?"no-response":l.request.isResponse?"non-success":"in-flight";return`${l.peerId.toString()}[block:${l.blockId}](${d})`}),f=new Error(`Some peers did not complete: ${a}${i?`; root: ${i.message}`:""}`),u=i;f.cause=u,f.errors=u?[u]:[],i=f}if(i){Promise.resolve().then(()=>this.cancelBatch(s,{blockIds:r,actionId:t.actionId}));let a=Array.from(Ft(s,f=>f.request?.isResponse&&!f.request.response.success));if(a.length>0)return{success:!1,missing:ro(a.flatMap(f=>f.request.response.missing).filter(f=>f!==void 0))};throw i}return{success:!0,pending:Array.from(Ft(s,a=>a.request?.isResponse&&a.request.response.success)).flatMap(a=>a.request.response.pending),blockIds:At(t.transforms)}}async cancel(t){let e=await this.batchesForPayload(t.blockIds,t.blockIds,xe,[]),r=Date.now()+this.abortOrCancelTimeoutMs;await ge(e,s=>this.getRepo(s.peerId).cancel({actionId:t.actionId,blockIds:s.payload},{expiration:r}),s=>s.payload,xe,r,async(s,o)=>this.keyNetwork.findCoordinator(await mt(s),o))}async queryClusterNominees(t){let e=await mt(t),r=await this.keyNetwork.findCluster(e);return{nominees:Object.keys(r).map(o=>ua(o))}}async commit(t){let e=[...new Set([...t.blockIds,t.tailId])];if(t.headerId&&!t.blockIds.includes(t.headerId)){let o=await this.commitBlock(t.headerId,e,t.actionId,t.rev);if(!o.success)return o}let r=await this.commitBlock(t.tailId,e,t.actionId,t.rev);if(!r.success)return r;let s=t.blockIds.filter(o=>o!==t.tailId&&!(t.headerId&&o===t.headerId&&!t.blockIds.includes(t.headerId)));if(s.length>0){let{batches:o,error:i}=await this.commitBlocks({blockIds:s,actionId:t.actionId,rev:t.rev});if(i)try{console.warn("[NetworkTransactor] non-tail commit had errors; proceeding after tail commit:",i.message)}catch{}}return{success:!0}}async commitBlock(t,e,r,s){let{batches:o,error:i}=await this.commitBlocks({blockIds:[t],actionId:r,rev:s});if(i){Promise.resolve().then(()=>this.cancel({blockIds:e,actionId:r}));let c=Array.from(Ft(o,a=>a.request?.isResponse&&!a.request.response.success));if(c.length>0)return{missing:ro(c.flatMap(a=>a.request.response.missing)),success:!1};throw i}return{success:!0}}async commitBlocks({blockIds:t,actionId:e,rev:r}){let s=Date.now()+this.timeoutMs,o=await this.batchesForPayload(t,t,xe,[]),i;try{await ge(o,c=>this.getRepo(c.peerId).commit({actionId:e,blockIds:c.payload,rev:r},{expiration:s}),c=>c.payload,xe,s,async(c,a)=>this.keyNetwork.findCoordinator(await mt(c),a))}catch(c){i=c}if(!to(o,c=>c.request?.isResponse&&c.request.response.success)){let c=this.formatBatchStatuses(o,f=>(f.request?.isResponse&&f.request.response?.success)??!1,f=>{let u=f.request==null?"no-response":f.request.isResponse?"non-success":"in-flight",l=f.request?.response,d=l&&l.success===!1?Array.isArray(l.missing)?` missing=${l.missing.length}`:" success=false":"";return`${f.peerId.toString()}[blocks:${f.payload instanceof Array?f.payload.length:1}](${u})${d?" "+d:""}`}),a=new Error(`Some peers did not complete: ${c}${i?`; root: ${i.message}`:""}`);a.cause=i,i=a}return{batches:o,error:i}}async batchesForPayload(t,e,r,s){return an(t,e,r,s,async(o,i)=>this.keyNetwork.findCoordinator(await mt(o),i))}async cancelBatch(t,e){let r=Date.now()+this.abortOrCancelTimeoutMs,s=Qs(Array.from(Ft(t)).map(o=>[o.blockId,o.peerId]),e.blockIds,xe,[]);await ge(s,o=>this.getRepo(o.peerId).cancel({actionId:e.actionId,blockIds:o.payload},{expiration:r}),o=>o.payload,xe,r,async(o,i)=>this.keyNetwork.findCoordinator(await mt(o),i))}formatBatchStatuses(t,e,r){let o=Array.from(pa(t)).map(r).join(", ");return o.length===0&&(o=Array.from(Ft(t)).map(r).join(", ")),o}};function ro(n){let t=no(n,({actionId:e})=>e);return Object.entries(t).map(([e,r])=>({actionId:e,transforms:dn(...r.map(s=>s.transforms))}))}var Me=class{collectionId;transactor;actionContext;constructor(t,e,r){this.collectionId=t,this.transactor=e,this.actionContext=r}createBlockHeader(t,e){return{type:t,id:e??this.generateId(),collectionId:this.collectionId}}generateId(){return X(Pe(32),"base64url")}async tryGet(t){let e=await this.transactor.get({blockIds:[t],context:this.actionContext});if(e){let{block:r,state:s}=e[t];return r}}async transact(t,e,r,s,o){let i=await this.transactor.pend({transforms:t,actionId:e,rev:r,policy:"r"});if(!i.success)return i;let c=Object.hasOwn(t.inserts,s),a=await this.transactor.commit({headerId:c?s:void 0,tailId:o,blockIds:i.blockIds,actionId:e,rev:r});if(!a.success)return a}};var Dt=class extends Vt{store;constructor(t){super(t),this.store=t}commit(){let t=this.reset();mn(t,this.store)}};var lr=class{source;cache=new Map;constructor(t){this.source=t}async tryGet(t){let e=this.cache.get(t);return e||(e=await this.source.tryGet(t),e&&this.cache.set(t,e)),structuredClone(e)}generateId(){return this.source.generateId()}createBlockHeader(t,e){return this.source.createBlockHeader(t,e)}clear(t=void 0){if(t)for(let e of t)this.cache.delete(e);else this.cache.clear()}transformCache(t){for(let e of t.deletes)this.cache.delete(e);for(let[,e]of Object.entries(t.inserts))this.cache.set(e.header.id,structuredClone(e));for(let[e,r]of Object.entries(t.updates))for(let s of r){let o=this.cache.get(e);o&&Lt(o,s)}}};function no(n,t){return n.reduce((e,r)=>{let s=t(r);return(e[s]??=[]).push(r),e},{})}function Ws(n,t,e,r){let s=n[t];return typeof s>"u"?(s=e(),n[t]=s):r&&r(s),s}function zf(n,t,e,r){let s=n.get(t);return typeof s>"u"?(s=e(),n.set(t,s)):r&&r(s),s}return ba(Yf);})();
2
+ "use strict";var OptimysticDbCore=(()=>{var Mn=Object.defineProperty;var rf=Object.getOwnPropertyDescriptor;var nf=Object.getOwnPropertyNames;var of=Object.prototype.hasOwnProperty;var sf=(r,t)=>()=>(r&&(t=r(r=0)),t);var at=(r,t)=>{for(var e in t)Mn(r,e,{get:t[e],enumerable:!0})},af=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of nf(t))!of.call(r,o)&&o!==e&&Mn(r,o,{get:()=>t[o],enumerable:!(n=rf(t,o))||n.enumerable});return r};var cf=r=>af(Mn({},"__esModule",{value:!0}),r);var Nc={};at(Nc,{ACTIONS_ENGINE_ID:()=>$s,ActionsEngine:()=>Ur,createActionsStatements:()=>Or});function Or(r){return r.map(t=>JSON.stringify(t))}var $s,Ur,Bn=sf(()=>{"use strict";$s="actions@1.0.0",Ur=class{coordinator;constructor(t){this.coordinator=t}async execute(t){try{let e=[];for(let n of t.statements){let o=JSON.parse(n);if(!o.collectionId||typeof o.collectionId!="string")return{success:!1,error:"Invalid statement: missing collectionId"};if(!o.actions||!Array.isArray(o.actions))return{success:!1,error:`Invalid statement: collection ${o.collectionId} missing or invalid actions array`};e.push(o),await this.coordinator.applyActions([o],t.stamp.id)}return{success:!0,actions:e}}catch(e){return{success:!1,error:`Failed to execute transaction: ${e instanceof Error?e.message:String(e)}`}}}}});var mh={};at(mh,{ACTIONS_ENGINE_ID:()=>$s,ActionsEngine:()=>Ur,Atomic:()=>Ut,BTree:()=>jt,CacheSource:()=>Lr,Chain:()=>Be,Collection:()=>ve,Diary:()=>Ts,DiaryHeaderBlockType:()=>Ls,EntriesPerBlock:()=>to,KeyBound:()=>Zn,KeyRange:()=>Yn,Keyset:()=>Xn,Latches:()=>ie,Log:()=>xt,LogDataBlockType:()=>Vs,LogHeaderBlockType:()=>Fs,NetworkTransactor:()=>ei,NodeCapacity:()=>ft,Path:()=>ue,PathBranch:()=>Bt,Pending:()=>Vr,Tracker:()=>Ft,TransactionContext:()=>Cn,TransactionCoordinator:()=>kn,TransactionSession:()=>Dn,TransactionValidator:()=>Tn,TransactorSource:()=>We,Tree:()=>Os,TreeHeaderBlockType:()=>Ns,apply:()=>_,applyOperation:()=>Nt,applyOperations:()=>ai,applyTransform:()=>uf,applyTransformToStore:()=>zn,blockIdToBytes:()=>mt,blockIdsForTransforms:()=>At,concatTransform:()=>jn,concatTransforms:()=>Vn,copyTransforms:()=>qn,createActionsStatements:()=>Or,createTransactionId:()=>Qe,createTransactionStamp:()=>Je,distinctBlockActionTransforms:()=>ri,emptyTransforms:()=>sr,ensured:()=>oi,ensuredMap:()=>ph,entryAt:()=>de,get:()=>X,groupBy:()=>ni,hashString:()=>ae,isTransformsEmpty:()=>Hn,mergeTransforms:()=>ci,nameof:()=>nt,pathValid:()=>hi,priorHash$:()=>Dd,registerBlockType:()=>bt,rootId$:()=>Us,transformForBlockId:()=>Fn,transformsFromTransform:()=>$n,withOperation:()=>ff});var Kn=new Map;function bt(r,t){if(Kn.has(r))throw new Error(`Block type ${r} (${t}) already registered (${Kn.get(r)})`);return Kn.set(r,t),r}function Nt(r,[t,e,n,o]){Array.isArray(o)?r[t].splice(e,n,...structuredClone(o)):r[t]=structuredClone(o)}function ai(r,t){for(let e of t)Nt(r,e)}function ff(r,[t,e,n,o]){if(Array.isArray(o)){let s=r[t];return{...r,[t]:[...s.slice(0,e),...structuredClone(o),...s.slice(e+n)]}}else return{...r,[t]:structuredClone(o)}}function At(r){if(!r)return[];let t=Object.keys(r.inserts??{}),e=Object.keys(r.updates??{}),n=r.deletes??[];return[...new Set([...t,...e,...n])]}function sr(){return{inserts:{},updates:{},deletes:[]}}function qn(r){let t=r.updates?Object.fromEntries(Object.entries(r.updates).map(([e,n])=>[e,structuredClone(n)])):void 0;return{inserts:{...r.inserts},updates:t,deletes:r.deletes?[...r.deletes]:void 0}}function ci(r,t){return{inserts:{...r.inserts,...t.inserts},updates:{...r.updates,...t.updates},deletes:[...r.deletes??[],...t.deletes??[]]}}function Hn(r){return Object.keys(r.inserts??{}).length===0&&Object.keys(r.updates??{}).length===0&&(r.deletes?.length??0)===0}function Vn(...r){return r.reduce((t,e)=>ci(t,e),sr())}function Fn(r,t){return{...r.inserts&&t in r.inserts?{insert:r.inserts[t]}:{},...r.updates&&t in r.updates?{updates:structuredClone(r.updates[t])}:{},...r.deletes?.includes(t)?{delete:!0}:{}}}function $n(r,t){return{inserts:r.insert?{[t]:r.insert}:{},updates:r.updates?{[t]:r.updates}:{},deletes:r.delete?[t]:[]}}function zn(r,t){for(let e of r.deletes??[])t.delete(e);for(let[,e]of Object.entries(r.inserts??{}))t.insert(e);for(let[e,n]of Object.entries(r.updates??{}))for(let o of n)t.update(e,o)}function uf(r,t){if(t.insert&&(r=t.insert),r&&t.updates&&ai(r,t.updates),!t.delete)return r}function jn(r,t,e){return{inserts:{...r.inserts,...e.insert?{[t]:e.insert}:{}},updates:{...r.updates,...e.updates?{[t]:e.updates}:{}},deletes:[...r.deletes??[],...e.delete?[t]:[]]}}async function X(r,t){let e=await r.tryGet(t);if(!e)throw Error(`Missing block (${t})`);return e}function _(r,t,e){Nt(t,e),r.update(t.header.id,e)}function nt(r,t){return t??r}var fe=bt("TL","TreeLeaf"),Gn=bt("TB","TreeBranch"),yt=nt("entries"),wt=nt("partitions"),zt=nt("nodes");var ft=64,jt=class r{store;trunk;keyFromEntry;compare;_version=0;constructor(t,e,n=s=>s,o=(s,i)=>s<i?-1:s>i?1:0){this.store=t,this.trunk=e,this.keyFromEntry=n,this.compare=o}static createRoot(t){return fi(t,[])}static create(t,e,n=i=>i,o=(i,a)=>i<a?-1:i>a?1:0,s){let i=r.createRoot(t);t.insert(i);let a=e(t,i.header.id,s);return new r(t,a,n,o)}async first(){return await this.getFirst(await this.trunk.get())}async last(){return await this.getLast(await this.trunk.get())}async find(t){return await this.getPath(await this.trunk.get(),t)}async get(t){return this.at(await this.find(t))}at(t){return this.validatePath(t),t.on?this.getEntry(t):void 0}async*range(t){let e=t.first?await this.findFirst(t):t.isAscending?await this.first():await this.last(),n=t.last?await this.findLast(t):t.isAscending?await this.last():await this.first();if(!n.on)return;let o=this.keyFromPath(n),i=(t.isAscending?this.internalAscending(e):this.internalDescending(e))[Symbol.asyncIterator](),a=t.isAscending?1:-1;for await(let c of i){if(!c.on||this.compare(this.keyFromPath(c),o)*a>0)break;yield c}}isValid(t){return t.version===this._version}async insert(t){Object.freeze(t);let e=await this.internalInsert(t);return e.on&&(e.version=++this._version),e}async updateAt(t,e){this.validatePath(t),t.on&&Object.freeze(e);let n=await this.internalUpdate(t,e);return n[0].on&&(n[0].version=++this._version),n}async upsert(t){let e=await this.find(this.keyFromEntry(t));return Object.freeze(t),e.on?this.updateEntry(e,t):await this.internalInsertAt(e,t),e.version=++this._version,e}async merge(t,e){let n=await this.keyFromEntry(t),o=await this.find(n);return o.on?await this.updateAt(o,e(this.getEntry(o))):(await this.internalInsertAt(o,Object.freeze(t)),o.on=!0,o.version=++this._version,[o,!1])}async deleteAt(t){this.validatePath(t);let e=await this.internalDelete(t);return e&&++this._version,e}async drop(){let t=await this.trunk.get();for await(let e of this.nodeIds(t))this.store.delete(e)}ascending(t){return this.validatePath(t),this.internalAscending(t.clone())}descending(t){return this.validatePath(t),this.internalDescending(t.clone())}async getCount(t){let e=0,n=t?t.path.clone():await this.first();if(t?.ascending??!0)for(;n.on;)e+=n.leafNode.entries.length-n.leafIndex,n.leafIndex=n.leafNode.entries.length-1,await this.internalNext(n);else for(;n.on;)e+=n.leafIndex+1,n.leafIndex=0,await this.internalPrior(n);return e}async next(t){let e=t.clone();return await this.moveNext(e),e}async moveNext(t){this.validatePath(t),await this.internalNext(t)}async prior(t){let e=t.clone();return this.movePrior(e),e}async movePrior(t){this.validatePath(t),await this.internalPrior(t)}keyFromPath(t){return this.keyFromEntry(t.leafNode.entries[t.leafIndex])}async*internalAscending(t){for(this.validatePath(t);t.on;)yield t,await this.moveNext(t)}async*internalDescending(t){for(this.validatePath(t);t.on;)yield t,await this.movePrior(t)}async findFirst(t){let e=await this.find(t.first.key);return(!e.on||t.first&&!t.first.inclusive)&&(t.isAscending?await this.internalNext(e):await this.internalPrior(e)),e}async findLast(t){let e=await this.find(t.last.key);return(!e.on||t.last&&!t.last.inclusive)&&(t.isAscending?await this.internalPrior(e):await this.internalNext(e)),e}async getPath(t,e){if(t.header.type===fe){let n=t,[o,s]=this.indexOfEntry(n.entries,e);return new ue([],n,s,o,this._version)}else{let n=t,o=this.indexOfKey(n.partitions,e),s=await this.getPath(await X(this.store,n.nodes[o]),e);return s.branches.unshift(new Bt(n,o)),s}}indexOfEntry(t,e){let n=0,o=t.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compare(e,this.keyFromEntry(t[s])),i===0)return[!0,s];i<0?o=s-1:n=s+1}return[!1,n]}indexOfKey(t,e){let n=0,o=t.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compare(e,t[s]),i===0)return s+1;i<0?o=s-1:n=s+1}return n}async internalNext(t){if(t.on)if(t.leafIndex>=t.leafNode.entries.length-1){let e=0,n=!1,o=t.branches.length-1;for(;e<=o&&!n;){let s=t.branches[o-e];s.index===s.node.partitions.length?++e:n=!0}if(!n)t.leafIndex=t.leafNode.entries.length,t.on=!1;else{t.branches.splice(-e,e);let s=t.branches.at(-1);++s.index,this.moveToFirst(await X(this.store,s.node.nodes[s.index]),t)}}else++t.leafIndex,t.on=!0;else if(t.on=t.branches.every(e=>e.index>=0&&e.index<e.node.nodes.length)&&t.leafIndex>=0&&t.leafIndex<t.leafNode.entries.length,t.on)return}async internalPrior(t){if(this.validatePath(t),t.leafIndex<=0){let e=0,n=!1,o=t.branches.length-1;for(;e<=o&&!n;)t.branches[o-e].index===0?++e:n=!0;if(!n)t.leafIndex=0,t.on=!1;else{t.branches.splice(-e,e);let s=t.branches.at(-1);--s.index,await this.moveToLast(await X(this.store,s.node.nodes[s.index]),t)}}else--t.leafIndex,t.on=!0}async internalUpdate(t,e){if(t.on){let n=this.keyFromPath(t),o=this.keyFromEntry(e);if(this.compare(n,o)!==0){let s=await this.internalInsert(e);return s.on&&(this.internalDelete(await this.find(n)),s=await this.find(o)),[s,!1]}else this.updateEntry(t,e)}return[t,!0]}async internalDelete(t){if(t.on){if(_(this.store,t.leafNode,[yt,t.leafIndex,1,[]]),t.branches.length>0){if(t.leafIndex===0&&t.leafNode.entries.length>0){let n=t.branches.at(-1);this.updatePartition(n.index,t,t.branches.length-1,this.keyFromPath(t))}let e=await this.rebalanceLeaf(t,t.branches.length);e&&await this.trunk.set(e)}return t.on=!1,!0}else return!1}async internalInsert(t){let e=await this.find(this.keyFromEntry(t));return e.on?(e.on=!1,e):(await this.internalInsertAt(e,t),e.on=!0,e)}async internalInsertAt(t,e){let n=this.leafInsert(t,e),o=t.branches.length-1;for(;n&&o>=0;)n=await this.branchInsert(t,o,n),--o;if(n){let s=ui(this.store,[n.key],[await this.trunk.getId(),n.right.header.id]);await this.store.insert(s),await this.trunk.set(s),t.branches.unshift(new Bt(s,n.indexDelta))}}async moveToFirst(t,e){if(t.header.type===fe){let n=t;e.leafNode=n,e.leafIndex=0,e.on=n.entries.length>0}else e.branches.push(new Bt(t,0)),await this.moveToFirst(await X(this.store,t.nodes[0]),e)}async moveToLast(t,e){if(t.header.type===fe){let n=t,o=n.entries.length;e.leafNode=n,e.on=o>0,e.leafIndex=o>0?o-1:0}else{let n=t,o=new Bt(n,n.partitions.length);e.branches.push(o),await this.moveToLast(await X(this.store,n.nodes[o.index]),e)}}async getFirst(t){if(t.header.type===fe){let e=t;return new ue([],e,0,e.entries.length>0,this._version)}else{let e=t,n=await this.getFirst(await X(this.store,e.nodes[0]));return n.branches.unshift(new Bt(e,0)),n}}async getLast(t){if(t.header.type===fe){let e=t,n=e.entries.length;return new ue([],e,n>0?n-1:0,n>0,this._version)}else{let e=t,n=e.nodes.length-1,o=await this.getLast(await X(this.store,e.nodes[n]));return o.branches.unshift(new Bt(e,n)),o}}leafInsert(t,e){let{leafNode:n,leafIndex:o}=t;if(n.entries.length<ft){_(this.store,n,[yt,o,0,[e]]);return}let s=n.entries.length+1>>>1,i=n.entries.slice(s);o>=s&&i.splice(o-s,0,e);let a=fi(this.store,i);return this.store.insert(a),_(this.store,n,[yt,s,n.entries.length-s,[]]),o<s?_(this.store,n,[yt,o,0,[e]]):(t.leafNode=a,t.leafIndex-=s),new $r(this.keyFromEntry(i[0]),a,o<s?0:1)}async branchInsert(t,e,n){let o=t.branches[e],{index:s,node:i}=o;if(o.index+=n.indexDelta,i.nodes.length<ft){_(this.store,i,[wt,s,0,[n.key]]),_(this.store,i,[zt,s+1,0,[n.right.header.id]]);return}let a=i.nodes.length+1>>>1,c=i.partitions.slice(a),f=i.nodes.slice(a),l=o.index<a?0:1;l&&(o.index-=a,c.splice(o.index,0,n.key),f.splice(o.index+1,0,n.right.header.id));let u=ui(this.store,c,f),h=i.partitions[a-1];return _(this.store,i,[wt,a-1,c.length+1,[]]),_(this.store,i,[zt,a,f.length,[]]),o.index<a&&(_(this.store,i,[wt,s,0,[n.key]]),_(this.store,i,[zt,s+1,0,[n.right.header.id]])),new $r(h,u,l)}async rebalanceLeaf(t,e){if(e===0||t.leafNode.entries.length>=ft>>>1)return;let n=t.leafNode,o=t.branches.at(e-1),s=o.index,i=o.node,a=i.nodes[s+1],c=a?await X(this.store,a):void 0;if(c&&c.entries.length>ft>>>1){let u=c.entries[0];_(this.store,c,[yt,0,1,[]]),_(this.store,n,[yt,n.entries.length,0,[u]]),this.updatePartition(s+1,t,e-1,this.keyFromEntry(u));return}let f=i.nodes[s-1],l=f?await X(this.store,f):void 0;if(l&&l.entries.length>ft>>>1){let u=l.entries[l.entries.length-1];_(this.store,l,[yt,l.entries.length-1,1,[]]),_(this.store,n,[yt,0,0,[u]]),this.updatePartition(s,t,e-1,this.keyFromEntry(u)),t.leafIndex+=1;return}if(c&&c.entries.length+n.entries.length<=ft)return _(this.store,n,[yt,n.entries.length,0,c.entries]),this.deletePartition(i,s),s===0&&this.updatePartition(s,t,e-1,this.keyFromEntry(n.entries[0])),this.store.delete(c.header.id),await this.rebalanceBranch(t,e-1);if(l&&l.entries.length+n.entries.length<=ft)return t.leafNode=l,t.leafIndex+=l.entries.length,_(this.store,l,[yt,l.entries.length,0,n.entries]),this.deletePartition(i,s-1),this.store.delete(n.header.id),await this.rebalanceBranch(t,e-1)}async rebalanceBranch(t,e){let n=t.branches[e],o=n.node;if(e===0&&o.partitions.length===0)return t.branches[e+1]?.node??t.leafNode;if(e===0||o.nodes.length>=ft>>>1)return;let s=t.branches.at(e-1),i=s.index,a=s.node,c=a.nodes[i+1],f=c?await X(this.store,c):void 0;if(f&&f.nodes.length>ft>>>1){let h=f.nodes[0],m=f.partitions[0];this.insertPartition(o,o.partitions.length,a.partitions[i],h),this.deletePartition(f,0,0),this.updatePartition(i+1,t,e-1,m);return}let l=a.nodes[i-1],u=l?await X(this.store,l):void 0;if(u&&u.nodes.length>ft>>>1){let h=u.nodes[u.nodes.length-1],m=u.partitions[u.partitions.length-1];this.insertPartition(o,0,a.partitions[i-1],h,0),this.deletePartition(u,u.partitions.length-1),n.index+=1,this.updatePartition(i,t,e-1,m);return}if(f&&f.nodes.length+o.nodes.length<=ft){let h=a.partitions[i];return this.deletePartition(a,i),_(this.store,o,[wt,o.partitions.length,0,[h]]),_(this.store,o,[wt,o.partitions.length,0,f.partitions]),_(this.store,o,[zt,o.nodes.length,0,f.nodes]),i===0&&a.partitions.length>0&&this.updatePartition(i,t,e-1,a.partitions[0]),this.store.delete(f.header.id),this.rebalanceBranch(t,e-1)}if(u&&u.nodes.length+o.nodes.length<=ft){let h=a.partitions[i-1];return this.deletePartition(a,i-1),_(this.store,u,[wt,u.partitions.length,0,[h]]),_(this.store,u,[wt,u.partitions.length,0,o.partitions]),_(this.store,u,[zt,u.nodes.length,0,o.nodes]),n.node=u,n.index+=u.nodes.length,this.store.delete(o.header.id),this.rebalanceBranch(t,e-1)}}updatePartition(t,e,n,o){let s=e.branches[n];t>0?_(this.store,s.node,[wt,t-1,1,[o]]):n!==0&&this.updatePartition(e.branches[n-1].index,e,n-1,o)}insertPartition(t,e,n,o,s=1){_(this.store,t,[wt,e,0,[n]]),_(this.store,t,[zt,e+s,0,[o]])}deletePartition(t,e,n=1){_(this.store,t,[wt,e,1,[]]),_(this.store,t,[zt,e+n,1,[]])}validatePath(t){if(!this.isValid(t))throw new Error("Path is invalid due to mutation of the tree")}async*nodeIds(t){if(t.header.type===Gn){let e=await Promise.all(t.nodes.map(n=>X(this.store,n)));for(let n of e)yield*this.nodeIds(n)}yield t.header.id}getEntry(t){return t.leafNode.entries[t.leafIndex]}updateEntry(t,e){_(this.store,t.leafNode,[yt,t.leafIndex,1,[e]])}},$r=class{key;right;indexDelta;constructor(t,e,n){this.key=t,this.right=e,this.indexDelta=n}};function fi(r,t){return{header:r.createBlockHeader(fe),entries:t}}function ui(r,t,e){return{header:r.createBlockHeader(Gn),partitions:t,nodes:e}}var Zn=class{key;inclusive;constructor(t,e=!0){this.key=t,this.inclusive=e}},Yn=class{first;last;isAscending;constructor(t,e,n=!0){this.first=t,this.last=e,this.isAscending=n}};var Xn=class extends jt{};var Bt=class r{node;index;constructor(t,e){this.node=t,this.index=e}clone(){return new r(this.node,this.index)}},ue=class r{branches;leafNode;leafIndex;on;version;constructor(t,e,n,o,s){this.branches=t,this.leafNode=e,this.leafIndex=n,this.on=o,this.version=s}isEqual(t){return this.leafNode===t.leafNode&&this.leafIndex===t.leafIndex&&this.on===t.on&&this.version===t.version}clone(){return new r(this.branches.map(t=>t.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var le=nt("entries"),li=nt("priorId"),Wn=nt("nextId"),Jn=bt("CHD","ChainDataBlock"),Qn=nt("headId"),zr=nt("tailId"),di=bt("CHH","ChainHeaderBlock");var to=32,Be=class r{store;id;options;constructor(t,e,n){this.store=t,this.id=e,this.options=n}static async create(t,e){let n=r.createTailBlock(t,e),o={...e?.createHeaderBlock?.(e?.newId)??{header:t.createBlockHeader(di,e?.newId)},headId:n.header.id,tailId:n.header.id};return t.insert(o),t.insert(n),new r(t,o.header.id,e)}static createTailBlock(t,e){return{...e?.createDataBlock?.()??{header:t.createBlockHeader(Jn)},entries:[],priorId:void 0,nextId:void 0}}static async open(t,e,n){let o=await t.tryGet(e);if(!o)return;let s=o;if(!Object.hasOwn(s,"headId")||!Object.hasOwn(s,"tailId")){let i=r.createTailBlock(t,n);t.insert(i),_(t,o,[Qn,0,0,i.header.id]),_(t,o,[zr,0,0,i.header.id])}return new r(t,e,n)}async add(...t){let e=await this.getTail();if(!e)throw new Error("Cannot add to non-existent chain");let{headerBlock:n,block:o}=e,s=o,i=new Ut(this.store),a=t.slice(0,to-s.entries.length);for(a.length>0&&(_(i,s,[le,s.entries.length,0,a]),t=t.slice(a.length));t.length>0;){let c={...this.options?.createDataBlock?.()??{header:this.store.createBlockHeader(Jn)},entries:t.splice(0,Math.min(to,t.length)),priorId:s.header.id,nextId:void 0};await this.options?.newBlock?.(c,o),i.insert(c),_(i,s,[Wn,0,0,c.header.id]),s=c}return s!==o&&_(i,n,[zr,0,0,s.header.id]),i.commit(),{headerBlock:n,block:s,index:s.entries.length-1}}updateAt(t,e){if(!hi(t))throw new Error("Invalid path");let{index:n,block:o}=t;_(this.store,o,[le,n,1,[e]])}async pop(t=1){if(t<=0)return[];let e=await this.getTail();if(!e)return[];let{headerBlock:n,block:o}=e,s=o,i=[],a=new Ut(this.store);for(;t>0;)if(s.entries.length>t){let c=s.entries.slice(-t);i.unshift(...c),_(a,s,[le,s.entries.length-t,t,[]]);break}else if(i.unshift(...s.entries),t-=s.entries.length,s.priorId)a.delete(s.header.id),s=await a.tryGet(s.priorId),_(a,s,[Wn,0,0,void 0]);else{_(a,s,[le,0,s.entries.length,[]]);break}return s!==o&&_(a,n,[zr,0,0,s.header.id]),a.commit(),i}async dequeue(t=1){if(t<=0)return[];let e=new Ut(this.store),n=await this.getHead();if(!n)return[];let{headerBlock:o,block:s}=n,i=s,a=[];for(;t>0;)if(i.entries.length>t){a.push(...i.entries.slice(0,t)),_(e,i,[le,0,t,[]]);break}else if(a.push(...i.entries),t-=i.entries.length,i.nextId)e.delete(i.header.id),i=await e.tryGet(i.nextId),_(e,i,[li,0,0,void 0]);else{_(e,i,[le,0,i.entries.length,[]]);break}return i!==s&&_(e,o,[Qn,0,0,i.header.id]),e.commit(),a}async*select(t,e=!0){let n=t??(e?await this.getHead():await this.getTail());if(!n)return;let o=n.block,s=n.index;if(e)for(;o;){for(;s<o.entries.length;++s)yield{headerBlock:n.headerBlock,block:o,index:s};o=o.nextId?await this.store.tryGet(o.nextId):void 0,s=0}else for(;o;){for(;s>=0;--s)yield{headerBlock:n.headerBlock,block:o,index:s};o=o.priorId?await this.store.tryGet(o.priorId):void 0,s=(o?.entries.length??0)-1}}async next(t){let{headerBlock:e,block:n,index:o}=t;return o<n.entries.length-1||!n.nextId?{headerBlock:e,block:n,index:o+1}:{headerBlock:e,block:await this.store.tryGet(n.nextId),index:0}}async prev(t){let{headerBlock:e,block:n,index:o}=t;if(o>0||!n.priorId)return{headerBlock:e,block:n,index:o-1};let s=await this.store.tryGet(n.priorId);return{headerBlock:e,block:s,index:s.entries.length-1}}async getTail(t){let e=t??await this.getHeader(),n=e?await this.store.tryGet(e.tailId):void 0;for(;n?.nextId;)n=await this.store.tryGet(n.nextId);return n?{headerBlock:e,block:n,index:n.entries.length-1}:void 0}async getHead(t){let e=t??await this.getHeader(),n=e?await this.store.tryGet(e.headId):void 0;for(;n?.priorId;)n=await this.store.tryGet(n.priorId);return n?{headerBlock:e,block:n,index:0}:void 0}async getHeader(){return await this.store.tryGet(this.id)}};function hi(r){return r.block.entries.length>r.index&&r.index>=0}function de(r){return r.block.entries[r.index]}var ir=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},jr=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var pi={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new jr("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Gr=pi;var gt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Zr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Yr=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Xr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var ar=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var eo=Symbol.for("@libp2p/peer-id");var cp=new Uint8Array(0);function mi(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Gt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function lf(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,b=0,p=0,S=d.length;p!==S&&d[p]===0;)p++,g++;for(var y=(S-p)*l+1>>>0,A=new Uint8Array(y);p!==S;){for(var k=d[p],N=0,C=y-1;(k!==0||N<b)&&C!==-1;C--,N++)k+=256*A[C]>>>0,A[C]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=N,p++}for(var E=y-b;E!==y&&A[E]===0;)E++;for(var I=c.repeat(g);E<y;++E)I+=r.charAt(A[E]);return I}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var b=0,p=0;d[g]===c;)b++,g++;for(var S=(d.length-g)*f+1>>>0,y=new Uint8Array(S);d[g];){var A=e[d.charCodeAt(g)];if(A===255)return;for(var k=0,N=S-1;(A!==0||k<p)&&N!==-1;N--,k++)A+=a*y[N]>>>0,y[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=k,g++}if(d[g]!==" "){for(var C=S-p;C!==S&&y[C]===0;)C++;for(var E=new Uint8Array(b+(S-C)),I=b;C!==S;)E[I++]=y[C++];return E}}}function m(d){var g=h(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:h,decode:m}}var df=lf,hf=df,yi=hf;var ro=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},no=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return gi(this,t)}},oo=class{decoders;constructor(t){this.decoders=t}or(t){return gi(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function gi(r,t){return new oo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var so=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new ro(t,e,n),this.decoder=new no(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function xi({name:r,prefix:t,encode:e,decode:n}){return new so(r,t,e,n)}function ke({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=yi(e,r);return xi({prefix:t,name:r,encode:n,decode:s=>Gt(o(s))})}function pf(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function mf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function yf(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function kt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=yf(n);return xi({prefix:t,name:r,encode(s){return mf(s,n,e)},decode(s){return pf(s,o,e,r)}})}var ot=ke({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mp=ke({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var cr=kt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xp=kt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),bp=kt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),wp=kt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ep=kt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),vp=kt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ip=kt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Sp=kt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ap=kt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Wr=ke({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Cp=ke({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gf=Ei,bi=128,xf=127,bf=~xf,wf=Math.pow(2,31);function Ei(r,t,e){t=t||[],e=e||0;for(var n=e;r>=wf;)t[e++]=r&255|bi,r/=128;for(;r&bf;)t[e++]=r&255|bi,r>>>=7;return t[e]=r|0,Ei.bytes=e-n+1,t}var Ef=io,vf=128,wi=127;function io(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw io.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&wi)<<o:(i&wi)*Math.pow(2,o),o+=7}while(i>=vf);return io.bytes=s-n,e}var If=Math.pow(2,7),Sf=Math.pow(2,14),Af=Math.pow(2,21),Bf=Math.pow(2,28),kf=Math.pow(2,35),Cf=Math.pow(2,42),Df=Math.pow(2,49),Tf=Math.pow(2,56),Lf=Math.pow(2,63),Nf=function(r){return r<If?1:r<Sf?2:r<Af?3:r<Bf?4:r<kf?5:r<Cf?6:r<Df?7:r<Tf?8:r<Lf?9:10},Uf={encode:gf,decode:Ef,encodingLength:Nf},Of=Uf,fr=Of;function ur(r,t=0){return[fr.decode(r,t),fr.decode.bytes]}function Ce(r,t,e=0){return fr.encode(r,t,e),t}function De(r){return fr.encodingLength(r)}function Le(r,t){let e=t.byteLength,n=De(r),o=n+De(e),s=new Uint8Array(o+e);return Ce(r,s,0),Ce(e,s,n),s.set(t,o),new Te(r,e,t,s)}function Ii(r){let t=Gt(r),[e,n]=ur(t),[o,s]=ur(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Te(e,o,i,t)}function Si(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&mi(r.bytes,e.bytes)}}var Te=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Ai(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return _f(e,co(r),t??ot.encoder);default:return Pf(e,co(r),t??cr.encoder)}}var Bi=new WeakMap;function co(r){let t=Bi.get(r);if(t==null){let e=new Map;return Bi.set(r,e),e}return t}var Zt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}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:t,multihash:e}=this;if(t!==lr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Mf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Le(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Si(t.multihash,n.multihash)}toString(t){return Ai(this,t)}toJSON(){return{"/":Ai(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??ki(n,o,s.bytes))}else if(e[Kf]===!0){let{version:n,multihash:o,code:s}=e,i=Ii(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==lr)throw new Error(`Version 0 CID must use dag-pb (code: ${lr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=ki(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,lr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Gt(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Te(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,h]=ur(t.subarray(e));return e+=h,u},o=n(),s=lr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=Rf(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return co(s).set(n,t),s}};function Rf(r,t){switch(r[0]){case"Q":{let e=t??ot;return[ot.prefix,e.decode(`${ot.prefix}${r}`)]}case ot.prefix:{let e=t??ot;return[ot.prefix,e.decode(r)]}case cr.prefix:{let e=t??cr;return[cr.prefix,e.decode(r)]}case Wr.prefix:{let e=t??Wr;return[Wr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function _f(r,t,e){let{prefix:n}=e;if(n!==ot.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Pf(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var lr=112,Mf=18;function ki(r,t,e){let n=De(r),o=n+De(t),s=new Uint8Array(o+e.byteLength);return Ce(r,s,0),Ce(t,s,n),s.set(e,o),s}var Kf=Symbol.for("@ipld/js-cid/CID");var Ci=0,qf="identity",Di=Gt;function Hf(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Le(Ci,Di(r))}var Ne={code:Ci,name:qf,encode:Di,digest:Hf};function Et(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Ot(r=0){return new Uint8Array(r)}function ut(r=0){return new Uint8Array(r)}function Jr(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=ut(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Li=Symbol.for("@achingbrain/uint8arraylist");function Ti(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Qr(r){return!!r?.[Li]}var lt=class r{bufs;length;[Li]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Qr(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Qr(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Ti(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Ti(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Qr(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Jr(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Jr(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let f=t>=a&&t<c,l=e>a&&e<=c;if(f&&l){if(t===a&&e===c){n.push(i);break}let u=t-a;n.push(i.subarray(u,u+(e-t)));break}if(f){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(l){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Qr(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let u=0;u<s;u++)i[u]=-1;for(let u=0;u<o;u++)i[n[u]]=u;let a=i,c=this.byteLength-n.byteLength,f=n.byteLength-1,l;for(let u=e;u<=c;u+=l){l=0;for(let h=f;h>=0;h--){let m=this.get(u+h);if(n[h]!==m){l=Math.max(1,h-a[m]);break}}if(l===0)return u}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=ut(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=Ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=Ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=Ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=ut(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=Ot(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=Ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=Ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=Ot(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=Ot(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var po={};at(po,{base10:()=>Zf});var Jp=new Uint8Array(0);function Ni(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Rt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Ui(r){return new TextEncoder().encode(r)}function Oi(r){return new TextDecoder().decode(r)}function Vf(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,b=0,p=0,S=d.length;p!==S&&d[p]===0;)p++,g++;for(var y=(S-p)*l+1>>>0,A=new Uint8Array(y);p!==S;){for(var k=d[p],N=0,C=y-1;(k!==0||N<b)&&C!==-1;C--,N++)k+=256*A[C]>>>0,A[C]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=N,p++}for(var E=y-b;E!==y&&A[E]===0;)E++;for(var I=c.repeat(g);E<y;++E)I+=r.charAt(A[E]);return I}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var b=0,p=0;d[g]===c;)b++,g++;for(var S=(d.length-g)*f+1>>>0,y=new Uint8Array(S);d[g];){var A=e[d.charCodeAt(g)];if(A===255)return;for(var k=0,N=S-1;(A!==0||k<p)&&N!==-1;N--,k++)A+=a*y[N]>>>0,y[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=k,g++}if(d[g]!==" "){for(var C=S-p;C!==S&&y[C]===0;)C++;for(var E=new Uint8Array(b+(S-C)),I=b;C!==S;)E[I++]=y[C++];return E}}}function m(d){var g=h(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:h,decode:m}}var Ff=Vf,$f=Ff,_i=$f;var fo=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},uo=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Pi(this,t)}},lo=class{decoders;constructor(t){this.decoders=t}or(t){return Pi(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Pi(r,t){return new lo({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ho=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new fo(t,e,n),this.decoder=new uo(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ue({name:r,prefix:t,encode:e,decode:n}){return new ho(r,t,e,n)}function Yt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=_i(e,r);return Ue({prefix:t,name:r,encode:n,decode:s=>Rt(o(s))})}function zf(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function jf(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function Gf(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function G({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Gf(n);return Ue({prefix:t,name:r,encode(s){return jf(s,n,e)},decode(s){return zf(s,o,e,r)}})}var Zf=Yt({prefix:"9",name:"base10",alphabet:"0123456789"});var mo={};at(mo,{base16:()=>Yf,base16upper:()=>Xf});var Yf=G({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Xf=G({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yo={};at(yo,{base2:()=>Wf});var Wf=G({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var go={};at(go,{base256emoji:()=>ru});var Mi=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}"),Jf=Mi.reduce((r,t,e)=>(r[e]=t,r),[]),Qf=Mi.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function tu(r){return r.reduce((t,e)=>(t+=Jf[e],t),"")}function eu(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Qf[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var ru=Ue({prefix:"\u{1F680}",name:"base256emoji",encode:tu,decode:eu});var xo={};at(xo,{base32:()=>Oe,base32hex:()=>iu,base32hexpad:()=>cu,base32hexpadupper:()=>fu,base32hexupper:()=>au,base32pad:()=>ou,base32padupper:()=>su,base32upper:()=>nu,base32z:()=>uu});var Oe=G({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),nu=G({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ou=G({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),su=G({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),iu=G({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),au=G({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cu=G({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),fu=G({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),uu=G({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var bo={};at(bo,{base36:()=>dr,base36upper:()=>lu});var dr=Yt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lu=Yt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wo={};at(wo,{base58btc:()=>Ct,base58flickr:()=>du});var Ct=Yt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),du=Yt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Eo={};at(Eo,{base64:()=>hu,base64pad:()=>pu,base64url:()=>mu,base64urlpad:()=>yu});var hu=G({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),pu=G({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),mu=G({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),yu=G({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var vo={};at(vo,{base8:()=>gu});var gu=G({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Io={};at(Io,{identity:()=>xu});var xu=Ue({prefix:"\0",name:"identity",encode:r=>Oi(r),decode:r=>Ui(r)});var p0=new TextEncoder,m0=new TextDecoder;var Ao={};at(Ao,{identity:()=>Hu});var Eu=Hi,Ki=128,vu=127,Iu=~vu,Su=Math.pow(2,31);function Hi(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Su;)t[e++]=r&255|Ki,r/=128;for(;r&Iu;)t[e++]=r&255|Ki,r>>>=7;return t[e]=r|0,Hi.bytes=e-n+1,t}var Au=So,Bu=128,qi=127;function So(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw So.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&qi)<<o:(i&qi)*Math.pow(2,o),o+=7}while(i>=Bu);return So.bytes=s-n,e}var ku=Math.pow(2,7),Cu=Math.pow(2,14),Du=Math.pow(2,21),Tu=Math.pow(2,28),Lu=Math.pow(2,35),Nu=Math.pow(2,42),Uu=Math.pow(2,49),Ou=Math.pow(2,56),Ru=Math.pow(2,63),_u=function(r){return r<ku?1:r<Cu?2:r<Du?3:r<Tu?4:r<Lu?5:r<Nu?6:r<Uu?7:r<Ou?8:r<Ru?9:10},Pu={encode:Eu,decode:Au,encodingLength:_u},Mu=Pu,hr=Mu;function pr(r,t=0){return[hr.decode(r,t),hr.decode.bytes]}function Re(r,t,e=0){return hr.encode(r,t,e),t}function _e(r){return hr.encodingLength(r)}function Me(r,t){let e=t.byteLength,n=_e(r),o=n+_e(e),s=new Uint8Array(o+e);return Re(r,s,0),Re(e,s,n),s.set(t,o),new Pe(r,e,t,s)}function Vi(r){let t=Rt(r),[e,n]=pr(t),[o,s]=pr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Pe(e,o,i,t)}function Fi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Ni(r.bytes,e.bytes)}}var Pe=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var $i=0,Ku="identity",zi=Rt;function qu(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return Me($i,zi(r))}var Hu={code:$i,name:Ku,encode:zi,digest:qu};var Co={};at(Co,{sha256:()=>Fu,sha512:()=>$u});var Vu=20;function ko({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Bo(r,t,e,n,o)}var Bo=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Vu,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?ji(n,this.code,e?.truncate):n.then(o=>ji(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function ji(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Me(t,r)}function Zi(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Fu=ko({name:"sha2-256",code:18,encode:Zi("SHA-256")}),$u=ko({name:"sha2-512",code:19,encode:Zi("SHA-512")});function Yi(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return ju(e,Do(r),t??Ct.encoder);default:return Gu(e,Do(r),t??Oe.encoder)}}var Xi=new WeakMap;function Do(r){let t=Xi.get(r);if(t==null){let e=new Map;return Xi.set(r,e),e}return t}var en=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}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:t,multihash:e}=this;if(t!==yr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Zu)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=Me(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Fi(t.multihash,n.multihash)}toString(t){return Yi(this,t)}toJSON(){return{"/":Yi(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Wi(n,o,s.bytes))}else if(e[Yu]===!0){let{version:n,multihash:o,code:s}=e,i=Vi(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==yr)throw new Error(`Version 0 CID must use dag-pb (code: ${yr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Wi(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,yr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Rt(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new Pe(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,h]=pr(t.subarray(e));return e+=h,u},o=n(),s=yr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=zu(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Do(s).set(n,t),s}};function zu(r,t){switch(r[0]){case"Q":{let e=t??Ct;return[Ct.prefix,e.decode(`${Ct.prefix}${r}`)]}case Ct.prefix:{let e=t??Ct;return[Ct.prefix,e.decode(r)]}case Oe.prefix:{let e=t??Oe;return[Oe.prefix,e.decode(r)]}case dr.prefix:{let e=t??dr;return[dr.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function ju(r,t,e){let{prefix:n}=e;if(n!==Ct.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Gu(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var yr=112,Zu=18;function Wi(r,t,e){let n=_e(r),o=n+_e(t),s=new Uint8Array(o+e.byteLength);return Re(r,s,0),Re(t,s,n),s.set(e,o),s}var Yu=Symbol.for("@ipld/js-cid/CID");var To={...Io,...yo,...vo,...po,...mo,...xo,...bo,...wo,...Eo,...go},P0={...Co,...Ao};function Qi(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Ji=Qi("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Lo=Qi("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=ut(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Xu={utf8:Ji,"utf-8":Ji,hex:To.base16,latin1:Lo,ascii:Lo,binary:Lo,...To},rn=Xu;function Xt(r,t="utf8"){let e=rn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function Y(r,t="utf8"){let e=rn[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Wu=parseInt("11111",2),No=parseInt("10000000",2),Ju=parseInt("01111111",2),ta={0:gr,1:gr,2:Qu,3:rl,4:nl,5:el,6:tl,16:gr,22:gr,48:gr};function Uo(r,t={offset:0}){let e=r[t.offset]&Wu;if(t.offset++,ta[e]!=null)return ta[e](r,t);throw new Error("No decoder for tag "+e)}function xr(r,t){let e=0;if((r[t.offset]&No)===No){let n=r[t.offset]&Ju,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function gr(r,t){xr(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Uo(r,t);if(n===null)break;e.push(n)}return e}function Qu(r,t){let e=xr(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function tl(r,t){let e=xr(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let f=r[t.offset];if(t.offset++,c.push(f&127),f<128){c.reverse();let l=0;for(let u=0;u<c.length;u++)l+=c[u]<<u*7;a+=`.${l}`,c=[]}}return a}function el(r,t){return t.offset++,null}function rl(r,t){let e=xr(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function nl(r,t){let e=xr(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function ol(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new lt;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Oo(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=ol(r.byteLength);return new lt(Uint8Array.from([t.byteLength|No]),t)}function ea(r){let t=new lt,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new lt(Uint8Array.from([2]),Oo(t),t)}function ra(r){let t=Uint8Array.from([0]),e=new lt(t,r);return new lt(Uint8Array.from([3]),Oo(e),e)}function nn(r,t=48){let e=new lt;for(let n of r)e.append(n);return new lt(Uint8Array.from([t]),Oo(e),e)}async function na(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var sl=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),il=Uint8Array.from([6,5,43,129,4,0,34]),al=Uint8Array.from([6,5,43,129,4,0,35]),cl={ext:!0,kty:"EC",crv:"P-256"},fl={ext:!0,kty:"EC",crv:"P-384"},ul={ext:!0,kty:"EC",crv:"P-521"},Ro=32,_o=48,Po=66;function oa(r){let t=Uo(r);return sa(t)}function sa(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Ro*2+1)return n=Y(t.subarray(e,e+Ro),"base64url"),o=Y(t.subarray(e+Ro),"base64url"),new Ke({...cl,key_ops:["verify"],x:n,y:o});if(t.byteLength===_o*2+1)return n=Y(t.subarray(e,e+_o),"base64url"),o=Y(t.subarray(e+_o),"base64url"),new Ke({...fl,key_ops:["verify"],x:n,y:o});if(t.byteLength===Po*2+1)return n=Y(t.subarray(e,e+Po),"base64url"),o=Y(t.subarray(e+Po),"base64url"),new Ke({...ul,key_ops:["verify"],x:n,y:o});throw new gt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function ia(r){return nn([ea(Uint8Array.from([1])),nn([ll(r.crv)],160),nn([ra(new lt(Uint8Array.from([4]),Xt(r.x??"","base64url"),Xt(r.y??"","base64url")))],161)]).subarray()}function ll(r){if(r==="P-256")return sl;if(r==="P-384")return il;if(r==="P-521")return al;throw new gt(`Invalid curve ${r}`)}var Ke=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=ia(this.jwk)),this._raw}toMultihash(){return Ne.digest(qe(this))}toCID(){return Zt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}async verify(t,e,n){return na(this.jwk,e,t,n)}};function he(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Dt(r,t=""){if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${r}`)}}function K(r,t,e=""){let n=he(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function on(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Dt(r.outputLen),Dt(r.blockLen)}function He(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ca(r,t){K(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Pt(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function sn(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function vt(r,t){return r<<32-t|r>>>t}var fa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dl=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Mt(r){if(K(r),fa)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=dl[r[e]];return t}var _t={_0:48,_9:57,A:65,F:70,a:97,f:102};function aa(r){if(r>=_t._0&&r<=_t._9)return r-_t._0;if(r>=_t.A&&r<=_t.F)return r-(_t.A-10);if(r>=_t.a&&r<=_t.f)return r-(_t.a-10)}function Kt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(fa)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=aa(r.charCodeAt(s)),a=aa(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ct(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];K(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function Mo(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Wt(r=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(r))}var Ko=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ua(r,t,e){return r&t^~r&e}function la(r,t,e){return r&t^r&e^t&e}var br=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=sn(this.buffer)}update(t){He(this),K(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=sn(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){He(this),ca(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Pt(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let u=i;u<o;u++)e[u]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=sn(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let f=c/4,l=this.get();if(f>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)a.setUint32(4*u,l[u],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},qt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var tt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var an=BigInt(4294967295),da=BigInt(32);function hl(r,t=!1){return t?{h:Number(r&an),l:Number(r>>da&an)}:{h:Number(r>>da&an)|0,l:Number(r&an)|0}}function ha(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=hl(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var qo=(r,t,e)=>r>>>e,Ho=(r,t,e)=>r<<32-e|t>>>e,pe=(r,t,e)=>r>>>e|t<<32-e,me=(r,t,e)=>r<<32-e|t>>>e,wr=(r,t,e)=>r<<64-e|t>>>e-32,Er=(r,t,e)=>r>>>e-32|t<<64-e;function Tt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var pa=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),ma=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ya=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),ga=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,xa=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),ba=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var ml=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jt=new Uint32Array(64),Vo=class extends br{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let u=0;u<16;u++,e+=4)Jt[u]=t.getUint32(e,!1);for(let u=16;u<64;u++){let h=Jt[u-15],m=Jt[u-2],d=vt(h,7)^vt(h,18)^h>>>3,g=vt(m,17)^vt(m,19)^m>>>10;Jt[u]=g+Jt[u-7]+d+Jt[u-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:f,H:l}=this;for(let u=0;u<64;u++){let h=vt(a,6)^vt(a,11)^vt(a,25),m=l+h+ua(a,c,f)+ml[u]+Jt[u]|0,g=(vt(n,2)^vt(n,13)^vt(n,22))+la(n,o,s)|0;l=f,f=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,l=l+this.H|0,this.set(n,o,s,i,a,c,f,l)}roundClean(){Pt(Jt)}destroy(){this.set(0,0,0,0,0,0,0,0),Pt(this.buffer)}},Fo=class extends Vo{A=qt[0]|0;B=qt[1]|0;C=qt[2]|0;D=qt[3]|0;E=qt[4]|0;F=qt[5]|0;G=qt[6]|0;H=qt[7]|0;constructor(){super(32)}};var wa=ha(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),yl=wa[0],gl=wa[1],Qt=new Uint32Array(80),te=new Uint32Array(80),$o=class extends br{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:f,El:l,Fh:u,Fl:h,Gh:m,Gl:d,Hh:g,Hl:b}=this;return[t,e,n,o,s,i,a,c,f,l,u,h,m,d,g,b]}set(t,e,n,o,s,i,a,c,f,l,u,h,m,d,g,b){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=l|0,this.Fh=u|0,this.Fl=h|0,this.Gh=m|0,this.Gl=d|0,this.Hh=g|0,this.Hl=b|0}process(t,e){for(let y=0;y<16;y++,e+=4)Qt[y]=t.getUint32(e),te[y]=t.getUint32(e+=4);for(let y=16;y<80;y++){let A=Qt[y-15]|0,k=te[y-15]|0,N=pe(A,k,1)^pe(A,k,8)^qo(A,k,7),C=me(A,k,1)^me(A,k,8)^Ho(A,k,7),E=Qt[y-2]|0,I=te[y-2]|0,P=pe(E,I,19)^wr(E,I,61)^qo(E,I,6),q=me(E,I,19)^Er(E,I,61)^Ho(E,I,6),U=ya(C,q,te[y-7],te[y-16]),w=ga(U,N,P,Qt[y-7],Qt[y-16]);Qt[y]=w|0,te[y]=U|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:f,Dl:l,Eh:u,El:h,Fh:m,Fl:d,Gh:g,Gl:b,Hh:p,Hl:S}=this;for(let y=0;y<80;y++){let A=pe(u,h,14)^pe(u,h,18)^wr(u,h,41),k=me(u,h,14)^me(u,h,18)^Er(u,h,41),N=u&m^~u&g,C=h&d^~h&b,E=xa(S,k,C,gl[y],te[y]),I=ba(E,p,A,N,yl[y],Qt[y]),P=E|0,q=pe(n,o,28)^wr(n,o,34)^wr(n,o,39),U=me(n,o,28)^Er(n,o,34)^Er(n,o,39),w=n&s^n&a^s&a,v=o&i^o&c^i&c;p=g|0,S=b|0,g=m|0,b=d|0,m=u|0,d=h|0,{h:u,l:h}=Tt(f|0,l|0,I|0,P|0),f=a|0,l=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let x=pa(P,U,v);n=ma(x,I,q,w),o=x|0}({h:n,l:o}=Tt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Tt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Tt(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l}=Tt(this.Dh|0,this.Dl|0,f|0,l|0),{h:u,l:h}=Tt(this.Eh|0,this.El|0,u|0,h|0),{h:m,l:d}=Tt(this.Fh|0,this.Fl|0,m|0,d|0),{h:g,l:b}=Tt(this.Gh|0,this.Gl|0,g|0,b|0),{h:p,l:S}=Tt(this.Hh|0,this.Hl|0,p|0,S|0),this.set(n,o,s,i,a,c,f,l,u,h,m,d,g,b,p,S)}roundClean(){Pt(Qt,te)}destroy(){Pt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},zo=class extends $o{Ah=tt[0]|0;Al=tt[1]|0;Bh=tt[2]|0;Bl=tt[3]|0;Ch=tt[4]|0;Cl=tt[5]|0;Dh=tt[6]|0;Dl=tt[7]|0;Eh=tt[8]|0;El=tt[9]|0;Fh=tt[10]|0;Fl=tt[11]|0;Gh=tt[12]|0;Gl=tt[13]|0;Hh=tt[14]|0;Hl=tt[15]|0;constructor(){super(64)}};var Ea=Mo(()=>new Fo,Ko(1));var va=Mo(()=>new zo,Ko(3));var Go=BigInt(0),jo=BigInt(1);function Ht(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function Ia(r){if(typeof r=="bigint"){if(!cn(r))throw new Error("positive bigint expected, got "+r)}else Dt(r);return r}function vr(r){let t=Ia(r).toString(16);return t.length&1?"0"+t:t}function Sa(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Go:BigInt("0x"+r)}function Ve(r){return Sa(Mt(r))}function ye(r){return Sa(Mt(un(K(r)).reverse()))}function fn(r,t){Dt(t),r=Ia(r);let e=Kt(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function Zo(r,t){return fn(r,t).reverse()}function un(r){return Uint8Array.from(r)}var cn=r=>typeof r=="bigint"&&Go<=r;function xl(r,t,e){return cn(r)&&cn(t)&&cn(e)&&t<=r&&r<e}function Ir(r,t,e,n){if(!xl(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function Yo(r){let t;for(t=0;r>Go;r>>=jo,t+=1);return t}var Sr=r=>(jo<<BigInt(r))-jo;function Aa(r,t,e){if(Dt(r,"hashLen"),Dt(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let n=b=>new Uint8Array(b),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),f=n(r),l=0,u=()=>{c.fill(1),f.fill(0),l=0},h=(...b)=>e(f,ct(c,...b)),m=(b=o)=>{f=h(s,b),c=h(),b.length!==0&&(f=h(i,b),c=h())},d=()=>{if(l++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,p=[];for(;b<t;){c=h();let S=c.slice();p.push(S),b+=c.length}return ct(...p)};return(b,p)=>{u(),m(b);let S;for(;!(S=p(d()));)m();return u(),S}}function ee(r,t={},e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let f=typeof c;if(f!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${f}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(e,!0)}function Fe(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var st=BigInt(0),W=BigInt(1),ge=BigInt(2),Ca=BigInt(3),Da=BigInt(4),Ta=BigInt(5),bl=BigInt(7),La=BigInt(8),wl=BigInt(9),Na=BigInt(16);function Z(r,t){let e=r%t;return e>=st?e:t+e}function F(r,t,e){let n=r;for(;t-- >st;)n*=n,n%=e;return n}function Ba(r,t){if(r===st)throw new Error("invert: expected non-zero number");if(t<=st)throw new Error("invert: expected positive modulus, got "+t);let e=Z(r,t),n=t,o=st,s=W,i=W,a=st;for(;e!==st;){let f=n/e,l=n%e,u=o-i*f,h=s-a*f;n=e,e=l,o=i,s=a,i=u,a=h}if(n!==W)throw new Error("invert: does not exist");return Z(o,t)}function Wo(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function Ua(r,t){let e=(r.ORDER+W)/Da,n=r.pow(t,e);return Wo(r,n,t),n}function El(r,t){let e=(r.ORDER-Ta)/La,n=r.mul(t,ge),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,ge),o),a=r.mul(s,r.sub(i,r.ONE));return Wo(r,a,t),a}function vl(r){let t=$e(r),e=Oa(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+bl)/Na;return(a,c)=>{let f=a.pow(c,i),l=a.mul(f,n),u=a.mul(f,o),h=a.mul(f,s),m=a.eql(a.sqr(l),c),d=a.eql(a.sqr(u),c);f=a.cmov(f,l,m),l=a.cmov(h,u,d);let g=a.eql(a.sqr(l),c),b=a.cmov(f,l,g);return Wo(a,b,c),b}}function Oa(r){if(r<Ca)throw new Error("sqrt is not defined for small field");let t=r-W,e=0;for(;t%ge===st;)t/=ge,e++;let n=ge,o=$e(r);for(;ka(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return Ua;let s=o.pow(n,t),i=(t+W)/ge;return function(c,f){if(c.is0(f))return f;if(ka(c,f)!==1)throw new Error("Cannot find square root");let l=e,u=c.mul(c.ONE,s),h=c.pow(f,t),m=c.pow(f,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let d=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(d++,g=c.sqr(g),d===l)throw new Error("Cannot find square root");let b=W<<BigInt(l-d-1),p=c.pow(u,b);l=d,u=c.sqr(p),h=c.mul(h,u),m=c.mul(m,p)}return m}}function Il(r){return r%Da===Ca?Ua:r%La===Ta?El:r%Na===wl?vl(r):Oa(r)}var Ra=(r,t)=>(Z(r,t)&W)===W,Sl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Jo(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=Sl.reduce((n,o)=>(n[o]="function",n),t);return ee(r,e),r}function Al(r,t,e){if(e<st)throw new Error("invalid exponent, negatives unsupported");if(e===st)return r.ONE;if(e===W)return t;let n=r.ONE,o=t;for(;e>st;)e&W&&(n=r.mul(n,o)),o=r.sqr(o),e>>=W;return n}function Ar(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function ka(r,t){let e=(r.ORDER-W)/ge,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function Bl(r,t){t!==void 0&&Dt(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}var Xo=class{ORDER;BITS;BYTES;isLE;ZERO=st;ONE=W;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=st)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=Bl(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return Z(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return st<=t&&t<this.ORDER}is0(t){return t===st}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&W)===W}neg(t){return Z(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return Z(t*t,this.ORDER)}add(t,e){return Z(t+e,this.ORDER)}sub(t,e){return Z(t-e,this.ORDER)}mul(t,e){return Z(t*e,this.ORDER)}pow(t,e){return Al(this,t,e)}div(t,e){return Z(t*Ba(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Ba(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=Il(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?Zo(t,this.BYTES):fn(t,this.BYTES)}fromBytes(t,e=!1){K(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let f=new Uint8Array(o);f.set(t,s?0:f.length-t.length),t=f}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?ye(t):Ve(t);if(a&&(c=Z(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return Ar(this,t)}cmov(t,e,n){return n?e:t}};function $e(r,t={}){return new Xo(r,t)}function _a(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Qo(r){let t=_a(r);return t+Math.ceil(t/2)}function ts(r,t,e=!1){K(r);let n=r.length,o=_a(t),s=Qo(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?ye(r):Ve(r),a=Z(i,t-W)+W;return e?Zo(a,o):fn(a,o)}var ze=BigInt(0),xe=BigInt(1);function Br(r,t){let e=t.negate();return r?e:t}function be(r,t){let e=Ar(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function qa(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function es(r,t){qa(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=Sr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Pa(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=xe);let f=t*n,l=f+Math.abs(a)-1,u=a===0,h=a<0,m=t%2!==0;return{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:m,offsetF:f}}var rs=new WeakMap,Ha=new WeakMap;function ns(r){return Ha.get(r)||1}function Ma(r){if(r!==ze)throw new Error("invalid wNAF")}var je=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>ze;)e&xe&&(n=n.add(o)),o=o.double(),e>>=xe;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=es(e,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let f=1;f<o;f++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=es(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:f,isZero:l,isNeg:u,isNegF:h,offsetF:m}=Pa(n,a,i);n=c,l?s=s.add(Br(h,e[m])):o=o.add(Br(u,e[f]))}return Ma(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=es(t,this.bits);for(let i=0;i<s.windows&&n!==ze;i++){let{nextN:a,offset:c,isZero:f,isNeg:l}=Pa(n,i,s);if(n=a,!f){let u=e[c];o=o.add(l?u.negate():u)}}return Ma(n),o}getPrecomputes(t,e,n){let o=rs.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),rs.set(e,o))),o}cached(t,e,n){let o=ns(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=ns(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){qa(e,this.bits),Ha.set(t,e),rs.delete(t)}hasCache(t){return ns(t)!==1}};function Va(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>ze||n>ze;)e&xe&&(s=s.add(o)),n&xe&&(i=i.add(o)),o=o.double(),e>>=xe,n>>=xe;return{p1:s,p2:i}}function Ka(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Jo(t),t}else return $e(r,{isLE:e})}function ln(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let f=t[c];if(!(typeof f=="bigint"&&f>ze))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ka(t.p,e.Fp,n),s=Ka(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function dn(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var re=BigInt(0),J=BigInt(1),os=BigInt(2),kl=BigInt(8);function Cl(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function Fa(r,t={}){let e=ln("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;ee(t,{},{uvRatio:"function"});let a=os<<BigInt(o.BYTES*8)-J,c=b=>n.create(b),f=t.uvRatio||((b,p)=>{try{return{isValid:!0,value:n.sqrt(n.div(b,p))}}catch{return{isValid:!1,value:re}}});if(!Cl(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function l(b,p,S=!1){let y=S?J:re;return Ir("coordinate "+b,p,y,a),p}function u(b){if(!(b instanceof d))throw new Error("EdwardsPoint expected")}let h=Fe((b,p)=>{let{X:S,Y:y,Z:A}=b,k=b.is0();p==null&&(p=k?kl:n.inv(A));let N=c(S*p),C=c(y*p),E=n.mul(A,p);if(k)return{x:re,y:J};if(E!==J)throw new Error("invZ was invalid");return{x:N,y:C}}),m=Fe(b=>{let{a:p,d:S}=s;if(b.is0())throw new Error("bad point: ZERO");let{X:y,Y:A,Z:k,T:N}=b,C=c(y*y),E=c(A*A),I=c(k*k),P=c(I*I),q=c(C*p),U=c(I*c(q+E)),w=c(P+c(S*c(C*E)));if(U!==w)throw new Error("bad point: equation left != right (1)");let v=c(y*A),x=c(k*N);if(v!==x)throw new Error("bad point: equation left != right (2)");return!0});class d{static BASE=new d(s.Gx,s.Gy,J,c(s.Gx*s.Gy));static ZERO=new d(re,J,J,re);static Fp=n;static Fn=o;X;Y;Z;T;constructor(p,S,y,A){this.X=l("x",p),this.Y=l("y",S),this.Z=l("z",y,!0),this.T=l("t",A),Object.freeze(this)}static CURVE(){return s}static fromAffine(p){if(p instanceof d)throw new Error("extended point not allowed");let{x:S,y}=p||{};return l("x",S),l("y",y),new d(S,y,J,c(S*y))}static fromBytes(p,S=!1){let y=n.BYTES,{a:A,d:k}=s;p=un(K(p,y,"point")),Ht(S,"zip215");let N=un(p),C=p[y-1];N[y-1]=C&-129;let E=ye(N),I=S?a:n.ORDER;Ir("point.y",E,re,I);let P=c(E*E),q=c(P-J),U=c(k*P-A),{isValid:w,value:v}=f(q,U);if(!w)throw new Error("bad point: invalid y coordinate");let x=(v&J)===J,B=(C&128)!==0;if(!S&&v===re&&B)throw new Error("bad point: x=0 and x_0=1");return B!==x&&(v=c(-v)),d.fromAffine({x:v,y:E})}static fromHex(p,S=!1){return d.fromBytes(Kt(p),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,S=!0){return g.createCache(this,p),S||this.multiply(os),this}assertValidity(){m(this)}equals(p){u(p);let{X:S,Y:y,Z:A}=this,{X:k,Y:N,Z:C}=p,E=c(S*C),I=c(k*A),P=c(y*C),q=c(N*A);return E===I&&P===q}is0(){return this.equals(d.ZERO)}negate(){return new d(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:p}=s,{X:S,Y:y,Z:A}=this,k=c(S*S),N=c(y*y),C=c(os*c(A*A)),E=c(p*k),I=S+y,P=c(c(I*I)-k-N),q=E+N,U=q-C,w=E-N,v=c(P*U),x=c(q*w),B=c(P*w),D=c(U*q);return new d(v,x,D,B)}add(p){u(p);let{a:S,d:y}=s,{X:A,Y:k,Z:N,T:C}=this,{X:E,Y:I,Z:P,T:q}=p,U=c(A*E),w=c(k*I),v=c(C*y*q),x=c(N*P),B=c((A+k)*(E+I)-U-w),D=x-v,L=x+v,O=c(w-S*U),T=c(B*D),R=c(L*O),M=c(B*O),$=c(D*L);return new d(T,R,$,M)}subtract(p){return this.add(p.negate())}multiply(p){if(!o.isValidNot0(p))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:S,f:y}=g.cached(this,p,A=>be(d,A));return be(d,[S,y])[0]}multiplyUnsafe(p,S=d.ZERO){if(!o.isValid(p))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return p===re?d.ZERO:this.is0()||p===J?this:g.unsafe(this,p,y=>be(d,y),S)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(p){return h(this,p)}clearCofactor(){return i===J?this:this.multiplyUnsafe(i)}toBytes(){let{x:p,y:S}=this.toAffine(),y=n.toBytes(S);return y[y.length-1]|=p&J?128:0,y}toHex(){return Mt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new je(d,o.BITS);return d.BASE.precompute(8),d}function $a(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');ee(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:s,Fn:i}=r,a=e.randomBytes||Wt,c=e.adjustScalarBytes||(E=>E),f=e.domain||((E,I,P)=>{if(Ht(P,"phflag"),I.length||P)throw new Error("Contexts/pre-hash are not supported");return E});function l(E){return i.create(ye(E))}function u(E){let I=y.secretKey;K(E,y.secretKey,"secretKey");let P=K(t(E),2*I,"hashedSecretKey"),q=c(P.slice(0,I)),U=P.slice(I,2*I),w=l(q);return{head:q,prefix:U,scalar:w}}function h(E){let{head:I,prefix:P,scalar:q}=u(E),U=o.multiply(q),w=U.toBytes();return{head:I,prefix:P,scalar:q,point:U,pointBytes:w}}function m(E){return h(E).pointBytes}function d(E=Uint8Array.of(),...I){let P=ct(...I);return l(t(f(P,K(E,void 0,"context"),!!n)))}function g(E,I,P={}){E=K(E,void 0,"message"),n&&(E=n(E));let{prefix:q,scalar:U,pointBytes:w}=h(I),v=d(P.context,q,E),x=o.multiply(v).toBytes(),B=d(P.context,x,w,E),D=i.create(v+B*U);if(!i.isValid(D))throw new Error("sign failed: invalid s");let L=ct(x,i.toBytes(D));return K(L,y.signature,"result")}let b={zip215:!0};function p(E,I,P,q=b){let{context:U,zip215:w}=q,v=y.signature;E=K(E,v,"signature"),I=K(I,void 0,"message"),P=K(P,y.publicKey,"publicKey"),w!==void 0&&Ht(w,"zip215"),n&&(I=n(I));let x=v/2,B=E.subarray(0,x),D=ye(E.subarray(x,v)),L,O,T;try{L=r.fromBytes(P,w),O=r.fromBytes(B,w),T=o.multiplyUnsafe(D)}catch{return!1}if(!w&&L.isSmallOrder())return!1;let R=d(U,O.toBytes(),L.toBytes(),I);return O.add(L.multiplyUnsafe(R)).subtract(T).clearCofactor().is0()}let S=s.BYTES,y={secretKey:S,publicKey:S,signature:2*S,seed:S};function A(E=a(y.seed)){return K(E,y.seed,"seed")}function k(E){return he(E)&&E.length===i.BYTES}function N(E,I){try{return!!r.fromBytes(E,I)}catch{return!1}}let C={getExtendedPublicKey:h,randomSecretKey:A,isValidSecretKey:k,isValidPublicKey:N,toMontgomery(E){let{y:I}=r.fromBytes(E),P=y.publicKey,q=P===32;if(!q&&P!==57)throw new Error("only defined for 25519 and 448");let U=q?s.div(J+I,J-I):s.div(I-J,I+J);return s.toBytes(U)},toMontgomerySecret(E){let I=y.secretKey;K(E,I);let P=t(E.subarray(0,I));return c(P).subarray(0,I)}};return Object.freeze({keygen:dn(A,m),getPublicKey:m,sign:g,verify:p,utils:C,Point:r,lengths:y})}var Dl=BigInt(1),za=BigInt(2);var Tl=BigInt(5),Ll=BigInt(8),ss=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Nl={p:ss,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Ll,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ul(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=ss,a=r*r%s*r%s,c=F(a,za,s)*a%s,f=F(c,Dl,s)*r%s,l=F(f,Tl,s)*f%s,u=F(l,t,s)*l%s,h=F(u,e,s)*u%s,m=F(h,n,s)*h%s,d=F(m,o,s)*m%s,g=F(d,o,s)*m%s,b=F(g,t,s)*l%s;return{pow_p_5_8:F(b,za,s)*r%s,b2:a}}function Ol(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var ja=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Rl(r,t){let e=ss,n=Z(t*t*t,e),o=Z(n*n*t,e),s=Ul(r*o).pow_p_5_8,i=Z(r*n*s,e),a=Z(t*i*i,e),c=i,f=Z(i*ja,e),l=a===r,u=a===Z(-r,e),h=a===Z(-r*ja,e);return l&&(i=c),(u||h)&&(i=f),Ra(i,e)&&(i=Z(-i,e)),{isValid:l||u,value:i}}var _l=Fa(Nl,{uvRatio:Rl});function Pl(r){return $a(_l,va,Object.assign({adjustScalarBytes:Ol},r))}var Ga=Pl({});var hn=32;var is,Ml=(async()=>{try{return await Gr.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Kl(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Gr.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Gr.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function ql(r,t,e){return Ga.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function Za(r,t,e){return is==null&&(is=await Ml),is?Kl(r,t,e):ql(r,t,e)}function pn(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var mn=class{type="Ed25519";raw;constructor(t){this.raw=as(t,hn)}toMultihash(){return Ne.digest(qe(this))}toCID(){return Zt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=Za(this.raw,e,t);return pn(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Xa(r){return r=as(r,hn),new mn(r)}function as(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new gt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var Vl=Math.pow(2,7),Fl=Math.pow(2,14),$l=Math.pow(2,21),Wa=Math.pow(2,28),Ja=Math.pow(2,35),Qa=Math.pow(2,42),tc=Math.pow(2,49),it=128,ne=127;function kr(r){if(r<Vl)return 1;if(r<Fl)return 2;if(r<$l)return 3;if(r<Wa)return 4;if(r<Ja)return 5;if(r<Qa)return 6;if(r<tc)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ec(r,t,e=0){switch(kr(r)){case 8:t[e++]=r&255|it,r/=128;case 7:t[e++]=r&255|it,r/=128;case 6:t[e++]=r&255|it,r/=128;case 5:t[e++]=r&255|it,r/=128;case 4:t[e++]=r&255|it,r>>>=7;case 3:t[e++]=r&255|it,r>>>=7;case 2:t[e++]=r&255|it,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function rc(r,t){let e=r[t],n=0;if(n+=e&ne,e<it||(e=r[t+1],n+=(e&ne)<<7,e<it)||(e=r[t+2],n+=(e&ne)<<14,e<it)||(e=r[t+3],n+=(e&ne)<<21,e<it)||(e=r[t+4],n+=(e&ne)*Wa,e<it)||(e=r[t+5],n+=(e&ne)*Ja,e<it)||(e=r[t+6],n+=(e&ne)*Qa,e<it)||(e=r[t+7],n+=(e&ne)*tc,e<it))return n;throw new RangeError("Could not decode varint")}var cs=new Float32Array([-0]),oe=new Uint8Array(cs.buffer);function nc(r,t,e){cs[0]=r,t[e]=oe[0],t[e+1]=oe[1],t[e+2]=oe[2],t[e+3]=oe[3]}function oc(r,t){return oe[0]=r[t],oe[1]=r[t+1],oe[2]=r[t+2],oe[3]=r[t+3],cs[0]}var fs=new Float64Array([-0]),rt=new Uint8Array(fs.buffer);function sc(r,t,e){fs[0]=r,t[e]=rt[0],t[e+1]=rt[1],t[e+2]=rt[2],t[e+3]=rt[3],t[e+4]=rt[4],t[e+5]=rt[5],t[e+6]=rt[6],t[e+7]=rt[7]}function ic(r,t){return rt[0]=r[t],rt[1]=r[t+1],rt[2]=r[t+2],rt[3]=r[t+3],rt[4]=r[t+4],rt[5]=r[t+5],rt[6]=r[t+6],rt[7]=r[t+7],fs[0]}var zl=BigInt(Number.MAX_SAFE_INTEGER),jl=BigInt(Number.MIN_SAFE_INTEGER),dt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return we;if(t<zl&&t>jl)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>ac&&(o=0n,++n>ac&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return we;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):we}},we=new dt(0,0);we.toBigInt=function(){return 0n};we.zzEncode=we.zzDecode=function(){return this};we.length=function(){return 1};var ac=4294967296n;function cc(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function fc(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function us(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function It(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function yn(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var ls=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,It(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw It(this,4);return yn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw It(this,4);return yn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw It(this,4);let t=oc(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw It(this,4);let t=ic(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw It(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return fc(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw It(this,t);this.pos+=t}else do if(this.pos>=this.len)throw It(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new dt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw It(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw It(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw It(this,8);let t=yn(this.buf,this.pos+=4),e=yn(this.buf,this.pos+=4);return new dt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=rc(this.buf,this.pos);return this.pos+=kr(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ds(r){return new ls(r instanceof Uint8Array?r:r.subarray())}function gn(r,t,e){let n=ds(r);return t.decode(n,void 0,e)}function hs(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return ut(i);o+i>t&&(n=ut(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Ee=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ps(){}var ys=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Gl=hs();function Zl(r){return globalThis.Buffer!=null?ut(r):Gl(r)}var Dr=class{len;head;tail;states;constructor(){this.len=0,this.head=new Ee(ps,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new Ee(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new gs((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(xn,10,dt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=dt.fromBigInt(t);return this._push(xn,e.length(),e)}uint64Number(t){return this._push(ec,kr(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=dt.fromBigInt(t).zzEncode();return this._push(xn,e.length(),e)}sint64Number(t){let e=dt.fromNumber(t).zzEncode();return this._push(xn,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ms,1,t?1:0)}fixed32(t){return this._push(Cr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=dt.fromBigInt(t);return this._push(Cr,4,e.lo)._push(Cr,4,e.hi)}fixed64Number(t){let e=dt.fromNumber(t);return this._push(Cr,4,e.lo)._push(Cr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(nc,4,t)}double(t){return this._push(sc,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ms,1,0):this.uint32(e)._push(Xl,e,t)}string(t){let e=cc(t);return e!==0?this.uint32(e)._push(us,e,t):this._push(ms,1,0)}fork(){return this.states=new ys(this),this.head=this.tail=new Ee(ps,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Ee(ps,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Zl(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ms(r,t,e){t[e]=r&255}function Yl(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var gs=class extends Ee{next;constructor(t,e){super(Yl,t,e),this.next=void 0}};function xn(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Cr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Xl(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Dr.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Wl,t,r),this},Dr.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Jl,t,r),this});function Wl(r,t,e){t.set(r,e)}function Jl(r,t,e){r.length<40?us(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Xt(r),e)}function xs(){return new Dr}function bn(r,t){let e=xs();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ge;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ge||(Ge={}));function wn(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function bs(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return wn("enum",Ge.VARINT,e,n)}function En(r,t){return wn("message",Ge.LENGTH_DELIMITED,r,t)}var ht;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(ht||(ht={}));var ws;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(ws||(ws={}));(function(r){r.codec=()=>bs(ws)})(ht||(ht={}));var Tr;(function(r){let t;r.codec=()=>(t==null&&(t=En((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ht.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ht.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>bn(e,r.codec()),r.decode=(e,n)=>gn(e,r.codec(),n)})(Tr||(Tr={}));var Es;(function(r){let t;r.codec=()=>(t==null&&(t=En((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ht.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=ht.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>bn(e,r.codec()),r.decode=(e,n)=>gn(e,r.codec(),n)})(Es||(Es={}));function Ze(r){if(isNaN(r)||r<=0)throw new gt("random bytes length must be a Number bigger than 0");return Wt(r)}var vn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(on(t),K(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Pt(o)}update(t){return He(this),this.iHash.update(t),this}digestInto(t){He(this),K(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vs=(r,t,e)=>new vn(r,t).update(e).digest();vs.create=(r,t)=>new vn(r,t);var lc=(r,t)=>(r+(r>=0?t:-t)/dc)/t;function td(r,t,e){let[[n,o],[s,i]]=t,a=lc(i*r,e),c=lc(-o*r,e),f=r-a*n-c*s,l=-a*o-c*i,u=f<Vt,h=l<Vt;u&&(f=-f),h&&(l=-l);let m=Sr(Math.ceil(Yo(e)/2))+Ye;if(f<Vt||f>=m||l<Vt||l>=m)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:f,k2neg:h,k2:l}}function Ss(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Is(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Ht(e.lowS,"lowS"),Ht(e.prehash,"prehash"),e.format!==void 0&&Ss(e.format),e}var As=class extends Error{constructor(t=""){super(t)}},se={Err:As,_tlv:{encode:(r,t)=>{let{Err:e}=se;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=vr(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?vr(o.length/2|128):"";return vr(r)+s+o+t},decode(r,t){let{Err:e}=se,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let f=t.subarray(n,n+c);if(f.length!==c)throw new e("tlv.decode: length bytes not complete");if(f[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let l of f)i=i<<8|l;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=se;if(r<Vt)throw new t("integer: negative integers are not allowed");let e=vr(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=se;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Ve(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=se,o=K(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:f,l}=n.decode(2,c);if(l.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(f)}},hexFromSig(r){let{_tlv:t,_int:e}=se,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Vt=BigInt(0),Ye=BigInt(1),dc=BigInt(2),In=BigInt(3),ed=BigInt(4);function hc(r,t={}){let e=ln("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;ee(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let f=mc(n,o);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(U,w,v){let{x,y:B}=w.toAffine(),D=n.toBytes(x);if(Ht(v,"isCompressed"),v){l();let L=!n.isOdd(B);return ct(pc(L),D)}else return ct(Uint8Array.of(4),D,n.toBytes(B))}function h(U){K(U,void 0,"Point");let{publicKey:w,publicKeyUncompressed:v}=f,x=U.length,B=U[0],D=U.subarray(1);if(x===w&&(B===2||B===3)){let L=n.fromBytes(D);if(!n.isValid(L))throw new Error("bad point: is not on curve, wrong x");let O=g(L),T;try{T=n.sqrt(O)}catch($){let V=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}l();let R=n.isOdd(T);return(B&1)===1!==R&&(T=n.neg(T)),{x:L,y:T}}else if(x===v&&B===4){let L=n.BYTES,O=n.fromBytes(D.subarray(0,L)),T=n.fromBytes(D.subarray(L,L*2));if(!b(O,T))throw new Error("bad point: is not on curve");return{x:O,y:T}}else throw new Error(`bad point: got length ${x}, expected compressed=${w} or uncompressed=${v}`)}let m=t.toBytes||u,d=t.fromBytes||h;function g(U){let w=n.sqr(U),v=n.mul(w,U);return n.add(n.add(v,n.mul(U,s.a)),s.b)}function b(U,w){let v=n.sqr(w),x=g(U);return n.eql(v,x)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let p=n.mul(n.pow(s.a,In),ed),S=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(p,S)))throw new Error("bad curve params: a or b");function y(U,w,v=!1){if(!n.isValid(w)||v&&n.is0(w))throw new Error(`bad point coordinate ${U}`);return w}function A(U){if(!(U instanceof I))throw new Error("Weierstrass Point expected")}function k(U){if(!c||!c.basises)throw new Error("no endo");return td(U,c.basises,o.ORDER)}let N=Fe((U,w)=>{let{X:v,Y:x,Z:B}=U;if(n.eql(B,n.ONE))return{x:v,y:x};let D=U.is0();w==null&&(w=D?n.ONE:n.inv(B));let L=n.mul(v,w),O=n.mul(x,w),T=n.mul(B,w);if(D)return{x:n.ZERO,y:n.ZERO};if(!n.eql(T,n.ONE))throw new Error("invZ was invalid");return{x:L,y:O}}),C=Fe(U=>{if(U.is0()){if(t.allowInfinityPoint&&!n.is0(U.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:v}=U.toAffine();if(!n.isValid(w)||!n.isValid(v))throw new Error("bad point: x or y not field elements");if(!b(w,v))throw new Error("bad point: equation left != right");if(!U.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function E(U,w,v,x,B){return v=new I(n.mul(v.X,U),v.Y,v.Z),w=Br(x,w),v=Br(B,v),w.add(v)}class I{static BASE=new I(s.Gx,s.Gy,n.ONE);static ZERO=new I(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(w,v,x){this.X=y("x",w),this.Y=y("y",v,!0),this.Z=y("z",x),Object.freeze(this)}static CURVE(){return s}static fromAffine(w){let{x:v,y:x}=w||{};if(!w||!n.isValid(v)||!n.isValid(x))throw new Error("invalid affine point");if(w instanceof I)throw new Error("projective point not allowed");return n.is0(v)&&n.is0(x)?I.ZERO:new I(v,x,n.ONE)}static fromBytes(w){let v=I.fromAffine(d(K(w,void 0,"point")));return v.assertValidity(),v}static fromHex(w){return I.fromBytes(Kt(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,v=!0){return q.createCache(this,w),v||this.multiply(In),this}assertValidity(){C(this)}hasEvenY(){let{y:w}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(w)}equals(w){A(w);let{X:v,Y:x,Z:B}=this,{X:D,Y:L,Z:O}=w,T=n.eql(n.mul(v,O),n.mul(D,B)),R=n.eql(n.mul(x,O),n.mul(L,B));return T&&R}negate(){return new I(this.X,n.neg(this.Y),this.Z)}double(){let{a:w,b:v}=s,x=n.mul(v,In),{X:B,Y:D,Z:L}=this,O=n.ZERO,T=n.ZERO,R=n.ZERO,M=n.mul(B,B),$=n.mul(D,D),V=n.mul(L,L),H=n.mul(B,D);return H=n.add(H,H),R=n.mul(B,L),R=n.add(R,R),O=n.mul(w,R),T=n.mul(x,V),T=n.add(O,T),O=n.sub($,T),T=n.add($,T),T=n.mul(O,T),O=n.mul(H,O),R=n.mul(x,R),V=n.mul(w,V),H=n.sub(M,V),H=n.mul(w,H),H=n.add(H,R),R=n.add(M,M),M=n.add(R,M),M=n.add(M,V),M=n.mul(M,H),T=n.add(T,M),V=n.mul(D,L),V=n.add(V,V),M=n.mul(V,H),O=n.sub(O,M),R=n.mul(V,$),R=n.add(R,R),R=n.add(R,R),new I(O,T,R)}add(w){A(w);let{X:v,Y:x,Z:B}=this,{X:D,Y:L,Z:O}=w,T=n.ZERO,R=n.ZERO,M=n.ZERO,$=s.a,V=n.mul(s.b,In),H=n.mul(v,D),z=n.mul(x,L),Q=n.mul(B,O),St=n.add(v,x),j=n.add(D,L);St=n.mul(St,j),j=n.add(H,z),St=n.sub(St,j),j=n.add(v,B);let et=n.add(D,O);return j=n.mul(j,et),et=n.add(H,Q),j=n.sub(j,et),et=n.add(x,B),T=n.add(L,O),et=n.mul(et,T),T=n.add(z,Q),et=n.sub(et,T),M=n.mul($,j),T=n.mul(V,Q),M=n.add(T,M),T=n.sub(z,M),M=n.add(z,M),R=n.mul(T,M),z=n.add(H,H),z=n.add(z,H),Q=n.mul($,Q),j=n.mul(V,j),z=n.add(z,Q),Q=n.sub(H,Q),Q=n.mul($,Q),j=n.add(j,Q),H=n.mul(z,j),R=n.add(R,H),H=n.mul(et,j),T=n.mul(St,T),T=n.sub(T,H),H=n.mul(St,z),M=n.mul(et,M),M=n.add(M,H),new I(T,R,M)}subtract(w){return this.add(w.negate())}is0(){return this.equals(I.ZERO)}multiply(w){let{endo:v}=t;if(!o.isValidNot0(w))throw new Error("invalid scalar: out of range");let x,B,D=L=>q.cached(this,L,O=>be(I,O));if(v){let{k1neg:L,k1:O,k2neg:T,k2:R}=k(w),{p:M,f:$}=D(O),{p:V,f:H}=D(R);B=$.add(H),x=E(v.beta,M,V,L,T)}else{let{p:L,f:O}=D(w);x=L,B=O}return be(I,[x,B])[0]}multiplyUnsafe(w){let{endo:v}=t,x=this;if(!o.isValid(w))throw new Error("invalid scalar: out of range");if(w===Vt||x.is0())return I.ZERO;if(w===Ye)return x;if(q.hasCache(this))return this.multiply(w);if(v){let{k1neg:B,k1:D,k2neg:L,k2:O}=k(w),{p1:T,p2:R}=Va(I,x,D,O);return E(v.beta,T,R,B,L)}else return q.unsafe(x,w)}toAffine(w){return N(this,w)}isTorsionFree(){let{isTorsionFree:w}=t;return i===Ye?!0:w?w(I,this):q.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=t;return i===Ye?this:w?w(I,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(w=!0){return Ht(w,"isCompressed"),this.assertValidity(),m(I,this,w)}toHex(w=!0){return Mt(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,q=new je(I,t.endo?Math.ceil(P/2):P);return I.BASE.precompute(8),I}function pc(r){return Uint8Array.of(r?2:3)}function mc(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function rd(r,t={}){let{Fn:e}=r,n=t.randomBytes||Wt,o=Object.assign(mc(r.Fp,e),{seed:Qo(e.ORDER)});function s(m){try{let d=e.fromBytes(m);return e.isValidNot0(d)}catch{return!1}}function i(m,d){let{publicKey:g,publicKeyUncompressed:b}=o;try{let p=m.length;return d===!0&&p!==g||d===!1&&p!==b?!1:!!r.fromBytes(m)}catch{return!1}}function a(m=n(o.seed)){return ts(K(m,o.seed,"seed"),e.ORDER)}function c(m,d=!0){return r.BASE.multiply(e.fromBytes(m)).toBytes(d)}function f(m){let{secretKey:d,publicKey:g,publicKeyUncompressed:b}=o;if(!he(m)||"_lengths"in e&&e._lengths||d===g)return;let p=K(m,void 0,"key").length;return p===g||p===b}function l(m,d,g=!0){if(f(m)===!0)throw new Error("first arg must be private key");if(f(d)===!1)throw new Error("second arg must be public key");let b=e.fromBytes(m);return r.fromBytes(d).multiply(b).toBytes(g)}let u={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=dn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:h,Point:r,utils:u,lengths:o})}function yc(r,t,e={}){on(t),ee(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let n=e.randomBytes||Wt,o=e.hmac||((v,x)=>vs(t,v,x)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:f,getPublicKey:l,getSharedSecret:u,utils:h,lengths:m}=rd(r,e),d={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},g=a*dc<s.ORDER;function b(v){let x=a>>Ye;return v>x}function p(v,x){if(!i.isValidNot0(x))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return x}function S(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function y(v,x){Ss(x);let B=m.signature,D=x==="compact"?B:x==="recovered"?B+1:void 0;return K(v,D)}class A{r;s;recovery;constructor(x,B,D){if(this.r=p("r",x),this.s=p("s",B),D!=null){if(S(),![0,1,2,3].includes(D))throw new Error("invalid recovery id");this.recovery=D}Object.freeze(this)}static fromBytes(x,B=d.format){y(x,B);let D;if(B==="der"){let{r:R,s:M}=se.toSig(K(x));return new A(R,M)}B==="recovered"&&(D=x[0],B="compact",x=x.subarray(1));let L=m.signature/2,O=x.subarray(0,L),T=x.subarray(L,L*2);return new A(i.fromBytes(O),i.fromBytes(T),D)}static fromHex(x,B){return this.fromBytes(Kt(x),B)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new A(this.r,this.s,x)}recoverPublicKey(x){let{r:B,s:D}=this,L=this.assertRecovery(),O=L===2||L===3?B+a:B;if(!s.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let T=s.toBytes(O),R=r.fromBytes(ct(pc((L&1)===0),T)),M=i.inv(O),$=N(K(x,void 0,"msgHash")),V=i.create(-$*M),H=i.create(D*M),z=r.BASE.multiplyUnsafe(V).add(R.multiplyUnsafe(H));if(z.is0())throw new Error("invalid recovery: point at infinify");return z.assertValidity(),z}hasHighS(){return b(this.s)}toBytes(x=d.format){if(Ss(x),x==="der")return Kt(se.hexFromSig(this));let{r:B,s:D}=this,L=i.toBytes(B),O=i.toBytes(D);return x==="recovered"?(S(),ct(Uint8Array.of(this.assertRecovery()),L,O)):ct(L,O)}toHex(x){return Mt(this.toBytes(x))}}let k=e.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let B=Ve(x),D=x.length*8-c;return D>0?B>>BigInt(D):B},N=e.bits2int_modN||function(x){return i.create(k(x))},C=Sr(c);function E(v){return Ir("num < 2^"+c,v,Vt,C),i.toBytes(v)}function I(v,x){return K(v,void 0,"message"),x?K(t(v),void 0,"prehashed message"):v}function P(v,x,B){let{lowS:D,prehash:L,extraEntropy:O}=Is(B,d);v=I(v,L);let T=N(v),R=i.fromBytes(x);if(!i.isValidNot0(R))throw new Error("invalid private key");let M=[E(R),E(T)];if(O!=null&&O!==!1){let z=O===!0?n(m.secretKey):O;M.push(K(z,void 0,"extraEntropy"))}let $=ct(...M),V=T;function H(z){let Q=k(z);if(!i.isValidNot0(Q))return;let St=i.inv(Q),j=r.BASE.multiply(Q).toAffine(),et=i.create(j.x);if(et===Vt)return;let Fr=i.create(St*i.create(V+et*R));if(Fr===Vt)return;let si=(j.x===et?0:2)|Number(j.y&Ye),ii=Fr;return D&&b(Fr)&&(ii=i.neg(Fr),si^=1),new A(et,ii,g?void 0:si)}return{seed:$,k2sig:H}}function q(v,x,B={}){let{seed:D,k2sig:L}=P(v,x,B);return Aa(t.outputLen,i.BYTES,o)(D,L).toBytes(B.format)}function U(v,x,B,D={}){let{lowS:L,prehash:O,format:T}=Is(D,d);if(B=K(B,void 0,"publicKey"),x=I(x,O),!he(v)){let R=v instanceof A?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}y(v,T);try{let R=A.fromBytes(v,T),M=r.fromBytes(B);if(L&&R.hasHighS())return!1;let{r:$,s:V}=R,H=N(x),z=i.inv(V),Q=i.create(H*z),St=i.create($*z),j=r.BASE.multiplyUnsafe(Q).add(M.multiplyUnsafe(St));return j.is0()?!1:i.create(j.x)===$}catch{return!1}}function w(v,x,B={}){let{prehash:D}=Is(B,d);return x=I(x,D),A.fromBytes(v,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:f,getPublicKey:l,getSharedSecret:u,utils:h,lengths:m,Point:r,sign:q,verify:U,recoverPublicKey:w,Signature:A,hash:t})}var ks={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},nd={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var gc=BigInt(2);function od(r){let t=ks.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),f=r*r*r%t,l=f*f*r%t,u=F(l,e,t)*l%t,h=F(u,e,t)*l%t,m=F(h,gc,t)*f%t,d=F(m,o,t)*m%t,g=F(d,s,t)*d%t,b=F(g,a,t)*g%t,p=F(b,c,t)*b%t,S=F(p,a,t)*g%t,y=F(S,e,t)*l%t,A=F(y,i,t)*d%t,k=F(A,n,t)*f%t,N=F(k,gc,t);if(!Bs.eql(Bs.sqr(N),r))throw new Error("Cannot find square root");return N}var Bs=$e(ks.p,{sqrt:od}),sd=hc(ks,{Fp:Bs,endo:nd}),Xe=yc(sd,Ea);var id=20;function Ds({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Cs(r,t,e,n,o)}var Cs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??id,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?xc(n,this.code,e?.truncate):n.then(o=>xc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function xc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Le(t,r)}function bc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var wc=Ds({name:"sha2-256",code:18,encode:bc("SHA-256")}),sg=Ds({name:"sha2-512",code:19,encode:bc("SHA-512")});function Ec(r,t,e,n){let o=wc.digest(e instanceof Uint8Array?e:e.subarray());if(pn(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Xe.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new ir(String(s))});try{return n?.signal?.throwIfAborted(),Xe.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new ir(String(s))}}var Sn=class{type="secp256k1";raw;_key;constructor(t){this._key=Ic(t),this.raw=vc(this._key)}toMultihash(){return Ne.digest(qe(this))}toCID(){return Zt.createV1(114,this.toMultihash())}toString(){return ot.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Et(this.raw,t.raw)}verify(t,e,n){return Ec(this._key,e,t,n)}};function Sc(r){return new Sn(r)}function vc(r){return Xe.Point.fromBytes(r).toBytes()}function Ic(r){try{return Xe.Point.fromBytes(r),r}catch(t){throw new Zr(String(t))}}function Ac(r){let{Type:t,Data:e}=Tr.decode(r.digest),n=e??new Uint8Array;switch(t){case ht.Ed25519:return Xa(n);case ht.secp256k1:return Sc(n);case ht.ECDSA:return oa(n);default:throw new ar}}function qe(r){return Tr.encode({Type:ht[r.type],Data:r.raw})}var ie=class{static lockQueues=new Map;static async acquire(t){let e=this.lockQueues.get(t)??Promise.resolve(),n,o=new Promise(i=>{n=i});return this.lockQueues.set(t,o),await e,()=>{n(),this.lockQueues.get(t)===o&&this.lockQueues.delete(t)}}};var ad=100,ve=class r{id;transactor;handlers;source;sourceCache;tracker;filterConflict;pending=[];latchId;constructor(t,e,n,o,s,i,a){this.id=t,this.transactor=e,this.handlers=n,this.source=o,this.sourceCache=s,this.tracker=i,this.filterConflict=a,this.latchId=`Collection:${this.id}`}static async createOrOpen(t,e,n){let o=new We(e,t,void 0),s=new Lr(o),i=new Ft(s);if(await o.tryGet(e)){let c=await xt.open(i,e);o.actionContext=await c.getActionContext()}else{let c=n.createHeaderBlock(e,i);i.insert(c),o.actionContext=void 0,await xt.open(i,e)}return new r(e,t,n.modules,o,s,i,n.filterConflict)}async act(...t){let e=await ie.acquire(this.latchId);try{await this.actInternal(...t)}finally{e()}}async actInternal(...t){await this.internalTransact(...t),this.pending.push(...t)}async internalTransact(...t){let e=new Ut(this.tracker);for(let n of t){let o=this.handlers[n.type];if(!o)throw new Error(`No handler for action type ${n.type}`);await o(n,e)}e.commit()}async update(){let t=await ie.acquire(this.latchId);try{await this.updateInternal()}finally{t()}}async updateInternal(){let t=new We(this.id,this.transactor,void 0),e=new Ft(t),n=this.source.actionContext,o=await xt.open(e,this.id),s=o?await o.getFrom(n?.rev??0):void 0,i=!1;for(let a of s?.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=s?.context}async sync(){let t=await ie.acquire(this.latchId);try{await this.syncInternal()}finally{t()}}async syncInternal(){let t=Ze(16),e=Y(t,"base64url");for(;this.pending.length||!Hn(this.tracker.transforms);){let n=[...this.pending],o=qn(this.tracker.transforms),s=new Ft(this.sourceCache,o),i=await xt.open(s,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(n,e,a,()=>s.transformedBlockIds()),f=await this.source.transact(s.transforms,e,a,this.id,c.tailPath.block.header.id);if(f)f.pending&&await new Promise(l=>setTimeout(l,ad)),await this.updateInternal();else{this.pending=this.pending.slice(n.length);let l=s.reset();await this.replayActions(),this.sourceCache.transformCache(l),this.source.actionContext=this.source.actionContext?{committed:[...this.source.actionContext.committed,{actionId:e,rev:a}],rev:a}:{committed:[{actionId:e,rev:a}],rev:a}}}}async updateAndSync(){let t=await ie.acquire(this.latchId);try{await this.updateInternal(),await this.syncInternal()}finally{t()}}async*selectLog(t=!0){let e=await xt.open(this.tracker,this.id);if(!e)throw new Error(`Log not found for collection ${this.id}`);for await(let n of e.select(void 0,t))n.action&&(yield*t?n.action.actions:n.action.actions.reverse())}async replayActions(){this.tracker.reset();for(let t of this.pending)await this.internalTransact(t)}doFilterConflict(t,e){if(this.filterConflict){let n=this.filterConflict(t,e);if(n)n!==t&&this.pending.push(n);else return!1}return!0}};var Ts=class r{collection;constructor(t){this.collection=t}static async create(t,e){let n={modules:{append:async(s,i)=>{}},createHeaderBlock:(s,i)=>({header:i.createBlockHeader(Ls,s)})},o=await ve.createOrOpen(t,e,n);return new r(o)}async append(t){let e={type:"append",data:t};await this.collection.act(e),await this.collection.updateAndSync()}async update(){await this.collection.update()}async*select(t=!0){for await(let e of this.collection.selectLog(t))yield e.data}};var Ls=bt("DIH","DiaryHeaderBlock");var Ns=bt("TRE","TreeHeaderBlock"),Us=nt("rootId");var Nr=class{store;collectionId;constructor(t,e){this.store=t,this.collectionId=e}async get(){return await X(this.store,await this.getId())}async set(t){let e=await X(this.store,this.collectionId);_(this.store,e,[Us,0,1,t.header.id])}async getId(){return(await X(this.store,this.collectionId)).rootId}};var Os=class r{collection;btree;constructor(t,e){this.collection=t,this.btree=e}static async createOrOpen(t,e,n=s=>s,o=(s,i)=>s<i?-1:s>i?1:0){let s,i={modules:{replace:async({data:c},f)=>{for(let[l,u]of c)u?await s.upsert(u):await s.deleteAt(await s.find(l))}},createHeaderBlock:(c,f)=>{let l;return s=jt.create(f,(u,h)=>(l=h,new Nr(f,c)),n,o),{header:f.createBlockHeader(Ns,c),rootId:l}}},a=await ve.createOrOpen(t,e,i);return s=s??new jt(a.tracker,new Nr(a.tracker,a.id),n,o),new r(a,s)}async replace(t){await this.collection.act({type:"replace",data:t}),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(t){return await this.btree.find(t)}async get(t){return await this.btree.get(t)}at(t){return this.btree.at(t)}range(t){return this.btree.range(t)}ascending(t){return this.btree.ascending(t)}descending(t){return this.btree.descending(t)}async getCount(t){return await this.btree.getCount(t)}async next(t){return await this.btree.next(t)}async moveNext(t){await this.btree.moveNext(t)}async prior(t){return await this.btree.prior(t)}async movePrior(t){await this.btree.movePrior(t)}isValid(t){return this.btree.isValid(t)}};var Bx=new Uint8Array(0);var cd=Cc,Bc=128,fd=127,ud=~fd,ld=Math.pow(2,31);function Cc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=ld;)t[e++]=r&255|Bc,r/=128;for(;r&ud;)t[e++]=r&255|Bc,r>>>=7;return t[e]=r|0,Cc.bytes=e-n+1,t}var dd=Rs,hd=128,kc=127;function Rs(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Rs.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&kc)<<o:(i&kc)*Math.pow(2,o),o+=7}while(i>=hd);return Rs.bytes=s-n,e}var pd=Math.pow(2,7),md=Math.pow(2,14),yd=Math.pow(2,21),gd=Math.pow(2,28),xd=Math.pow(2,35),bd=Math.pow(2,42),wd=Math.pow(2,49),Ed=Math.pow(2,56),vd=Math.pow(2,63),Id=function(r){return r<pd?1:r<md?2:r<yd?3:r<gd?4:r<xd?5:r<bd?6:r<wd?7:r<Ed?8:r<vd?9:10},Sd={encode:cd,decode:dd,encodingLength:Id},Ad=Sd,_s=Ad;function Ps(r,t,e=0){return _s.encode(r,t,e),t}function Ms(r){return _s.encodingLength(r)}function Dc(r,t){let e=t.byteLength,n=Ms(r),o=n+Ms(e),s=new Uint8Array(o+e);return Ps(r,s,0),Ps(e,s,n),s.set(t,o),new Ks(r,e,t,s)}var Ks=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var Cd=20;function Hs({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new qs(r,t,e,n,o)}var qs=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??Cd,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Tc(n,this.code,e?.truncate):n.then(o=>Tc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Tc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return Dc(t,r)}function Lc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var An=Hs({name:"sha2-256",code:18,encode:Lc("SHA-256")}),_x=Hs({name:"sha2-512",code:19,encode:Lc("SHA-512")});var Dd=nt("priorHash"),xt=class r{chain;constructor(t){this.chain=t}get id(){return this.chain.id}static async open(t,e){let n=await Be.open(t,e,r.getChainOptions(t));return n?new r(n):void 0}static async create(t,e){return new r(await Be.create(t,{...r.getChainOptions(t),newId:e}))}async addActions(t,e,n,o,s=[],i=Date.now()){let a={timestamp:i,rev:n,action:{actionId:e,actions:t,blockIds:[],collectionIds:s}},c=await this.chain.add(a),f={...a,action:{...a.action,blockIds:o()}};return this.chain.updateAt(c,f),{entry:f,tailPath:c}}async addCheckpoint(t,e,n=Date.now()){let o={timestamp:n,rev:e,checkpoint:{pendings:t}},s=await this.chain.add(o);return{entry:o,tailPath:s}}async getActionContext(){let t=await this.chain.getTail();if(!t)return;let e=await this.findCheckpoint(t);return{committed:e?[...e.pendings,...await this.pendingFrom(e.path)]:[],rev:e?.rev??0}}async getFrom(t){let e=[],n=[],o,s;for await(let i of this.chain.select(void 0,!1)){let a=de(i);if(o=o??a.rev,a.checkpoint){s=i,n.unshift(...a.checkpoint.pendings);break}n.unshift({actionId:a.action.actionId,rev:a.rev}),t!==void 0&&a.rev>t&&e.unshift(a.action)}if(s)for await(let i of this.chain.select(s,!1)){let a=de(i);if(t!==void 0&&a.rev>t)a.action&&e.unshift(a.action);else break}return{context:o?{committed:n,rev:o}:void 0,entries:e}}async*select(t,e=!0){for await(let n of this.chain.select(t,e))yield de(n)}async findCheckpoint(t){let e,n;for await(let o of this.chain.select(t,!1)){let s=de(o);if(n=n??s.rev,s.checkpoint)return{path:o,pendings:s.checkpoint.pendings,rev:n};e=o}return e?{path:e,pendings:[],rev:n}:void 0}async pendingFrom(t){let e=[];for await(let n of this.chain.select(t)){let o=de(n);o?.action&&e.push({actionId:o.action.actionId,rev:o.rev})}return e}static getChainOptions(t){return{createDataBlock:()=>({header:t.createBlockHeader("LGD")}),createHeaderBlock:e=>({header:t.createBlockHeader("LGH",e)}),newBlock:async(e,n)=>{if(n){let o=await An.digest(new TextEncoder().encode(JSON.stringify(n)));e.priorHash=Y(o.digest,"base64url")}}}}};var Vs="LGD",Fs="LGH";function ae(r){let t=5381;for(let e=0;e<r.length;e++)t=(t<<5)+t+r.charCodeAt(e)|0;return Math.abs(t).toString(36)}function Je(r,t,e,n){let o=JSON.stringify({peerId:r,timestamp:t,schemaHash:e,engineId:n}),s=`stamp:${ae(o)}`;return{peerId:r,timestamp:t,schemaHash:e,engineId:n,id:s}}function Qe(r,t,e){let n=JSON.stringify({stampId:r,statements:t,reads:e});return`tx:${ae(n)}`}Bn();Bn();var kn=class{transactor;collections;constructor(t,e){this.transactor=t,this.collections=e}async applyActions(t,e){for(let{collectionId:n,actions:o}of t){let s=this.collections.get(n);if(!s)throw new Error(`Collection not found: ${n}`);for(let i of o){let a={...i,transaction:e};await s.act(a)}}}async commit(t){let e=Array.from(this.collections.entries()).map(([c,f])=>({collectionId:c,collection:f,transforms:f.tracker.transforms})).filter(({transforms:c})=>Object.keys(c.inserts??{}).length+Object.keys(c.updates??{}).length+(c.deletes?.length??0)>0);if(e.length===0)return;let n=new Map,o=new Map;for(let{collectionId:c,collection:f,transforms:l}of e){n.set(c,l);let u=await xt.open(f.tracker,c);if(!u)throw new Error(`Log not found for collection ${c}`);let h=await u.chain.getTail();h&&o.set(c,h.block.header.id)}let s=e.flatMap(({collectionId:c,transforms:f})=>[...Object.entries(f.inserts??{}).map(([l,u])=>({type:"insert",collectionId:c,blockId:l,block:u})),...Object.entries(f.updates??{}).map(([l,u])=>({type:"update",collectionId:c,blockId:l,operations:u})),...(f.deletes??[]).map(l=>({type:"delete",collectionId:c,blockId:l}))]),i=this.hashOperations(s),a=await this.coordinateTransaction(t,i,n,o);if(!a.success)throw new Error(`Transaction commit failed: ${a.error}`)}async rollback(t){for(let e of this.collections.values())e.tracker.reset()}getTransforms(){let t=new Map;for(let[e,n]of this.collections.entries()){let o=n.tracker.transforms;(Object.keys(o.inserts??{}).length>0||Object.keys(o.updates??{}).length>0||(o.deletes?.length??0)>0)&&t.set(e,o)}return t}resetTransforms(){for(let t of this.collections.values())t.tracker.reset()}hashOperations(t){let e=JSON.stringify(t);return`ops:${ae(e)}`}async commitTransaction(t){let e=Array.from(t.getCollectionActions().entries()).map(([f,l])=>({collectionId:f,actions:l}));if(e.length===0)return{success:!0};let n=Or(e),o=t.getReads(),s=Je("local",Date.now(),"",t.engine),i={stamp:s,statements:n,reads:o,id:Qe(s.id,n,o)},{ActionsEngine:a}=await Promise.resolve().then(()=>(Bn(),Nc)),c=new a(this);return await this.execute(i,c)}async execute(t,e){let n=await e.execute(t);if(!n.success)return n;if(!n.actions||n.actions.length===0)return{success:!0};let o=new Map,s=new Map,i=new Map,a=n.actions.map(u=>u.collectionId);for(let u of n.actions){let h=await this.applyActionsToCollection(u,t,a);if(!h.success)return{success:!1,error:h.error};o.set(u.collectionId,h.transforms),s.set(u.collectionId,h.logTailBlockId),i.set(u.collectionId,h.results)}let c=Array.from(o.entries()).flatMap(([u,h])=>[...Object.entries(h.inserts??{}).map(([m,d])=>({type:"insert",collectionId:u,blockId:m,block:d})),...Object.entries(h.updates??{}).map(([m,d])=>({type:"update",collectionId:u,blockId:m,operations:d})),...(h.deletes??[]).map(m=>({type:"delete",collectionId:u,blockId:m}))]),f=this.hashOperations(c),l=await this.coordinateTransaction(t,f,o,s);return l.success?{success:!0,actions:n.actions,results:i}:l}async applyActionsToCollection(t,e,n){let o=this.collections.get(t.collectionId);if(!o)return{success:!1,error:`Collection not found: ${t.collectionId}`};let s=o.tracker.transforms,i=await xt.open(o.tracker,t.collectionId);if(!i)return{success:!1,error:`Log not found for collection ${t.collectionId}`};let a=e.id,c=(o.source.actionContext?.rev??0)+1,f=await i.addActions(t.actions,a,c,()=>At(s),n);return{success:!0,transforms:s,logTailBlockId:f.tailPath.block.header.id,results:[]}}async coordinateTransaction(t,e,n,o){let s=Array.from(o.values()),i=await this.gatherPhase(s),a=await this.pendPhase(t,e,n,i);if(!a.success)return a;let c=await this.commitPhase(t.id,s,a.pendedBlockIds);return c.success?{success:!0}:(await this.cancelPhase(t.id,n),c)}async gatherPhase(t){if(t.length===1||!this.transactor.queryClusterNominees)return null;let e=t.map(s=>this.transactor.queryClusterNominees(s));return(await Promise.all(e)).reduce((s,i)=>(i.nominees.forEach(a=>s.add(a)),s),new Set)}async pendPhase(t,e,n,o){if(n.size===0)return{success:!1,error:"No transforms to pend"};let s=new Map,i=t.id,a=o?Array.from(o):void 0;for(let[c,f]of n.entries()){let l=this.collections.get(c);if(!l)return{success:!1,error:`Collection not found: ${c}`};let u=(l.source.actionContext?.rev??0)+1,h={actionId:i,rev:u,transforms:f,policy:"r",transaction:t,operationsHash:e,superclusterNominees:a},m=await this.transactor.pend(h);if(!m.success)return{success:!1,error:`Pend failed for collection ${c}: ${m.reason}`};s.set(c,m.blockIds)}return{success:!0,pendedBlockIds:s}}async commitPhase(t,e,n){for(let[o,s]of n.entries()){let i=this.collections.get(o);if(!i)return{success:!1,error:`Collection not found: ${o}`};let a=(i.source.actionContext?.rev??0)+1,c=e.find(u=>s.includes(u));if(!c)return{success:!1,error:`Log tail block not found for collection ${o}`};let f={actionId:t,blockIds:s,tailId:c,rev:a};if(!(await this.transactor.commit(f)).success)return{success:!1,error:`Commit failed for collection ${o}`}}return{success:!0}}async cancelPhase(t,e){for(let[n,o]of e.entries()){if(!this.collections.get(n))continue;let i=At(o);await this.transactor.cancel({actionId:t,blockIds:i})}}};var Cn=class{coordinator;transactionId;engine;collectionActions=new Map;reads=[];constructor(t,e,n){this.coordinator=t,this.transactionId=e,this.engine=n}async addAction(t,e){let n={...e,transaction:this.transactionId},o=this.coordinator.collections.get(t);o&&await o.act(n),this.collectionActions.has(t)||this.collectionActions.set(t,[]),this.collectionActions.get(t).push(n)}addRead(t){this.reads.push(t)}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 Dn=class{coordinator;engine;statements=[];stamp;committed=!1;rolledBack=!1;constructor(t,e,n="local",o=""){this.coordinator=t,this.engine=e,this.stamp=Je(n,Date.now(),o,"unknown")}async execute(t,e){if(this.committed)return{success:!1,error:"Transaction already committed"};if(this.rolledBack)return{success:!1,error:"Transaction already rolled back"};try{let n;if(e)n=e;else{let o={stamp:this.stamp,statements:[t],reads:[],id:"temp"},s=await this.engine.execute(o);if(!s.success||!s.actions)return{success:!1,error:s.error||"Failed to translate statement"};n=s.actions}return await this.coordinator.applyActions(n,this.stamp.id),this.statements.push(t),{success:!0}}catch(n){return{success:!1,error:`Failed to execute statement: ${n instanceof Error?n.message:String(n)}`}}}async commit(){if(this.committed)return{success:!1,error:"Transaction already committed"};if(this.rolledBack)return{success:!1,error:"Transaction already rolled back"};let t={stamp:this.stamp,statements:this.statements,reads:[],id:Qe(this.stamp.id,this.statements,[])};return await this.coordinator.commit(t),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 Tn=class{engines;createValidationCoordinator;constructor(t,e){this.engines=t,this.createValidationCoordinator=e}async validate(t,e){let{stamp:n,statements:o}=t,s=this.engines.get(n.engineId);if(!s)return{valid:!1,reason:`Unknown engine: ${n.engineId}`};let i=await s.getSchemaHash();if(i!==n.schemaHash)return{valid:!1,reason:`Schema mismatch: local=${i}, sender=${n.schemaHash}`};let a=this.createValidationCoordinator();try{let c=await s.engine.execute(t);if(!c.success)return{valid:!1,reason:`Re-execution failed: ${c.error}`};c.actions&&c.actions.length>0&&await a.applyActions(c.actions,n.id);let f=a.getTransforms(),l=this.collectOperations(f),u=this.hashOperations(l);return u!==e?{valid:!1,reason:"Operations hash mismatch",computedHash:u}:{valid:!0,computedHash:u}}finally{a.dispose()}}async getSchemaHash(t){let e=this.engines.get(t);return e?await e.getSchemaHash():void 0}collectOperations(t){return Array.from(t.entries()).flatMap(([e,n])=>[...Object.entries(n.inserts??{}).map(([o,s])=>({type:"insert",collectionId:e,blockId:o,block:s})),...Object.entries(n.updates??{}).map(([o,s])=>({type:"update",collectionId:e,blockId:o,operations:s})),...(n.deletes??[]).map(o=>({type:"delete",collectionId:e,blockId:o}))])}hashOperations(t){let e=JSON.stringify(t);return`ops:${ae(e)}`}};var gb=new Uint8Array(0);function Uc(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ce(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Td(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),f=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function u(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,b=0,p=0,S=d.length;p!==S&&d[p]===0;)p++,g++;for(var y=(S-p)*l+1>>>0,A=new Uint8Array(y);p!==S;){for(var k=d[p],N=0,C=y-1;(k!==0||N<b)&&C!==-1;C--,N++)k+=256*A[C]>>>0,A[C]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=N,p++}for(var E=y-b;E!==y&&A[E]===0;)E++;for(var I=c.repeat(g);E<y;++E)I+=r.charAt(A[E]);return I}function h(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var b=0,p=0;d[g]===c;)b++,g++;for(var S=(d.length-g)*f+1>>>0,y=new Uint8Array(S);d[g];){var A=e[d.charCodeAt(g)];if(A===255)return;for(var k=0,N=S-1;(A!==0||k<p)&&N!==-1;N--,k++)A+=a*y[N]>>>0,y[N]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");p=k,g++}if(d[g]!==" "){for(var C=S-p;C!==S&&y[C]===0;)C++;for(var E=new Uint8Array(b+(S-C)),I=b;C!==S;)E[I++]=y[C++];return E}}}function m(d){var g=h(d);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:u,decodeUnsafe:h,decode:m}}var Ld=Td,Nd=Ld,Oc=Nd;var zs=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},js=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Rc(this,t)}},Gs=class{decoders;constructor(t){this.decoders=t}or(t){return Rc(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Rc(r,t){return new Gs({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Zs=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new zs(t,e,n),this.decoder=new js(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function _c({name:r,prefix:t,encode:e,decode:n}){return new Zs(r,t,e,n)}function tr({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Oc(e,r);return _c({prefix:t,name:r,encode:n,decode:s=>ce(o(s))})}function Ud(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let f=0;f<o;++f){let l=t[r[f]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|l,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Od(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function Rd(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function Lt({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Rd(n);return _c({prefix:t,name:r,encode(s){return Od(s,n,e)},decode(s){return Ud(s,o,e,r)}})}var pt=tr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sb=tr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Rr=Lt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kb=Lt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Cb=Lt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Db=Lt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Tb=Lt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Lb=Lt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Nb=Lt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ub=Lt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ob=Lt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ln=tr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Pb=tr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var _d=Kc,Pc=128,Pd=127,Md=~Pd,Kd=Math.pow(2,31);function Kc(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Kd;)t[e++]=r&255|Pc,r/=128;for(;r&Md;)t[e++]=r&255|Pc,r>>>=7;return t[e]=r|0,Kc.bytes=e-n+1,t}var qd=Ys,Hd=128,Mc=127;function Ys(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ys.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Mc)<<o:(i&Mc)*Math.pow(2,o),o+=7}while(i>=Hd);return Ys.bytes=s-n,e}var Vd=Math.pow(2,7),Fd=Math.pow(2,14),$d=Math.pow(2,21),zd=Math.pow(2,28),jd=Math.pow(2,35),Gd=Math.pow(2,42),Zd=Math.pow(2,49),Yd=Math.pow(2,56),Xd=Math.pow(2,63),Wd=function(r){return r<Vd?1:r<Fd?2:r<$d?3:r<zd?4:r<jd?5:r<Gd?6:r<Zd?7:r<Yd?8:r<Xd?9:10},Jd={encode:_d,decode:qd,encodingLength:Wd},Qd=Jd,_r=Qd;function Pr(r,t=0){return[_r.decode(r,t),_r.decode.bytes]}function er(r,t,e=0){return _r.encode(r,t,e),t}function rr(r){return _r.encodingLength(r)}function or(r,t){let e=t.byteLength,n=rr(r),o=n+rr(e),s=new Uint8Array(o+e);return er(r,s,0),er(e,s,n),s.set(t,o),new nr(r,e,t,s)}function Mr(r){let t=ce(r),[e,n]=Pr(t),[o,s]=Pr(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new nr(e,o,i,t)}function Hc(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Uc(r.bytes,e.bytes)}}var nr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function Vc(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return eh(e,Xs(r),t??pt.encoder);default:return rh(e,Xs(r),t??Rr.encoder)}}var Fc=new WeakMap;function Xs(r){let t=Fc.get(r);if(t==null){let e=new Map;return Fc.set(r,e),e}return t}var Ie=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}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:t,multihash:e}=this;if(t!==Kr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==nh)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:t,digest:e}=this.multihash,n=or(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Hc(t.multihash,n.multihash)}toString(t){return Vc(this,t)}toJSON(){return{"/":Vc(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??$c(n,o,s.bytes))}else if(e[oh]===!0){let{version:n,multihash:o,code:s}=e,i=Mr(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==Kr)throw new Error(`Version 0 CID must use dag-pb (code: ${Kr}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=$c(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,Kr,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ce(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new nr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[u,h]=Pr(t.subarray(e));return e+=h,u},o=n(),s=Kr;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),f=e+c,l=f-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:f}}static parse(t,e){let[n,o]=th(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Xs(s).set(n,t),s}};function th(r,t){switch(r[0]){case"Q":{let e=t??pt;return[pt.prefix,e.decode(`${pt.prefix}${r}`)]}case pt.prefix:{let e=t??pt;return[pt.prefix,e.decode(r)]}case Rr.prefix:{let e=t??Rr;return[Rr.prefix,e.decode(r)]}case Ln.prefix:{let e=t??Ln;return[Ln.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function eh(r,t,e){let{prefix:n}=e;if(n!==pt.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function rh(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var Kr=112,nh=18;function $c(r,t,e){let n=rr(r),o=n+rr(t),s=new Uint8Array(o+e.byteLength);return er(r,s,0),er(t,s,n),s.set(e,o),s}var oh=Symbol.for("@ipld/js-cid/CID");var zc=0,sh="identity",jc=ce;function ih(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return or(zc,jc(r))}var Un={code:zc,name:sh,encode:jc,digest:ih};var ah=20;function Js({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new Ws(r,t,e,n,o)}var Ws=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??ah,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Gc(n,this.code,e?.truncate):n.then(o=>Gc(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Gc(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return or(t,r)}function Zc(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var Yc=Js({name:"sha2-256",code:18,encode:Zc("SHA-256")}),Jb=Js({name:"sha2-512",code:19,encode:Zc("SHA-512")});var Xc=Symbol.for("nodejs.util.inspect.custom"),ch=114,qr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[eo]=!0;toString(){return this.string==null&&(this.string=pt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ie.createV1(ch,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Et(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Xc](){return`PeerId(${this.toString()})`}},On=class extends qr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Rn=class extends qr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},_n=class extends qr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},fh=2336,Hr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Un.digest(Xt(this.url))}[Xc](){return`PeerId(${this.url})`}[eo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ie.createV1(fh,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=Y(t)),t.toString()===this.toString())}};var uh=114,Wc=2336;function Jc(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Mr(pt.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return lh(Ie.parse(r));if(t==null)throw new gt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Mr(t.decode(r))}return Qc(e)}function Qc(r){if(hh(r))return new On({multihash:r});if(dh(r))try{let t=Ac(r);if(t.type==="Ed25519")return new Rn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new _n({multihash:r,publicKey:t})}catch{let e=Y(r.digest);return new Hr(new URL(e))}throw new Xr("Supplied PeerID Multihash is invalid")}function lh(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==uh&&r.code!==Wc)throw new Yr("Supplied PeerID CID is invalid");if(r.code===Wc){let t=Y(r.multihash.digest);return new Hr(new URL(t))}return Qc(r.multihash)}function dh(r){return r.code===Un.code}function hh(r){return r.code===Yc.code}async function mt(r){let t=new TextEncoder().encode(r);return(await An.digest(t)).digest}function tf(r){for(let t in r)return!1;return!0}var Vr=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(t){this.promise=t,t.then(e=>(this.duration=Date.now()-this.t1,this.response=e,e),e=>{this.duration=Date.now()-this.t1,this.error=e})}};function Qs(r,t,e,n){let o=r.reduce((s,[i,a])=>{let c=a.toString(),f=s.get(c)??{peerId:a,blockId:i,excludedPeers:n};return s.set(c,{...f,payload:e(t,i,f.payload)}),s},new Map);return Array.from(o.values())}function*ef(r){let t=[...r];for(;t.length>0;){let e=t.pop();(!e.request||!e.request.isResponse)&&(yield e),e.subsumedBy&&e.subsumedBy.length&&t.push(...e.subsumedBy)}}function ti(r,t){for(let e of r){let n=!1,o=[e];for(;o.length>0;){let s=o.pop();if(t(s)){n=!0;break}if(s.subsumedBy&&s.subsumedBy.length)for(let i=0;i<s.subsumedBy.length;i++)o.push(s.subsumedBy[i])}if(!n)return!1}return!0}function*$t(r,t){let e=[...r];for(;e.length>0;){let n=e.pop();(!t||t(n))&&(yield n),n.subsumedBy&&n.subsumedBy.length&&e.push(...n.subsumedBy)}}function Se(r,t,e){return[...e??[],t]}async function Ae(r,t,e,n,o,s){let i=new WeakMap;for(let c of r)i.set(c,c);let a=async c=>{await Promise.all(c.map(async f=>{f.request=new Vr(t(f).catch(async l=>{if(o>Date.now()){let u=[f.peerId,...f.excludedPeers??[]],h=await Pn(e(f),f.payload,n,u,s);if(h.length>0&&o>Date.now()){let m=i.get(f)??f;m.subsumedBy=[...m.subsumedBy??[],...h];for(let d of h)i.set(d,m);await a(h)}}throw l}))})),await Promise.all(c.map(f=>f.request?.result().catch(()=>{})))};await a(r)}async function Pn(r,t,e,n,o){let s=new Set(r),i=await Promise.all(Array.from(s).map(async a=>[a,await o(a,{excludedPeers:n})]));return Qs(i,t,e,n)}var ei=class{keyNetwork;timeoutMs;abortOrCancelTimeoutMs;getRepo;constructor(t){this.keyNetwork=t.keyNetwork,this.timeoutMs=t.timeoutMs,this.abortOrCancelTimeoutMs=t.abortOrCancelTimeoutMs,this.getRepo=t.getRepo}async get(t){let e=Array.from(new Set(t.blockIds)),n=await this.batchesForPayload(e,e,(h,m,d)=>[...d??[],...h.filter(g=>g===m)],[]),o=Date.now()+this.timeoutMs,s;try{await Ae(n,h=>this.getRepo(h.peerId).get({blockIds:h.payload,context:t.context},{expiration:o}),h=>h.payload,(h,m,d)=>[...d??[],...h.filter(g=>g===m)],o,async(h,m)=>this.keyNetwork.findCoordinator(await mt(h),m))}catch(h){s=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(d=>{let g=m[d];return g&&typeof g=="object"&&"block"in g&&g.block!=null})},c=Array.from($t(n)).filter(h=>!i(h)||!a(h));if(c.length>0&&Date.now()<o)try{let h=new Map;for(let m of c){let d=new Set([m.peerId,...m.excludedPeers??[]]);h.set(m,d);let g=await Pn(m.payload,m.payload,(b,p,S)=>[...S??[],...b.filter(y=>y===p)],Array.from(d),async(b,p)=>this.keyNetwork.findCoordinator(await mt(b),p));g.length>0&&(m.subsumedBy=[...m.subsumedBy??[],...g],await Ae(g,b=>this.getRepo(b.peerId).get({blockIds:b.payload,context:t.context},{expiration:o}),b=>b.payload,(b,p,S)=>[...S??[],...b.filter(y=>y===p)],o,async(b,p)=>this.keyNetwork.findCoordinator(await mt(b),p)))}}catch(h){s||(s=h)}let f=Array.from($t(n,h=>h.request?.isResponse&&!tf(h.request.response))),l=new Map;for(let h of f){let m=h.request.response;for(let[d,g]of Object.entries(m)){let b=l.get(d),p=g&&typeof g=="object"&&"block"in g&&g.block!=null,S=b&&typeof b=="object"&&"block"in b&&b.block!=null;(!b||p&&!S)&&l.set(d,g)}}if(e.filter(h=>!l.has(h)).length>0){let h=this.formatBatchStatuses(n,d=>d.request?.isResponse??!1,d=>{let g=d.request==null?"no-response":d.request.isResponse?"response":"in-flight";return`${d.peerId.toString()}[block:${d.blockId}](${g})`}),m=new Error(`Some peers did not complete: ${h}${s?`; root: ${s.message}`:""}`);throw m.cause=s,m}return Object.fromEntries(l)}async getStatus(t){let e=[...new Set(t.flatMap(o=>o.blockIds))];if(e.length===0)return t.map(o=>({...o,statuses:[]}));let n=await this.get({blockIds:e});return t.map(o=>({...o,statuses:o.blockIds.map(s=>{let i=n[s];if(!i)return"aborted";let{state:a}=i;return a.pendings?.includes(o.actionId)?"pending":a.latest?.actionId===o.actionId?"committed":"aborted"})}))}async consolidateCoordinators(t,e,n){let o=await Promise.all(t.map(async a=>({blockId:a,coordinator:await this.keyNetwork.findCoordinator(await mt(a),{excludedPeers:[]})}))),s=new Map;for(let{blockId:a,coordinator:c}of o){let f=c.toString(),l=s.get(f)??[];l.push(a),s.set(f,l)}let i=[];for(let[a,c]of s){let f=o.find(u=>u.coordinator.toString()===a).coordinator,l={inserts:{},updates:{},deletes:[]};for(let u of c)l=n(e,u,l);i.push({peerId:f,payload:l,blockId:c[0],coordinatingBlockIds:c,excludedPeers:[]})}return i}async pend(t){let e=(c,f,l)=>{let u=Fn(c,f);return l?jn(l,f,u):$n(u,f)},n=At(t.transforms),o=await this.consolidateCoordinators(n,t.transforms,e),s=Date.now()+this.timeoutMs,i;try{await Ae(o,c=>this.getRepo(c.peerId).pend({...t,transforms:c.payload},{expiration:s,coordinatingBlockIds:c.coordinatingBlockIds}),c=>At(c.payload),e,s,async(c,f)=>this.keyNetwork.findCoordinator(await mt(c),f));try{let c=this.keyNetwork;if(typeof c?.recordCoordinator=="function")for(let f of Array.from($t(o)))c.recordCoordinator(await mt(f.blockId),f.peerId)}catch(c){console.warn("Failed to record coordinator hint",c)}}catch(c){i=c}if(!ti(o,c=>c.request?.isResponse&&c.request.response.success)){let c=this.formatBatchStatuses(o,u=>(u.request?.isResponse&&u.request.response?.success)??!1,u=>{let h=u.request==null?"no-response":u.request.isResponse?"non-success":"in-flight";return`${u.peerId.toString()}[block:${u.blockId}](${h})`}),f=new Error(`Some peers did not complete: ${c}${i?`; root: ${i.message}`:""}`),l=i;f.cause=l,f.errors=l?[l]:[],i=f}if(i){Promise.resolve().then(()=>this.cancelBatch(o,{blockIds:n,actionId:t.actionId}));let c=Array.from($t(o,f=>f.request?.isResponse&&!f.request.response.success));if(c.length>0)return{success:!1,missing:ri(c.flatMap(f=>f.request.response.missing).filter(f=>f!==void 0))};throw i}return{success:!0,pending:Array.from($t(o,c=>c.request?.isResponse&&c.request.response.success)).flatMap(c=>c.request.response.pending),blockIds:At(t.transforms)}}async cancel(t){let e=await this.batchesForPayload(t.blockIds,t.blockIds,Se,[]),n=Date.now()+this.abortOrCancelTimeoutMs;await Ae(e,o=>this.getRepo(o.peerId).cancel({actionId:t.actionId,blockIds:o.payload},{expiration:n}),o=>o.payload,Se,n,async(o,s)=>this.keyNetwork.findCoordinator(await mt(o),s))}async queryClusterNominees(t){let e=await mt(t),n=await this.keyNetwork.findCluster(e);return{nominees:Object.keys(n).map(s=>Jc(s))}}async commit(t){let e=[...new Set([...t.blockIds,t.tailId])];if(t.headerId&&!t.blockIds.includes(t.headerId)){let s=await this.commitBlock(t.headerId,e,t.actionId,t.rev);if(!s.success)return s}let n=await this.commitBlock(t.tailId,e,t.actionId,t.rev);if(!n.success)return n;let o=t.blockIds.filter(s=>s!==t.tailId&&!(t.headerId&&s===t.headerId&&!t.blockIds.includes(t.headerId)));if(o.length>0){let{batches:s,error:i}=await this.commitBlocks({blockIds:o,actionId:t.actionId,rev:t.rev});if(i)try{console.warn("[NetworkTransactor] non-tail commit had errors; proceeding after tail commit:",i.message)}catch{}}return{success:!0}}async commitBlock(t,e,n,o){let{batches:s,error:i}=await this.commitBlocks({blockIds:[t],actionId:n,rev:o});if(i){Promise.resolve().then(()=>this.cancel({blockIds:e,actionId:n}));let a=Array.from($t(s,c=>c.request?.isResponse&&!c.request.response.success));if(a.length>0)return{missing:ri(a.flatMap(c=>c.request.response.missing)),success:!1};throw i}return{success:!0}}async commitBlocks({blockIds:t,actionId:e,rev:n}){let o=Date.now()+this.timeoutMs,s=await this.batchesForPayload(t,t,Se,[]),i;try{await Ae(s,a=>this.getRepo(a.peerId).commit({actionId:e,blockIds:a.payload,rev:n},{expiration:o}),a=>a.payload,Se,o,async(a,c)=>this.keyNetwork.findCoordinator(await mt(a),c))}catch(a){i=a}if(!ti(s,a=>a.request?.isResponse&&a.request.response.success)){let a=this.formatBatchStatuses(s,f=>(f.request?.isResponse&&f.request.response?.success)??!1,f=>{let l=f.request==null?"no-response":f.request.isResponse?"non-success":"in-flight",u=f.request?.response,h=u&&u.success===!1?Array.isArray(u.missing)?` missing=${u.missing.length}`:" success=false":"";return`${f.peerId.toString()}[blocks:${f.payload instanceof Array?f.payload.length:1}](${l})${h?" "+h:""}`}),c=new Error(`Some peers did not complete: ${a}${i?`; root: ${i.message}`:""}`);c.cause=i,i=c}return{batches:s,error:i}}async batchesForPayload(t,e,n,o){return Pn(t,e,n,o,async(s,i)=>this.keyNetwork.findCoordinator(await mt(s),i))}async cancelBatch(t,e){let n=Date.now()+this.abortOrCancelTimeoutMs,o=Qs(Array.from($t(t)).map(s=>[s.blockId,s.peerId]),e.blockIds,Se,[]);await Ae(o,s=>this.getRepo(s.peerId).cancel({actionId:e.actionId,blockIds:s.payload},{expiration:n}),s=>s.payload,Se,n,async(s,i)=>this.keyNetwork.findCoordinator(await mt(s),i))}formatBatchStatuses(t,e,n){let s=Array.from(ef(t)).map(n).join(", ");return s.length===0&&(s=Array.from($t(t)).map(n).join(", ")),s}};function ri(r){let t=ni(r,({actionId:e})=>e);return Object.entries(t).map(([e,n])=>({actionId:e,transforms:Vn(...n.map(o=>o.transforms))}))}var We=class{collectionId;transactor;actionContext;constructor(t,e,n){this.collectionId=t,this.transactor=e,this.actionContext=n}createBlockHeader(t,e){return{type:t,id:e??this.generateId(),collectionId:this.collectionId}}generateId(){return Y(Ze(32),"base64url")}async tryGet(t){let e=await this.transactor.get({blockIds:[t],context:this.actionContext});if(e){let{block:n,state:o}=e[t];return n}}async transact(t,e,n,o,s){let i=await this.transactor.pend({transforms:t,actionId:e,rev:n,policy:"r"});if(!i.success)return i;let a=t.inserts&&Object.hasOwn(t.inserts,o),c=await this.transactor.commit({headerId:a?o:void 0,tailId:s,blockIds:i.blockIds,actionId:e,rev:n});if(!c.success)return c}};var Ft=class{source;transforms;constructor(t,e=sr()){this.source=t,this.transforms=e}async tryGet(t){let e=await this.source.tryGet(t);if(e){if((this.transforms.updates?.[t]??[]).forEach(o=>Nt(e,o)),this.transforms.deletes?.includes(t))return}else if(this.transforms.inserts&&Object.hasOwn(this.transforms.inserts,t))return structuredClone(this.transforms.inserts[t]);return e}generateId(){return this.source.generateId()}createBlockHeader(t,e){return this.source.createBlockHeader(t,e)}insert(t){let e=this.transforms.inserts??={};e[t.header.id]=structuredClone(t);let n=this.transforms.deletes,o=n?.indexOf(t.header.id)??-1;o>=0&&n.splice(o,1)}update(t,e){let n=this.transforms.inserts?.[t];if(n)Nt(n,e);else{let o=this.transforms.updates??={};oi(o,t,()=>[]).push(structuredClone(e))}}delete(t){this.transforms.inserts&&delete this.transforms.inserts[t],this.transforms.updates&&delete this.transforms.updates[t],(this.transforms.deletes??=[]).push(t)}reset(t=sr()){let e=this.transforms;return this.transforms=t,e}transformedBlockIds(){return Array.from(new Set(At(this.transforms)))}conflicts(t){return this.transformedBlockIds().filter(e=>t.has(e))}};var Ut=class extends Ft{store;constructor(t){super(t),this.store=t}commit(){let t=this.reset();zn(t,this.store)}};var Lr=class{source;cache=new Map;constructor(t){this.source=t}async tryGet(t){let e=this.cache.get(t);return e||(e=await this.source.tryGet(t),e&&this.cache.set(t,e)),structuredClone(e)}generateId(){return this.source.generateId()}createBlockHeader(t,e){return this.source.createBlockHeader(t,e)}clear(t=void 0){if(t)for(let e of t)this.cache.delete(e);else this.cache.clear()}transformCache(t){for(let e of t.deletes??[])this.cache.delete(e);for(let[,e]of Object.entries(t.inserts??{}))this.cache.set(e.header.id,structuredClone(e));for(let[e,n]of Object.entries(t.updates??{}))for(let o of n){let s=this.cache.get(e);s&&Nt(s,o)}}};function ni(r,t){return r.reduce((e,n)=>{let o=t(n);return(e[o]??=[]).push(n),e},{})}function oi(r,t,e,n){let o=r[t];return typeof o>"u"?(o=e(),r[t]=o):n&&n(o),o}function ph(r,t,e,n){let o=r.get(t);return typeof o>"u"?(o=e(),r.set(t,o)):n&&n(o),o}return cf(mh);})();
3
3
  /*! Bundled license information:
4
4
 
5
5
  @noble/hashes/utils.js: