@anfenn/dync 1.0.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.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +212 -0
  3. package/dist/capacitor.cjs +228 -0
  4. package/dist/capacitor.cjs.map +1 -0
  5. package/dist/capacitor.d.cts +62 -0
  6. package/dist/capacitor.d.ts +62 -0
  7. package/dist/capacitor.js +9 -0
  8. package/dist/capacitor.js.map +1 -0
  9. package/dist/chunk-LGHOZECP.js +3884 -0
  10. package/dist/chunk-LGHOZECP.js.map +1 -0
  11. package/dist/chunk-SQB6E7V2.js +191 -0
  12. package/dist/chunk-SQB6E7V2.js.map +1 -0
  13. package/dist/dexie-Bv-fV10P.d.cts +444 -0
  14. package/dist/dexie-DJFApKsM.d.ts +444 -0
  15. package/dist/dexie.cjs +381 -0
  16. package/dist/dexie.cjs.map +1 -0
  17. package/dist/dexie.d.cts +3 -0
  18. package/dist/dexie.d.ts +3 -0
  19. package/dist/dexie.js +343 -0
  20. package/dist/dexie.js.map +1 -0
  21. package/dist/expoSqlite.cjs +98 -0
  22. package/dist/expoSqlite.cjs.map +1 -0
  23. package/dist/expoSqlite.d.cts +17 -0
  24. package/dist/expoSqlite.d.ts +17 -0
  25. package/dist/expoSqlite.js +61 -0
  26. package/dist/expoSqlite.js.map +1 -0
  27. package/dist/index.cjs +3916 -0
  28. package/dist/index.cjs.map +1 -0
  29. package/dist/index.d.cts +8 -0
  30. package/dist/index.d.ts +8 -0
  31. package/dist/index.js +20 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/index.shared-CPIge2ZM.d.ts +234 -0
  34. package/dist/index.shared-YSn6c01d.d.cts +234 -0
  35. package/dist/node.cjs +126 -0
  36. package/dist/node.cjs.map +1 -0
  37. package/dist/node.d.cts +80 -0
  38. package/dist/node.d.ts +80 -0
  39. package/dist/node.js +89 -0
  40. package/dist/node.js.map +1 -0
  41. package/dist/react/index.cjs +1754 -0
  42. package/dist/react/index.cjs.map +1 -0
  43. package/dist/react/index.d.cts +40 -0
  44. package/dist/react/index.d.ts +40 -0
  45. package/dist/react/index.js +78 -0
  46. package/dist/react/index.js.map +1 -0
  47. package/dist/types-CSbIAfu2.d.cts +46 -0
  48. package/dist/types-CSbIAfu2.d.ts +46 -0
  49. package/dist/wa-sqlite.cjs +318 -0
  50. package/dist/wa-sqlite.cjs.map +1 -0
  51. package/dist/wa-sqlite.d.cts +175 -0
  52. package/dist/wa-sqlite.d.ts +175 -0
  53. package/dist/wa-sqlite.js +281 -0
  54. package/dist/wa-sqlite.js.map +1 -0
  55. package/package.json +171 -0
  56. package/src/addVisibilityChangeListener.native.ts +33 -0
  57. package/src/addVisibilityChangeListener.ts +24 -0
  58. package/src/capacitor.ts +4 -0
  59. package/src/core/StateManager.ts +272 -0
  60. package/src/core/firstLoad.ts +332 -0
  61. package/src/core/pullOperations.ts +212 -0
  62. package/src/core/pushOperations.ts +290 -0
  63. package/src/core/tableEnhancers.ts +457 -0
  64. package/src/core/types.ts +3 -0
  65. package/src/createLocalId.native.ts +8 -0
  66. package/src/createLocalId.ts +6 -0
  67. package/src/dexie.ts +2 -0
  68. package/src/expoSqlite.ts +2 -0
  69. package/src/helpers.ts +87 -0
  70. package/src/index.native.ts +28 -0
  71. package/src/index.shared.ts +613 -0
  72. package/src/index.ts +28 -0
  73. package/src/logger.ts +26 -0
  74. package/src/node.ts +4 -0
  75. package/src/react/index.ts +2 -0
  76. package/src/react/useDync.ts +156 -0
  77. package/src/storage/dexie/DexieAdapter.ts +72 -0
  78. package/src/storage/dexie/DexieQueryContext.ts +14 -0
  79. package/src/storage/dexie/DexieStorageCollection.ts +124 -0
  80. package/src/storage/dexie/DexieStorageTable.ts +123 -0
  81. package/src/storage/dexie/DexieStorageWhereClause.ts +103 -0
  82. package/src/storage/dexie/helpers.ts +1 -0
  83. package/src/storage/dexie/index.ts +7 -0
  84. package/src/storage/memory/MemoryAdapter.ts +55 -0
  85. package/src/storage/memory/MemoryCollection.ts +215 -0
  86. package/src/storage/memory/MemoryQueryContext.ts +14 -0
  87. package/src/storage/memory/MemoryTable.ts +336 -0
  88. package/src/storage/memory/MemoryWhereClause.ts +134 -0
  89. package/src/storage/memory/index.ts +7 -0
  90. package/src/storage/memory/types.ts +24 -0
  91. package/src/storage/sqlite/SQLiteAdapter.ts +564 -0
  92. package/src/storage/sqlite/SQLiteCollection.ts +294 -0
  93. package/src/storage/sqlite/SQLiteTable.ts +604 -0
  94. package/src/storage/sqlite/SQLiteWhereClause.ts +341 -0
  95. package/src/storage/sqlite/SqliteQueryContext.ts +30 -0
  96. package/src/storage/sqlite/drivers/BetterSqlite3Driver.ts +156 -0
  97. package/src/storage/sqlite/drivers/CapacitorFastSqlDriver.ts +114 -0
  98. package/src/storage/sqlite/drivers/CapacitorSQLiteDriver.ts +137 -0
  99. package/src/storage/sqlite/drivers/ExpoSQLiteDriver.native.ts +67 -0
  100. package/src/storage/sqlite/drivers/WaSqliteDriver.ts +537 -0
  101. package/src/storage/sqlite/drivers/wa-sqlite-vfs.d.ts +46 -0
  102. package/src/storage/sqlite/helpers.ts +144 -0
  103. package/src/storage/sqlite/index.ts +11 -0
  104. package/src/storage/sqlite/schema.ts +44 -0
  105. package/src/storage/sqlite/types.ts +164 -0
  106. package/src/storage/types.ts +112 -0
  107. package/src/types.ts +186 -0
  108. package/src/wa-sqlite.ts +4 -0
