@moyodb/sdk 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/assets/browser-worker-p7uX85l-.js +4 -0
- package/dist/assets/browser-worker-p7uX85l-.js.map +1 -0
- package/dist/assets/shared-worker-BALTqEUe.js +2 -0
- package/dist/assets/shared-worker-BALTqEUe.js.map +1 -0
- package/dist/chunks/{indexing-B0duqlUs.js → indexing-DdpU69Fd.js} +302 -69
- package/dist/chunks/{indexing-B0duqlUs.js.map → indexing-DdpU69Fd.js.map} +1 -1
- package/dist/codec.d.ts.map +1 -1
- package/dist/compression.d.ts.map +1 -1
- package/dist/engine/README.md +2 -2
- package/dist/engine/moyodb_engine.d.ts +2 -2
- package/dist/engine/moyodb_engine.js +22 -22
- package/dist/engine/moyodb_engine_bg.wasm +0 -0
- package/dist/engine/moyodb_engine_bg.wasm.d.ts +2 -2
- package/dist/engine/package.json +1 -1
- package/dist/engine/snippets/{moyodb-engine-1d53039816cbc2f7 → moyodb-engine-1f8134232168280b}/js/opfs_shim.js +8 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/indexing.d.ts +7 -0
- package/dist/indexing.d.ts.map +1 -1
- package/dist/moyodb-sdk.js +1329 -931
- package/dist/moyodb-sdk.js.map +1 -1
- package/dist/node-engine.js +382 -47
- package/dist/node-engine.js.map +1 -1
- package/dist/node.js +332 -44
- package/dist/node.js.map +1 -1
- package/dist/registry.d.ts.map +1 -1
- package/dist/subscriptions.d.ts.map +1 -1
- package/dist/worker-client.d.ts.map +1 -1
- package/dist/worker-server.d.ts.map +1 -1
- package/dist/worker.d.ts +10 -3
- package/dist/worker.d.ts.map +1 -1
- package/package.json +2 -1
- package/dist/assets/browser-worker-Bj2ErRvC.js +0 -4
- package/dist/assets/browser-worker-Bj2ErRvC.js.map +0 -1
- package/dist/assets/shared-worker-CMeTcusa.js +0 -2
- package/dist/assets/shared-worker-CMeTcusa.js.map +0 -1
package/README.md
CHANGED
|
@@ -19,7 +19,7 @@ Rust/WASM transactional database for browsers, Node.js, and native Rust applicat
|
|
|
19
19
|
|
|
20
20
|
It provides ordered keys, typed records, SQL queries, indexes, snapshots, TTL, and recovery checks. Browser storage uses OPFS; Node.js and native Rust storage use local files. The SDK runs storage operations in a worker.
|
|
21
21
|
|
|
22
|
-
Version 1.
|
|
22
|
+
Version 1.5.0 creates fresh databases with storage format 2. Format 1 databases are rejected before their files are changed; no in-place migration is provided. Self-contained snapshot versions 1–3 can be imported into a fresh format 2 database. The Release 1.0.1 public API, key and index encodings remain covered by historical fixtures. Unknown storage formats fail before modifying durable data.
|
|
23
23
|
|
|
24
24
|
Large values use immutable contiguous `PAY2` extents in the main file. Leaf cells with value kind `External` (3) store a descriptor and an optional prefix. Payload bodies are flushed before their references enter the WAL. B-tree page and WAL record layouts retain `PAG1` and `WAL1`; the manifest's format version distinguishes the new storage contract.
|
|
25
25
|
|
|
@@ -30,7 +30,7 @@ New SDK stores use Snappy compression by default for values of at least 1,024 by
|
|
|
30
30
|
## Quick start
|
|
31
31
|
|
|
32
32
|
```bash
|
|
33
|
-
npm install @moyodb/sdk@1.
|
|
33
|
+
npm install @moyodb/sdk@1.5.0
|
|
34
34
|
```
|
|
35
35
|
|
|
36
36
|
```ts
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
function e(e){return typeof e==`object`&&!!e}function t(e,t){return e<t?-1:+(e>t)}function n(e){return!Number.isFinite(e)||e<=0?0:e>2147483647?2147483647:e}const r=`moyodb:worker-protocol:response`,i=/* @__PURE__ */ `open.close.destroy.deleteDB.begin.commit.rollback.autocommit.createStore.dropStore.clearStore.get.getMany.has.put.putMany.delete.deleteMany.applyBatch.scan.scanPage.closeCursor.getByIndex.scanByIndex.scanByIndexPage.getIndexes.reconcileIndexes.listStores.getVersion.changesSince.setSchemaVersion.exportSnapshot.importSnapshot.reset.compact.rebuild.stats.storageInfo.requestPersistence.setFailpoint`.split(`.`),a=/* @__PURE__ */ new Set([`get`,`getMany`,`has`,`put`,`putMany`,`delete`,`deleteMany`,`applyBatch`,`scan`,`getByIndex`,`scanByIndex`,`createStore`,`dropStore`,`clearStore`]);function o(e){return typeof e==`string`&&a.has(e)}const s=`moyodb:packed-binary-list:v1`,c=`moyodb:packed-scan-rows:v1`,l=`moyodb:packed-engine-scan-rows:v1`,u=`moyodb:packed-batch-ops:v1`,d=`moyodb:packed-optional-values:v1`,f=4294967295,p=16777216,m=[],h=new Set(i);function g(e){return typeof e==`string`&&h.has(e)}function _(t){return e(t)&&t.type===`moyodb:worker-protocol:request`&&t.version===1&&typeof t.id==`number`&&Number.isSafeInteger(t.id)&&typeof t.command==`string`&&Array.isArray(t.args)}function v(e){return ee(e,`moyodb:worker-protocol:request-batch`,`requests`)}function ee(t,n,r){return e(t)&&t.type===n&&t.version===1&&Array.isArray(t[r])&&t[r].length>0&&t[r].length<=128}function y(t){return e(t)&&(t.type===`moyodb:worker-protocol:request`||t.type===`moyodb:worker-protocol:response`||t.type===`moyodb:worker-protocol:request-batch`||t.type===`moyodb:worker-protocol:response-batch`||t.type===`moyodb:worker-protocol:ready`)}function te(t){if(e(t)){let e=Te(t.code);return{name:Te(t.name)??e??`Error`,code:e,message:Te(t.message)??`Unknown error`,stack:Te(t.stack)}}return{name:`Error`,message:String(t)}}function b(e,t,n=e){let r=Error(t);return r.name=e,ne(r,n),r}function ne(e,t){Object.defineProperty(e,"code",{value:t,enumerable:!0,configurable:!0})}function re(e,t){if(e===`autocommit`){let[e,n,r]=t;if(o(n)&&Array.isArray(r))return[e,n,re(n,[0,...r]).slice(1)]}if(e===`getMany`||e===`deleteMany`){let[e,n,r]=t;if(!Array.isArray(r)){if(!C(r,s))throw b(`WorkerProtocolError`,`invalid packed binary-list argument`);return[e,n,be(r)]}}if(e===`putMany`){let[e,n,r,i]=t;if(!Array.isArray(r)){if(!C(r,s))throw b(`WorkerProtocolError`,`invalid packed putMany argument`);return[e,n,xe(r,!1),i]}}if(e===`applyBatch`){let[e,n,r]=t;if(!Array.isArray(r)){if(!C(r,u))throw b(`WorkerProtocolError`,`invalid packed batch argument`);return[e,n,we(r,!1)]}}return t}function ie(e){return C(e,s)?e.bytes:null}function ae(e){return C(e,u)?e.bytes:null}function oe(e){return be({__moyodbPacked:s,bytes:e})}function se(e){return xe({__moyodbPacked:s,bytes:e},!0)}function ce(e){return we({__moyodbPacked:u,bytes:e},!1)}function le(e){return we({__moyodbPacked:u,bytes:e},!0)}function ue(e){return{__moyodbPacked:d,bytes:e}}function de(e){if(!(e instanceof Uint8Array)||e.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed optional-values payload`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0),r=T(4,w(n,4,`packed optional-values metadata`),`packed optional-values header`);if(r>e.byteLength)throw b(`WorkerProtocolError`,`packed optional-values metadata exceeds payload length`);let i=Array(n),a=r;for(let r=0;r<n;r+=1){let n=t.getUint32(4+r*4,!0);if(n===f){i[r]=null;continue}let o=a+n;if(o>e.byteLength)throw b(`WorkerProtocolError`,`packed optional-values item exceeds payload length`);i[r]=e.subarray(a,o),a=o}if(a!==e.byteLength)throw b(`WorkerProtocolError`,`packed optional-values payload has trailing bytes`);return i}function fe(t,n){if((t===`scan`||t===`scanByIndex`)&&(me(n)||C(n,c)))return{result:n,transfer:_e(n.bytes)};if(t===`scanPage`){let t=n;if(e(t)&&(me(t.rows)||C(t.rows,c)))return{result:t,transfer:_e(t.rows.bytes)};if(e(t)&&Array.isArray(t.rows)){let e=Ce(t.rows);return{result:{...t,rows:e??t.rows},transfer:e?[e.bytes.buffer]:x(t.rows)}}}if(t===`getMany`&&C(n,d))return{result:n,transfer:_e(n.bytes)};if(t===`scanByIndexPage`){let t=n;if(e(t)&&C(t.rows,c))return{result:t,transfer:x(t)};if(e(t)&&Array.isArray(t.rows)){let e=t.rows.length>0?Ce(t.rows):null,n={rows:e??t.rows,cursor:t.cursor},r=e?[e.bytes.buffer]:x(t.rows),i=S(t.cursor);return{result:n,transfer:i===null?r:[...r,i]}}}if(t===`getMany`){let e=n;if(Array.isArray(e)&&e.length>0){let t=Se(e);if(t)return{result:t,transfer:[t.bytes.buffer]}}return{result:n,transfer:x(n)}}if(t===`scan`||t===`scanByIndex`){let e=n;if(Array.isArray(e)&&e.length>0){let t=Ce(e);if(t)return{result:t,transfer:[t.bytes.buffer]}}return{result:n,transfer:x(n)}}return t===`get`||t===`getByIndex`||t===`exportSnapshot`?{result:n,transfer:_e(n)}:t===`changesSince`?{result:n,transfer:ve(n)}:{result:n,transfer:[]}}function pe(e){return{__moyodbPacked:l,bytes:e}}function me(t){return e(t)&&t.__moyodbPacked===l&&t.bytes instanceof Uint8Array}function he(e){if(!(e instanceof Uint8Array)||e.byteLength<4)throw b(`WorkerProtocolError`,`invalid engine scan packet`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0);if(n>(e.byteLength-4)/8)throw b(`WorkerProtocolError`,`engine scan row count exceeds packet length`);let r=Array(n),i=4;for(let a=0;a<n;a+=1){if(i+8>e.byteLength)throw b(`WorkerProtocolError`,`truncated engine scan row`);let n=t.getUint32(i,!0),o=t.getUint32(i+4,!0),s=i+8,c=s+n,l=c+o;if(l>e.byteLength)throw b(`WorkerProtocolError`,`engine scan row exceeds packet length`);r[a]={key:e.subarray(s,c),value:e.subarray(c,l)},i=l}if(i!==e.byteLength)throw b(`WorkerProtocolError`,`engine scan packet has trailing bytes`);return r}function x(e){let t=S(e);if(t!==null)return[t];if(typeof e!=`object`||!e)return m;let n=/* @__PURE__ */ new Set;return ye(e,n,/* @__PURE__ */ new WeakSet),n.size===0?m:Array.from(n)}function ge(e,t){let n=t.length>0?structuredClone(e,{transfer:t.length===1?t:Array.from(new Set(t))}):structuredClone(e),r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new WeakSet,a=0,o=e=>{if(typeof e==`string`){a+=8+e.length*2;return}if(typeof e!=`object`||!e){a+=8;return}if(!i.has(e)){if(i.add(e),a+=8,e instanceof ArrayBuffer)r.add(e),a+=e.byteLength;else if(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)a+=e.byteLength;else if(ArrayBuffer.isView(e))o(e.buffer);else if(Array.isArray(e))for(let t of e)o(t);else if(e instanceof Map)for(let[t,n]of e)o(t),o(n);else if(e instanceof Set)for(let t of e)o(t);else{let t=e;for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(a+=8+e.length*2,o(t[e]))}}};return o(n),{value:n,transfer:r.size===0?m:Array.from(r),byteLength:a}}function _e(e){let t=S(e);return t===null?m:[t]}function S(e){if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e)){let t=e.buffer;if(t instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===t.byteLength)return t}return null}function ve(t){if(!e(t)||!Array.isArray(t.changes)||t.changes.length===0)return m;let n=null;for(let r of t.changes){if(!e(r))continue;let t=S(r.key);t!==null&&(n??=/* @__PURE__ */ new Set,n.add(t));let i=S(r.value);i!==null&&(n??=/* @__PURE__ */ new Set,n.add(i))}return n===null||n.size===0?m:Array.from(n)}function ye(e,t,n){if(e==null)return;if(e instanceof ArrayBuffer){t.add(e);return}if(ArrayBuffer.isView(e)){let n=e.buffer;n instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===n.byteLength&&t.add(n);return}if(typeof e!=`object`)return;let r=e;if(n.has(r))return;if(n.add(r),Array.isArray(e)){for(let r of e)ye(r,t,n);return}let i=e;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&ye(i[e],t,n)}function be(e){let t=e.bytes;if(!(t instanceof Uint8Array)||t.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed binary-list payload`);let n=new DataView(t.buffer,t.byteOffset,t.byteLength),r=n.getUint32(0,!0),i=T(4,w(r,4,`packed binary-list metadata`),`packed binary-list header`);if(i>t.byteLength)throw b(`WorkerProtocolError`,`packed binary-list metadata exceeds payload length`);let a=Array(r),o=4,s=i;for(let e=0;e<r;e+=1){let r=n.getUint32(o,!0);o+=4;let i=s+r;if(i>f||i>t.byteLength)throw b(`WorkerProtocolError`,`packed binary-list item exceeds payload length`);a[e]=t.subarray(s,i),s=i}if(s!==t.byteLength)throw b(`WorkerProtocolError`,`packed binary-list payload has trailing bytes`);return a}function xe(e,t){let n=e.bytes;if(!(n instanceof Uint8Array)||n.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed putMany payload`);let r=new DataView(n.buffer,n.byteOffset,n.byteLength),i=r.getUint32(0,!0);if(i%2!=0)throw b(`WorkerProtocolError`,`packed putMany payload has an odd item count`);let a=T(4,w(i,4,`packed putMany metadata`),`packed putMany header`);if(a>n.byteLength)throw b(`WorkerProtocolError`,`packed putMany metadata exceeds payload length`);let o=i/2,s=Array(o),c=4,l=a;for(let e=0;e<o;e+=1){let i=r.getUint32(c,!0),a=r.getUint32(c+4,!0);c+=8;let o=l+i;if(o>f||o>n.byteLength)throw b(`WorkerProtocolError`,`packed putMany key exceeds payload length`);let u=o+a;if(u>f||u>n.byteLength)throw b(`WorkerProtocolError`,`packed putMany value exceeds payload length`);t?s[e]=n.subarray(l,o):s[e]=[n.subarray(l,o),n.subarray(o,u)],l=u}if(l!==n.byteLength)throw b(`WorkerProtocolError`,`packed putMany payload has trailing bytes`);return s}function Se(e){let t=e.length,n=w(t,5,`packed nullable binary-list metadata`),r=0;for(let n=0;n<t;n+=1){let t=e[n];if(t===null)continue;if(!(t instanceof Uint8Array))throw b(`WorkerProtocolError`,`nullable binary-list payload item is not a Uint8Array or null`);let i=E(t.byteLength,`nullable binary-list item length`);if(r+=i,r>f)throw b(`WorkerProtocolError`,`packed nullable binary-list payload exceeds 32-bit payload limit`)}let i=T(4,n,`packed nullable binary-list header`),a=T(i,r,`packed nullable binary-list total`);if(a>p)return null;let o=new Uint8Array(a),s=new DataView(o.buffer);s.setUint32(0,t,!0);let c=4,l=i;for(let n=0;n<t;n+=1){let t=e[n];if(t===null){s.setUint8(c,0),s.setUint32(c+1,0,!0),c+=5;continue}let r=t.byteLength;s.setUint8(c,1),s.setUint32(c+1,r,!0),c+=5,o.set(t,l),l+=r}return{__moyodbPacked:`moyodb:packed-nullable-binary-list:v1`,bytes:o}}function Ce(t){let n=t.length,r=w(n,8,`packed scan row metadata`),i=0;for(let r=0;r<n;r+=1){let n=t[r];if(!e(n)||!(n.key instanceof Uint8Array)||!(n.value instanceof Uint8Array))throw b(`WorkerProtocolError`,`scan row payload key/value is not a Uint8Array`);let a=E(n.key.byteLength,`scan row key length`),o=E(n.value.byteLength,`scan row value length`);if(i+=a+o,i>f)throw b(`WorkerProtocolError`,`packed scan row payload exceeds 32-bit payload limit`)}let a=T(4,r,`packed scan row header`),o=T(a,i,`packed scan row total`);if(o>p)return null;let s=new Uint8Array(o),l=new DataView(s.buffer);l.setUint32(0,n,!0);let u=4,d=a;for(let e=0;e<n;e+=1){let n=t[e],r=n.key,i=n.value,a=r.byteLength,o=i.byteLength;l.setUint32(u,a,!0),l.setUint32(u+4,o,!0),u+=8,s.set(r,d),d+=a,s.set(i,d),d+=o}return{__moyodbPacked:c,bytes:s}}function we(e,t){let n=e.bytes;if(!(n instanceof Uint8Array)||n.byteLength<4)throw b(`WorkerProtocolError`,`invalid packed batch payload`);let r=new DataView(n.buffer,n.byteOffset,n.byteLength),i=r.getUint32(0,!0),a=T(4,w(i,9,`packed batch metadata`),`packed batch header`);if(a>n.byteLength)throw b(`WorkerProtocolError`,`packed batch metadata exceeds payload length`);let o=Array(i),s=4,c=a;for(let e=0;e<i;e+=1){let i=r.getUint8(s),a=r.getUint32(s+1,!0),l=r.getUint32(s+5,!0);s+=9;let u=c+a;if(u>f||u>n.byteLength)throw b(`WorkerProtocolError`,`packed batch key exceeds payload length`);let d=n.subarray(c,u);if(c=u,i===0){if(l!==0)throw b(`WorkerProtocolError`,`packed delete operation has a value payload`);o[e]={kind:`delete`,key:d};continue}if(i!==1)throw b(`WorkerProtocolError`,`packed batch operation has invalid kind byte: ${i}`);let p=c+l;if(p>f||p>n.byteLength)throw b(`WorkerProtocolError`,`packed batch value exceeds payload length`);t?o[e]={kind:`put`,key:d}:o[e]={kind:`put`,key:d,value:n.subarray(c,p)},c=p}if(c!==n.byteLength)throw b(`WorkerProtocolError`,`packed batch payload has trailing bytes`);return o}function C(t,n){return e(t)&&t.__moyodbPacked===n&&t.bytes instanceof Uint8Array}function w(e,t,n){if(!Number.isSafeInteger(e)||e<0)throw b(`WorkerProtocolError`,`${n} count is invalid: ${e}`);return E(e*t,n)}function T(e,t,n){return E(e+t,n)}function E(e,t){if(!Number.isSafeInteger(e)||e<0||e>f)throw b(`WorkerProtocolError`,`${t} exceeds 32-bit payload limit`);return e}function Te(e){return typeof e==`string`?e:void 0}const Ee=/* @__PURE__ */ new Set([`commit`,`rollback`,`createStore`,`dropStore`,`clearStore`,`get`,`getMany`,`has`,`put`,`putMany`,`delete`,`deleteMany`,`applyBatch`,`scan`,`getByIndex`,`scanByIndex`,`scanByIndexPage`,`getIndexes`,`reconcileIndexes`,`setSchemaVersion`]),De=/* @__PURE__ */ new Set([`open`,`close`,`destroy`,`importSnapshot`,`reset`,`compact`,`rebuild`]),Oe=/* @__PURE__ */ new Set([`deleteDB`,`storageInfo`,`requestPersistence`]),ke=()=>{};var Ae=class{#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Set;#n=Promise.resolve();#r=/* @__PURE__ */ new Map;schedule(t,n,r){if(Oe.has(t))return r();if(De.has(t))return this.#r.size===0?this.#a(r):this.#a(async()=>{let e=await r();return this.#r.clear(),e});if(t!==`scanPage`&&t!==`closeCursor`&&!((t===`commit`||t===`rollback`)&&this.#r.size>0))return this.#i(je(t,n),r);let i=t===`scanPage`&&e(n[0])?n[0]:null,a=i?.cursorId??(t===`closeCursor`?n[0]:void 0),o=(typeof a==`number`?this.#r.get(a):void 0)??(i&&typeof i.txId==`number`?i.txId:typeof a==`number`?`cursor:${a}`:je(t,n));return this.#i(o,async()=>{try{let t=await r();return i&&e(t)&&(typeof a==`number`&&this.#r.delete(a),typeof t.cursorId==`number`&&this.#r.set(t.cursorId,o??`cursor:${t.cursorId}`)),t}finally{if(t===`closeCursor`&&typeof a==`number`&&this.#r.delete(a),t===`commit`||t===`rollback`)for(let[e,t]of this.#r)t===n[0]&&this.#r.delete(e)}})}#i(e,t){let n=this.#n,r=e===null?void 0:this.#e.get(e),i=(async()=>(await n,r&&await r,t()))(),a=i.then(ke,ke);return this.#t.add(a),e!==null&&this.#e.set(e,a),a.then(()=>{this.#t.delete(a),e!==null&&this.#e.get(e)===a&&this.#e.delete(e)}),i}#a(e){let t=this.#n,n=Array.from(this.#t),r=(async()=>(await t,await Promise.all(n),e()))();return this.#n=r.then(ke,ke),r}};function je(e,t){return Ee.has(e)&&typeof t[0]==`number`?t[0]:e===`autocommit`&&t[0]===`readwrite`?`autocommit:readwrite`:null}var Me=class{scope;queued=[];queuedBytes=0;flushScheduled=!1;flushChannel=null;closed=!1;constructor(e){this.scope=e}enqueue(e,t=[],n=!1){if(this.closed)return;let r=We(e);if(this.queued.length>0&&this.queuedBytes+r>1048576&&this.flush(),n||this.queued.length+1>=128||this.queuedBytes+r>=1048576){this.queued.push({response:e,transfer:t}),this.queuedBytes+=r,this.flush();return}let i=Ue(e,t);this.queued.push({response:i.value,transfer:i.transfer}),this.queuedBytes+=i.byteLength,this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>{if(this.closed||this.queued.length===0){this.flushScheduled=!1;return}this.flushChannel??=this.createFlushChannel(),this.flushChannel.port2.postMessage(null)}))}close(){this.closed=!0,this.queued=[],this.queuedBytes=0,this.flushChannel?.port1.close(),this.flushChannel?.port2.close(),this.flushChannel=null}createFlushChannel(){let e=new MessageChannel;return e.port1.addEventListener(`message`,()=>{this.flushScheduled=!1,this.flush()}),e.port1.start(),e}flush(){let e=this.queued;if(this.queued=[],this.queuedBytes=0,this.closed||e.length===0)return;let t=e.length===1?e[0].response:{type:`moyodb:worker-protocol:response-batch`,version:1,responses:e.map(e=>e.response)},n=[];for(let t of e)for(let e of t.transfer)n.push(e);Ve(this.scope,t,n)}};function Ne(e,t=self){let n=new Ae,r=new Me(t),i=i=>{if(i.origin===``||i.origin===t.location.origin){if(v(i.data)){let a=i.data.requests.length,o=(e,t)=>{--a,r.enqueue(e,t,a===0)};for(let r of i.data.requests)Pe(t,e,n,r,o);return}Pe(t,e,n,i.data)}};return t.addEventListener(`message`,i),t.postMessage({type:`moyodb:worker-protocol:ready`,version:1,batching:1}),{close(){t.removeEventListener(`message`,i),r.close()}}}async function Pe(e,t,n,r,i=(t,n)=>Ve(e,t,n)){if(!y(r))return;let a=typeof r.id==`number`&&Number.isSafeInteger(r.id)?r.id:0;if(!_(r)){i(Be(a,b(`WorkerProtocolError`,`invalid worker protocol request`)));return}if(!g(r.command)){i(Be(r.id,b(`WorkerProtocolError`,`unsupported worker command: ${String(r.command)}`)));return}let s=r.command,c=r.args;try{let e=s,a;if(s===`autocommit`){let[n,r,i]=c;if(n!==`readonly`&&n!==`readwrite`||!o(r)||!Array.isArray(i))throw b(`WorkerProtocolError`,`invalid autocommit request`);Fe(t,r),e=r,a=()=>Le(t,n,r,i)}else Fe(t,s),a=()=>Ie(t,s,c);let l=await n.schedule(s,c,a),u=fe(e,l);i(ze(r.id,u.result),u.transfer)}catch(e){i(Be(r.id,e))}}function Fe(e,t){if(typeof e[t]!=`function`)throw b(`WorkerProtocolError`,`worker command is not implemented: ${t}`)}function Ie(e,t,n){let r=Re(e,t,n);return r===null?e[t].apply(e,re(t,n)):r}async function Le(e,t,n,r){let i=await e.begin(t),a;try{a=await Ie(e,n,[i,...r])}catch(t){try{await e.rollback(i)}catch{}throw t}return t===`readwrite`?await e.commit(i):await e.rollback(i),a}function Re(e,t,n){let r=e;if(t===`getMany`||t===`deleteMany`){let[e,i,a]=n;if(typeof e!=`number`||typeof i!=`string`)return null;let o=ie(a);return o===null?null:t===`getMany`&&typeof r.getManyPacked==`function`?r.getManyPacked(e,i,o):t===`deleteMany`&&typeof r.deleteManyPacked==`function`?r.deleteManyPacked(e,i,o):null}if(t===`putMany`){let[e,t,i,a]=n;if(typeof e!=`number`||typeof t!=`string`||typeof r.putManyPacked!=`function`)return null;let o=ie(i);return o===null?null:r.putManyPacked(e,t,o,a)}if(t===`applyBatch`){let[e,t,i]=n;if(typeof e!=`number`||typeof t!=`string`||typeof r.applyBatchPacked!=`function`)return null;let a=ae(i);return a===null?null:r.applyBatchPacked(e,t,a)}return null}function ze(e,t){return{type:r,version:1,id:e,ok:!0,result:t}}function Be(e,t){return{type:r,version:1,id:e,ok:!1,error:te(t)}}function Ve(e,t,n=[]){if(n.length>0)try{e.postMessage(t,n);return}catch{}e.postMessage(t)}const He=/* @__PURE__ */ new Set([DataView,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,Int8Array,Int16Array,Int32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array]);function Ue(e,t){let n=/* @__PURE__ */ new Set;for(let r of t){if(!(r instanceof ArrayBuffer)||D(r))return ge(e,t);n.add(r)}let r=/* @__PURE__ */ new Map;if(!Ge(e,r,/* @__PURE__ */ new WeakSet))return ge(e,t);let i=/* @__PURE__ */ new Map;for(let e of n)i.set(e,Ze(e));let a=[],o=/* @__PURE__ */ new WeakMap,s=e=>{if(typeof e!=`object`||!e)return e;let t=o.get(e);if(t!==void 0)return t;if(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)return o.set(e,e),e;if(e instanceof ArrayBuffer){let t=i.get(e)??e.slice(0);return o.set(e,t),a.push(t),t}if(ArrayBuffer.isView(e)){let t=r.get(e);if(!t)throw b(`WorkerProtocolError`,`worker payload could not be queued`);let n=e.buffer,i=Xe(e,typeof SharedArrayBuffer<`u`&&n instanceof SharedArrayBuffer?n:s(n),t);return o.set(e,i),i}if(Array.isArray(e)){let t=Array(e.length);o.set(e,t);for(let n=0;n<e.length;n+=1)n in e&&(t[n]=s(e[n]));return t}let n=Object.getPrototypeOf(e)===null?Object.create(null):{};o.set(e,n);let c=e;for(let e in c)Object.prototype.hasOwnProperty.call(c,e)&&(n[e]=s(c[e]));return n},c=s(e);return{value:c,transfer:a,byteLength:We(c)}}function We(e){let t=0,n=/* @__PURE__ */ new WeakSet,r=e=>{if(Number.isFinite(t)){if(typeof e==`string`){t+=8+e.length*2;return}if(typeof e!=`object`||!e){t+=8;return}if(!n.has(e)){if(n.add(e),t+=8,e instanceof ArrayBuffer)t+=e.byteLength;else if(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)t+=e.byteLength;else if(ArrayBuffer.isView(e))r(e.buffer);else if(Array.isArray(e)){if(Object.getPrototypeOf(e)!==Array.prototype||Ke(e)){t=1/0;return}for(let n=0;n<e.length;n+=1){let i=Object.getOwnPropertyDescriptor(e,String(n));if(i&&!(`value`in i)){t=1/0;return}r(i?.value)}}else if(e instanceof Map)for(let[t,n]of e)r(t),r(n);else if(e instanceof Set)for(let t of e)r(t);else{let n=e;for(let e in n)if(Object.prototype.hasOwnProperty.call(n,e)){let i=Object.getOwnPropertyDescriptor(n,e);if(e===`__proto__`||!i||!(`value`in i)){t=1/0;return}t+=8+e.length*2,r(i.value)}}}}};return r(e),t}function Ge(e,t,n){if(typeof e==`function`||typeof e==`symbol`)return!1;if(typeof e!=`object`||!e||n.has(e))return!0;if(n.add(e),typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||e instanceof ArrayBuffer)return!D(e);if(ArrayBuffer.isView(e)){if(!Je(e))return!1;let n=e.buffer;return typeof SharedArrayBuffer<`u`&&n instanceof SharedArrayBuffer?!D(n)&&(t.set(e,Ye(e)),!0):!(n instanceof ArrayBuffer)||D(n)?!1:(t.set(e,Ye(e)),!0)}if(e instanceof Map||e instanceof Set||e instanceof Date||e instanceof RegExp)return!1;if(Array.isArray(e)){if(Ke(e)||qe(e))return!1;for(let r of e)if(!Ge(r,t,n))return!1;return!0}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null||qe(e))return!1;let i=e;for(let e in i)if(Object.prototype.hasOwnProperty.call(i,e)&&!Ge(i[e],t,n))return!1;return!0}function Ke(e){let t=e;for(let n in t){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let t=Number(n);if(!Number.isInteger(t)||t<0||t>=e.length||String(t)!==n)return!0}return!1}function qe(e){for(let t of Object.getOwnPropertySymbols(e))if(Object.prototype.propertyIsEnumerable.call(e,t))return!0;return!1}function Je(e){return He.has(e.constructor)}function Ye(e){return e instanceof DataView?{offset:e.byteOffset,length:e.byteLength,dataView:!0}:{offset:e.byteOffset,length:e.length,dataView:!1}}function Xe(e,t,n){if(n.dataView)return new DataView(t,n.offset,n.length);let r=e.constructor;return new r(t,n.offset,n.length)}function Ze(e){let t=e;return typeof t.transfer==`function`?t.transfer():structuredClone(e,{transfer:[e]})}function D(e){return e.resizable===!0}const Qe=new TextEncoder;new TextDecoder,new TextDecoder(`utf-8`,{fatal:!0});const $e=BigInt(`0xffffffffffffffff`);new DataView((/* @__PURE__ */ new Uint8Array(9)).buffer);function O(e){return Qe.encode(e)}function et(e){return nt(e)}function tt(e){return rt(e)}function nt(e){if(e===null)return Uint8Array.of(16);if(typeof e==`boolean`)return Uint8Array.of(e?33:32);if(typeof e==`number`)return lt(e);if(typeof e==`string`)return st(e);if(e instanceof Uint8Array){let t=new Uint8Array(1+e.length);return t[0]=80,t.set(e,1),t}throw TypeError(`compound key parts must be string, number, boolean, null, or Uint8Array`)}function rt(e){let t=0;for(let n=0;n<e.length;n+=1)t+=it(e[n])+2;let n=new Uint8Array(t),r=0;for(let t=0;t<e.length;t+=1)r=ot(n,at(n,r,e[t]));return n}function it(e){let t=0;for(let n=0;n<e.length;n+=1)e[n]===0&&(t+=1);return e.length+t}function at(e,t,n){for(let r=0;r<n.length;r+=1){let i=n[r];i===0?(e[t]=0,e[t+1]=255,t+=2):(e[t]=i,t+=1)}return t}function ot(e,t){return e[t]=0,e[t+1]=0,t+2}function st(e){let t=ct(e,null,0,!1),n=new Uint8Array(1+t);return n[0]=64,ct(e,n,1,!1),n}function ct(e,t,n,r){for(let i=0;i<e.length;i+=1){let a=e.charCodeAt(i);if(a<=127){r&&a===0?(t!==null&&(t[n]=0,t[n+1]=255),n+=2):(t!==null&&(t[n]=a),n+=1);continue}if(a<=2047){t!==null&&(t[n]=192|a>>6,t[n+1]=128|a&63),n+=2;continue}if(a>=55296&&a<=56319){let r=e.charCodeAt(i+1);if(r>=56320&&r<=57343){let e=(a-55296<<10)+(r-56320)+65536;t!==null&&(t[n]=240|e>>18,t[n+1]=128|e>>12&63,t[n+2]=128|e>>6&63,t[n+3]=128|e&63),n+=4,i+=1;continue}}if(a>=55296&&a<=57343)throw TypeError(`compound key string parts must contain valid Unicode scalar values`);t!==null&&(t[n]=224|a>>12,t[n+1]=128|a>>6&63,t[n+2]=128|a&63),n+=3}return n}function lt(e){let t=/* @__PURE__ */ new Uint8Array(9);return ut(new DataView(t.buffer),e),t}function ut(e,t){if(!Number.isFinite(t))throw TypeError(`compound key number parts must be finite`);let n=Object.is(t,-0)?0:t;e.setUint8(0,48),e.setFloat64(1,n,!1);let r=e.getBigUint64(1,!1);r=(r&1n<<63n)==0n?r^1n<<63n:~r&$e,e.setBigUint64(1,r,!1)}const dt=65536,ft=16384,pt=4294967295,mt=new Uint32Array(ft);function k(e){let t=/* @__PURE__ */ Error(`invalid Snappy block: ${e}`);return t.name=`CorruptionError`,t}function ht(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function gt(e,t){return Math.imul(e,2654435761)>>>32-t}function _t(e){if(e.byteLength>pt)throw RangeError(`Snappy input exceeds the 32-bit length limit`);let t=new Uint8Array(e.byteLength+Math.ceil(e.byteLength/6)+32),n=0,r=e.byteLength;for(;r>=128;)t[n++]=r&127|128,r=Math.floor(r/128);t[n++]=r;let i=(r,i)=>{if(r===i)return;let a=i-r-1;if(a<60)t[n++]=a<<2;else{let e=a<=255?1:a<=65535?2:a<=16777215?3:4;t[n++]=59+e<<2;for(let r=0;r<e;r+=1)t[n++]=a&255,a>>>=8}t.set(e.subarray(r,i),n),n+=i-r},a=(e,r)=>{for(;r>0;){let i=Math.min(r,64);i>=4&&i<=11&&e<2048?(t[n++]=1|i-4<<2|e>>>8<<5,t[n++]=e&255):(t[n++]=2|i-1<<2,t[n++]=e&255,t[n++]=e>>>8),r-=i}},o=8;for(;1<<o<Math.min(e.byteLength,ft);)o+=1;let s=1<<o,c=mt;for(let t=0;t<e.byteLength;t+=dt){let n=Math.min(t+dt,e.byteLength);c.fill(0,0,s);let r=t,l=t,u=0;for(;r+4<=n;){let s=ht(e,r),d=gt(s,o),f=c[d];c[d]=r-t+1;let p=t+f-1;if(f===0||s!==ht(e,p)){u+=1,r+=1+Math.min(u>>>5,64);continue}i(l,r);let m=r;for(r+=4;r<n&&e[r]===e[p+r-m];)r+=1;a(m-p,r-m),l=r,u=0,r+4<=n&&(c[gt(ht(e,r-1),o)]=r-t)}i(l,n)}return t.subarray(0,n)}function vt(e,t,n){if(!Number.isSafeInteger(t)||t<0||t>pt)throw RangeError(`invalid Snappy output limit`);let r=0,i=0;for(let t=0;;t+=1){if(r>=e.byteLength||t===5)throw k(`truncated or invalid length`);let n=e[r++];if(t===4&&n>15)throw k(`length exceeds 32 bits`);if(i+=(n&127)*2**(t*7),n<128)break}if(i>t)throw k(`output exceeds ${t} byte limit`);if(n!==void 0&&i!==n)throw k(`length mismatch: expected ${n} bytes, got ${i}`);let a=new Uint8Array(i),o=0;for(;r<e.byteLength;){let t=e[r++],n=t&3;if(n===0){let n=t>>>2;if(n<60)n+=1;else{let t=n-59;if(t>e.byteLength-r)throw k(`truncated literal length`);n=1;for(let i=0;i<t;i+=1)n+=e[r++]*2**(i*8)}if(n>e.byteLength-r||n>i-o)throw k(`literal exceeds input or output`);a.set(e.subarray(r,r+n),o),r+=n,o+=n;continue}let s=n===1?1:n===2?2:4;if(s>e.byteLength-r)throw k(`truncated copy offset`);let c=n===1?4+(t>>>2&7):1+(t>>>2),l=n===1?(t&224)<<3:0;for(let t=0;t<s;t+=1)l+=e[r++]*2**(t*8);if(l===0||l>o||c>i-o)throw k(`copy exceeds output or has an invalid offset`);let u=0;for(;u<c;){let e=Math.min(l+u,c-u);a.copyWithin(o+u,o-l,o-l+e),u+=e}o+=c}if(o!==i)throw k(`length mismatch: expected ${i} bytes, got ${o}`);return a}const A=O(`BDBZVAL1`),yt=O(`BDBZSNP1`),bt=1024,j=8388608,xt=268435456,M=(()=>{let e=/* @__PURE__ */ new Uint32Array(2048);for(let t=0;t<256;t+=1){let n=t;for(let e=0;e<8;e+=1)n&1?n=n>>>1^3988292384:n>>>=1;e[t]=n>>>0}for(let t=0;t<256;t+=1){let n=e[t];for(let r=1;r<8;r+=1)n=n>>>8^e[n&255],e[r*256+t]=n>>>0}return e})();function N(e,t){let n=Error(t);return n.name=e,n}function St(e){switch(e){case!1:return 0;case`gzip`:return 1;case`deflate`:return 2;case`snappy`:return 3;default:throw N(`InternalError`,`unsupported compression kind: ${String(e)}`)}}function Ct(e){switch(e){case 0:return!1;case 1:return`gzip`;case 2:return`deflate`;case 3:return`snappy`;default:throw N(`CorruptionError`,`invalid compression tag: ${e}`)}}function wt(){return N(`UnsupportedPlatformError`,`CompressionStream and DecompressionStream are required for moyodb compression`)}function Tt(){if(typeof CompressionStream!=`function`||typeof DecompressionStream!=`function`)throw wt()}function Et(e){let t=4294967295,n=0,r=e.byteLength-7;for(;n<r;n+=8){let r=t^e[n]^e[n+1]<<8^e[n+2]<<16^e[n+3]<<24;t=M[1792+(r&255)]^M[1536+(r>>>8&255)]^M[1280+(r>>>16&255)]^M[1024+(r>>>24)]^M[768+e[n+4]]^M[512+e[n+5]]^M[256+e[n+6]]^M[e[n+7]]}for(;n<e.byteLength;n+=1)t=t>>>8^M[(t^e[n])&255];return(t^4294967295)>>>0}function Dt(e,t,n,r){let i=new Uint8Array(18+r.byteLength);return Ot(i,0,e,t,n,r),i}function Ot(e,t,n,r,i,a){let o=Et(a);e.set(a,t+18),e.set(n,t),e[t+8]=1,e[t+9]=r;let s=new DataView(e.buffer,e.byteOffset+t,18);s.setUint32(10,i,!0),s.setUint32(14,o,!0)}function kt(e,t,n,r,i){let a=Et(i);e.set(t),e[8]=1,e[9]=n;let o=new DataView(e.buffer,e.byteOffset,18);o.setUint32(10,r,!0),o.setUint32(14,a,!0)}function At(e,t,n,r,i){let a=new Uint8Array(18+i),o=18;for(let e of r)a.set(e,o),o+=e.byteLength;return kt(a,e,t,n,a.subarray(18)),a}function jt(e,t){return(t+18)*100<=e*90}function Mt(e){if(e.byteLength<65536)return!0;let t=0;for(let n=0;n<3;n+=1){let r=Math.floor((e.byteLength-bt)*n/2);t+=_t(e.subarray(r,r+bt)).byteLength}return jt(bt*3,t)}function Nt(e){if(e.byteLength>j)throw N(`ValueTooLargeError`,`value has ${e.byteLength} bytes, exceeding the ${j} byte limit`)}function Pt(e,t){if(t===!1)return{payload:e,rawLength:e.byteLength,byteLength:e.byteLength,kindTag:null};Nt(e);let n=e,r=0;if(e.byteLength>=1024&&Mt(e)){let t=_t(e);jt(e.byteLength,t.byteLength)&&(n=t,r=3)}return{payload:n,rawLength:e.byteLength,byteLength:18+n.byteLength,kindTag:r}}function Ft(e,t,n){if(!Number.isSafeInteger(n)||n<0||e.byteLength>t.byteLength-n)throw N(`InternalError`,`prepared store value exceeds its destination`);return e.kindTag===null?t.set(e.payload,n):Ot(t,n,A,e.kindTag,e.rawLength,e.payload),n+e.byteLength}function It(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}function Lt(e){let t=0;return new ReadableStream({pull(n){if(t<e.byteLength){let r=Math.min(t+65536,e.byteLength);n.enqueue(e.subarray(t,r)),t=r}t===e.byteLength&&n.close()}})}function Rt(e,t,n=!0){if(t.byteLength<e.byteLength)return null;for(let n=0;n<e.byteLength;n+=1)if(t[n]!==e[n])return null;if(t.byteLength<18){if(n)throw N(`CorruptionError`,`truncated compression envelope: expected at least 18 bytes, got ${t.byteLength}`);return null}let r=new DataView(t.buffer,t.byteOffset,18);return{version:t[8],kindTag:t[9],rawLength:r.getUint32(10,!0),payloadChecksum:r.getUint32(14,!0)}}async function zt(e,t,n){Tt();let r;try{r=Lt(e).pipeThrough(new CompressionStream(t))}catch{throw wt()}let i=r.getReader(),a=[],o=0,s=!1;try{for(let e=await i.read();!e.done;e=await i.read()){let t=e.value;if(o+=t.byteLength,n!==void 0&&o>=n){s=!0,await i.cancel(`compressed output is not smaller than the raw payload`);break}a.push(t)}}catch(e){if(!s)throw N(`InternalError`,`failed to compress bytes with ${t}: ${String(e)}`)}finally{try{i.releaseLock()}catch{}}return s||n!==void 0&&o>=n?null:{chunks:a,totalBytes:o}}async function Bt(e,t,n,r){if(t===`snappy`)return vt(e,r??j,r);Tt();let i;try{i=Lt(It(e)).pipeThrough(new DecompressionStream(t))}catch{throw wt()}try{return await Vt(i,n,r)}catch(e){throw N(`CorruptionError`,`failed to decompress ${n}: ${String(e)}`)}}async function Vt(e,t,n){let r=e.getReader(),i=[],a=0;try{for(let e=await r.read();!e.done;e=await r.read()){let o=e.value;if(a+=o.byteLength,n!==void 0&&a>n)throw await r.cancel(`decompressed ${t} exceeded ${n} bytes`),N(`CorruptionError`,`decompressed ${t} exceeds ${n} byte limit`);i.push(o)}}finally{r.releaseLock()}if(i.length===1)return i[0];let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o}function Ht(e){let t=(e&12)>>>2;switch(t){case 0:return!1;case 1:return`gzip`;case 2:return`deflate`;case 3:return`snappy`;default:throw N(`CorruptionError`,`invalid store compression flags: ${t}`)}}async function Ut(e,t){if(Nt(e),t===!1)return e;if(t===`snappy`){let n=Pt(e,t),r=new Uint8Array(n.byteLength);return Ft(n,r,0),r}if(e.byteLength<1024)return Dt(A,0,e.byteLength,e);let n=new Uint8Array(18+e.byteLength),r=n.subarray(18);r.set(e);let i=await zt(r,t,r.byteLength);return i===null||!jt(r.byteLength,i.totalBytes)?(kt(n,A,0,r.byteLength,r),n):At(A,St(t),r.byteLength,i.chunks,i.totalBytes)}async function P(e,t){let n=Rt(A,e,t.strict);if(!n)return e;if(n.version!==1){if(t.strict)throw N(`CorruptionError`,`unsupported value record version: ${n.version}`);return e}let r;try{r=Ct(n.kindTag)}catch(n){if(t.strict)throw n;return e}let i=e.subarray(18);if(Et(i)!==n.payloadChecksum){if(t.strict)throw N(`CorruptionError`,`value record checksum mismatch`);return e}if(r===!1){if(i.byteLength!==n.rawLength){if(t.strict)throw N(`CorruptionError`,`value record length mismatch: expected ${n.rawLength} bytes, got ${i.byteLength}`);return e}return i.slice()}if(n.rawLength>j)throw N(`CorruptionError`,`compressed value advertises ${n.rawLength} decompressed bytes, exceeding the ${j} byte limit`);let a=await Bt(i,r,`value record (${r})`,n.rawLength);if(a.byteLength!==n.rawLength)throw N(`CorruptionError`,`decompressed value length mismatch: expected ${n.rawLength} bytes, got ${a.byteLength}`);return a}async function Wt(e,t){if(t===!1)return e;if(![`gzip`,`deflate`].includes(t))throw N(`InternalError`,`unsupported snapshot compression kind: ${String(t)}`);if(e.byteLength>xt)throw N(`SerializationError`,`snapshot has ${e.byteLength} bytes, exceeding the ${xt} byte limit`);let n=It(e),r=await zt(n,t);if(r===null)throw N(`InternalError`,`failed to compress bytes with ${t}`);return At(yt,St(t),n.byteLength,r.chunks,r.totalBytes)}async function Gt(e){let t=Rt(yt,e);if(!t)return e;if(t.version!==1)throw N(`CorruptionError`,`unsupported snapshot compression version: ${t.version}`);let n=Ct(t.kindTag);if(n===!1)throw N(`CorruptionError`,`snapshot compression envelope cannot store kind "none"`);if(n===`snappy`)throw N(`CorruptionError`,`invalid snapshot compression tag: ${t.kindTag}`);let r=e.subarray(18);if(Et(r)!==t.payloadChecksum)throw N(`CorruptionError`,`snapshot compression checksum mismatch`);if(t.rawLength>xt)throw N(`CorruptionError`,`compressed snapshot advertises ${t.rawLength} decompressed bytes, exceeding the ${xt} byte limit`);let i=await Bt(r,n,`snapshot export (${n})`,t.rawLength);if(i.byteLength!==t.rawLength)throw N(`CorruptionError`,`decompressed snapshot length mismatch: expected ${t.rawLength} bytes, got ${i.byteLength}`);return i}var Kt=class extends Error{constructor(e,t){super(t),this.name=e,Object.setPrototypeOf(this,new.target.prototype)}},qt=class extends Kt{constructor(e){super(`ReservedStoreNameError`,e)}},Jt=class extends Kt{constructor(e){super(`InvalidRangeError`,e)}},F=class extends Kt{constructor(e){super(`SerializationError`,e)}},I=class extends Kt{constructor(e){super(`InvalidOpenOptionsError`,e)}};const Yt=new TextDecoder(`utf-8`,{fatal:!0}),Xt=Symbol(`moyodb.indexing.missing`),Zt=BigInt(`0xcbf29ce484222325`),Qt=BigInt(`0x100000001b3`),$t=BigInt(`0xffffffffffffffff`),en=`__browserdb:index:`,L=`__browserdb:indexes`;function R(e){return e.startsWith(`__browserdb:`)}function tn(e){if(R(e))throw new qt(`reserved store name: ${e}`)}function nn(e){if(e===void 0)return[];if(!Array.isArray(e))throw new I(`indexes must be an array`);let t=[],n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map;for(let i of e){if(typeof i!=`object`||!i||Array.isArray(i))throw new I(`each index definition must be an object`);let{store:e,name:a,keyPath:o,unique:s}=i;if(typeof e!=`string`||e.length===0)throw new I(`index store must be a non-empty string`);if(typeof a!=`string`||a.length===0)throw new I(`index name must be a non-empty string`);tn(e);let c=bn(o);if(s!==void 0&&typeof s!=`boolean`)throw new I(`index unique must be a boolean`);let l={store:e,name:a,keyPath:c.paths,compound:c.compound,unique:s??!1,internalStore:Cn(e,a)},u=an(l.store,l.name);if(n.has(u))throw new I(`duplicate index definition ${l.store}.${l.name}`);n.add(u);let d=r.get(l.internalStore);if(d&&d!==u)throw new I(`index definitions ${d} and ${u} map to the same internal store ${l.internalStore}`);r.set(l.internalStore,u),t.push(l)}return t.sort(rn),t}function rn(e,n){let r=t(e.store,n.store);if(r!==0)return r;let i=t(e.name,n.name);if(i!==0)return i;let a=Number(e.unique)-Number(n.unique);return a===0?t(Sn(e),Sn(n)):a}function an(e,t){return JSON.stringify([e,t])}function on(e,t,n){return e.find(e=>e.store===t&&e.name===n)??null}function sn(e,t){return tt([O(e),O(t)])}function cn(e){return O(JSON.stringify(yn(e)))}function ln(e){let t;try{t=JSON.parse(Yt.decode(e));let[n]=nn([t]);return n}catch(e){throw new F(`invalid persisted index metadata: ${String(e)}`)}}function un(e,t){let n=new Uint8Array(An(e)+An(t));return jn(n,jn(n,0,e),t),n}function dn(e){try{return Nn(e)}catch(e){throw e instanceof F?e:new F(`invalid index entry key encoding: ${String(e)}`)}}function fn(e){let t=B(e),n=Mn(t.slice());return n?{gte:t,lt:n}:{gte:t}}function pn(e={}){if(e.gt!==void 0&&e.gte!==void 0)throw new Jt(`range cannot include both gt and gte`);if(e.lt!==void 0&&e.lte!==void 0)throw new Jt(`range cannot include both lt and lte`);if(e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<0||e.limit>4294967295))throw new Jt(`limit must be an integer between 0 and 4294967295`)}function mn(e={}){pn(e);let t={};if(e.reverse!==void 0&&(t.reverse=e.reverse),e.limit!==void 0&&(t.limit=e.limit),e.gte&&(t.gte=B(e.gte)),e.gt){let n=Mn(B(e.gt));n&&(t.gte=n)}if(e.lt&&(t.lt=B(e.lt)),e.lte){let n=Mn(B(e.lte));n&&(t.lt=n)}return t}function hn(e,t){return _n(e,En(t))}function gn(e){let t=!1,n;return r=>(t||=(n=En(e),!0),_n(r,n))}function _n(e,t){if(e.compound){let n=[];for(let r of e.keyPath){let e=Dn(t,r);if(e===Xt)return null;n.push(On(e))}return tt(n)}let n=Dn(t,e.keyPath[0]);return n===Xt?null:On(n)}function z(e){return e.map(e=>({store:e.store,name:e.name,keyPath:[...e.keyPath],compound:e.compound,unique:e.unique,internalStore:e.internalStore}))}function vn(e){return e.map(yn)}function yn(e){return{store:e.store,name:e.name,keyPath:e.compound?[...e.keyPath]:e.keyPath[0],unique:e.unique}}function bn(e){if(typeof e==`string`)return xn(e),{paths:[e],compound:!1};if(!Array.isArray(e)||e.length===0||!e.every(e=>typeof e==`string`))throw new I(`index keyPath must be a non-empty string or non-empty string[]`);for(let t of e)xn(t);return{paths:[...e],compound:!0}}function xn(e){if(e.length===0)throw new I(`index keyPath strings must be non-empty`);if(e.startsWith(`.`)||e.endsWith(`.`)||e.includes(`..`))throw new I(`invalid index keyPath: ${e}`)}function Sn(e){return e.compound?`[${e.keyPath.join(`,`)}]`:e.keyPath[0]}function Cn(e,t){let n=wn(O(e)),r=wn(O(t)),i=`${en}${n}:${r}`;if(O(i).length<=255)return i;let a=O(`${e}\u0000${t}`);return`${en}h:${Tn(a)}`}function wn(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/u,``)}function Tn(e){let t=Zt;for(let n of e)t^=BigInt(n),t=t*Qt&$t;return t.toString(16).padStart(16,`0`)}function En(e){try{return JSON.parse(Yt.decode(e))}catch(e){throw new F(`indexed values must be valid UTF-8 JSON: ${String(e)}`)}}function Dn(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||!Object.hasOwn(n,e))return Xt;n=Reflect.get(n,e)}return n}function On(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e instanceof Uint8Array)try{return et(e)}catch(e){throw e instanceof TypeError?new F(`invalid indexed keyPath value: ${e.message}`):e}throw new F(`indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${kn(e)}`)}function kn(e){return Array.isArray(e)?`array`:typeof e}function An(e){let t=0,n=e.length;for(let r=0;r<n;r+=1)e[r]===0&&(t+=1);return n+t+2}function jn(e,t,n){let r=n.length;for(let i=0;i<r;i+=1){let r=n[i];r===0?(e[t]=0,e[t+1]=255,t+=2):(e[t]=r,t+=1)}return e[t]=0,e[t+1]=0,t+2}function B(e){let t=new Uint8Array(An(e));return jn(t,0,e),t}function Mn(e){for(let t=e.length-1;t>=0;--t)if(e[t]!==255)return e[t]+=1,t+1===e.length?e:e.subarray(0,t+1);return null}function Nn(e){let t={unescaped:0,end:0};if(!Pn(e,0,t))throw new F(`invalid index entry key encoding`);let n=t.unescaped,r=t.end;if(!Pn(e,r,t))throw new F(`invalid index entry key encoding`);let i=t.unescaped,a=t.end;if(a!==e.length)for(;;){if(!Pn(e,a,t))throw new F(`invalid index entry key encoding`);if(t.end<=a)throw TypeError(`invalid compound key encoding`);if(a=t.end,a===e.length)throw new F(`invalid index entry key encoding`)}let o=new Uint8Array(n),s=new Uint8Array(i);return Fn(e,0,o),Fn(e,r,s),{logicalKey:o,primaryKey:s}}function Pn(e,t,n){if(t>=e.length)return!1;let r=0;for(let i=t;i<e.length;i+=1){if(e[i]!==0){r+=1;continue}let t=e[i+1];if(t===255){r+=1,i+=1;continue}if(t===0)return n.unescaped=r,n.end=i+2,!0;throw TypeError(`invalid compound key encoding`)}throw TypeError(`compound key terminated unexpectedly`)}function Fn(e,t,n){let r=n.length,i=0;for(let a=t;i<r;a+=1){let t=e[a];if(t!==0){n[i]=t,i+=1;continue}if(e[a+1]===255){n[i]=0,i+=1,a+=1;continue}return}}function V(e){return BigInt(e)}function H(e){let t=typeof e==`bigint`?Number(e):e;if(!Number.isSafeInteger(t)||t<0)throw X(`SerializationError`,`WASM integer exceeds the JavaScript safe integer range`);return t}function In(e){return e==null?null:H(e)}function Ln(e){return e.ttl===void 0?e:{...e,ttl:V(e.ttl)}}function Rn(e){pn(e);let t={};return e.gt!==void 0&&(t.gt=e.gt),e.gte!==void 0&&(t.gte=e.gte),e.lt!==void 0&&(t.lt=e.lt),e.lte!==void 0&&(t.lte=e.lte),e.reverse!==void 0&&(t.reverse=e.reverse),e.limit!==void 0&&(t.limit=e.limit),t}const zn={},Bn=/* @__PURE__ */ new Uint8Array,Vn=1024,U=4294967295,Hn=8388608,Un=8389662,Wn=4194304,Gn=4096,Kn=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function W(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=n();return e.set(t,i),i}function qn(t){return e(t)&&t.type===`moyodb:persistence-bridge:response`&&typeof t.id==`number`&&typeof t.granted==`boolean`}var Jn=class{port=null;nextRequestId=1;pending=/* @__PURE__ */ new Map;readyResolve=null;ready;constructor(){this.ready=new Promise(e=>{this.readyResolve=e}),self.addEventListener(`message`,this.handleInitMessage)}async persisted(){return this.request(`persisted`)}async persist(){return this.request(`persist`)}close(){self.removeEventListener(`message`,this.handleInitMessage),this.readyResolve&&=(this.readyResolve(null),null),this.port&&=(this.port.onmessage=null,this.port.close(),null);for(let e of this.pending.values())e.resolve(!1);this.pending.clear()}async request(e){let t=await this.ready;return!t||this.port!==t?!1:new Promise(n=>{let r=this.nextRequestId;this.nextRequestId+=1,this.pending.set(r,{resolve:n});let i={type:`moyodb:persistence-bridge:request`,id:r,op:e};try{t.postMessage(i)}catch{this.pending.delete(r),n(!1)}})}handleInitMessage=e=>{if(e.origin!==``&&e.origin!==self.location.origin||e.data?.type!==`moyodb:persistence-bridge:init`||e.ports.length===0)return;let t=e.ports[0];if(this.port){t.close();return}this.port=t,this.port.onmessage=this.handleResponse,this.port.start(),self.removeEventListener(`message`,this.handleInitMessage),this.readyResolve?.(t),this.readyResolve=null};handleResponse=e=>{let t=e.data;if(!qn(t))return;let n=this.pending.get(t.id);n&&(this.pending.delete(t.id),n.resolve(!!t.granted))}};async function Yn(){let e=navigator.storage;if(typeof e.estimate!=`function`)return{usage:0,quota:0};let t=await e.estimate();return{usage:t.usage??0,quota:t.quota??0}}function G(e){let t=``;for(let n=0;n<e.byteLength;n+=1)t+=Kn[e[n]];return t}function K(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}function Xn(e){let t=Rn(e);for(let e of[`gt`,`gte`,`lt`,`lte`]){let n=t[e];n!==void 0&&(t[e]=n.slice())}return t}function Zn(e,t){for(let n of[`gt`,`gte`,`lt`,`lte`]){let r=e[n],i=t[n];if(r===void 0?i!==void 0:i===void 0||!K(r,i))return!1}return e.reverse===t.reverse&&e.limit===t.limit}function Qn(e,t){return e===void 0||t===void 0?e===t:K(e,t)}function $n(e){return e===void 0?void 0:e.slice()}function er(e,t){return tr(e)+tr(t)}function tr(e){let t=2;for(let n=0;n<e.length;n+=1)t+=e[n]===0?2:1;return t}function nr(e){if(e.byteLength>Hn){let t=/* @__PURE__ */ Error(`stored value has ${e.byteLength} bytes, exceeding the ${Hn} byte limit`);throw t.name=`ValueTooLargeError`,t}return e}function q(e){return e instanceof Uint8Array?e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e:e.slice():new Uint8Array(e)}function rr(t){if(!e(t))return null;let n=t.name??t.code;return typeof n==`string`?n:null}function J(e,t){return rr(e)===t}const ir=O(`BDBIDX1`),ar=new TextDecoder(`utf-8`,{fatal:!0});function or(e,t){if(t.length===0)return e;let n=O(JSON.stringify(vn(t))),r=/* @__PURE__ */ new ArrayBuffer(4);new DataView(r).setUint32(0,n.byteLength,!0);let i=new Uint8Array(e.byteLength+n.byteLength+4+ir.byteLength),a=0;return i.set(e,a),a+=e.byteLength,i.set(n,a),a+=n.byteLength,i.set(new Uint8Array(r),a),a+=4,i.set(ir,a),i}function sr(e){let t=ir.byteLength;if(e.byteLength<t+4)return{snapshot:e,indexes:[]};let n=e.byteLength-t;if(!K(e.subarray(n),ir))return{snapshot:e,indexes:[]};let r=n-4;if(r<0)return{snapshot:e,indexes:[]};let i=r-new DataView(e.buffer,e.byteOffset+r,4).getUint32(0,!0);if(i<0)throw X(`CorruptionError`,`invalid snapshot index trailer length`);let a;try{a=JSON.parse(ar.decode(e.subarray(i,r)))}catch(e){throw X(`CorruptionError`,`invalid snapshot index trailer: ${String(e)}`)}return{snapshot:e.subarray(0,i),indexes:nn(a)}}function cr(e){return new BroadcastChannel(`db:${e}:events`)}function Y(e,t){let n=cr(e);try{n.postMessage({type:t,dbName:e,txid:null})}finally{n.close()}}var lr=class{releaseResolver=null;requestPromise=null;held=!1;async acquire(e,t){let r=new Promise(e=>{this.releaseResolver=e}),i=`db:${e}:owner`;if(t===0){let t=null,n=new Promise(e=>{t=e}),a=navigator.locks.request(i,{mode:`exclusive`,ifAvailable:!0},async e=>e?(this.held=!0,t?.(!0),await r,!0):(t?.(!1),!1));if(!await n)throw X(`DatabaseBusyError`,`database ${e} is already owned by another tab`);this.requestPromise=a;return}let a=new AbortController,o=setTimeout(()=>a.abort(),n(t)),s=null,c=new Promise(e=>{s=e});this.requestPromise=navigator.locks.request(i,{mode:`exclusive`,signal:a.signal},async e=>(clearTimeout(o),this.held=!0,s?.(),await r,!0));try{await Promise.race([c,this.requestPromise])}catch{if(!this.held)throw X(`DatabaseBusyError`,`timed out waiting for ownership of ${e}`)}}async release(){if(this.held){this.releaseResolver?.();try{await this.requestPromise}finally{this.releaseResolver=null,this.requestPromise=null,this.held=!1}}}},ur=class{options;dbName=null;engine=null;events=null;lease=null;wasmReady=null;persistenceBridge;txChanges=/* @__PURE__ */ new Map;txModes=/* @__PURE__ */ new Map;primaryCursors=/* @__PURE__ */ new Map;nextPrimaryCursorId=1;txIndexSchemas=/* @__PURE__ */ new Map;indexesBySchema=/* @__PURE__ */ new WeakMap;readonlyIndexCache=/* @__PURE__ */ new Map;indexBoundCache=null;txEnsuredRawStores=/* @__PURE__ */ new Map;txIndexSchemaChanged=/* @__PURE__ */ new Set;txStoreCompression=/* @__PURE__ */ new Map;committedIndexes=null;committedStoreCompression=null;openOptions=null;maintenanceOperation=null;constructor(e={}){this.options=e,this.persistenceBridge=e.persistence??new Jn}async open(e){if(this.engine)return;fr(),dr(),this.dbName=e.dbName,this.events=new BroadcastChannel(`db:${e.dbName}:events`),this.lease=new lr;let t=null;try{await this.lease.acquire(e.dbName,e.options.ownerWaitMs),t=new(await(this.loadWasm())).WasmEngine,await t.open(e.dbName,{create_if_missing:e.options.createIfMissing,cache_pages:e.options.cachePages}),e.options.changeFeed&&pr(t,e.options.changeFeed),e.options.debugFailpoint&&t.set_failpoint(e.options.debugFailpoint),this.engine=t,this.openOptions=e.options,this.clearRuntimeCaches(),this.maintenanceOperation=null,this.events.postMessage({type:`owner_changed`,dbName:e.dbName,txid:null})}catch(e){throw await this.cleanupAfterFailedOpen(t),$(e)}}async close(){this.ensureNotInMaintenance();let e=this.dbName;this.clearRuntimeCaches();try{this.engine?.close()}catch(e){throw $(e)}finally{this.engine=null,e&&this.events&&this.events.postMessage({type:`db_closed`,dbName:e,txid:null}),this.events?.close(),this.events=null,e&&this.lease&&await this.lease.release(),e&&Y(e,`owner_changed`),this.disposePersistenceBridge(),this.lease=null,this.dbName=null,this.openOptions=null,this.maintenanceOperation=null}}async destroy(){this.ensureNotInMaintenance();let e=this.dbName;if(!e)return;let t=null;try{this.rollbackAllTransactions(),this.engine?.abandon(),await(await this.loadWasm()).deleteDB(e),Y(e,`db_deleted`)}catch(e){t=e}finally{if(this.engine=null,this.clearRuntimeCaches(),this.events?.close(),this.events=null,this.lease)try{await this.lease.release()}catch(e){t===null&&(t=e)}Y(e,`owner_changed`),this.disposePersistenceBridge(),this.lease=null,this.dbName=null,this.openOptions=null,this.maintenanceOperation=null}if(t!==null)throw $(t)}async deleteDB(e){fr(),dr();let t=new lr,n=null,r=!1;try{await t.acquire(e,0),r=!0,await(await this.loadWasm()).deleteDB(e),Y(e,`db_deleted`)}catch(e){n=e}finally{try{await t.release()}catch(e){n===null&&(n=e)}r&&Y(e,`owner_changed`)}if(n!==null)throw $(n)}begin(e){this.recoverEngineIfNeeded();let t=this.loadCommittedIndexSchema(),n=this.loadCommittedStoreCompression(),r=H(this.withEngine(t=>t.begin_tx(e)));return this.txChanges.set(r,/* @__PURE__ */ new Map),this.txModes.set(r,e),this.txIndexSchemas.set(r,t),this.txStoreCompression.set(r,{owned:!1,values:n}),Promise.resolve(r)}commit(e){let t=this.txChanges.get(e)??/* @__PURE__ */ new Map,n=this.txIndexSchemaChanged.has(e)?this.txIndexSchemas.get(e):void 0,r=this.txStoreCompression.get(e),i=this.txModes.get(e),a;try{a=H(this.withEngine(t=>t.commit_tx(V(e))))}catch(t){try{this.engine&&!this.engine.needs_recovery()&&this.withEngine(t=>t.rollback_tx(V(e)))}catch{}this.cleanupTxState(e);let n=this.recoverEngineIfNeeded();if(!n?.pendingCommitted||n.pendingTxid===null||J(t,`RecoveryRequiredError`)||J(t,`InjectedFailureError`))throw t;a=n.pendingTxid}if(n&&(this.committedIndexes=z(n)),i===`readwrite`&&r&&(this.committedStoreCompression=r.values),this.cleanupTxState(e),this.dbName&&this.events){let e={type:`commit_applied`,dbName:this.dbName,txid:a,stores:this.finalizeTrackedChanges(t)};this.events.postMessage(e)}return Promise.resolve(a)}rollback(e){try{this.withEngine(t=>t.rollback_tx(V(e)))}finally{this.cleanupTxState(e)}return Promise.resolve()}async autocommit(e,t,n){let r=await this.begin(e),i=this[t],a;try{a=await i.apply(this,[r,...n])}catch(e){try{await this.rollback(r)}catch{}throw e}return e===`readwrite`?await this.commit(r):await this.rollback(r),a}createStore(e,t,n={}){let r=R(t)?!1:n.compression??`snappy`;return this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.create_store(V(e),t,{compression:r})),this.recordStoreCompressionCreate(e,t,r),this.ensureInternalStoresForStore(e,t),this.markStoreTouched(e,t),Promise.resolve()}dropStore(e,t){let n=this.indexesForStoreInTx(e,t);this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.drop_store(V(e),t)),this.recordStoreCompressionDrop(e,t);for(let t of n)this.dropRawStoreIfExists(e,t.internalStore);return this.recordStoreLevelChange(e,t,`drop`),Promise.resolve()}clearStore(e,t){let n=this.indexesForStoreInTx(e,t);this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.clear_store(V(e),t));for(let t of n)this.clearRawStoreIfExists(e,t.internalStore);return this.recordStoreLevelChange(e,t,`clear`),Promise.resolve()}async get(e,t,n){return this.readStoreValue(e,t,n)}async getMany(e,t,n){let r=this.withEngine(r=>r.get_many(V(e),t,n)),i=!R(t)&&this.storeCompressionForTx(e,t)!==!1;for(let e=0;e<r.length;e+=1){let t=r[e];t!==null&&(r[e]=q(t))}return i?this.decodeStoreValues(e,t,r):r}async getManyPacked(e,t,n){let r=q(this.withEngine(r=>r.get_many_packed(V(e),t,n)));return R(t)||this.storeCompressionForTx(e,t)===!1?ue(r):this.decodeStoreValues(e,t,de(r))}has(e,t,n){return Promise.resolve(this.withEngine(r=>r.has(V(e),t,n)))}async put(e,t,n,r,i={}){await this.putEntry(e,t,n,r,i)}async putEntry(e,t,n,r,i,a,o){let s=a??this.indexesForStoreInTx(e,t),c=o??this.storeCompressionForTx(e,t);if(s.length===0){let a=this.prepareStoredValue(t,r,c),o=a instanceof Uint8Array?a:await a,s=this.withEngine(r=>r.put(V(e),t,n,o,Ln(i)));this.recordPutChange(e,t,n,s);return}await this.putIndexedMany(e,t,[n,r],s,i)}async putMany(e,t,n,r={}){if(n.length===0)return;let i=this.indexesForStoreInTx(e,t);if(i.length===0){let i=await this.encodeEntriesForWrite(e,t,n),a;try{a=this.withEngine(n=>n.put_many(V(e),t,i,Ln(r)))}catch(r){let i=Q(r);throw this.recordPutChanges(e,t,n,i),r}if(a.length!==n.length)throw Z(`put_many`,a.length,n.length);this.recordPutChanges(e,t,n,a);return}let a=Array(n.length*2);for(let e=0;e<n.length;e+=1)a[e*2]=n[e][0],a[e*2+1]=n[e][1];await this.putIndexedMany(e,t,a,i,r)}async putManyPacked(e,t,n,r={}){let i=this.indexesForStoreInTx(e,t);if(i.length!==0){let a=oe(n);if(a.length%2!=0)throw X(`WorkerProtocolError`,`packed putMany payload has an odd item count`);await this.putIndexedMany(e,t,a,i,r);return}let a=this.storeCompressionForTx(e,t)===!1?null:oe(n);if(a!==null&&a.length%2!=0)throw X(`WorkerProtocolError`,`packed putMany payload has an odd item count`);let o=a===null?se(n):a.filter((e,t)=>t%2==0);if(o.length===0)return;let s=a===null?n:await this.encodePackedEntriesForWrite(e,t,a,o),c;try{c=this.withEngine(n=>n.put_many_packed(V(e),t,s,Ln(r)))}catch(n){let r=Q(n);throw this.recordPutKeyChanges(e,t,o,r),n}if(c.length!==o.length)throw Z(`put_many_packed`,c.length,o.length);this.recordPutKeyChanges(e,t,o,c)}async delete(e,t,n){let r=this.indexesForStoreInTx(e,t),i=r.length===0?null:await this.readStoreValue(e,t,n),a=i===null?null:gn(i),o=a===null?[]:r.map(e=>({def:e,logicalKey:a(e)}));if(!this.withEngine(r=>r.delete(V(e),t,n)))return this.recordDeleteChange(e,t,n,!1),!1;for(let t of o)t.logicalKey!==null&&this.deleteIndexEntryIfPresent(e,t.def,t.logicalKey,n);return this.recordDeleteChange(e,t,n,!0),!0}async deleteMany(e,t,n){if(n.length!==0){if(this.indexesForStoreInTx(e,t).length===0){let r;try{r=this.withEngine(r=>r.delete_many(V(e),t,n))}catch(r){let i=Q(r);for(let r=0;r<i.length&&r<n.length;r+=1)this.recordDeleteChange(e,t,n[r],i[r]);throw r}if(r.length!==n.length)throw Z(`delete_many`,r.length,n.length);for(let i=0;i<n.length;i+=1)this.recordDeleteChange(e,t,n[i],r[i]);return}for(let r of n)await this.delete(e,t,r)}}async deleteManyPacked(e,t,n){let r=this.indexesForStoreInTx(e,t),i=oe(n);if(i.length===0)return;if(r.length!==0){await this.deleteMany(e,t,i);return}let a;try{a=this.withEngine(r=>r.delete_many_packed(V(e),t,n))}catch(n){let r=Q(n);for(let n=0;n<r.length&&n<i.length;n+=1)this.recordDeleteChange(e,t,i[n],r[n]);throw n}if(a.length!==i.length)throw Z(`delete_many_packed`,a.length,i.length);for(let n=0;n<i.length;n+=1)this.recordDeleteChange(e,t,i[n],a[n]===1)}async applyBatch(e,t,n){if(n.length!==0){if(this.indexesForStoreInTx(e,t).length===0){let r=await this.encodeBatchOpsForWrite(e,t,n),i;try{i=this.withEngine(n=>n.apply_batch(V(e),t,r))}catch(r){throw this.recordBatchOutcomes(e,t,n,gr(r)),r}if(i.length!==n.length)throw Z(`apply_batch`,i.length,n.length);this.recordBatchOutcomes(e,t,n,i);return}for(let r of n)r.kind===`put`?await this.put(e,t,r.key,r.value):await this.delete(e,t,r.key)}}async applyBatchPacked(e,t,n){if(this.indexesForStoreInTx(e,t).length!==0||this.storeCompressionForTx(e,t)!==!1){let r=ce(n);if(r.length===0)return;await this.applyBatch(e,t,r);return}let r=le(n);if(r.length===0)return;let i;try{i=this.withEngine(r=>r.apply_batch_packed(V(e),t,n))}catch(n){throw this.recordBatchOutcomes(e,t,r,gr(n)),n}if(i.length!==r.length)throw Z(`apply_batch_packed`,i.length,r.length);for(let n=0;n<r.length;n+=1){let a=r[n];a.kind===`put`?this.recordPutChange(e,t,a.key,i[n]===1):this.recordDeleteChange(e,t,a.key,i[n]===1)}}async scan(e,t,n){return this.readStoreScan(e,t,n)}async scanPage(e){if(!Number.isSafeInteger(e.maxRows)||e.maxRows<=0||e.maxRows>U||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<4||e.maxBytes>U)throw X(`InvalidRangeError`,`scan page budgets must be positive u32 integers; maxBytes must be at least 4`);let t=e.cursorId,n=t===void 0?void 0:this.primaryCursors.get(t);if(t!==void 0){if(!n)throw X(`TransactionClosedError`,`scan cursor is closed`);if(n.store!==e.store||n.callerTxId!==e.txId||!Zn(n.range,e.range??zn))throw X(`InvalidRangeError`,`scan continuation does not match the cursor`)}else{let r=e.txId===void 0,i=e.txId??await this.begin(`readonly`),a=Xn(e.range??zn),o;try{o=this.withEngine(t=>t.open_scan_cursor(V(i),e.store,Rn(a),!1))}catch(e){if(r)try{await this.rollback(i)}catch{}throw e}t=this.nextPrimaryCursorId++,n={engineId:o,txId:i,ownsTx:r,store:e.store,range:a,callerTxId:e.txId},this.primaryCursors.set(t,n)}try{let r=this.withEngine(t=>t.scan_cursor_next(n.engineId,e.maxRows,e.maxBytes)),i=q(r.packet),a=i.byteLength<4?-1:new DataView(i.buffer,i.byteOffset,4).getUint32(0,!0);if(a!==r.rowCount||a>e.maxRows||i.byteLength>e.maxBytes)throw X(`CorruptionError`,`scan cursor returned an invalid page budget or count`);let o=this.storeCompressionForTx(n.txId,n.store)===!1?null:he(i),s=i.byteLength;if(o!==null){s=4;for(let t of o)if(t.value=await P(t.value,{strict:!0}),s+=8+t.key.byteLength+t.value.byteLength,s>e.maxBytes)throw X(`ValueTooLargeError`,`decoded scan page exceeds maxBytes`)}return r.exhausted&&await this.closeCursor(t),{rows:o??pe(i),done:r.exhausted,bytes:s,...r.exhausted?{}:{cursorId:t}}}catch(e){try{await this.closeCursor(t)}catch{}throw e}}async closeCursor(e){let t=this.primaryCursors.get(e);if(t){this.primaryCursors.delete(e);try{this.withEngine(e=>e.close_scan_cursor(t.engineId))}finally{t.ownsTx&&await this.rollback(t.txId)}}}async getByIndex(e,t,n,r){let i=this.resolveIndexDefinition(e,t,n),a=await this.loadVisibleIndexPage(e,i,{gte:r,lte:r},null,1);return a.rows.length===0?null:a.rows[0].value}async scanByIndex(e,t,n,r={}){pn(r);let i=this.resolveIndexDefinition(e,t,n),a=[],o=r.limit??1/0;if(o<=0)return a;let s=this.physicalIndexRange(e,i,r),c=null;for(;o>0;){let t=await this.loadVisibleIndexPage(e,i,r,c,Math.min(o,256),Un,s);if(a.push(...t.rows),o-=t.rows.length,t.cursor===null)break;c=t.cursor}return a}async scanByIndexPage(e,t,n,r,i,a,o=Un){if(!Number.isSafeInteger(a)||a<=0)throw X(`InvalidRangeError`,`index scan page limit must be a positive integer`);if(!Number.isSafeInteger(o)||o<4||o>U)throw X(`InvalidRangeError`,`index scan page maxBytes must be a u32 integer of at least 4`);let s=this.resolveIndexDefinition(e,t,n);return this.loadVisibleIndexPage(e,s,r,i,a,o,this.physicalIndexRange(e,s,r))}getIndexes(e){return Promise.resolve(vn(e===void 0?this.loadCommittedIndexSchema():this.indexSchemaForTx(e)))}async reconcileIndexes(e,t){let n=nn(t);this.ensureRawStore(e,L);let r=this.readIndexSchemaInTx(e),i=new Set(n.map(e=>e.internalStore));for(let t of r)i.has(t.internalStore)||this.dropRawStoreIfExists(e,t.internalStore);this.clearRawStoreIfExists(e,L);let a=null,o=0,s=null,c=typeof this.engine?.has_many==`function`,l=/* @__PURE__ */ new Map;for(let t of n){if(a!==t.store&&(l.clear(),o=0,s=null,a=t.store),this.ensureRawStore(e,t.internalStore),this.clearRawStoreIfExists(e,t.internalStore),this.rawStoreExistsInTx(e,t.store)){let n;if(s!==null){let r=this.withEngine(n=>n.has_many(V(e),t.store,s.map(e=>e.key)));if(r.length!==s.length)throw Z(`has_many`,r.length,s.length);n=s.filter((e,t)=>r[t])}else if(n=await this.readStoreScan(e,t.store,zn),c&&n.length<=Gn){let e=0;for(let t of n)if(e+=t.key.byteLength+t.value.byteLength,e>Wn)break;e<=Wn&&(s=n)}for(let r of n){let n=G(r.key),i=l.get(n),a;if(i&&(i.bytes===r.value||K(i.bytes,r.value)))a=i.document,i.bytes=r.value;else{a=En(r.value);let e=i?.inputBytes??0,t=r.key.byteLength+r.value.byteLength;(i||l.size<Gn)&&o-e+t<=Wn?(l.set(n,{bytes:r.value,inputBytes:t,document:a}),o+=t-e):i&&(l.delete(n),o-=e)}let s=_n(t,a);s!==null&&(await this.assertUniqueIndexAvailability(e,t,s,r.key),this.putIndexEntry(e,t,this.buildIndexEntryKey(t,s,r.key),Bn))}}this.putRawValue(e,L,sn(t.store,t.name),cn(t))}this.txIndexSchemas.set(e,z(n)),this.txIndexSchemaChanged.add(e)}listStores(){return Promise.resolve(this.currentStoreNames())}getVersion(){return Promise.resolve(H(this.withEngine(e=>e.get_schema_version())))}async changesSince(e,t={}){let n=t.stores?.filter(e=>!R(e)),r={...t,stores:n?[...n]:void 0,limit:n?t.limit:void 0},i=this.withEngine(t=>t.changes_since(V(e),r)),a=n?new Set(n):null,o=[];for(let e of i.changes){if(R(e.store)||a&&!a.has(e.store))continue;let n=t.limit===void 0||o.length<t.limit?q(e.key):null,r;e.value!==void 0&&(r=await this.decodeStoreValueForFeed(e.store,q(e.value))),n!==null&&o.push({txId:H(e.txId),store:e.store,key:n,kind:e.kind,value:r})}return{latestTxId:H(i.latestTxId),changes:o}}setSchemaVersion(e,t){return this.withEngine(n=>n.set_schema_version(V(e),V(t))),Promise.resolve()}async exportSnapshot(e={}){let t=z(this.loadCommittedIndexSchema());return await Wt(or(q(this.withEngine(e=>e.export_snapshot())),t),e.compression??!1)}async importSnapshot(e){this.ensureNotInMaintenance();let t=sr(await Gt(e));await this.runGenerationOperation(`import`,t)}async reset(){let e=this.dbName;if(!e)throw X(`InternalError`,`engine is not open`);let t=z(this.loadCommittedIndexSchema());this.rollbackAllTransactions();let n=this.currentStoreNames().map(e=>({store:e,changes:[{key:/* @__PURE__ */ new Uint8Array,kind:`clear`}]})),r=H(this.withEngine(e=>e.reset()));if(this.committedIndexes=[],await this.applyCommittedIndexSchema(t),this.events){let t={type:`commit_applied`,dbName:e,txid:r,stores:n};this.events.postMessage(t)}}async compact(){return this.runGenerationOperation(`compact`)}async rebuild(){return this.runGenerationOperation(`rebuild`)}stats(){let e=this.withEngine(e=>e.stats());return Promise.resolve({...e,db_id:typeof e.db_id==`bigint`?Number(e.db_id):e.db_id,catalog_root_page_id:H(e.catalog_root_page_id),next_page_id:H(e.next_page_id),last_committed_txid:H(e.last_committed_txid),last_replayed_wal_offset:H(e.last_replayed_wal_offset),manifest_len:H(e.manifest_len),main_len:H(e.main_len),wal_len:H(e.wal_len),health:hr(e.health),store_count:this.currentStoreNames().length})}async storageInfo(){let[e,t,n]=await Promise.all([this.dbDirectorySize(),Yn(),this.persistenceBridge.persisted()]);return{dbSize:e,originUsage:t.usage,originQuota:t.quota,persisted:n}}async requestPersistence(){return this.persistenceBridge.persist()}setFailpoint(e){return this.withEngine(t=>t.set_failpoint(e)),Promise.resolve()}requireDbName(){if(!this.dbName)throw X(`InternalError`,`engine is not open`);return this.dbName}ensureNotInMaintenance(){if(this.maintenanceOperation)throw X(`DatabaseBusyError`,`database ${this.dbName??`database`} is busy: ${this.maintenanceOperation} in progress`)}currentCachePages(){return this.openOptions?.cachePages??256}async dbDirectorySize(){return(await this.loadWasm()).dbDirectorySize(this.requireDbName())}async applyCommittedIndexSchema(e){let t=z(e);if(t.length===0){this.committedIndexes=[];return}let n=H(this.withEngine(e=>e.begin_tx(`readwrite`),{allowDuringMaintenance:!0}));this.txChanges.set(n,/* @__PURE__ */ new Map),this.txModes.set(n,`readwrite`),this.txStoreCompression.set(n,{owned:!1,values:this.loadCommittedStoreCompression()});try{await this.reconcileIndexes(n,vn(t)),H(this.withEngine(e=>e.commit_tx(V(n)),{allowDuringMaintenance:!0})),this.committedIndexes=z(t)}catch(e){try{this.withEngine(e=>e.rollback_tx(V(n)),{allowDuringMaintenance:!0})}catch{}throw e}finally{this.cleanupTxState(n)}}async runGenerationOperation(e,t){let n=this.requireDbName();if(this.maintenanceOperation)throw X(`DatabaseBusyError`,`database ${n} is busy: ${this.maintenanceOperation} in progress`);this.maintenanceOperation=e;let r=performance.now(),i=null,a=null,o=null,s=!1;try{i=await this.loadWasm();let c=await i.dbDirectorySize(n),l=z(t?.indexes??this.loadCommittedIndexSchema());this.rollbackAllTransactions({allowDuringMaintenance:!0});let u=await i.readActiveGeneration(n);o=(await i.prepareRebuildTarget(n)).generationName,a=new i.WasmEngine,await a.openGeneration(n,o,{create_if_missing:!0,cache_pages:this.currentCachePages()});let d=a;if(this.withEngine(n=>t?H(n.import_snapshot_into(d,t.snapshot)):e===`rebuild`?n.compact_into_skipping_stores(d,[...l.map(e=>e.internalStore),L]):n.compact_into(d),{allowDuringMaintenance:!0}),(e===`rebuild`||t)&&l.length>0){let e=this.engine,t=this.maintenanceOperation;this.engine=d,this.maintenanceOperation=null;try{this.committedIndexes=[],this.committedStoreCompression=null,await this.applyCommittedIndexSchema(l)}finally{this.engine=e,this.maintenanceOperation=t,this.committedStoreCompression=null}}try{await i.swapActiveGeneration(n,o,u),s=!0}catch(e){if(s=await mr(i,n)===o,!s)throw e}let f=this.engine;this.engine=a,a=null,this.committedIndexes=l,this.committedStoreCompression=null;try{f?.abandon()}catch{}try{await i.cleanupInactiveEntries(n)}catch{}let p=t?c:await i.dbDirectorySize(n);return{sizeBefore:c,sizeAfter:p,reclaimedBytes:Math.max(0,c-p),durationMs:performance.now()-r}}catch(e){if(!s){this.committedIndexes=null,this.committedStoreCompression=null;try{a?.abandon()}catch{}if(o!==null&&i!==null){let e=await mr(i,n);if(e!==void 0&&e!==o)try{await i.cleanupInactiveEntries(n)}catch{}}}throw $(e)}finally{this.maintenanceOperation=null}}recoverEngineIfNeeded(){let e=this.engine;if(!e||!e.needs_recovery())return null;let t;try{t=e.recover()}catch(e){throw X(`RecoveryRequiredError`,`database ${this.dbName??``} needs recovery and recovery failed: ${$(e).message}`)}finally{this.clearRuntimeCaches()}return{pendingTxid:In(t.pendingTxid),pendingCommitted:t.pendingCommitted===!0}}cleanupTxState(e){for(let[t,n]of this.primaryCursors)if(n.txId===e){this.primaryCursors.delete(t);try{this.engine?.close_scan_cursor(n.engineId)}catch{}}this.txChanges.delete(e),this.txModes.delete(e),this.txIndexSchemas.delete(e),this.readonlyIndexCache.delete(e),this.txEnsuredRawStores.delete(e),this.txIndexSchemaChanged.delete(e),this.txStoreCompression.delete(e),this.indexBoundCache?.txId===e&&(this.indexBoundCache=null)}getOrCreateTrackedTxn(e){return W(this.txChanges,e,()=>/* @__PURE__ */ new Map)}getOrCreateTrackedStore(e,t){return W(this.getOrCreateTrackedTxn(e),t,()=>({touched:!1,storeLevel:null,keys:/* @__PURE__ */ new Map}))}recordStoreLevelChange(e,t,n){if(R(t))return;let r=this.getOrCreateTrackedStore(e,t);r.touched=!0,r.storeLevel=n,r.keys.clear()}recordPutChange(e,t,n,r){this.recordKeyChange(e,t,n,r,`put`)}recordPutChanges(e,t,n,r){if(R(t))return;let i=this.getOrCreateTrackedStore(e,t);i.touched=!0;let a=Math.min(n.length,r.length);for(let e=0;e<a;e+=1)this.setTrackedKeyChange(i,n[e][0],r[e],`put`)}recordPutKeyChanges(e,t,n,r){if(R(t))return;let i=this.getOrCreateTrackedStore(e,t);i.touched=!0;let a=Math.min(n.length,r.length);for(let e=0;e<a;e+=1)this.setTrackedKeyChange(i,n[e],r[e]===!0||r[e]===1,`put`)}recordDeleteChange(e,t,n,r){r&&this.recordKeyChange(e,t,n,!0,`delete`)}recordKeyChange(e,t,n,r,i){if(R(t))return;let a=this.getOrCreateTrackedStore(e,t);a.touched=!0,this.setTrackedKeyChange(a,n,r,i)}setTrackedKeyChange(e,t,n,r){let i=G(t),a=e.keys.get(i);e.keys.set(i,{key:a?.key??t.slice(),baselineExists:a?.baselineExists??n,finalKind:r})}markStoreTouched(e,t){R(t)||(this.getOrCreateTrackedStore(e,t).touched=!0)}recordBatchOutcomes(e,t,n,r){for(let i=0;i<r.length&&i<n.length;i+=1){let a=n[i],o=r[i];a.kind===`put`&&o.kind===`put`?this.recordPutChange(e,t,a.key,o.baselineExists):a.kind===`delete`&&o.kind===`delete`&&this.recordDeleteChange(e,t,a.key,o.deleted)}}finalizeTrackedChanges(e){let t=[];for(let[n,r]of e){if(!r.touched||R(n))continue;let e=[];r.storeLevel!==null&&e.push({key:/* @__PURE__ */ new Uint8Array,kind:r.storeLevel});for(let t of r.keys.values())(t.finalKind!==`delete`||t.baselineExists)&&e.push({key:t.key,kind:t.finalKind});t.push({store:n,changes:e})}return t}rollbackAllTransactions(e={}){if(!this.engine||this.txChanges.size===0){this.clearTxCaches();return}let t=Array.from(this.txChanges.keys());for(let n of t)try{this.withEngine(e=>e.rollback_tx(V(n)),e)}finally{this.cleanupTxState(n)}}currentStoreNames(){return this.allRawStoreNames().filter(e=>!R(e))}allRawStoreNames(){return this.withEngine(e=>e.list_stores())}loadCommittedStoreCompression(){if(this.committedStoreCompression)return this.committedStoreCompression;let e=this.withEngine(e=>e.list_store_configs()),t=/* @__PURE__ */ new Map;for(let n of e){if(typeof n.name!=`string`)throw X(`CorruptionError`,`invalid store config row: missing name`);let e=typeof n.flags==`bigint`?Number(n.flags):n.flags;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw X(`CorruptionError`,`invalid store flags for ${n.name}`);t.set(n.name,Ht(e))}return this.committedStoreCompression=t,t}ensureTxStoreCompression(e){let t=this.txStoreCompression.get(e);if(t?.owned)return t.values;let n=new Map(t?.values);return this.txStoreCompression.set(e,{owned:!0,values:n}),n}recordStoreCompressionCreate(e,t,n){R(t)||this.ensureTxStoreCompression(e).set(t,n)}recordStoreCompressionDrop(e,t){R(t)||this.ensureTxStoreCompression(e).delete(t)}storeCompressionForTx(e,t){if(R(t))return!1;let n=this.txStoreCompression.get(e);return n?n.values.get(t)??!1:this.loadCommittedStoreCompression().get(t)??!1}async encodeEntriesForWrite(e,t,n){if(R(t))return n;let r=this.storeCompressionForTx(e,t);if(r===!1)return n;let i=[];for(let[e,t]of n)i.push([e,await Ut(t,r)]);return i}async encodePackedEntriesForWrite(e,t,n,r){let i=Array(n.length/2);for(let r=0;r<i.length;r+=1){let a=this.preparePutValue(e,t,n[r*2+1]);i[r]=a instanceof Promise?await a:a}return this.packPreparedPutEntries(r,i)}preparePutValue(e,t,n){let r=this.storeCompressionForTx(e,t);return r===`snappy`||r===!1?Pt(n,r):Ut(n,r)}packPreparedPutEntries(e,t){let n=4+e.length*8;for(let r=0;r<e.length;r+=1)if(n+=e[r].byteLength+t[r].byteLength,n>U)throw X(`WorkerProtocolError`,`compressed packed putMany exceeds the u32 byte limit`);let r=new Uint8Array(n),i=new DataView(r.buffer);i.setUint32(0,e.length*2,!0);let a=4+e.length*8;for(let n=0;n<t.length;n+=1){let o=e[n],s=t[n];i.setUint32(4+n*8,o.byteLength,!0),i.setUint32(8+n*8,s.byteLength,!0),r.set(o,a),a+=o.byteLength,s instanceof Uint8Array?(r.set(s,a),a+=s.byteLength):a=Ft(s,r,a)}return r}async putIndexedMany(e,t,n,r,i){let a=[],o=[],s=[],c=4,l=/* @__PURE__ */ new Set,u=/* @__PURE__ */ new Set,d=()=>{if(a.length===0)return;let n=a,r=o,d=s;a=[],o=[],s=[],c=4,l.clear(),u.clear();let f=this.packPreparedPutEntries(n,r),p;try{p=this.withEngine(n=>n.put_many_indexed_packed(V(e),t,f,d,Ln(i)))}catch(r){let i=Q(r);throw i.length>0&&this.recordPutKeyChanges(e,t,n,i),r}if(p.length!==n.length)throw X(`InternalError`,`put_many_indexed_packed outcome count mismatch: ${p.length} != ${n.length}`);this.recordPutKeyChanges(e,t,n,p)};for(let f=0;f<n.length/2;f+=1){let p=n[f*2],m=n[f*2+1],h=G(p);l.has(h)&&d();try{let n=await this.readStoreValue(e,t,p),i=n===null?null:gn(n),g=gn(m),_=r.map(e=>({def:e,oldLogicalKey:i===null?null:i(e),newLogicalKey:g(e),newPhysicalKey:null}));if(_.some(e=>e.def.unique&&e.newLogicalKey!==null&&u.has(`${e.def.internalStore}:${G(e.newLogicalKey)}`))){d(),--f;continue}this.ensureInternalStoresForDefinitions(e,r);for(let t of _)t.newLogicalKey!==null&&(t.newPhysicalKey=this.buildIndexEntryKey(t.def,t.newLogicalKey,p),(t.oldLogicalKey===null||!K(t.oldLogicalKey,t.newLogicalKey))&&await this.assertUniqueIndexAvailability(e,t.def,t.newLogicalKey,p));let v=this.preparePutValue(e,t,m),ee=v instanceof Promise?await v:v,y=[];for(let e of _)e.oldLogicalKey!==null&&(e.newLogicalKey===null||!K(e.oldLogicalKey,e.newLogicalKey))&&y.push({store:e.def.internalStore,kind:`delete`,key:un(e.oldLogicalKey,p)});for(let e of _)if(e.newPhysicalKey!==null&&y.push({store:e.def.internalStore,kind:`put`,key:e.newPhysicalKey}),e.def.unique)for(let t of[e.oldLogicalKey,e.newLogicalKey])t!==null&&u.add(`${e.def.internalStore}:${G(t)}`);a.push(p),o.push(ee),s.push(y),c+=8+p.byteLength+ee.byteLength;for(let e of y)c+=e.key.byteLength;l.add(h)}catch(e){throw d(),e}(i.ttl!==void 0||a.length>=64||c>=4194304)&&d()}d()}async encodeBatchOpsForWrite(e,t,n){if(R(t))return n;let r=this.storeCompressionForTx(e,t);if(r===!1)return n;let i=[];for(let e of n)i.push(e.kind===`put`?{kind:`put`,key:e.key,value:await Ut(e.value,r)}:e);return i}prepareStoredValue(e,t,n){return R(e)?t:n===!1?nr(t):Ut(t,n)}async decodeStoreValueForFeed(e,t){return R(e)?t:P(t,{strict:(this.loadCommittedStoreCompression().get(e)??!1)!==!1})}async readStoreValue(e,t,n,r){let i=this.readRawValue(e,t,n);return i===null||R(t)||(r??this.storeCompressionForTx(e,t))===!1?i:await P(i,{strict:!0})}async readStoreScan(e,t,n){let r=this.readRawScan(e,t,n);if(R(t)||this.storeCompressionForTx(e,t)===!1)return r;let i=r.map(e=>e.value);await this.decodeStoreValues(e,t,i);for(let e=0;e<r.length;e+=1)r[e].value=i[e];return r}async decodeStoreValues(e,t,n){let r={next:0,failed:!1,failure:void 0};if(await Promise.all(Array.from({length:Math.min(8,n.length)},async()=>{for(;!r.failed&&r.next<n.length;){let e=r.next++,t=n[e];if(t!==null)try{n[e]=await P(t,{strict:!0})}catch(e){r.failed||(r.failed=!0,r.failure=e)}}})),r.failed)throw r.failure;return n}indexesForStoreInTx(e,t){let n=this.indexSchemaForTx(e),r=this.indexesBySchema.get(n);if(!r){r=/* @__PURE__ */ new Map;for(let e of n){let t=r.get(e.store);t?t.push(e):r.set(e.store,[e])}this.indexesBySchema.set(n,r)}return r.get(t)??[]}resolveIndexDefinition(e,t,n){if(this.txModes.get(e)===`readonly`){let r=this.readonlyIndexCache.get(e)?.get(t);if(r){let i=r.get(n);if(i)return i;let a=on(this.indexesForStoreInTx(e,t),t,n);if(!a)throw X(`IndexNotFoundError`,`index not found: ${t}.${n}`);return r.set(n,a),a}}if(!this.rawStoreExistsInTx(e,t))throw X(`StoreNotFoundError`,`store not found: ${t}`);let r=on(this.indexesForStoreInTx(e,t),t,n);if(!r)throw X(`IndexNotFoundError`,`index not found: ${t}.${n}`);return this.txModes.get(e)===`readonly`&&W(W(this.readonlyIndexCache,e,()=>/* @__PURE__ */ new Map),t,()=>/* @__PURE__ */ new Map).set(n,r),r}physicalIndexRange(e,t,n){pn(n);let r=n.reverse===!0,i=this.indexBoundCache;if(i!==null&&i.txId===e&&i.def===t&&i.reverse===r&&Qn(i.gt,n.gt)&&Qn(i.gte,n.gte)&&Qn(i.lt,n.lt)&&Qn(i.lte,n.lte))return i.physical;let{limit:a,...o}=n,s=mn(o);return this.indexBoundCache={txId:e,def:t,reverse:r,gt:$n(n.gt),gte:$n(n.gte),lt:$n(n.lt),lte:$n(n.lte),physical:s},s}indexSchemaForTx(e){let t=this.txIndexSchemas.get(e);if(t)return t;if(this.committedIndexes)return this.committedIndexes;let n=this.readIndexSchemaInTx(e);return this.committedIndexes=z(n),this.committedIndexes}loadCommittedIndexSchema(){if(this.committedIndexes)return this.committedIndexes;let e=H(this.withEngine(e=>e.begin_tx(`readonly`)));try{let t=this.readIndexSchemaInTx(e);return this.committedIndexes=z(t),this.committedIndexes}finally{this.withEngine(t=>t.rollback_tx(V(e)))}}readIndexSchemaInTx(e){if(!this.rawStoreExistsInTx(e,`__browserdb:indexes`))return[];let t=this.readRawScan(e,L,zn).map(e=>ln(e.value));return t.sort(rn),t}rawStoreExistsInTx(e,t){try{return this.readRawScan(e,t,{limit:0}),!0}catch(e){if(J(e,`StoreNotFoundError`))return!1;throw e}}ensureRawStore(e,t){let n=this.txModes.get(e)===`readwrite`;n&&this.txEnsuredRawStores.get(e)?.has(t)||(this.ignoreNamedError(`StoreExistsError`,()=>{this.withEngine(n=>n.create_store(V(e),t))}),n&&W(this.txEnsuredRawStores,e,()=>/* @__PURE__ */ new Set).add(t))}clearRawStoreIfExists(e,t){try{this.withEngine(n=>n.clear_store(V(e),t))}catch(n){if(!J(n,`StoreNotFoundError`))throw n;this.txEnsuredRawStores.get(e)?.delete(t)}}dropRawStoreIfExists(e,t){this.txEnsuredRawStores.get(e)?.delete(t),this.ignoreNamedError(`StoreNotFoundError`,()=>{this.withEngine(n=>n.drop_store(V(e),t))})}ensureInternalStoresForDefinitions(e,t){for(let n of t)this.ensureRawStore(e,n.internalStore)}ensureInternalStoresForStore(e,t){this.ensureInternalStoresForDefinitions(e,this.indexesForStoreInTx(e,t))}readRawValue(e,t,n){let r=this.withEngine(r=>r.get(V(e),t,n));return r===null?null:q(r)}readRawScan(e,t,n){let r=this.withEngine(r=>r.scan(V(e),t,Rn(n)));for(let e of r)e.key=q(e.key),e.value=q(e.value);return r}readIndexKeyScan(e,t,n){if(typeof this.engine?.open_scan_cursor!=`function`||typeof this.engine?.scan_cursor_next!=`function`||typeof this.engine?.close_scan_cursor!=`function`)return this.readRawScan(e,t,n);let r=n.limit??512,i=4+r*1032,a=this.withEngine(r=>r.open_scan_cursor(V(e),t,Rn(n),!0));try{let e=this.withEngine(e=>e.scan_cursor_next(a,r,i)),t=q(e.packet),n=he(t);if(n.length!==e.rowCount||n.length>r||t.byteLength>i||n.some(e=>e.value.byteLength!==0))throw X(`CorruptionError`,`index key cursor returned an invalid page`);return n}finally{this.withEngine(e=>e.close_scan_cursor(a))}}putRawValue(e,t,n,r){this.withEngine(i=>i.put(V(e),t,n,r))}putIndexEntry(e,t,n,r){if(typeof this.engine?.put_index_entry_checked==`function`){let r=dn(n).primaryKey,i=this.readNativeValueState(e,t.store,r);if(i?.revisionKnown){this.withEngine(a=>a.put_index_entry_checked(V(e),t.store,t.internalStore,r,n,i.revisionEpoch,i.revisionOrdinal));return}}this.putRawValue(e,t.internalStore,n,r)}readNativeValueState(e,t,n){if(typeof this.engine?.get_many_value_states!=`function`)return null;try{let r=new Uint8Array(8+n.byteLength),i=new DataView(r.buffer);i.setUint32(0,1,!0),i.setUint32(4,n.byteLength,!0),r.set(n,8);let a=q(this.withEngine(n=>n.get_many_value_states(V(e),t,r)));return this.decodeNativeValueStates(a,1)?.[0]??null}catch{return null}}packNativeKeys(e){let t=4+e.length*4;for(let n of e)t+=n.byteLength;let n=new Uint8Array(t),r=new DataView(n.buffer);r.setUint32(0,e.length,!0);let i=4+e.length*4;for(let t=0;t<e.length;t+=1){let a=e[t];r.setUint32(4+t*4,a.byteLength,!0),n.set(a,i),i+=a.byteLength}return n}decodeNativeValueStates(e,t){if(e.byteLength!==4+t*32)return null;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==t)return null;let r=Array(t);for(let e=0;e<t;e+=1){let t=4+e*32,i=n.getUint32(t,!0),a=n.getBigUint64(t+12,!0),o=n.getBigUint64(t+20,!0);if(i&-8||(i&3)==3||i&4&&(!(i&3)||a===0n||o===0n))return null;r[e]={live:!!(i&1),expired:!!(i&2),revisionKnown:!!(i&4),expiresAt:n.getBigUint64(t+4,!0),revisionEpoch:a,revisionOrdinal:o,maxValueBytes:n.getUint32(t+28,!0)}}return r}inspectIndexedValue(e,t,n,r){let i=this.readNativeValueState(e,t.store,r);if(i===null)return`unknown`;if(!i.live)return i.expired&&this.txModes.get(e)===`readwrite`&&this.withEngine(n=>n.has(V(e),t.store,r))?`unknown`:`missing`;if(!i.revisionKnown)return`unknown`;let a=this.readNativeValueState(e,t.internalStore,n);return a?.live&&a.revisionKnown&&a.revisionEpoch===i.revisionEpoch&&a.revisionOrdinal===i.revisionOrdinal?`trusted`:`unknown`}deleteIndexEntryIfPresent(e,t,n,r){let i=this.buildIndexEntryKey(t,n,r);this.ignoreNamedError(`StoreNotFoundError`,()=>{this.withEngine(n=>n.delete(V(e),t.internalStore,i))})}buildIndexEntryKey(e,t,n){let r=un(t,n);if(r.byteLength>Vn)throw X(`KeyTooLargeError`,`index key too large for ${e.store}.${e.name}`);return r}assertIndexEntryKeySize(e,t,n){if(er(t,n)>Vn)throw X(`KeyTooLargeError`,`index key too large for ${e.store}.${e.name}`)}async assertUniqueIndexAvailability(e,t,n,r,i){if(!t.unique)return;let a=fn(n),o=null,s=1;for(;;){let c={...a,limit:s};o!==null&&(c.gt=o,delete c.gte);let l=this.readIndexKeyScan(e,t.internalStore,c);for(let a of l){o=a.key;let s=dn(a.key);if(K(s.primaryKey,r))continue;let c=this.inspectIndexedValue(e,t,a.key,s.primaryKey);if(c===`missing`){this.cleanupStaleIndexRow(e,t,a.key);continue}if(c===`trusted`)throw X(`UniqueIndexConstraintError`,`unique index constraint violation on ${t.store}.${t.name}`);let l=await this.readStoreValue(e,t.store,s.primaryKey,i);if(l===null){this.cleanupStaleIndexRow(e,t,a.key);continue}let u=hn(t,l);if(u===null||!K(u,n)){this.cleanupStaleIndexRow(e,t,a.key);continue}throw X(`UniqueIndexConstraintError`,`unique index constraint violation on ${t.store}.${t.name}`)}if(l.length<s)return;s=Math.min(512,s*2)}}async loadVisibleIndexPage(e,t,n,r,i,a=Un,o){let{limit:s,...c}=n,l=o??mn(c),u=l.reverse===!0,d=this.storeCompressionForTx(e,t.store),f=r,p=[],m=4,h=1;for(;;){let n=Math.min(512,Math.max(i-p.length,h)),r={...l,limit:n};f!==null&&(u?(delete r.lte,r.lt=f):(delete r.gte,r.gt=f));let o;try{o=this.readIndexKeyScan(e,t.internalStore,r)}catch(e){if(J(e,`StoreNotFoundError`))return{rows:[],cursor:null};throw e}let s=p.length,c=0,g=0,_=null;for(let n=0;n<o.length;n+=1){n===g&&(c=n,_=this.readIndexPrimaryValues(e,t,o,n,Math.min(o.length,n+i-p.length),a-m),g=n+(_?.entries.length??1),_&&d!==!1&&this.stabilizeWasmValues(_.values));let r=o[n],s=_?await this.resolveVisibleIndexedValue(e,t,r.key,_.entries[n-c],_.values[n-c],_.trusted[n-c],d,!0):await this.visibleIndexedRow(e,t,r.key,d);if(_!==null&&(_.values[n-c]=null),!s){f=r.key;continue}let l=m+8+s.key.byteLength+s.value.byteLength;if(l>a){if(p.length===0)throw X(`ValueTooLargeError`,`indexed scan row exceeds maxBytes`);if(f===null)throw X(`InternalError`,`indexed scan lost its continuation key`);return{rows:p,cursor:f.slice()}}if(p.push(s),m=l,f=r.key,p.length>=i)return{rows:p,cursor:r.key}}if(o.length<n)return{rows:p,cursor:null};h=p.length===s?Math.min(512,n*2):1}}readIndexPrimaryValues(e,t,n,r,i,a){if(this.txModes.get(e)!==`readonly`||i-r<=1||typeof this.engine?.get_many_value_sizes!=`function`&&typeof this.engine?.get_many_value_states!=`function`)return null;let o,s,c,l,u;try{o=n.slice(r,i).map(e=>dn(e.key));let d=this.packNativeKeys(o.map(e=>e.primaryKey)),f=null,p=null,m;if(typeof this.engine?.get_many_value_states==`function`){if(f=this.decodeNativeValueStates(q(this.withEngine(n=>n.get_many_value_states(V(e),t.store,d))),o.length),f===null)return null;if(m=Uint32Array.from(f,e=>e.live?e.maxValueBytes:U),f.some(e=>e.live&&e.revisionKnown)){let a=this.packNativeKeys(n.slice(r,i).map(e=>e.key));if(p=this.decodeNativeValueStates(q(this.withEngine(n=>n.get_many_value_states(V(e),t.internalStore,a))),o.length),p===null)return null}}else m=this.withEngine(n=>n.get_many_value_sizes(V(e),t.store,d));if(m.length!==o.length)return null;let h=0;for(let e of o){let t=m[h];if(!Number.isSafeInteger(t)||t<0||t>U)return null;let n=t===U?0:8+e.primaryKey.byteLength+t;if(n>a)break;a-=n,h+=1}if(h<=1)return null;o.length=h,c=Array(h).fill(!1);let g=[];u=[],s=Array(h).fill(null);for(let e=0;e<h;e+=1){let t=f?.[e];(t===void 0||t.live)&&(g.push(o[e].primaryKey),u.push(e));let n=p?.[e];c[e]=!!(t?.live&&t.revisionKnown&&n?.live&&n.revisionKnown&&t.revisionEpoch===n.revisionEpoch&&t.revisionOrdinal===n.revisionOrdinal)}l=g.length===0?[]:this.withEngine(n=>n.get_many(V(e),t.store,g))}catch{return null}if(l.length!==u.length)throw Z(`get_many`,l.length,u.length);for(let e=0;e<l.length;e+=1)s[u[e]]=l[e],l[e]=null;return{entries:o,values:s,trusted:c}}stabilizeWasmValues(e){for(let t=0;t<e.length;t+=1){let n=e[t];n!==null&&(e[t]=q(n))}}visibleIndexedRow(e,t,n,r){let i=dn(n),a=this.inspectIndexedValue(e,t,n,i.primaryKey);if(a===`missing`)return this.cleanupStaleIndexRow(e,t,n),null;let o=this.readRawValue(e,t.store,i.primaryKey);return this.resolveVisibleIndexedValue(e,t,n,i,o,a===`trusted`,r,!0)}resolveVisibleIndexedValue(e,t,n,r,i,a=!1,o,s){if(i===null)return this.cleanupStaleIndexRow(e,t,n),null;let c=s?i:q(i);return o===!1?this.finishVisibleIndexedValue(e,t,n,r,c,a):P(c,{strict:!0}).then(i=>this.finishVisibleIndexedValue(e,t,n,r,i,a))}finishVisibleIndexedValue(e,t,n,r,i,a){if(!a){let a=hn(t,i);if(a===null||!K(a,r.logicalKey))return this.cleanupStaleIndexRow(e,t,n),null}return{key:r.primaryKey,value:i}}cleanupStaleIndexRow(e,t,n){if(this.txModes.get(e)===`readwrite`)try{this.withEngine(r=>r.delete(V(e),t.internalStore,n))}catch{}}async loadWasm(){return this.wasmReady||=this.options.loadWasm?this.options.loadWasm():(async()=>{let e=new URL(`../engine/moyodb_engine.js`,``+import.meta.url).href,t=new URL(`../engine/moyodb_engine_bg.wasm`,``+import.meta.url).href,n=await import(
|
|
2
|
+
/* @vite-ignore */
|
|
3
|
+
e);return await n.default({module_or_path:t}),n})(),this.wasmReady}withEngine(e,t={}){if(this.maintenanceOperation&&!t.allowDuringMaintenance&&this.ensureNotInMaintenance(),!this.engine)throw X(`InternalError`,`engine is not open`);try{return e(this.engine)}catch(e){throw $(e)}}ignoreNamedError(e,t){try{t()}catch(t){if(J(t,e))return;throw t}}clearTxCaches(){this.primaryCursors.clear(),this.txChanges.clear(),this.txModes.clear(),this.txIndexSchemas.clear(),this.readonlyIndexCache.clear(),this.indexBoundCache=null,this.txEnsuredRawStores.clear(),this.txIndexSchemaChanged.clear(),this.txStoreCompression.clear()}clearRuntimeCaches(){this.clearTxCaches(),this.committedIndexes=null,this.committedStoreCompression=null}async cleanupAfterFailedOpen(e){try{e?.abandon()}catch{}if(this.engine=null,this.clearRuntimeCaches(),this.events?.close(),this.events=null,this.lease)try{await this.lease.release()}catch{}this.lease=null,this.disposePersistenceBridge(),this.dbName=null,this.openOptions=null,this.maintenanceOperation=null}disposePersistenceBridge(){this.persistenceBridge.close()}};function dr(){if(typeof navigator.storage.getDirectory!=`function`)throw X(`UnsupportedPlatformError`,`navigator.storage.getDirectory is unavailable`);if(typeof BroadcastChannel>`u`)throw X(`UnsupportedPlatformError`,`BroadcastChannel is unavailable`);if(typeof FileSystemFileHandle>`u`||typeof FileSystemFileHandle.prototype.createSyncAccessHandle!=`function`)throw X(`UnsupportedPlatformError`,`createSyncAccessHandle is unavailable`)}function fr(){if(!self.isSecureContext)throw X(`UnsupportedPlatformError`,`moyodb requires a secure context (HTTPS)`)}function X(e,t){let n=Error(t);return n.name=e,Object.defineProperty(n,"code",{value:e,enumerable:!0,configurable:!0}),n}function pr(e,t){let n=e.change_feed_policy(),r=In(n.retainTxids);if(n.enabled===t.enabled&&(!t.enabled||r===t.retainTxids))return;let i=e.begin_tx(`readwrite`);try{e.set_change_feed_policy(i,{enabled:t.enabled,retainTxids:t.retainTxids}),e.commit_tx(i)}catch(t){try{e.rollback_tx(i)}catch{}throw $(t)}}async function mr(e,t){try{return await e.readActiveGeneration(t)}catch{return}}function hr(e){return e.state===`recoveryRequired`?{state:`recoveryRequired`,reason:e.reason,pendingTxid:In(e.pendingTxid)}:{state:e.state}}function Z(e,t,n){return X(`InternalError`,`${e} outcome count mismatch: ${t} != ${n}`)}function Q(t){return!e(t)||!Array.isArray(t.partial)?[]:t.partial.filter(e=>typeof e==`boolean`)}function gr(t){return!e(t)||!Array.isArray(t.partial)?[]:t.partial.filter(t=>!e(t)||typeof t.kind!=`string`?!1:t.kind===`put`&&typeof t.baselineExists==`boolean`||t.kind===`delete`&&typeof t.deleted==`boolean`)}function $(t){if(t instanceof Error)return t;if(e(t)){let e=X(typeof t.code==`string`?t.code:typeof t.name==`string`?t.name:`Error`,typeof t.message==`string`?t.message:`Unknown error`);return`partial`in t&&Object.defineProperty(e,"partial",{value:t.partial,enumerable:!0,configurable:!0}),e}return X(`Error`,String(t))}const _r=new ur;let vr=Ne(_r),yr=!1;self.addEventListener(`message`,t=>{if(t.origin!==``&&t.origin!==self.location.origin||!e(t.data)||t.data.type!==`moyodb:worker-port:init`||!t.ports[0])return;let n=t.ports[0];if(yr){n.close();return}yr=!0,vr.close();let r={location:{origin:self.location.origin},postMessage:(e,t)=>n.postMessage(e,t??[]),addEventListener:(e,t)=>n.addEventListener(e,t),removeEventListener:(e,t)=>n.removeEventListener(e,t)};vr=Ne(_r,r),n.start()});
|
|
4
|
+
//# sourceMappingURL=browser-worker-p7uX85l-.js.map
|