@moyodb/sdk 1.1.0 → 1.4.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/CONTRIBUTING.md +46 -0
- package/README.md +144 -0
- package/dist/assets/browser-worker-Bj2ErRvC.js +4 -0
- package/dist/assets/browser-worker-Bj2ErRvC.js.map +1 -0
- package/dist/assets/shared-worker-CMeTcusa.js +2 -0
- package/dist/assets/shared-worker-CMeTcusa.js.map +1 -0
- package/dist/chunks/{indexing-BzmFhWXs.js → indexing-B0duqlUs.js} +131 -124
- package/dist/chunks/indexing-B0duqlUs.js.map +1 -0
- package/dist/compression.d.ts +16 -2
- package/dist/compression.d.ts.map +1 -1
- package/dist/demo.d.ts.map +1 -1
- package/dist/engine/README.md +32 -3
- package/dist/engine/moyodb_engine.d.ts +36 -10
- package/dist/engine/moyodb_engine.js +261 -51
- package/dist/engine/moyodb_engine_bg.wasm +0 -0
- package/dist/engine/moyodb_engine_bg.wasm.d.ts +18 -10
- package/dist/engine/package.json +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/indexing.d.ts.map +1 -1
- package/dist/internal.d.ts +6 -0
- package/dist/internal.d.ts.map +1 -1
- package/dist/moyodb-sdk.js +1069 -835
- package/dist/moyodb-sdk.js.map +1 -1
- package/dist/node-engine.js +731 -111
- package/dist/node-engine.js.map +1 -1
- package/dist/node-storage.d.mts +4 -0
- package/dist/node-storage.mjs +38 -3
- package/dist/node-worker-client.d.ts +1 -0
- package/dist/node-worker-client.d.ts.map +1 -1
- package/dist/node-worker.mjs +2 -1
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +302 -67
- package/dist/node.js.map +1 -1
- package/dist/registry.d.ts.map +1 -1
- package/dist/shared-worker-client.d.ts +4 -0
- package/dist/shared-worker-client.d.ts.map +1 -1
- package/dist/shared-worker.d.ts.map +1 -1
- package/dist/snappy.d.ts +3 -0
- package/dist/snappy.d.ts.map +1 -0
- package/dist/sql-parser.d.ts.map +1 -1
- package/dist/types.d.ts +33 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/worker-api.d.ts +19 -6
- package/dist/worker-api.d.ts.map +1 -1
- package/dist/worker-client.d.ts +7 -2
- package/dist/worker-client.d.ts.map +1 -1
- package/dist/worker-protocol.d.ts +18 -3
- package/dist/worker-protocol.d.ts.map +1 -1
- package/dist/worker-server.d.ts.map +1 -1
- package/dist/worker.d.ts +33 -4
- package/dist/worker.d.ts.map +1 -1
- package/package.json +6 -5
- package/dist/assets/browser-worker-DP6Mjz7c.js +0 -4
- package/dist/assets/browser-worker-DP6Mjz7c.js.map +0 -1
- package/dist/assets/shared-worker-DKzhauVf.js +0 -2
- package/dist/assets/shared-worker-DKzhauVf.js.map +0 -1
- package/dist/chunks/indexing-BzmFhWXs.js.map +0 -1
- package/dist/engine/snippets/moyodb-engine-cff0a0e2441a7a8f/js/opfs_shim.js +0 -513
- /package/dist/engine/snippets/{moyodb-engine-8ebe6af0cc2e81b7 → moyodb-engine-1d53039816cbc2f7}/js/opfs_shim.js +0 -0
package/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Contributions for MoyoDB 1.0.0 and later are governed by the [Mother of Licenses 1.0](LICENSE), including the upstream workflow in Section 6, the contribution terms in Section 9, and the patent terms in Section 10. Read these terms before submitting work.
|
|
4
|
+
|
|
5
|
+
Submit changes to the official [eluvane/MoyoDB repository](https://github.com/eluvane/MoyoDB). Technical forks, review branches, patches, and temporary test artifacts are permitted for bona fide upstream review under Section 6. Identify their contribution-only purpose and the official upstream project; do not publish them as general-use releases or an independent product. Private modifications may continue under Section 3 after the contribution process ends.
|
|
6
|
+
|
|
7
|
+
Contributors retain ownership of their original work. Section 9 grants the licensor, Eluvane, broad, irrevocable, royalty-free copyright permissions, including commercial use, sublicensing, transfer, and relicensing. Section 10 governs patent permissions. These grants do not entitle contributors to payment or revenue sharing unless separately agreed in writing or required by applicable law.
|
|
8
|
+
|
|
9
|
+
By knowingly submitting a Contribution with notice of Section 9, you accept its contribution terms. Contribution and patent grants remain governed by Sections 9 and 10. The default workflow does not require a separate acceptance statement or checkbox in the pull request or an accompanying message.
|
|
10
|
+
|
|
11
|
+
Submit only material you own or are authorized to contribute. Identify known third-party material and its license terms in the submission. Material you cannot license under these terms requires a separate arrangement with the licensor before incorporation.
|
|
12
|
+
|
|
13
|
+
For licensing questions or a separate agreement, contact [keiko1337@proton.me](mailto:keiko1337@proton.me).
|
|
14
|
+
|
|
15
|
+
## Opening a pull request
|
|
16
|
+
|
|
17
|
+
Keep each pull request focused on one concrete change and follow the title and description rules below. Keep unrelated cleanup and local build output out of the diff. The title and description should describe the final change for a reviewer who has not seen the development conversation.
|
|
18
|
+
|
|
19
|
+
### Title
|
|
20
|
+
|
|
21
|
+
Write a short, descriptive title in English, starting with an action and naming the affected behavior. For example, `Fix OPFS recovery after an interrupted checkpoint` or `Document SDK transaction boundaries`. Describe the concrete result; avoid generic titles and broad completion claims.
|
|
22
|
+
|
|
23
|
+
### Description
|
|
24
|
+
|
|
25
|
+
Use the prose style of [ouro pull request #118](https://github.com/eluvane/ouro/pull/118): compact English paragraphs that describe the final behavior, its implementation and material limits. Start directly with the concrete change and its effect. Use one or two connected paragraphs for most changes, grouping related behavior in the same paragraph. Add another paragraph only when a distinct part of the change needs it. Include a concrete trigger or before/after example when it makes the result clearer.
|
|
26
|
+
|
|
27
|
+
Mention material compatibility, durability, security, performance, or release impact and limitations only when they apply. Breaking changes need migration guidance. Describe the final implementation and keep the title and description aligned with its scope; omit conversational history and abandoned approaches unless they explain a relevant tradeoff.
|
|
28
|
+
|
|
29
|
+
Do not add description headings such as `Summary`, `Changes`, `Testing` or `Contribution terms`, bullet inventories, technical checklists or a list of validation commands. Omit empty template scaffolding and unsupported claims such as “fully safe” or “production-ready.” Keep detailed commands and execution evidence in CI output or the accompanying task report. If a missing or failed check materially limits confidence in the change, state that limitation briefly in the prose.
|
|
30
|
+
|
|
31
|
+
Keep the pull request description as prose only, matching ouro #118. Do not append license-acceptance statements, contribution checkboxes or other boilerplate footers. Identify third-party material and its license terms in the prose when applicable; do not add a declaration when no such material is included.
|
|
32
|
+
|
|
33
|
+
### Coding agents
|
|
34
|
+
|
|
35
|
+
Follow the same title and description rules, including the ouro #118 prose format. Describe the final diff for a reviewer who has not read the conversation; do not replace the requested prose with a sectioned report. Create branches and pull requests only when requested, preserve any supplied branch, title, and base, and do not merge without an explicit maintainer instruction. Local documentation or code edits do not by themselves authorize publishing a pull request.
|
|
36
|
+
|
|
37
|
+
## Markdown style
|
|
38
|
+
|
|
39
|
+
Use visible dashes for unordered prose items in Markdown files and pull request descriptions. Escape the marker with a backslash (`\-`), and use a trailing backslash between adjacent items so GitHub keeps each item on its own line:
|
|
40
|
+
|
|
41
|
+
```markdown
|
|
42
|
+
\- First item\
|
|
43
|
+
\- Second item
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Preserve task-list checkboxes, numbered steps, tables, and code examples in their native syntax. Report generators must follow the same dash convention in their Markdown output.
|
package/README.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img
|
|
3
|
+
width="100%"
|
|
4
|
+
src="https://capsule-render.vercel.app/api?type=waving&height=220&color=0:0B1220,50:1E1B4B,100:4F46E5&text=MoyoDB&fontColor=E2E8F0&fontSize=54&fontAlignY=50"
|
|
5
|
+
alt="Header banner"
|
|
6
|
+
/>
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
<img alt="Rust" src="https://img.shields.io/badge/Rust-1E293B?style=for-the-badge" />
|
|
11
|
+
<img alt="WebAssembly" src="https://img.shields.io/badge/WebAssembly-1E293B?style=for-the-badge" />
|
|
12
|
+
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-1E293B?style=for-the-badge" />
|
|
13
|
+
<img alt="JavaScript" src="https://img.shields.io/badge/JavaScript-1E293B?style=for-the-badge" />
|
|
14
|
+
<img alt="Lean 4" src="https://img.shields.io/badge/Lean%204-1E293B?style=for-the-badge" />
|
|
15
|
+
<img alt="npm" src="https://img.shields.io/badge/npm-1E293B?style=for-the-badge" />
|
|
16
|
+
</p>
|
|
17
|
+
|
|
18
|
+
Rust/WASM transactional database for browsers, Node.js, and native Rust applications.
|
|
19
|
+
|
|
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
|
+
|
|
22
|
+
Version 1.4.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
|
+
|
|
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
|
+
|
|
26
|
+
Fresh user and index stores use a 32-byte `BDREV001` value header with expiry and a native record revision. Managed index writes retain the primary record's revision. Matching live revisions let index validation use metadata without reading the document. Raw changes, legacy values and revision mismatches retain document validation. Snapshot export omits physical revisions; import assigns new ones, and compaction preserves them.
|
|
27
|
+
|
|
28
|
+
New SDK stores use Snappy compression by default for values of at least 1,024 bytes. The compressed record is kept only when it saves at least 10% of the stored bytes. For values of at least 64 KiB, three small samples first check whether compression is likely to save space. This may leave some compressible values raw. Set `compression: false` when creating a store to retain raw values; `gzip` and `deflate` remain available. The maximum decoded value is 8 MiB.
|
|
29
|
+
|
|
30
|
+
## Quick start
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npm install @moyodb/sdk@1.4.0
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { openDB, utf8Decode, utf8Encode } from '@moyodb/sdk';
|
|
38
|
+
|
|
39
|
+
const db = await openDB('app', { requestPersistence: false });
|
|
40
|
+
await db.createStore('kv');
|
|
41
|
+
await db.put('kv', utf8Encode('hello'), utf8Encode('world'));
|
|
42
|
+
|
|
43
|
+
const value = await db.get('kv', utf8Encode('hello'));
|
|
44
|
+
console.log(value ? utf8Decode(value) : null);
|
|
45
|
+
|
|
46
|
+
await db.close();
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Node.js and native storage
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { openNodeDB, utf8Encode, utf8Decode } from '@moyodb/sdk/node';
|
|
53
|
+
|
|
54
|
+
const db = await openNodeDB('app', { directory: './data' });
|
|
55
|
+
if (!(await db.listStores()).includes('kv')) await db.createStore('kv');
|
|
56
|
+
await db.put('kv', utf8Encode('hello'), utf8Encode('world'));
|
|
57
|
+
console.log(utf8Decode((await db.get('kv', utf8Encode('hello')))!));
|
|
58
|
+
await db.close();
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Node.js and `NativeFileBackend::open_db(root, name, create_if_missing)` share `root/stackdb/hex(UTF8 name)`. Database names contain valid Unicode and at most 127 UTF-8 bytes. File flushes use `fsync`; the directory lease excludes competing Node and native owners and releases an abandoned lease only after confirming that its process exited.
|
|
62
|
+
|
|
63
|
+
## Multiple clients and transactions
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
const db = await openDB('app', { workerMode: 'shared' });
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Pages from the same origin share a storage owner through SharedWorker. Each client owns its transactions. Closing one handle preserves the other clients. When the page hosting the storage worker closes, another page reopens storage; database handles remain usable and active transactions receive invalidation.
|
|
70
|
+
|
|
71
|
+
Shared mode requires trusted same-origin scripts and clients. The selected hosting page supplies the storage worker endpoint. A client that supplies a different endpoint can observe other clients' operations, including uncommitted values and imported snapshots, and forge results. Session-local transaction and cursor IDs separate handle ownership and cleanup. They do not authenticate the storage endpoint or protect clients from a malicious host. Same-origin scripts already share access to the origin's OPFS and committed database state. Use separate origins for applications that do not trust each other.
|
|
72
|
+
|
|
73
|
+
Read and write transactions can overlap. Readers retain their snapshots. Commits publish sequentially; a writer whose snapshot is stale closes with `TransactionConflictError` before writing its changes. Start a new transaction to retry. Schema upgrades have one migration owner.
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
for await (const row of db.scanIter('kv')) {
|
|
77
|
+
console.log(row);
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
let cursor: number | undefined;
|
|
82
|
+
try {
|
|
83
|
+
do {
|
|
84
|
+
const page = await db.scanPage('kv', {}, { cursor, maxRows: 256, maxBytes: 64 * 1024 });
|
|
85
|
+
cursor = page.cursor;
|
|
86
|
+
console.log(page.rows);
|
|
87
|
+
if (page.done) break;
|
|
88
|
+
} while (cursor !== undefined);
|
|
89
|
+
} finally {
|
|
90
|
+
if (cursor !== undefined) await db.closeScanCursor(cursor);
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Paged scans retain one snapshot until exhaustion or explicit cursor close. Breaking out of `scanIter` closes its cursor. Primary and index pages limit both row count and byte size, including decoded values. A first row larger than the byte budget rejects the page.
|
|
95
|
+
|
|
96
|
+
## Typed records
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { createRecordStore, jsonRecordCodec, keyCodecs } from '@moyodb/sdk';
|
|
100
|
+
|
|
101
|
+
const users = await createRecordStore(db, 'users', {
|
|
102
|
+
key: keyCodecs.string,
|
|
103
|
+
value: jsonRecordCodec<{ name: string }>()
|
|
104
|
+
});
|
|
105
|
+
await users.put('alice', { name: 'Alice' });
|
|
106
|
+
console.log(await users.get('alice'));
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Record stores support CRUD, batches, ordered ranges, managed indexes, and automatic transactions. Scalar and tuple key codecs retain the existing byte encodings. JSON codecs reject values that JSON cannot preserve; pass a type guard to validate an application schema.
|
|
110
|
+
|
|
111
|
+
## SQL
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { createSqlClient } from '@moyodb/sdk';
|
|
115
|
+
|
|
116
|
+
const sql = createSqlClient(db);
|
|
117
|
+
await sql.execute('CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, name TEXT NOT NULL)');
|
|
118
|
+
await sql.execute('INSERT INTO people VALUES (?, ?)', [1, 'Alice']);
|
|
119
|
+
console.log(await sql.query('SELECT name FROM people WHERE id = ?', [1]));
|
|
120
|
+
console.log(await sql.explain('SELECT name FROM people WHERE id = ?', [1]));
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Each statement runs in one transaction. Supported commands are `CREATE TABLE`, `DROP TABLE`, `INSERT`, `SELECT`, `UPDATE`, and `DELETE`, with positional parameters, predicates, ordering, and pagination. Columns support signed 64-bit `INTEGER`, `REAL`, `TEXT`, `BOOLEAN`, and `BLOB`; large integers use `bigint`, and blobs use `Uint8Array`. Tables have a primary key or a persistent generated row ID.
|
|
124
|
+
|
|
125
|
+
The planner reads the transaction's actual index catalog and chooses primary-key or supported scalar secondary-index access. Other predicates use a table scan; ordering sorts the result in memory. SQL schema uses `_moyodb_sql_catalog` and a reserved ownership record in each table. Access tables through SQL so schema, ownership records, row encodings, and indexes remain consistent.
|
|
126
|
+
|
|
127
|
+
## Verification
|
|
128
|
+
|
|
129
|
+
\- Lean checks run with all built-in/extra linters, Heron, JunkLinter and the full Batteries set; every finding fails CI. Run `npm run lint:lean` locally.\
|
|
130
|
+
\- `proofs/moyodb_proofs` models abstract KV/WAL/transaction semantics and independently checks real inline B-tree pages. The B-tree checker has kernel-checked certificates for structure, contents and routing for every byte-string key; CI compares real Rust mutations, lookup/scan and retained COW roots with Lean-computed states and rejects two production mutation witnesses. Format 2 external descriptors receive structural length and extent-address validation, with kernel-checked boundary examples. Their logical contents are rejected by the content checker because `PAY2` bodies are absent from its input. This proves properties of the Lean checker and checks concrete Rust executions; the Rust engine, checksums, overflow and external payload bodies, OPFS I/O, flush ordering and power loss remain outside those proofs.\
|
|
131
|
+
\- The traces exported to `proofs/artifacts` are replayed against the Rust engine by `crates/engine/tests/proof_artifacts.rs` as conformance scenarios.\
|
|
132
|
+
\- Crash behavior is covered by tests: `crates/engine/tests/crash_matrix.rs`, `crates/engine/tests/fault_injection.rs` (failed and short writes plus torn flushes at every WAL, main-file, and superblock operation during commit, checkpoint, and recovery), and `crates/engine/js/opfs_shim.test.mjs` for control-file publication.
|
|
133
|
+
|
|
134
|
+
## License
|
|
135
|
+
|
|
136
|
+
Copyright © 2026 Eluvane. The licensor is Eluvane; licensing requests go to [keiko1337@proton.me](mailto:keiko1337@proton.me). The official repository is [eluvane/MoyoDB](https://github.com/eluvane/MoyoDB).
|
|
137
|
+
|
|
138
|
+
MoyoDB **1.0.0** is the first release covered by the [Mother of Licenses 1.0](LICENSE) (`LicenseRef-MoL-1.0`). Earlier published releases retain their original licenses. Third-party dependencies and any separately licensed material retain their own licenses and notices.
|
|
139
|
+
|
|
140
|
+
MoL permits royalty-free use, including commercial use of unmodified code or Authorized Builds inside your own products. Private modifications and production patches are permitted for your own internal use, provided the modified code is not distributed, published, made available to third parties, or used to create a standalone or competing product or provide Project-as-a-Service. The upstream contribution workflow in Section 6 remains permitted. Other publication or distribution of modified versions, independent forks, resale of MoyoDB itself, and hosting MoyoDB itself as a service require written permission. MoyoDB under MoL is source-available, not OSI-approved open source.
|
|
141
|
+
|
|
142
|
+
## Contributing
|
|
143
|
+
|
|
144
|
+
Read [CONTRIBUTING.md](CONTRIBUTING.md) and Sections 9 and 10 of the license before submitting changes. The contribution and patent terms apply upon submission; no separate acceptance statement or PR checkbox is required by default.
|
|
@@ -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=we(t.code);return{name:we(t.name)??e??`Error`,code:e,message:we(t.message)??`Unknown error`,stack:we(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(!w(r,s))throw b(`WorkerProtocolError`,`invalid packed binary-list argument`);return[e,n,ye(r)]}}if(e===`putMany`){let[e,n,r,i]=t;if(!Array.isArray(r)){if(!w(r,s))throw b(`WorkerProtocolError`,`invalid packed putMany argument`);return[e,n,be(r,!1),i]}}if(e===`applyBatch`){let[e,n,r]=t;if(!Array.isArray(r)){if(!w(r,u))throw b(`WorkerProtocolError`,`invalid packed batch argument`);return[e,n,Ce(r,!1)]}}return t}function ie(e){return w(e,s)?e.bytes:null}function ae(e){return w(e,u)?e.bytes:null}function oe(e){return ye({__moyodbPacked:s,bytes:e})}function se(e){return be({__moyodbPacked:s,bytes:e},!0)}function ce(e){return Ce({__moyodbPacked:u,bytes:e},!1)}function le(e){return Ce({__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=E(4,T(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)||w(n,c)))return{result:n,transfer:S(n.bytes)};if(t===`scanPage`){let t=n;if(e(t)&&(me(t.rows)||w(t.rows,c)))return{result:t,transfer:S(t.rows.bytes)};if(e(t)&&Array.isArray(t.rows)){let e=Se(t.rows);return{result:{...t,rows:e??t.rows},transfer:e?[e.bytes.buffer]:x(t.rows)}}}if(t===`getMany`&&w(n,d))return{result:n,transfer:S(n.bytes)};if(t===`scanByIndexPage`){let t=n;if(e(t)&&w(t.rows,c))return{result:t,transfer:x(t)};if(e(t)&&Array.isArray(t.rows)){let e=t.rows.length>0?Se(t.rows):null,n={rows:e??t.rows,cursor:t.cursor},r=e?[e.bytes.buffer]:x(t.rows),i=C(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=xe(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=Se(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:S(n)}:t===`changesSince`?{result:n,transfer:_e(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=C(e);if(t!==null)return[t];if(typeof e!=`object`||!e)return m;let n=/* @__PURE__ */ new Set;return ve(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 S(e){let t=C(e);return t===null?m:[t]}function C(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 _e(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=C(r.key);t!==null&&(n??=/* @__PURE__ */ new Set,n.add(t));let i=C(r.value);i!==null&&(n??=/* @__PURE__ */ new Set,n.add(i))}return n===null||n.size===0?m:Array.from(n)}function ve(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)ve(r,t,n);return}let i=e;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&ve(i[e],t,n)}function ye(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=E(4,T(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 be(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=E(4,T(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 xe(e){let t=e.length,n=T(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=D(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=E(4,n,`packed nullable binary-list header`),a=E(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 Se(t){let n=t.length,r=T(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=D(n.key.byteLength,`scan row key length`),o=D(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=E(4,r,`packed scan row header`),o=E(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 Ce(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=E(4,T(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 w(t,n){return e(t)&&t.__moyodbPacked===n&&t.bytes instanceof Uint8Array}function T(e,t,n){if(!Number.isSafeInteger(e)||e<0)throw b(`WorkerProtocolError`,`${n} count is invalid: ${e}`);return D(e*t,n)}function E(e,t,n){return D(e+t,n)}function D(e,t){if(!Number.isSafeInteger(e)||e<0||e>f)throw b(`WorkerProtocolError`,`${t} exceeds 32-bit payload limit`);return e}function we(e){return typeof e==`string`?e:void 0}const Te=/* @__PURE__ */ new Set([`commit`,`rollback`,`createStore`,`dropStore`,`clearStore`,`get`,`getMany`,`has`,`put`,`putMany`,`delete`,`deleteMany`,`applyBatch`,`scan`,`getByIndex`,`scanByIndex`,`scanByIndexPage`,`getIndexes`,`reconcileIndexes`,`setSchemaVersion`]),Ee=/* @__PURE__ */ new Set([`open`,`close`,`destroy`,`importSnapshot`,`reset`,`compact`,`rebuild`]),De=/* @__PURE__ */ new Set([`deleteDB`,`storageInfo`,`requestPersistence`]),Oe=()=>{};var ke=class{#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Set;#n=Promise.resolve();#r=/* @__PURE__ */ new Map;schedule(t,n,r){if(De.has(t))return r();if(Ee.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(Ae(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}`:Ae(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(Oe,Oe);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(Oe,Oe),r}};function Ae(e,t){return Te.has(e)&&typeof t[0]==`number`?t[0]:e===`autocommit`&&t[0]===`readwrite`?`autocommit:readwrite`:null}var je=class{scope;queued=[];queuedBytes=0;flushScheduled=!1;flushChannel=null;closed=!1;constructor(e){this.scope=e}enqueue=(e,t=[])=>{if(this.closed)return;let n=ge(e,t);this.queued.length>0&&this.queuedBytes+n.byteLength>1048576&&this.flush(),this.queued.push({response:n.value,transfer:n.transfer}),this.queuedBytes+=n.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)})),(this.queued.length>=128||this.queuedBytes>=1048576)&&this.flush()};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);Be(this.scope,t,n)}};function Me(e,t=self){let n=new ke,r=new je(t),i=i=>{if(i.origin===``||i.origin===t.location.origin){if(v(i.data)){let a=i.data.requests.length,o=(e,t)=>{r.enqueue(e,t),--a,a===0&&r.flush()};for(let r of i.data.requests)Ne(t,e,n,r,o);return}Ne(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 Ne(e,t,n,r,i=(t,n)=>Be(e,t,n)){if(!y(r))return;let a=typeof r.id==`number`&&Number.isSafeInteger(r.id)?r.id:0;if(!_(r)){i(ze(a,b(`WorkerProtocolError`,`invalid worker protocol request`)));return}if(!g(r.command)){i(ze(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`);Pe(t,r),e=r,a=()=>Ie(t,n,r,i)}else Pe(t,s),a=()=>Fe(t,s,c);let l=await n.schedule(s,c,a),u=fe(e,l);i(Re(r.id,u.result),u.transfer)}catch(e){i(ze(r.id,e))}}function Pe(e,t){if(typeof e[t]!=`function`)throw b(`WorkerProtocolError`,`worker command is not implemented: ${t}`)}function Fe(e,t,n){let r=Le(e,t,n);return r===null?e[t].apply(e,re(t,n)):r}async function Ie(e,t,n,r){let i=await e.begin(t),a;try{a=await Fe(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 Le(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 Re(e,t){return{type:r,version:1,id:e,ok:!0,result:t}}function ze(e,t){return{type:r,version:1,id:e,ok:!1,error:te(t)}}function Be(e,t,n=[]){if(n.length>0)try{e.postMessage(t,n);return}catch{}e.postMessage(t)}const Ve=new TextEncoder;new TextDecoder,new TextDecoder(`utf-8`,{fatal:!0});const He=BigInt(`0xffffffffffffffff`);function O(e){return Ve.encode(e)}function Ue(e){return qe(e)}function k(e){return Je(e)}function We(e){let t=[],n=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==0){n.push(i);continue}let a=e[r+1];if(a===255){n.push(0),r+=1;continue}if(a===0){t.push(Uint8Array.from(n)),n.length=0,r+=1;continue}throw TypeError(`invalid compound key encoding`)}if(n.length!==0)throw TypeError(`compound key terminated unexpectedly`);return t}function Ge(e){let t=e.slice();for(let e=t.length-1;e>=0;--e)if(t[e]!==255)return t[e]+=1,t.subarray(0,e+1);return null}function Ke(e){let t=Ge(e);return t?{gte:e,lt:t}:{gte:e}}function qe(e){if(e===null)return Uint8Array.of(16);if(typeof e==`boolean`)return Uint8Array.of(e?33:32);if(typeof e==`number`)return Ye(e);if(typeof e==`string`){for(let t of e){let e=t.codePointAt(0);if(e>=55296&&e<=57343)throw TypeError(`compound key string parts must contain valid Unicode scalar values`)}let t=O(e),n=new Uint8Array(1+t.length);return n[0]=64,n.set(t,1),n}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 Je(e){let t=0;for(let n of e){for(let e of n)t+=e===0?2:1;t+=2}let n=new Uint8Array(t),r=0;for(let t of e){for(let e of t)e===0?(n[r]=0,n[r+1]=255,r+=2):(n[r]=e,r+=1);n[r]=0,n[r+1]=0,r+=2}return n}function Ye(e){if(!Number.isFinite(e))throw TypeError(`compound key number parts must be finite`);let t=Object.is(e,-0)?0:e,n=/* @__PURE__ */ new ArrayBuffer(9),r=new DataView(n);r.setUint8(0,48),r.setFloat64(1,t,!1);let i=r.getBigUint64(1,!1);return i=(i&1n<<63n)==0n?i^1n<<63n:~i&He,r.setBigUint64(1,i,!1),new Uint8Array(n)}const Xe=65536,Ze=16384,Qe=4294967295,$e=new Uint32Array(Ze);function A(e){let t=/* @__PURE__ */ Error(`invalid Snappy block: ${e}`);return t.name=`CorruptionError`,t}function et(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function tt(e,t){return Math.imul(e,2654435761)>>>32-t}function nt(e){if(e.byteLength>Qe)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,Ze);)o+=1;let s=1<<o,c=$e;for(let t=0;t<e.byteLength;t+=Xe){let n=Math.min(t+Xe,e.byteLength);c.fill(0,0,s);let r=t,l=t,u=0;for(;r+4<=n;){let s=et(e,r),d=tt(s,o),f=c[d];c[d]=r-t+1;let p=t+f-1;if(f===0||s!==et(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[tt(et(e,r-1),o)]=r-t)}i(l,n)}return t.subarray(0,n)}function rt(e,t,n){if(!Number.isSafeInteger(t)||t<0||t>Qe)throw RangeError(`invalid Snappy output limit`);let r=0,i=0;for(let t=0;;t+=1){if(r>=e.byteLength||t===5)throw A(`truncated or invalid length`);let n=e[r++];if(t===4&&n>15)throw A(`length exceeds 32 bits`);if(i+=(n&127)*2**(t*7),n<128)break}if(i>t)throw A(`output exceeds ${t} byte limit`);if(n!==void 0&&i!==n)throw A(`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 A(`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 A(`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 A(`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 A(`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 A(`length mismatch: expected ${i} bytes, got ${o}`);return a}const j=O(`BDBZVAL1`),it=O(`BDBZSNP1`),at=1024,M=8388608,ot=268435456,N=(()=>{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 P(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 P(`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 P(`CorruptionError`,`invalid compression tag: ${e}`)}}function lt(){return P(`UnsupportedPlatformError`,`CompressionStream and DecompressionStream are required for moyodb compression`)}function ut(){if(typeof CompressionStream!=`function`||typeof DecompressionStream!=`function`)throw lt()}function dt(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=N[1792+(r&255)]^N[1536+(r>>>8&255)]^N[1280+(r>>>16&255)]^N[1024+(r>>>24)]^N[768+e[n+4]]^N[512+e[n+5]]^N[256+e[n+6]]^N[e[n+7]]}for(;n<e.byteLength;n+=1)t=t>>>8^N[(t^e[n])&255];return(t^4294967295)>>>0}function F(e,t,n,r){let i=new Uint8Array(18+r.byteLength);return ft(i,0,e,t,n,r),i}function ft(e,t,n,r,i,a){let o=dt(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 pt(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-at)*n/2);t+=nt(e.subarray(r,r+at)).byteLength}return pt(at*3,t)}function ht(e,t,n){return pt(e.byteLength,t.byteLength)?F(j,st(n),e.byteLength,t):F(j,0,e.byteLength,e)}function gt(e){if(e.byteLength>M)throw P(`ValueTooLargeError`,`value has ${e.byteLength} bytes, exceeding the ${M} byte limit`)}function _t(e,t){if(t===!1)return{payload:e,rawLength:e.byteLength,byteLength:e.byteLength,kindTag:null};gt(e);let n=e,r=0;if(e.byteLength>=1024&&mt(e)){let t=nt(e);pt(e.byteLength,t.byteLength)&&(n=t,r=3)}return{payload:n,rawLength:e.byteLength,byteLength:18+n.byteLength,kindTag:r}}function vt(e,t,n){if(!Number.isSafeInteger(n)||n<0||e.byteLength>t.byteLength-n)throw P(`InternalError`,`prepared store value exceeds its destination`);return e.kindTag===null?t.set(e.payload,n):ft(t,n,j,e.kindTag,e.rawLength,e.payload),n+e.byteLength}function yt(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}function bt(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 xt(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 P(`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 St(e,t){ut();let n;try{n=bt(e).pipeThrough(new CompressionStream(t))}catch{throw lt()}try{return new Uint8Array(await new Response(n).arrayBuffer())}catch(e){throw P(`InternalError`,`failed to compress bytes with ${t}: ${String(e)}`)}}async function Ct(e,t,n,r){if(t===`snappy`)return rt(e,r??M,r);ut();let i;try{i=bt(yt(e)).pipeThrough(new DecompressionStream(t))}catch{throw lt()}try{return await wt(i,n,r)}catch(e){throw P(`CorruptionError`,`failed to decompress ${n}: ${String(e)}`)}}async function wt(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`),P(`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 Tt(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 P(`CorruptionError`,`invalid store compression flags: ${t}`)}}async function I(e,t){if(t===!1)return e;if(t===`snappy`){let n=_t(e,t),r=new Uint8Array(n.byteLength);return vt(n,r,0),r}if(gt(e),e.byteLength<1024)return F(j,0,e.byteLength,e);let n=yt(e);return ht(n,await St(n,t),t)}async function Et(e,t){let n=xt(j,e,t.strict);if(!n)return e;if(n.version!==1){if(t.strict)throw P(`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(dt(i)!==n.payloadChecksum){if(t.strict)throw P(`CorruptionError`,`value record checksum mismatch`);return e}if(r===!1){if(i.byteLength!==n.rawLength){if(t.strict)throw P(`CorruptionError`,`value record length mismatch: expected ${n.rawLength} bytes, got ${i.byteLength}`);return e}return i.slice()}if(n.rawLength>M)throw P(`CorruptionError`,`compressed value advertises ${n.rawLength} decompressed bytes, exceeding the ${M} byte limit`);let a=await Ct(i,r,`value record (${r})`,n.rawLength);if(a.byteLength!==n.rawLength)throw P(`CorruptionError`,`decompressed value length mismatch: expected ${n.rawLength} bytes, got ${a.byteLength}`);return a}async function Dt(e,t){if(t===!1)return e;if(![`gzip`,`deflate`].includes(t))throw P(`InternalError`,`unsupported snapshot compression kind: ${String(t)}`);let n=yt(e),r=await St(n,t);return F(it,st(t),n.byteLength,r)}async function Ot(e){let t=xt(it,e);if(!t)return e;if(t.version!==1)throw P(`CorruptionError`,`unsupported snapshot compression version: ${t.version}`);let n=ct(t.kindTag);if(n===!1)throw P(`CorruptionError`,`snapshot compression envelope cannot store kind "none"`);if(n===`snappy`)throw P(`CorruptionError`,`invalid snapshot compression tag: ${t.kindTag}`);let r=e.subarray(18);if(dt(r)!==t.payloadChecksum)throw P(`CorruptionError`,`snapshot compression checksum mismatch`);if(t.rawLength>ot)throw P(`CorruptionError`,`compressed snapshot advertises ${t.rawLength} decompressed bytes, exceeding the ${ot} byte limit`);let i=await Ct(r,n,`snapshot export (${n})`,t.rawLength);if(i.byteLength!==t.rawLength)throw P(`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)}},At=class extends kt{constructor(e){super(`ReservedStoreNameError`,e)}},L=class extends kt{constructor(e){super(`SerializationError`,e)}},R=class extends kt{constructor(e){super(`InvalidOpenOptionsError`,e)}};const jt=new TextDecoder(`utf-8`,{fatal:!0}),Mt=Symbol(`moyodb.indexing.missing`),Nt=BigInt(`0xcbf29ce484222325`),Pt=BigInt(`0x100000001b3`),Ft=BigInt(`0xffffffffffffffff`),It=`__browserdb:index:`,z=`__browserdb:indexes`;function B(e){return e.startsWith(`__browserdb:`)}function Lt(e){if(B(e))throw new At(`reserved store name: ${e}`)}function Rt(e){if(e===void 0)return[];if(!Array.isArray(e))throw new R(`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 R(`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 R(`index store must be a non-empty string`);if(typeof a!=`string`||a.length===0)throw new R(`index name must be a non-empty string`);Lt(e);let c=en(o);if(s!==void 0&&typeof s!=`boolean`)throw new R(`index unique must be a boolean`);let l={store:e,name:a,keyPath:c.paths,compound:c.compound,unique:s??!1,internalStore:rn(e,a)},u=Bt(l.store,l.name);if(n.has(u))throw new R(`duplicate index definition ${l.store}.${l.name}`);n.add(u);let d=r.get(l.internalStore);if(d&&d!==u)throw new R(`index definitions ${d} and ${u} map to the same internal store ${l.internalStore}`);r.set(l.internalStore,u),t.push(l)}return t.sort(zt),t}function zt(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(nn(e),nn(n)):a}function Bt(e,t){return JSON.stringify([e,t])}function Vt(e,t,n){return e.find(e=>e.store===t&&e.name===n)??null}function Ht(e,t){return k([O(e),O(t)])}function Ut(e){return O(JSON.stringify($t(e)))}function Wt(e){let t;try{t=JSON.parse(jt.decode(e));let[n]=Rt([t]);return n}catch(e){throw new L(`invalid persisted index metadata: ${String(e)}`)}}function Gt(e,t){return k([e,t])}function Kt(e){let t;try{t=We(e)}catch(e){throw new L(`invalid index entry key encoding: ${String(e)}`)}if(t.length!==2)throw new L(`invalid index entry key encoding`);return{logicalKey:t[0],primaryKey:t[1]}}function qt(e){return Ke(k([e]))}function Jt(e={}){dn(e);let t={};if(e.reverse!==void 0&&(t.reverse=e.reverse),e.limit!==void 0&&(t.limit=e.limit),e.gte&&(t.gte=k([e.gte])),e.gt){let n=Ge(k([e.gt]));n&&(t.gte=n)}if(e.lt&&(t.lt=k([e.lt])),e.lte){let n=Ge(k([e.lte]));n&&(t.lt=n)}return t}function Yt(e,t){return Zt(e,sn(t))}function Xt(e){let t=!1,n;return r=>(t||=(n=sn(e),!0),Zt(r,n))}function Zt(e,t){if(e.compound){let n=[];for(let r of e.keyPath){let e=cn(t,r);if(e===Mt)return null;n.push(ln(e))}return k(n)}let n=cn(t,e.keyPath[0]);return n===Mt?null:ln(n)}function V(e){return e.map(e=>({store:e.store,name:e.name,keyPath:[...e.keyPath],compound:e.compound,unique:e.unique,internalStore:e.internalStore}))}function Qt(e){return e.map($t)}function $t(e){return{store:e.store,name:e.name,keyPath:e.compound?[...e.keyPath]:e.keyPath[0],unique:e.unique}}function en(e){if(typeof e==`string`)return tn(e),{paths:[e],compound:!1};if(!Array.isArray(e)||e.length===0||!e.every(e=>typeof e==`string`))throw new R(`index keyPath must be a non-empty string or non-empty string[]`);for(let t of e)tn(t);return{paths:[...e],compound:!0}}function tn(e){if(e.length===0)throw new R(`index keyPath strings must be non-empty`);if(e.startsWith(`.`)||e.endsWith(`.`)||e.includes(`..`))throw new R(`invalid index keyPath: ${e}`)}function nn(e){return e.compound?`[${e.keyPath.join(`,`)}]`:e.keyPath[0]}function rn(e,t){let n=an(O(e)),r=an(O(t)),i=`${It}${n}:${r}`;if(O(i).length<=255)return i;let a=O(`${e}\u0000${t}`);return`${It}h:${on(a)}`}function an(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/u,``)}function on(e){let t=Nt;for(let n of e)t^=BigInt(n),t=t*Pt&Ft;return t.toString(16).padStart(16,`0`)}function sn(e){try{return JSON.parse(jt.decode(e))}catch(e){throw new L(`indexed values must be valid UTF-8 JSON: ${String(e)}`)}}function cn(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||!Object.hasOwn(n,e))return Mt;n=Reflect.get(n,e)}return n}function ln(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e instanceof Uint8Array)try{return Ue(e)}catch(e){throw e instanceof TypeError?new L(`invalid indexed keyPath value: ${e.message}`):e}throw new L(`indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${un(e)}`)}function un(e){return Array.isArray(e)?`array`:typeof e}function dn(e){if(e.gt!==void 0&&e.gte!==void 0)throw TypeError(`index range cannot specify both gt and gte`);if(e.lt!==void 0&&e.lte!==void 0)throw TypeError(`index range cannot specify both lt and lte`)}function H(e){return BigInt(e)}function U(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 fn(e){return e==null?null:U(e)}function pn(e){return e.ttl===void 0?e:{...e,ttl:H(e.ttl)}}function mn(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 hn={},gn=/* @__PURE__ */ new Uint8Array,W=4294967295,_n=8389662,vn=4194304,yn=4096,bn=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function xn(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=n();return e.set(t,i),i}function Sn(t){return e(t)&&t.type===`moyodb:persistence-bridge:response`&&typeof t.id==`number`&&typeof t.granted==`boolean`}var Cn=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(!Sn(t))return;let n=this.pending.get(t.id);n&&(this.pending.delete(t.id),n.resolve(!!t.granted))}};async function wn(){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+=bn[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 Tn(e){let t=mn(e);for(let e of[`gt`,`gte`,`lt`,`lte`]){let n=t[e];n!==void 0&&(t[e]=n.slice())}return t}function En(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 q(e){return e instanceof Uint8Array?e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e:e.slice():new Uint8Array(e)}function Dn(t){if(!e(t))return null;let n=t.name??t.code;return typeof n==`string`?n:null}function J(e,t){return Dn(e)===t}const On=O(`BDBIDX1`),kn=new TextDecoder(`utf-8`,{fatal:!0});function An(e,t){if(t.length===0)return e;let n=O(JSON.stringify(Qt(t))),r=/* @__PURE__ */ new ArrayBuffer(4);new DataView(r).setUint32(0,n.byteLength,!0);let i=new Uint8Array(e.byteLength+n.byteLength+4+On.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(On,a),i}function jn(e){let t=On.byteLength;if(e.byteLength<t+4)return{snapshot:e,indexes:[]};let n=e.byteLength-t;if(!K(e.subarray(n),On))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(kn.decode(e.subarray(i,r)))}catch(e){throw X(`CorruptionError`,`invalid snapshot index trailer: ${String(e)}`)}return{snapshot:e.subarray(0,i),indexes:Rt(a)}}function Mn(e){return new BroadcastChannel(`db:${e}:events`)}function Y(e,t){let n=Mn(e);try{n.postMessage({type:t,dbName:e,txid:null})}finally{n.close()}}var Nn=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}}}},Pn=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;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 Cn}async open(e){if(this.engine)return;In(),Fn(),this.dbName=e.dbName,this.events=new BroadcastChannel(`db:${e.dbName}:events`),this.lease=new Nn;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&&Ln(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){In(),Fn();let t=new Nn,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=U(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=U(this.withEngine(t=>t.commit_tx(H(e))))}catch(t){try{this.engine&&!this.engine.needs_recovery()&&this.withEngine(t=>t.rollback_tx(H(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=V(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(H(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=B(t)?!1:n.compression??`snappy`;return this.txEnsuredRawStores.get(e)?.delete(t),this.withEngine(n=>n.create_store(H(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(H(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(H(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(H(e),t,n)),i=!B(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(H(e),t,n)));return B(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(H(e),t,n)))}async put(e,t,n,r,i={}){let a=this.indexesForStoreInTx(e,t);if(a.length===0){let a=await this.encodeStoreValueForWrite(e,t,r),o=this.withEngine(r=>r.put(H(e),t,n,a,pn(i)));this.recordPutChange(e,t,n,o);return}await this.putIndexedMany(e,t,[n,r],a,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(H(e),t,i,pn(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(H(e),t,s,pn(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:Xt(i),o=a===null?[]:r.map(e=>({def:e,logicalKey:a(e)}));if(!this.withEngine(r=>r.delete(H(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(H(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(H(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(H(e),t,r))}catch(r){throw this.recordBatchOutcomes(e,t,n,Bn(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(H(e),t,n))}catch(n){throw this.recordBatchOutcomes(e,t,r,Bn(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>W||!Number.isSafeInteger(e.maxBytes)||e.maxBytes<4||e.maxBytes>W)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||!En(n.range,e.range??hn))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=Tn(e.range??hn),o;try{o=this.withEngine(t=>t.open_scan_cursor(H(i),e.store,mn(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 this.decodeStoreValue(n.txId,n.store,t.value),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={}){let i=this.resolveIndexDefinition(e,t,n),a=[],o=r.limit??1/0,s=null;for(;o>0;){let t=await this.loadVisibleIndexPage(e,i,r,s,Math.min(o,256));if(a.push(...t.rows),o-=t.rows.length,t.cursor===null)break;s=t.cursor}return a}async scanByIndexPage(e,t,n,r,i,a,o=_n){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>W)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)}getIndexes(e){return Promise.resolve(Qt(e===void 0?this.loadCommittedIndexSchema():this.indexSchemaForTx(e)))}async reconcileIndexes(e,t){let n=Rt(t);this.ensureRawStore(e,z);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,z);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(H(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,hn),c&&n.length<=yn){let e=0;for(let t of n)if(e+=t.key.byteLength+t.value.byteLength,e>vn)break;e<=vn&&(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=sn(r.value);let e=i?.inputBytes??0,t=r.key.byteLength+r.value.byteLength;(i||l.size<yn)&&o-e+t<=vn?(l.set(n,{bytes:r.value,inputBytes:t,document:a}),o+=t-e):i&&(l.delete(n),o-=e)}let s=Zt(t,a);s!==null&&(await this.assertUniqueIndexAvailability(e,t,s,r.key),this.putIndexEntry(e,t,this.buildIndexEntryKey(t,s,r.key),gn))}}this.putRawValue(e,z,Ht(t.store,t.name),Ut(t))}this.txIndexSchemas.set(e,V(n)),this.txIndexSchemaChanged.add(e)}listStores(){return Promise.resolve(this.currentStoreNames())}getVersion(){return Promise.resolve(U(this.withEngine(e=>e.get_schema_version())))}async changesSince(e,t={}){let n=t.stores?.filter(e=>!B(e)),r={...t,stores:n?[...n]:void 0,limit:n?t.limit:void 0},i=this.withEngine(t=>t.changes_since(H(e),r)),a=n?new Set(n):null,o=[];for(let e of i.changes){if(B(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:U(e.txId),store:e.store,key:n,kind:e.kind,value:r})}return{latestTxId:U(i.latestTxId),changes:o}}setSchemaVersion(e,t){return this.withEngine(n=>n.set_schema_version(H(e),H(t))),Promise.resolve()}async exportSnapshot(e={}){let t=V(this.loadCommittedIndexSchema());return await Dt(An(q(this.withEngine(e=>e.export_snapshot())),t),e.compression??!1)}async importSnapshot(e){this.ensureNotInMaintenance();let t=jn(await Ot(e));await this.runGenerationOperation(`import`,t)}async reset(){let e=this.dbName;if(!e)throw X(`InternalError`,`engine is not open`);let t=V(this.loadCommittedIndexSchema());this.rollbackAllTransactions();let n=this.currentStoreNames().map(e=>({store:e,changes:[{key:/* @__PURE__ */ new Uint8Array,kind:`clear`}]})),r=U(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:U(e.catalog_root_page_id),next_page_id:U(e.next_page_id),last_committed_txid:U(e.last_committed_txid),last_replayed_wal_offset:U(e.last_replayed_wal_offset),manifest_len:U(e.manifest_len),main_len:U(e.main_len),wal_len:U(e.wal_len),health:zn(e.health),store_count:this.currentStoreNames().length})}async storageInfo(){let[e,t,n]=await Promise.all([this.dbDirectorySize(),wn(),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=V(e);if(t.length===0){this.committedIndexes=[];return}let n=U(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,Qt(t)),U(this.withEngine(e=>e.commit_tx(H(n)),{allowDuringMaintenance:!0})),this.committedIndexes=V(t)}catch(e){try{this.withEngine(e=>e.rollback_tx(H(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=V(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?U(n.import_snapshot_into(d,t.snapshot)):e===`rebuild`?n.compact_into_skipping_stores(d,[...l.map(e=>e.internalStore),z]):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 Rn(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 Rn(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:fn(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.txEnsuredRawStores.delete(e),this.txIndexSchemaChanged.delete(e),this.txStoreCompression.delete(e)}getOrCreateTrackedTxn(e){return xn(this.txChanges,e,()=>/* @__PURE__ */ new Map)}getOrCreateTrackedStore(e,t){return xn(this.getOrCreateTrackedTxn(e),t,()=>({touched:!1,storeLevel:null,keys:/* @__PURE__ */ new Map}))}recordStoreLevelChange(e,t,n){if(B(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(B(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(B(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(B(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){B(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||B(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(H(n)),e)}finally{this.cleanupTxState(n)}}currentStoreNames(){return this.allRawStoreNames().filter(e=>!B(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,Tt(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){B(t)||this.ensureTxStoreCompression(e).set(t,n)}recordStoreCompressionDrop(e,t){B(t)||this.ensureTxStoreCompression(e).delete(t)}storeCompressionForTx(e,t){if(B(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(B(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 I(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?_t(n,r):I(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>W)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=vt(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(H(e),t,f,d,pn(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:Xt(n),g=Xt(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:Gt(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(B(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 I(e.value,r)}:e);return i}async encodeStoreValueForWrite(e,t,n){return B(t)?n:I(n,this.storeCompressionForTx(e,t))}async decodeStoreValue(e,t,n){return B(t)||this.storeCompressionForTx(e,t)===!1?n:Et(n,{strict:!0})}async decodeStoreValueForFeed(e,t){return B(e)?t:Et(t,{strict:(this.loadCommittedStoreCompression().get(e)??!1)!==!1})}async readStoreValue(e,t,n){let r=this.readRawValue(e,t,n);return r===null?null:this.decodeStoreValue(e,t,r)}async readStoreScan(e,t,n){let r=this.readRawScan(e,t,n);if(B(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 i=r.next++,a=n[i];if(a!==null)try{n[i]=await this.decodeStoreValue(e,t,a)}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.rawStoreExistsInTx(e,t))throw X(`StoreNotFoundError`,`store not found: ${t}`);let r=Vt(this.indexesForStoreInTx(e,t),t,n);if(!r)throw X(`IndexNotFoundError`,`index not found: ${t}.${n}`);return r}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=V(n),this.committedIndexes}loadCommittedIndexSchema(){if(this.committedIndexes)return this.committedIndexes;let e=U(this.withEngine(e=>e.begin_tx(`readonly`)));try{let t=this.readIndexSchemaInTx(e);return this.committedIndexes=V(t),this.committedIndexes}finally{this.withEngine(t=>t.rollback_tx(H(e)))}}readIndexSchemaInTx(e){if(!this.rawStoreExistsInTx(e,`__browserdb:indexes`))return[];let t=this.readRawScan(e,z,hn).map(e=>Wt(e.value));return t.sort(zt),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(H(e),t))}),n&&xn(this.txEnsuredRawStores,e,()=>/* @__PURE__ */ new Set).add(t))}clearRawStoreIfExists(e,t){try{this.withEngine(n=>n.clear_store(H(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(H(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(H(e),t,n));return r===null?null:q(r)}readRawScan(e,t,n){let r=this.withEngine(r=>r.scan(H(e),t,mn(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(H(e),t,mn(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(H(e),t,n,r))}putIndexEntry(e,t,n,r){if(typeof this.engine?.put_index_entry_checked==`function`){let r=Kt(n).primaryKey,i=this.readNativeValueState(e,t.store,r);if(i?.revisionKnown){this.withEngine(a=>a.put_index_entry_checked(H(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(H(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(H(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(H(e),t.internalStore,i))})}buildIndexEntryKey(e,t,n){let r=Gt(t,n);if(r.byteLength>1024)throw X(`KeyTooLargeError`,`index key too large for ${e.store}.${e.name}`);return r}async assertUniqueIndexAvailability(e,t,n,r){if(!t.unique)return;let i=qt(n),a=null,o=1;for(;;){let s={...i,limit:o};a!==null&&(s.gt=a,delete s.gte);let c=this.readIndexKeyScan(e,t.internalStore,s);for(let i of c){a=i.key;let o=Kt(i.key);if(K(o.primaryKey,r))continue;let s=this.inspectIndexedValue(e,t,i.key,o.primaryKey);if(s===`missing`){this.cleanupStaleIndexRow(e,t,i.key);continue}if(s===`trusted`)throw X(`UniqueIndexConstraintError`,`unique index constraint violation on ${t.store}.${t.name}`);let c=await this.readStoreValue(e,t.store,o.primaryKey);if(c===null){this.cleanupStaleIndexRow(e,t,i.key);continue}let l=Yt(t,c);if(l===null||!K(l,n)){this.cleanupStaleIndexRow(e,t,i.key);continue}throw X(`UniqueIndexConstraintError`,`unique index constraint violation on ${t.store}.${t.name}`)}if(c.length<o)return;o=Math.min(512,o*2)}}async loadVisibleIndexPage(e,t,n,r,i,a=_n){let{limit:o,...s}=n,c=Jt(s),l=c.reverse===!0,u=r,d=[],f=4,p=1;for(;;){let n=Math.min(512,Math.max(i-d.length,p)),r={...c,limit:n};u!==null&&(l?(delete r.lte,r.lt=u):(delete r.gte,r.gt=u));let o;try{o=this.readIndexKeyScan(e,t.internalStore,r)}catch(e){if(J(e,`StoreNotFoundError`))return{rows:[],cursor:null};throw e}let s=d.length,m=0,h=0,g=null;for(let n=0;n<o.length;n+=1){n===h&&(m=n,g=this.readIndexPrimaryValues(e,t,o,n,Math.min(o.length,n+i-d.length),a-f),h=n+(g?.entries.length??1));let r=o[n],s=g?await this.resolveVisibleIndexedValue(e,t,r.key,g.entries[n-m],g.values[n-m],g.trusted[n-m]):await this.resolveVisibleIndexedRow(e,t,r.key);if(g!==null&&(g.values[n-m]=null),!s){u=r.key;continue}let c=f+8+s.key.byteLength+s.value.byteLength;if(c>a){if(d.length===0)throw X(`ValueTooLargeError`,`indexed scan row exceeds maxBytes`);if(u===null)throw X(`InternalError`,`indexed scan lost its continuation key`);return{rows:d,cursor:u.slice()}}if(d.push(s),f=c,u=r.key,d.length>=i)return{rows:d,cursor:r.key.slice()}}if(o.length<n)return{rows:d,cursor:null};p=d.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=>Kt(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(H(e),t.store,d))),o.length),f===null)return null;if(m=Uint32Array.from(f,e=>e.live?e.maxValueBytes:W),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(H(e),t.internalStore,a))),o.length),p===null)return null}}else m=this.withEngine(n=>n.get_many_value_sizes(H(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>W)return null;let n=t===W?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(H(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}}async resolveVisibleIndexedRow(e,t,n){let r=Kt(n),i=this.inspectIndexedValue(e,t,n,r.primaryKey);if(i===`missing`)return this.cleanupStaleIndexRow(e,t,n),null;let a=this.readRawValue(e,t.store,r.primaryKey);return this.resolveVisibleIndexedValue(e,t,n,r,a,i===`trusted`)}async resolveVisibleIndexedValue(e,t,n,r,i,a=!1){if(i===null)return this.cleanupStaleIndexRow(e,t,n),null;let o=await this.decodeStoreValue(e,t.store,q(i));if(!a){let i=Yt(t,o);if(i===null||!K(i,r.logicalKey))return this.cleanupStaleIndexRow(e,t,n),null}return{key:r.primaryKey,value:o}}cleanupStaleIndexRow(e,t,n){if(this.txModes.get(e)===`readwrite`)try{this.withEngine(r=>r.delete(H(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.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 Fn(){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 In(){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 Ln(e,t){let n=e.change_feed_policy(),r=fn(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 Rn(e,t){try{return await e.readActiveGeneration(t)}catch{return}}function zn(e){return e.state===`recoveryRequired`?{state:`recoveryRequired`,reason:e.reason,pendingTxid:fn(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 Bn(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 Vn=new Pn;let Hn=Me(Vn),Un=!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(Un){n.close();return}Un=!0,Hn.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)};Hn=Me(Vn,r),n.start()});
|
|
4
|
+
//# sourceMappingURL=browser-worker-Bj2ErRvC.js.map
|