@@ -0,0 +1,175 @@
1
+ import { S as SQLiteDatabaseDriver, a as SQLiteRunResult, b as SQLiteQueryResult } from './types-CSbIAfu2.js';
2
+
3
+ /**
4
+ * Virtual File System (VFS) options for wa-sqlite.
5
+ * Each VFS has different trade-offs for performance, durability, and compatibility.
6
+ *
7
+ * @see https://github.com/rhashimoto/wa-sqlite/tree/master/src/examples#vfs-comparison
8
+ */
9
+ type WaSqliteVfsType =
10
+ /**
11
+ * IDBBatchAtomicVFS - IndexedDB-backed storage
12
+ * - Works on ALL contexts (Window, Worker, SharedWorker, service worker)
13
+ * - Supports multiple connections
14
+ * - Full durability with batch atomic writes
15
+ * - Good general-purpose choice for maximum compatibility
16
+ * @recommended For apps that need to work in main thread and don't need OPFS
17
+ */
18
+ 'IDBBatchAtomicVFS'
19
+ /**
20
+ * IDBMirrorVFS - IndexedDB with in-memory mirror
21
+ * - Works on ALL contexts
22
+ * - Supports multiple connections
23
+ * - Much faster than IDBBatchAtomicVFS
24
+ * - Database must fit in available memory
25
+ * @recommended For small databases where performance is critical
26
+ */
27
+ | 'IDBMirrorVFS'
28
+ /**
29
+ * OPFSCoopSyncVFS - OPFS with cooperative synchronous access
30
+ * - Requires Worker context
31
+ * - Supports multiple connections
32
+ * - Filesystem transparent (can import/export files)
33
+ * - Good balance of performance and compatibility
34
+ * @recommended For apps needing OPFS with multi-connection support
35
+ */
36
+ | 'OPFSCoopSyncVFS'
37
+ /**
38
+ * AccessHandlePoolVFS - OPFS-backed storage (fastest single connection)
39
+ * - Requires Worker context
40
+ * - Single connection only (no multi-tab support)
41
+ * - Best performance, supports WAL mode
42
+ * - NOT filesystem transparent
43
+ * @recommended For single-tab apps where performance is critical
44
+ */
45
+ | 'AccessHandlePoolVFS';
46
+ /**
47
+ * Options for configuring the WaSqliteDriver.
48
+ */
49
+ interface WaSqliteDriverOptions {
50
+ /**
51
+ * Virtual File System to use for storage.
52
+ * @default 'IDBBatchAtomicVFS'
53
+ */
54
+ vfs?: WaSqliteVfsType;
55
+ /**
56
+ * Directory path for the database in OPFS VFS modes.
57
+ * Only used with OPFS-based VFS types.
58
+ * @default '/'
59
+ */
60
+ directory?: string;
61
+ /**
62
+ * SQLite page size in bytes.
63
+ * Larger pages can improve read performance for large BLOBs.
64
+ * Cannot be changed after database creation for IDBBatchAtomicVFS/IDBMirrorVFS.
65
+ * @default 4096
66
+ */
67
+ pageSize?: number;
68
+ /**
69
+ * SQLite cache size in pages (negative = KB, positive = pages).
70
+ * Larger cache improves performance but uses more memory.
71
+ * For IDBBatchAtomicVFS, must be large enough to hold journal for batch atomic mode.
72
+ * @default -2000 (2MB)
73
+ */
74
+ cacheSize?: number;
75
+ /**
76
+ * Enable WAL (Write-Ahead Logging) mode.
77
+ * Only supported with AccessHandlePoolVFS (with locking_mode=exclusive).
78
+ * For other VFS types, this is ignored.
79
+ * @default false
80
+ */
81
+ wal?: boolean;
82
+ /**
83
+ * Set synchronous pragma for durability vs performance trade-off.
84
+ * - 'full': Maximum durability (default)
85
+ * - 'normal': Relaxed durability, better performance (supported by IDBBatchAtomicVFS, IDBMirrorVFS, OPFSPermutedVFS)
86
+ * - 'off': No sync, fastest but risks data loss on crash
87
+ * @default 'full'
88
+ */
89
+ synchronous?: 'full' | 'normal' | 'off';
90
+ }
91
+ /**
92
+ * SQLite driver for web browsers using wa-sqlite with IndexedDB or OPFS persistence.
93
+ * Provides robust, persistent SQLite storage in the browser that prevents data loss.
94
+ *
95
+ * ## Data Safety Features
96
+ *
97
+ * - **IDBBatchAtomicVFS** (default): Uses IndexedDB batch atomic writes to ensure transactions
98
+ * are either fully committed or not at all. Multi-tab safe.
99
+ * - **IDBMirrorVFS**: IndexedDB with in-memory mirror. Much faster, database must fit in RAM.
100
+ * - **OPFSCoopSyncVFS**: OPFS with cooperative sync. Multi-connection, filesystem transparent.
101
+ * - **AccessHandlePoolVFS**: Uses OPFS Access Handles for high performance. Single-tab only.
102
+ * - Full durability by default (`PRAGMA synchronous=full`)
103
+ * - Automatic journal mode configuration for each VFS type
104
+ *
105
+ * ## VFS Selection Guide
106
+ *
107
+ * | VFS | Best For | Multi-Tab | Speed |
108
+ * |-----|----------|-----------|-------|
109
+ * | IDBBatchAtomicVFS | General use, main thread | ✅ | Good |
110
+ * | IDBMirrorVFS | Small DBs, main thread | ✅ | Fast |
111
+ * | OPFSCoopSyncVFS | Web Workers, file export | ✅ | Good |
112
+ * | AccessHandlePoolVFS | Single-tab performance | ❌ | Fastest |
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * import { WaSqliteDriver } from '@anfenn/dync/wa-sqlite';
117
+ * import { SQLiteAdapter } from '@anfenn/dync';
118
+ *
119
+ * // Default: IDBBatchAtomicVFS (works in main thread, multi-tab safe)
120
+ * const driver = new WaSqliteDriver('myapp.db');
121
+ *
122
+ * // For OPFS (faster, requires Worker, filesystem transparent)
123
+ * const opfsDriver = new WaSqliteDriver('myapp.db', { vfs: 'OPFSCoopSyncVFS' });
124
+ *
125
+ * const adapter = new SQLiteAdapter('myapp', driver);
126
+ * ```
127
+ */
128
+ declare class WaSqliteDriver implements SQLiteDatabaseDriver {
129
+ readonly type = "WaSqliteDriver";
130
+ private db;
131
+ private sqlite3;
132
+ private readonly options;
133
+ private opened;
134
+ private openPromise;
135
+ private executionLock;
136
+ readonly name: string;
137
+ constructor(databaseName: string, options?: WaSqliteDriverOptions);
138
+ /**
139
+ * Execute a callback with exclusive database access.
140
+ * This prevents concurrent operations which can corrupt the database.
141
+ */
142
+ private withLock;
143
+ open(): Promise<void>;
144
+ private _open;
145
+ private loadWasmModule;
146
+ private createVFS;
147
+ private buildDatabasePath;
148
+ private configurePragmas;
149
+ close(): Promise<void>;
150
+ execute(statement: string): Promise<void>;
151
+ run(statement: string, values?: unknown[]): Promise<SQLiteRunResult>;
152
+ /**
153
+ * Convert values for SQLite compatibility.
154
+ * - Booleans must be converted to integers (SQLite has no boolean type)
155
+ */
156
+ private convertValues;
157
+ query(statement: string, values?: unknown[]): Promise<SQLiteQueryResult>;
158
+ /**
159
+ * Check if the database is currently open.
160
+ */
161
+ isOpen(): boolean;
162
+ /**
163
+ * Get the VFS type being used by this driver.
164
+ */
165
+ getVfsType(): WaSqliteVfsType;
166
+ /**
167
+ * Delete the database.
168
+ * This will close the database if open and remove all persisted data.
169
+ * For IndexedDB-based VFS, this deletes the IndexedDB database.
170
+ * For OPFS-based VFS, this removes the files from OPFS.
171
+ */
172
+ delete(): Promise<void>;
173
+ }
174
+
175
+ export { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult, WaSqliteDriver, type WaSqliteDriverOptions, type WaSqliteVfsType };
@@ -0,0 +1,281 @@
1
+ // src/storage/sqlite/drivers/WaSqliteDriver.ts
2
+ var cachedModuleFactory = null;
3
+ var cachedModule = null;
4
+ var cachedSqlite3 = null;
5
+ var registeredVFS = /* @__PURE__ */ new Map();
6
+ var WaSqliteDriver = class {
7
+ type = "WaSqliteDriver";
8
+ db = null;
9
+ sqlite3 = null;
10
+ options;
11
+ opened = false;
12
+ openPromise = null;
13
+ // Mutex to prevent concurrent database operations (critical for wa-sqlite)
14
+ executionLock = Promise.resolve();
15
+ name;
16
+ constructor(databaseName, options = {}) {
17
+ this.name = databaseName;
18
+ this.options = {
19
+ vfs: "IDBBatchAtomicVFS",
20
+ directory: "/",
21
+ pageSize: 4096,
22
+ cacheSize: -2e3,
23
+ wal: false,
24
+ synchronous: "full",
25
+ ...options
26
+ };
27
+ }
28
+ /**
29
+ * Execute a callback with exclusive database access.
30
+ * This prevents concurrent operations which can corrupt the database.
31
+ */
32
+ async withLock(fn) {
33
+ const previousLock = this.executionLock;
34
+ let releaseLock;
35
+ this.executionLock = new Promise((resolve) => {
36
+ releaseLock = resolve;
37
+ });
38
+ try {
39
+ await previousLock;
40
+ return await fn();
41
+ } finally {
42
+ releaseLock();
43
+ }
44
+ }
45
+ async open() {
46
+ if (this.opened) return;
47
+ if (this.openPromise) return this.openPromise;
48
+ this.openPromise = this._open();
49
+ try {
50
+ await this.openPromise;
51
+ } finally {
52
+ this.openPromise = null;
53
+ }
54
+ }
55
+ async _open() {
56
+ const module = await this.loadWasmModule();
57
+ if (!cachedSqlite3) {
58
+ const { Factory } = await import("@journeyapps/wa-sqlite");
59
+ cachedSqlite3 = Factory(module);
60
+ }
61
+ this.sqlite3 = cachedSqlite3;
62
+ const vfsName = `dync_${this.options.vfs}_${this.name}`.replace(/[^a-zA-Z0-9_-]/g, "_");
63
+ let existingVfs = registeredVFS.get(vfsName);
64
+ if (!existingVfs) {
65
+ existingVfs = await this.createVFS(module, vfsName);
66
+ this.sqlite3.vfs_register(existingVfs, true);
67
+ registeredVFS.set(vfsName, existingVfs);
68
+ }
69
+ const dbPath = this.buildDatabasePath();
70
+ this.db = await this.sqlite3.open_v2(dbPath);
71
+ await this.configurePragmas();
72
+ this.opened = true;
73
+ }
74
+ async loadWasmModule() {
75
+ if (!cachedModule) {
76
+ if (!cachedModuleFactory) {
77
+ const wasmModule = await import("@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs");
78
+ cachedModuleFactory = wasmModule.default;
79
+ }
80
+ cachedModule = await cachedModuleFactory();
81
+ }
82
+ return cachedModule;
83
+ }
84
+ async createVFS(module, vfsName) {
85
+ const vfsType = this.options.vfs;
86
+ let VFSClass;
87
+ let vfsOptions = void 0;
88
+ switch (vfsType) {
89
+ case "IDBBatchAtomicVFS": {
90
+ const mod = await import("@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js");
91
+ VFSClass = mod.IDBBatchAtomicVFS;
92
+ vfsOptions = { lockPolicy: "exclusive" };
93
+ break;
94
+ }
95
+ case "IDBMirrorVFS": {
96
+ const mod = await import("@journeyapps/wa-sqlite/src/examples/IDBMirrorVFS.js");
97
+ VFSClass = mod.IDBMirrorVFS;
98
+ break;
99
+ }
100
+ case "OPFSCoopSyncVFS": {
101
+ const mod = await import("@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js");
102
+ VFSClass = mod.OPFSCoopSyncVFS;
103
+ break;
104
+ }
105
+ case "AccessHandlePoolVFS": {
106
+ const mod = await import("@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js");
107
+ VFSClass = mod.AccessHandlePoolVFS;
108
+ break;
109
+ }
110
+ default:
111
+ throw new Error(`Unsupported VFS type: ${vfsType}`);
112
+ }
113
+ return VFSClass.create(vfsName, module, vfsOptions);
114
+ }
115
+ buildDatabasePath() {
116
+ const vfsType = this.options.vfs;
117
+ if (vfsType === "IDBBatchAtomicVFS" || vfsType === "IDBMirrorVFS") {
118
+ return this.name;
119
+ }
120
+ const directory = this.options.directory.replace(/\/$/, "");
121
+ return `${directory}/${this.name}`;
122
+ }
123
+ async configurePragmas() {
124
+ if (!this.db || !this.sqlite3) return;
125
+ try {
126
+ await this.sqlite3.exec(this.db, `PRAGMA page_size = ${this.options.pageSize}`);
127
+ } catch {
128
+ }
129
+ await this.sqlite3.exec(this.db, `PRAGMA cache_size = ${this.options.cacheSize}`);
130
+ if (this.options.wal && this.options.vfs === "AccessHandlePoolVFS") {
131
+ await this.sqlite3.exec(this.db, "PRAGMA locking_mode = exclusive");
132
+ await this.sqlite3.exec(this.db, "PRAGMA journal_mode = WAL");
133
+ }
134
+ }
135
+ async close() {
136
+ if (!this.opened || !this.db || !this.sqlite3) return;
137
+ await this.withLock(async () => {
138
+ try {
139
+ await this.sqlite3.exec(this.db, "PRAGMA wal_checkpoint(TRUNCATE)");
140
+ } catch {
141
+ }
142
+ await this.sqlite3.close(this.db);
143
+ this.db = null;
144
+ this.opened = false;
145
+ });
146
+ }
147
+ async execute(statement) {
148
+ await this.open();
149
+ if (!this.db || !this.sqlite3) {
150
+ throw new Error("Database not initialized");
151
+ }
152
+ await this.withLock(async () => {
153
+ await this.sqlite3.exec(this.db, statement);
154
+ });
155
+ }
156
+ async run(statement, values = []) {
157
+ await this.open();
158
+ if (!this.db || !this.sqlite3) {
159
+ throw new Error("Database not initialized");
160
+ }
161
+ return this.withLock(async () => {
162
+ const convertedValues = this.convertValues(values);
163
+ for await (const stmt of this.sqlite3.statements(this.db, statement)) {
164
+ if (stmt === null) {
165
+ break;
166
+ }
167
+ this.sqlite3.reset(stmt);
168
+ if (convertedValues.length > 0) {
169
+ this.sqlite3.bind_collection(stmt, convertedValues);
170
+ }
171
+ await this.sqlite3.step(stmt);
172
+ }
173
+ return {
174
+ changes: this.sqlite3.changes(this.db),
175
+ lastId: Number(this.sqlite3.last_insert_id(this.db))
176
+ };
177
+ });
178
+ }
179
+ /**
180
+ * Convert values for SQLite compatibility.
181
+ * - Booleans must be converted to integers (SQLite has no boolean type)
182
+ */
183
+ convertValues(values) {
184
+ return values.map((value) => {
185
+ if (typeof value === "boolean") {
186
+ return value ? 1 : 0;
187
+ }
188
+ return value;
189
+ });
190
+ }
191
+ async query(statement, values = []) {
192
+ await this.open();
193
+ if (!this.db || !this.sqlite3) {
194
+ throw new Error("Database not initialized");
195
+ }
196
+ return this.withLock(async () => {
197
+ const { SQLITE_ROW } = await import("@journeyapps/wa-sqlite");
198
+ const allRows = [];
199
+ let columns = [];
200
+ const convertedValues = this.convertValues(values);
201
+ for await (const stmt of this.sqlite3.statements(this.db, statement)) {
202
+ if (stmt === null) {
203
+ break;
204
+ }
205
+ this.sqlite3.reset(stmt);
206
+ if (convertedValues.length > 0) {
207
+ this.sqlite3.bind_collection(stmt, convertedValues);
208
+ }
209
+ if (columns.length === 0) {
210
+ columns = this.sqlite3.column_names(stmt);
211
+ }
212
+ while (await this.sqlite3.step(stmt) === SQLITE_ROW) {
213
+ const row = this.sqlite3.row(stmt);
214
+ allRows.push(row);
215
+ }
216
+ }
217
+ return { columns, values: allRows };
218
+ });
219
+ }
220
+ /**
221
+ * Check if the database is currently open.
222
+ */
223
+ isOpen() {
224
+ return this.opened;
225
+ }
226
+ /**
227
+ * Get the VFS type being used by this driver.
228
+ */
229
+ getVfsType() {
230
+ return this.options.vfs;
231
+ }
232
+ /**
233
+ * Delete the database.
234
+ * This will close the database if open and remove all persisted data.
235
+ * For IndexedDB-based VFS, this deletes the IndexedDB database.
236
+ * For OPFS-based VFS, this removes the files from OPFS.
237
+ */
238
+ async delete() {
239
+ if (this.opened) {
240
+ await this.close();
241
+ }
242
+ const vfsType = this.options.vfs;
243
+ if (vfsType === "IDBBatchAtomicVFS" || vfsType === "IDBMirrorVFS") {
244
+ await new Promise((resolve, reject) => {
245
+ const request = indexedDB.deleteDatabase(this.name);
246
+ request.onsuccess = () => resolve();
247
+ request.onerror = () => reject(request.error);
248
+ request.onblocked = () => {
249
+ console.warn(`Database deletion blocked for ${this.name}. Close all connections and try again.`);
250
+ };
251
+ });
252
+ } else {
253
+ const dbPath = this.buildDatabasePath();
254
+ const root = await navigator.storage.getDirectory();
255
+ try {
256
+ const pathParts = dbPath.split("/").filter(Boolean);
257
+ let current = root;
258
+ for (let i = 0; i < pathParts.length - 1; i++) {
259
+ current = await current.getDirectoryHandle(pathParts[i]);
260
+ }
261
+ const filename = pathParts[pathParts.length - 1];
262
+ await current.removeEntry(filename, { recursive: true });
263
+ const associatedFiles = [`${filename}-journal`, `${filename}-wal`, `${filename}-shm`];
264
+ for (const file of associatedFiles) {
265
+ try {
266
+ await current.removeEntry(file, { recursive: false });
267
+ } catch {
268
+ }
269
+ }
270
+ } catch (error) {
271
+ if (error.name !== "NotFoundError") {
272
+ throw error;
273
+ }
274
+ }
275
+ }
276
+ }
277
+ };
278
+ export {
279
+ WaSqliteDriver
280
+ };
281
+ //# sourceMappingURL=wa-sqlite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/sqlite/drivers/WaSqliteDriver.ts"],"sourcesContent":["import type { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult } from '../types';\n\n/**\n * Virtual File System (VFS) options for wa-sqlite.\n * Each VFS has different trade-offs for performance, durability, and compatibility.\n *\n * @see https://github.com/rhashimoto/wa-sqlite/tree/master/src/examples#vfs-comparison\n */\nexport type WaSqliteVfsType =\n /**\n * IDBBatchAtomicVFS - IndexedDB-backed storage\n * - Works on ALL contexts (Window, Worker, SharedWorker, service worker)\n * - Supports multiple connections\n * - Full durability with batch atomic writes\n * - Good general-purpose choice for maximum compatibility\n * @recommended For apps that need to work in main thread and don't need OPFS\n */\n | 'IDBBatchAtomicVFS'\n /**\n * IDBMirrorVFS - IndexedDB with in-memory mirror\n * - Works on ALL contexts\n * - Supports multiple connections\n * - Much faster than IDBBatchAtomicVFS\n * - Database must fit in available memory\n * @recommended For small databases where performance is critical\n */\n | 'IDBMirrorVFS'\n /**\n * OPFSCoopSyncVFS - OPFS with cooperative synchronous access\n * - Requires Worker context\n * - Supports multiple connections\n * - Filesystem transparent (can import/export files)\n * - Good balance of performance and compatibility\n * @recommended For apps needing OPFS with multi-connection support\n */\n | 'OPFSCoopSyncVFS'\n /**\n * AccessHandlePoolVFS - OPFS-backed storage (fastest single connection)\n * - Requires Worker context\n * - Single connection only (no multi-tab support)\n * - Best performance, supports WAL mode\n * - NOT filesystem transparent\n * @recommended For single-tab apps where performance is critical\n */\n | 'AccessHandlePoolVFS';\n\n/**\n * Options for configuring the WaSqliteDriver.\n */\nexport interface WaSqliteDriverOptions {\n /**\n * Virtual File System to use for storage.\n * @default 'IDBBatchAtomicVFS'\n */\n vfs?: WaSqliteVfsType;\n\n /**\n * Directory path for the database in OPFS VFS modes.\n * Only used with OPFS-based VFS types.\n * @default '/'\n */\n directory?: string;\n\n /**\n * SQLite page size in bytes.\n * Larger pages can improve read performance for large BLOBs.\n * Cannot be changed after database creation for IDBBatchAtomicVFS/IDBMirrorVFS.\n * @default 4096\n */\n pageSize?: number;\n\n /**\n * SQLite cache size in pages (negative = KB, positive = pages).\n * Larger cache improves performance but uses more memory.\n * For IDBBatchAtomicVFS, must be large enough to hold journal for batch atomic mode.\n * @default -2000 (2MB)\n */\n cacheSize?: number;\n\n /**\n * Enable WAL (Write-Ahead Logging) mode.\n * Only supported with AccessHandlePoolVFS (with locking_mode=exclusive).\n * For other VFS types, this is ignored.\n * @default false\n */\n wal?: boolean;\n\n /**\n * Set synchronous pragma for durability vs performance trade-off.\n * - 'full': Maximum durability (default)\n * - 'normal': Relaxed durability, better performance (supported by IDBBatchAtomicVFS, IDBMirrorVFS, OPFSPermutedVFS)\n * - 'off': No sync, fastest but risks data loss on crash\n * @default 'full'\n */\n synchronous?: 'full' | 'normal' | 'off';\n}\n\n// Internal VFS interface for lifecycle management\ninterface WaSqliteVFS {\n close(): Promise<void>;\n name: string;\n}\n\n// VFS class type with static create method\ninterface VFSClass {\n create(name: string, module: any, options?: any): Promise<WaSqliteVFS>;\n}\n\n// Cached module factory and instance\nlet cachedModuleFactory: (() => Promise<any>) | null = null;\nlet cachedModule: any = null;\nlet cachedSqlite3: any = null;\n// Track VFS instances by name to avoid re-registering\nconst registeredVFS = new Map<string, WaSqliteVFS>();\n\n/**\n * SQLite driver for web browsers using wa-sqlite with IndexedDB or OPFS persistence.\n * Provides robust, persistent SQLite storage in the browser that prevents data loss.\n *\n * ## Data Safety Features\n *\n * - **IDBBatchAtomicVFS** (default): Uses IndexedDB batch atomic writes to ensure transactions\n * are either fully committed or not at all. Multi-tab safe.\n * - **IDBMirrorVFS**: IndexedDB with in-memory mirror. Much faster, database must fit in RAM.\n * - **OPFSCoopSyncVFS**: OPFS with cooperative sync. Multi-connection, filesystem transparent.\n * - **AccessHandlePoolVFS**: Uses OPFS Access Handles for high performance. Single-tab only.\n * - Full durability by default (`PRAGMA synchronous=full`)\n * - Automatic journal mode configuration for each VFS type\n *\n * ## VFS Selection Guide\n *\n * | VFS | Best For | Multi-Tab | Speed |\n * |-----|----------|-----------|-------|\n * | IDBBatchAtomicVFS | General use, main thread | ✅ | Good |\n * | IDBMirrorVFS | Small DBs, main thread | ✅ | Fast |\n * | OPFSCoopSyncVFS | Web Workers, file export | ✅ | Good |\n * | AccessHandlePoolVFS | Single-tab performance | ❌ | Fastest |\n *\n * @example\n * ```ts\n * import { WaSqliteDriver } from '@anfenn/dync/wa-sqlite';\n * import { SQLiteAdapter } from '@anfenn/dync';\n *\n * // Default: IDBBatchAtomicVFS (works in main thread, multi-tab safe)\n * const driver = new WaSqliteDriver('myapp.db');\n *\n * // For OPFS (faster, requires Worker, filesystem transparent)\n * const opfsDriver = new WaSqliteDriver('myapp.db', { vfs: 'OPFSCoopSyncVFS' });\n *\n * const adapter = new SQLiteAdapter('myapp', driver);\n * ```\n */\nexport class WaSqliteDriver implements SQLiteDatabaseDriver {\n readonly type = 'WaSqliteDriver';\n private db: number | null = null;\n private sqlite3: any = null;\n private readonly options: Required<WaSqliteDriverOptions>;\n private opened = false;\n private openPromise: Promise<void> | null = null;\n // Mutex to prevent concurrent database operations (critical for wa-sqlite)\n private executionLock: Promise<void> = Promise.resolve();\n readonly name: string;\n\n constructor(databaseName: string, options: WaSqliteDriverOptions = {}) {\n this.name = databaseName;\n this.options = {\n vfs: 'IDBBatchAtomicVFS',\n directory: '/',\n pageSize: 4096,\n cacheSize: -2000,\n wal: false,\n synchronous: 'full',\n ...options,\n };\n }\n\n /**\n * Execute a callback with exclusive database access.\n * This prevents concurrent operations which can corrupt the database.\n */\n private async withLock<T>(fn: () => Promise<T>): Promise<T> {\n // Chain onto the existing lock\n const previousLock = this.executionLock;\n let releaseLock: () => void;\n this.executionLock = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n\n try {\n // Wait for previous operation to complete\n await previousLock;\n // Execute our operation\n return await fn();\n } finally {\n // Release the lock\n releaseLock!();\n }\n }\n\n async open(): Promise<void> {\n if (this.opened) return;\n if (this.openPromise) return this.openPromise;\n\n this.openPromise = this._open();\n\n try {\n await this.openPromise;\n } finally {\n this.openPromise = null;\n }\n }\n\n private async _open(): Promise<void> {\n // Load wa-sqlite module (asyncify build for async VFS support)\n const module = await this.loadWasmModule();\n\n // Create SQLite API from module (cached - must only create once per module)\n if (!cachedSqlite3) {\n const { Factory } = await import('@journeyapps/wa-sqlite');\n cachedSqlite3 = Factory(module);\n }\n this.sqlite3 = cachedSqlite3;\n\n // For IDB-based VFS, the VFS name is also used as the IndexedDB database name\n // Use a unique name based on database name to avoid conflicts\n const vfsName = `dync_${this.options.vfs}_${this.name}`.replace(/[^a-zA-Z0-9_-]/g, '_');\n\n // Reuse existing VFS instance or create and register a new one\n let existingVfs = registeredVFS.get(vfsName);\n if (!existingVfs) {\n existingVfs = await this.createVFS(module, vfsName);\n // Register VFS with SQLite as default (like PowerSync does)\n this.sqlite3.vfs_register(existingVfs, true);\n registeredVFS.set(vfsName, existingVfs);\n }\n\n // Build database path - for IDB VFS, this is the \"file\" path within the VFS\n const dbPath = this.buildDatabasePath();\n\n // Open database (VFS is registered as default)\n this.db = await this.sqlite3.open_v2(dbPath);\n\n // Configure database pragmas for performance and durability\n await this.configurePragmas();\n\n this.opened = true;\n }\n\n private async loadWasmModule(): Promise<any> {\n if (!cachedModule) {\n if (!cachedModuleFactory) {\n // Dynamically import the asyncify build for async VFS support\n const wasmModule = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');\n cachedModuleFactory = wasmModule.default;\n }\n // Cache the module instance - all VFS and sqlite3 APIs must share the same module\n cachedModule = await cachedModuleFactory();\n }\n return cachedModule;\n }\n\n private async createVFS(module: any, vfsName: string): Promise<WaSqliteVFS> {\n const vfsType = this.options.vfs;\n let VFSClass: VFSClass;\n let vfsOptions: any = undefined;\n\n // Dynamically import VFS implementation\n // Note: We cast to unknown first because the package types don't include the static create method\n switch (vfsType) {\n case 'IDBBatchAtomicVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');\n VFSClass = mod.IDBBatchAtomicVFS as unknown as VFSClass;\n // Use exclusive lock policy like PowerSync does\n vfsOptions = { lockPolicy: 'exclusive' };\n break;\n }\n case 'IDBMirrorVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBMirrorVFS.js');\n VFSClass = mod.IDBMirrorVFS as unknown as VFSClass;\n break;\n }\n case 'OPFSCoopSyncVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');\n VFSClass = mod.OPFSCoopSyncVFS as unknown as VFSClass;\n break;\n }\n case 'AccessHandlePoolVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');\n VFSClass = mod.AccessHandlePoolVFS as unknown as VFSClass;\n break;\n }\n default:\n throw new Error(`Unsupported VFS type: ${vfsType}`);\n }\n\n return VFSClass.create(vfsName, module, vfsOptions);\n }\n\n private buildDatabasePath(): string {\n const vfsType = this.options.vfs;\n\n // For IDB-based VFS, use database name directly\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n return this.name;\n }\n\n // For OPFS-based VFS, build full path\n const directory = this.options.directory.replace(/\\/$/, '');\n return `${directory}/${this.name}`;\n }\n\n private async configurePragmas(): Promise<void> {\n if (!this.db || !this.sqlite3) return;\n\n // Page size can only be set on new/empty databases\n // For IDBBatchAtomicVFS, it cannot be changed after creation\n // Try to set it, but ignore errors if the database already exists\n try {\n await this.sqlite3.exec(this.db, `PRAGMA page_size = ${this.options.pageSize}`);\n } catch {\n // Page size already set, ignore\n }\n\n // Cache size for performance\n await this.sqlite3.exec(this.db, `PRAGMA cache_size = ${this.options.cacheSize}`);\n\n // WAL mode only for AccessHandlePoolVFS with exclusive locking\n if (this.options.wal && this.options.vfs === 'AccessHandlePoolVFS') {\n await this.sqlite3.exec(this.db, 'PRAGMA locking_mode = exclusive');\n await this.sqlite3.exec(this.db, 'PRAGMA journal_mode = WAL');\n }\n // Note: For IDB-based VFS, we don't set journal_mode - let the VFS handle it\n }\n\n async close(): Promise<void> {\n if (!this.opened || !this.db || !this.sqlite3) return;\n\n // Wait for any pending operations to complete by acquiring the lock\n await this.withLock(async () => {\n // Ensure all data is flushed before closing\n // This is critical for IDB-based VFS which batch writes\n try {\n await this.sqlite3!.exec(this.db!, 'PRAGMA wal_checkpoint(TRUNCATE)');\n } catch {\n // Ignore if WAL mode not enabled\n }\n\n await this.sqlite3!.close(this.db!);\n\n // Don't close the shared VFS - it may be used by other connections\n // The VFS will be cleaned up when all references are gone\n this.db = null;\n this.opened = false;\n });\n }\n\n async execute(statement: string): Promise<void> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n await this.withLock(async () => {\n await this.sqlite3.exec(this.db, statement);\n });\n }\n\n async run(statement: string, values: unknown[] = []): Promise<SQLiteRunResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Execute the statement\n await this.sqlite3.step(stmt);\n }\n\n return {\n changes: this.sqlite3.changes(this.db),\n lastId: Number(this.sqlite3.last_insert_id(this.db)),\n };\n });\n }\n\n /**\n * Convert values for SQLite compatibility.\n * - Booleans must be converted to integers (SQLite has no boolean type)\n */\n private convertValues(values: unknown[]): unknown[] {\n return values.map((value) => {\n if (typeof value === 'boolean') {\n return value ? 1 : 0;\n }\n return value;\n });\n }\n\n async query(statement: string, values: unknown[] = []): Promise<SQLiteQueryResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n const { SQLITE_ROW } = await import('@journeyapps/wa-sqlite');\n const allRows: unknown[][] = [];\n let columns: string[] = [];\n\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Get column names\n if (columns.length === 0) {\n columns = this.sqlite3.column_names(stmt);\n }\n\n // Fetch all rows\n while ((await this.sqlite3.step(stmt)) === SQLITE_ROW) {\n const row = this.sqlite3.row(stmt);\n allRows.push(row);\n }\n }\n\n return { columns, values: allRows };\n });\n }\n\n /**\n * Check if the database is currently open.\n */\n isOpen(): boolean {\n return this.opened;\n }\n\n /**\n * Get the VFS type being used by this driver.\n */\n getVfsType(): WaSqliteVfsType {\n return this.options.vfs;\n }\n\n /**\n * Delete the database.\n * This will close the database if open and remove all persisted data.\n * For IndexedDB-based VFS, this deletes the IndexedDB database.\n * For OPFS-based VFS, this removes the files from OPFS.\n */\n async delete(): Promise<void> {\n // Close if open\n if (this.opened) {\n await this.close();\n }\n\n const vfsType = this.options.vfs;\n\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n // Delete IndexedDB database\n await new Promise<void>((resolve, reject) => {\n const request = indexedDB.deleteDatabase(this.name);\n request.onsuccess = () => resolve();\n request.onerror = () => reject(request.error);\n request.onblocked = () => {\n console.warn(`Database deletion blocked for ${this.name}. Close all connections and try again.`);\n };\n });\n } else {\n // For OPFS-based VFS, remove the directory\n const dbPath = this.buildDatabasePath();\n const root = await navigator.storage.getDirectory();\n\n try {\n // Try to remove the file/directory\n const pathParts = dbPath.split('/').filter(Boolean);\n let current = root;\n\n // Navigate to parent directory\n for (let i = 0; i < pathParts.length - 1; i++) {\n current = await current.getDirectoryHandle(pathParts[i]!);\n }\n\n // Remove the database file\n const filename = pathParts[pathParts.length - 1]!;\n await current.removeEntry(filename, { recursive: true });\n\n // Also try to remove associated journal/wal files\n const associatedFiles = [`${filename}-journal`, `${filename}-wal`, `${filename}-shm`];\n for (const file of associatedFiles) {\n try {\n await current.removeEntry(file, { recursive: false });\n } catch {\n // Ignore if file doesn't exist\n }\n }\n } catch (error) {\n // Ignore if directory doesn't exist\n if ((error as Error).name !== 'NotFoundError') {\n throw error;\n }\n }\n }\n }\n}\n"],"mappings":";AA6GA,IAAI,sBAAmD;AACvD,IAAI,eAAoB;AACxB,IAAI,gBAAqB;AAEzB,IAAM,gBAAgB,oBAAI,IAAyB;AAuC5C,IAAM,iBAAN,MAAqD;AAAA,EAC/C,OAAO;AAAA,EACR,KAAoB;AAAA,EACpB,UAAe;AAAA,EACN;AAAA,EACT,SAAS;AAAA,EACT,cAAoC;AAAA;AAAA,EAEpC,gBAA+B,QAAQ,QAAQ;AAAA,EAC9C;AAAA,EAET,YAAY,cAAsB,UAAiC,CAAC,GAAG;AACnE,S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,YAAY,UAAU,EAAE,WAAW,KAAK,CAAC;AAGvD,cAAM,kBAAkB,CAAC,GAAG,QAAQ,YAAY,GAAG,QAAQ,QAAQ,GAAG,QAAQ,MAAM;AACpF,mBAAW,QAAQ,iBAAiB;AAChC,cAAI;AACA,kBAAM,QAAQ,YAAY,MAAM,EAAE,WAAW,MAAM,CAAC;AAAA,UACxD,QAAQ;AAAA,UAER;AAAA,QACJ;AAAA,MACJ,SAAS,OAAO;AAEZ,YAAK,MAAgB,SAAS,iBAAiB;AAC3C,gBAAM;AAAA,QACV;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,171 @@
1
+ {
2
+ "name": "@anfenn/dync",
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "description": "Write once, run IndexedDB & SQLite with sync anywhere - React, React Native, Expo, Capacitor, Electron & Node.js",
6
+ "keywords": [],
7
+ "license": "MIT",
8
+ "author": "Adam Fennell",
9
+ "type": "module",
10
+ "react-native": "./src/index.native.ts",
11
+ "exports": {
12
+ ".": {
13
+ "react-native": "./src/index.native.ts",
14
+ "import": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
18
+ "require": {
19
+ "types": "./dist/index.d.cts",
20
+ "default": "./dist/index.cjs"
21
+ }
22
+ },
23
+ "./dexie": {
24
+ "import": {
25
+ "types": "./dist/dexie.d.ts",
26
+ "default": "./dist/dexie.js"
27
+ },
28
+ "require": {
29
+ "types": "./dist/dexie.d.cts",
30
+ "default": "./dist/dexie.cjs"
31
+ }
32
+ },
33
+ "./expo-sqlite": {
34
+ "react-native": "./src/expoSqlite.ts",
35
+ "import": {
36
+ "types": "./dist/expoSqlite.d.ts",
37
+ "default": "./dist/expoSqlite.js"
38
+ },
39
+ "require": {
40
+ "types": "./dist/expoSqlite.d.cts",
41
+ "default": "./dist/expoSqlite.cjs"
42
+ }
43
+ },
44
+ "./react": {
45
+ "react-native": "./src/react/index.ts",
46
+ "import": {
47
+ "types": "./dist/react/index.d.ts",
48
+ "default": "./dist/react/index.js"
49
+ },
50
+ "require": {
51
+ "types": "./dist/react/index.d.cts",
52
+ "default": "./dist/react/index.cjs"
53
+ }
54
+ },
55
+ "./capacitor": {
56
+ "import": {
57
+ "types": "./dist/capacitor.d.ts",
58
+ "default": "./dist/capacitor.js"
59
+ },
60
+ "require": {
61
+ "types": "./dist/capacitor.d.cts",
62
+ "default": "./dist/capacitor.cjs"
63
+ }
64
+ },
65
+ "./node": {
66
+ "import": {
67
+ "types": "./dist/node.d.ts",
68
+ "default": "./dist/node.js"
69
+ },
70
+ "require": {
71
+ "types": "./dist/node.d.cts",
72
+ "default": "./dist/node.cjs"
73
+ }
74
+ },
75
+ "./wa-sqlite": {
76
+ "import": {
77
+ "types": "./dist/wa-sqlite.d.ts",
78
+ "default": "./dist/wa-sqlite.js"
79
+ },
80
+ "require": {
81
+ "types": "./dist/wa-sqlite.d.cts",
82
+ "default": "./dist/wa-sqlite.cjs"
83
+ }
84
+ }
85
+ },
86
+ "main": "./dist/index.cjs",
87
+ "module": "./dist/index.js",
88
+ "types": "./dist/index.d.ts",
89
+ "files": [
90
+ "dist",
91
+ "src",
92
+ "package.json",
93
+ "LICENSE"
94
+ ],
95
+ "scripts": {
96
+ "build": "pnpm run format && pnpm run lint && pnpm exec tsc --noEmit && tsup",
97
+ "build:all": "pnpm run build && pnpm --filter react-capacitor build",
98
+ "dev": "tsup --watch",
99
+ "dev:capacitor": "pnpm --filter react-capacitor run dev",
100
+ "dev:expo:web": "pnpm --filter react-native-expo-sqlite web --clear",
101
+ "dev:expo:start": "pnpm --filter react-native-expo-sqlite start --clear",
102
+ "lint": "eslint . --fix \"src/**/*.{js,jsx,ts,tsx,json}\"",
103
+ "format": "prettier --write \"**/*.{ts,tsx,md}\"",
104
+ "size": "pnpm --filter size size",
105
+ "test": "pnpm --filter tests test",
106
+ "test:all": "pnpm --filter tests test:all",
107
+ "test:ci": "pnpm --filter tests test:ci",
108
+ "test:browser:full": "pnpm --filter tests test:browser:full",
109
+ "reinstall": "find . -name node_modules -type d -prune -exec rm -rf {} + && pnpm install"
110
+ },
111
+ "devDependencies": {
112
+ "@capacitor-community/sqlite": "7.0.2",
113
+ "@capgo/capacitor-fast-sql": "7.2.13",
114
+ "@eslint/js": "9.39.2",
115
+ "@types/better-sqlite3": "7.6.13",
116
+ "@types/react": "19.1.10",
117
+ "dexie": "^4.2.1",
118
+ "eslint": "9.39.2",
119
+ "expo-crypto": "15.0.8",
120
+ "expo-sqlite": "16.0.10",
121
+ "prettier": "3.7.4",
122
+ "react": "19.1.0",
123
+ "tsup": "8.5.1",
124
+ "typescript": "5.9.3",
125
+ "typescript-eslint": "8.49.0",
126
+ "@journeyapps/wa-sqlite": "1.4.1"
127
+ },
128
+ "peerDependencies": {
129
+ "@journeyapps/wa-sqlite": ">=1.0.0",
130
+ "@capacitor-community/sqlite": ">=7.0.0",
131
+ "@capgo/capacitor-fast-sql": ">=7.0.0",
132
+ "better-sqlite3": ">=11.0.0",
133
+ "dexie": ">=4.0.0",
134
+ "expo-crypto": ">=15.0.0",
135
+ "expo-sqlite": ">=16.0.0",
136
+ "react": ">=18.0.0"
137
+ },
138
+ "peerDependenciesMeta": {
139
+ "@journeyapps/wa-sqlite": {
140
+ "optional": true
141
+ },
142
+ "@capacitor-community/sqlite": {
143
+ "optional": true
144
+ },
145
+ "@capgo/capacitor-fast-sql": {
146
+ "optional": true
147
+ },
148
+ "better-sqlite3": {
149
+ "optional": true
150
+ },
151
+ "dexie": {
152
+ "optional": true
153
+ },
154
+ "react": {
155
+ "optional": true
156
+ },
157
+ "expo-crypto": {
158
+ "optional": true
159
+ },
160
+ "expo-sqlite": {
161
+ "optional": true
162
+ }
163
+ },
164
+ "pnpm": {
165
+ "onlyBuiltDependencies": [
166
+ "better-sqlite3",
167
+ "esbuild",
168
+ "unrs-resolver"
169
+ ]
170
+ }
171
+ }