@anfenn/dync 1.0.4 → 1.0.5

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.
@@ -1,4 +1,4 @@
1
- import { a as ApiFunctions, h as SyncOptions, B as BatchSync, D as Dync, i as SyncState } from '../index.shared-DsDBNWlz.cjs';
1
+ import { a as ApiFunctions, h as SyncOptions, B as BatchSync, D as Dync, i as SyncState } from '../index.shared-XsB8HrvX.cjs';
2
2
  import { c as StorageAdapter } from '../dexie-1_xyU5MV.cjs';
3
3
  import '../types-CSbIAfu2.cjs';
4
4
  import 'dexie';
@@ -1,4 +1,4 @@
1
- import { a as ApiFunctions, h as SyncOptions, B as BatchSync, D as Dync, i as SyncState } from '../index.shared-Byhq6TyU.js';
1
+ import { a as ApiFunctions, h as SyncOptions, B as BatchSync, D as Dync, i as SyncState } from '../index.shared-3gbnIINY.js';
2
2
  import { c as StorageAdapter } from '../dexie-ChZ0o0Sz.js';
3
3
  import '../types-CSbIAfu2.js';
4
4
  import 'dexie';
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Dync
3
- } from "../chunk-PCA4XM2N.js";
3
+ } from "../chunk-YAAFAS64.js";
4
4
  import "../chunk-SQB6E7V2.js";
5
5
 
6
6
  // src/react/useDync.ts
@@ -267,9 +267,9 @@ var WaSqliteDriver = class {
267
267
  }
268
268
  /**
269
269
  * Delete the database.
270
- * This will close the database if open and remove all persisted data.
270
+ * This will close the database if open and delete all persisted data.
271
271
  * For IndexedDB-based VFS, this deletes the IndexedDB database.
272
- * For OPFS-based VFS, this removes the files from OPFS.
272
+ * For OPFS-based VFS, this deletes the files from OPFS.
273
273
  */
274
274
  async delete() {
275
275
  if (this.opened) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/wa-sqlite.ts","../src/storage/sqlite/drivers/WaSqliteDriver.ts"],"sourcesContent":["// wa-sqlite Browser SQLite Driver\n// Import this entry point for browser/web builds with SQLite support\nexport { WaSqliteDriver, type WaSqliteDriverOptions, type WaSqliteVfsType } from './storage/sqlite/drivers/WaSqliteDriver';\nexport type { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult } from './storage/sqlite/types';\n","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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC6GA,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,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,MACX,KAAK;AAAA,MACL,WAAW;AAAA,MACX,UAAU;AAAA,MACV,WAAW;AAAA,MACX,KAAK;AAAA,MACL,aAAa;AAAA,MACb,GAAG;AAAA,IACP;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,SAAY,IAAkC;AAExD,UAAM,eAAe,KAAK;AAC1B,QAAI;AACJ,SAAK,gBAAgB,IAAI,QAAc,CAAC,YAAY;AAChD,oBAAc;AAAA,IAClB,CAAC;AAED,QAAI;AAEA,YAAM;AAEN,aAAO,MAAM,GAAG;AAAA,IACpB,UAAE;AAEE,kBAAa;AAAA,IACjB;A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qlite.ts","../src/storage/sqlite/drivers/WaSqliteDriver.ts"],"sourcesContent":["// wa-sqlite Browser SQLite Driver\n// Import this entry point for browser/web builds with SQLite support\nexport { WaSqliteDriver, type WaSqliteDriverOptions, type WaSqliteVfsType } from './storage/sqlite/drivers/WaSqliteDriver';\nexport type { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult } from './storage/sqlite/types';\n","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 delete all persisted data.\n * For IndexedDB-based VFS, this deletes the IndexedDB database.\n * For OPFS-based VFS, this deletes 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, delete the directory\n const dbPath = this.buildDatabasePath();\n const root = await navigator.storage.getDirectory();\n\n try {\n // Try to delete 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 // Delete the database file\n const filename = pathParts[pathParts.length - 1]!;\n await current.removeEntry(filename, { recursive: true });\n\n // Also try to delete 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC6GA,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,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,MACX,KAAK;AAAA,MACL,WAAW;AAAA,MACX,UAAU;AAAA,MACV,WAAW;AAAA,MACX,KAAK;AAAA,MACL,aAAa;AAAA,MACb,GAAG;AAAA,IACP;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,SAAY,IAAkC;AAExD,UAAM,eAAe,KAAK;AAC1B,QAAI;AACJ,SAAK,gBAAgB,IAAI,QAAc,CAAC,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K,MAAgB,SAAS,iBAAiB;AAC3C,gBAAM;AAAA,QACV;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;","names":["module"]}
@@ -165,9 +165,9 @@ declare class WaSqliteDriver implements SQLiteDatabaseDriver {
165
165
  getVfsType(): WaSqliteVfsType;
166
166
  /**
167
167
  * Delete the database.
168
- * This will close the database if open and remove all persisted data.
168
+ * This will close the database if open and delete all persisted data.
169
169
  * For IndexedDB-based VFS, this deletes the IndexedDB database.
170
- * For OPFS-based VFS, this removes the files from OPFS.
170
+ * For OPFS-based VFS, this deletes the files from OPFS.
171
171
  */
172
172
  delete(): Promise<void>;
173
173
  }
@@ -165,9 +165,9 @@ declare class WaSqliteDriver implements SQLiteDatabaseDriver {
165
165
  getVfsType(): WaSqliteVfsType;
166
166
  /**
167
167
  * Delete the database.
168
- * This will close the database if open and remove all persisted data.
168
+ * This will close the database if open and delete all persisted data.
169
169
  * For IndexedDB-based VFS, this deletes the IndexedDB database.
170
- * For OPFS-based VFS, this removes the files from OPFS.
170
+ * For OPFS-based VFS, this deletes the files from OPFS.
171
171
  */
172
172
  delete(): Promise<void>;
173
173
  }
package/dist/wa-sqlite.js CHANGED
@@ -231,9 +231,9 @@ var WaSqliteDriver = class {
231
231
  }
232
232
  /**
233
233
  * Delete the database.
234
- * This will close the database if open and remove all persisted data.
234
+ * This will close the database if open and delete all persisted data.
235
235
  * For IndexedDB-based VFS, this deletes the IndexedDB database.
236
- * For OPFS-based VFS, this removes the files from OPFS.
236
+ * For OPFS-based VFS, this deletes the files from OPFS.
237
237
  */
238
238
  async delete() {
239
239
  if (this.opened) {
@@ -1 +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,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,MACX,KAAK;AAAA,MACL,WAAW;AAAA,MACX,UAAU;AAAA,MACV,WAAW;AAAA,MACX,KAAK;AAAA,MACL,aAAa;AAAA,MACb,GAAG;AAAA,IACP;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,SAAY,IAAkC;AAExD,UAAM,eAAe,KAAK;AAC1B,QAAI;AACJ,SAAK,gBAAgB,IAAI,QAAc,CAAC,YAAY;AAChD,oBAAc;AAAA,IAClB,CAAC;AAED,QAAI;AAEA,YAAM;AAEN,aAAO,MAAM,GAAG;AAAA,IACpB,UAAE;AAEE,kBAAa;AAAA,IACjB;AAAA,EACJ;AAAA,EAEA,MAAM,OAAsB;AACxB,QAAI,KAAK,OAAQ;AACjB,QAAI,KAAK,YAAa,QAAO,KAAK;AAElC,SAAK,cAAc,KAAK,MAAM;AAE9B,QAAI;AACA,YAAM,KAAK;AAAA,IACf,UAAE;AACE,WAAK,cAAc;AAAA,IACvB;AAAA,EACJ;AAAA,EAEA,MAAc,QAAuB;AAEjC,UAAM,SAAS,MAAM,KAAK,eAAe;AAGzC,QAAI,CAAC,eAAe;AAChB,YAAM,EAAE,QAAQ,IAAI,MAAM,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,gBAAQ,YAAY,MAAM;AACtB,kBAAQ,KAAK,iCAAiC,KAAK,IAAI,wCAAwC;AAAA,QACnG;AAAA,MACJ,CAAC;AAAA,IACL,OAAO;AAEH,YAAM,SAAS,KAAK,kBAAkB;AACtC,YAAM,OAAO,MAAM,UAAU,QAAQ,aAAa;AAElD,UAAI;AAEA,cAAM,YAAY,OAAO,MAAM,GAAG,EAAE,OAAO,OAAO;AAClD,YAAI,UAAU;AAGd,iBAAS,IAAI,GAAG,IAAI,UAAU,SAAS,GAAG,KAAK;AAC3C,oBAAU,MAAM,QAAQ,mBAAmB,UAAU,CAAC,CAAE;AAAA,QAC5D;AAGA,cAAM,WAAW,UAAU,UAAU,SAAS,CAAC;AAC/C,cAAM,QAAQ,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":[]}
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 delete all persisted data.\n * For IndexedDB-based VFS, this deletes the IndexedDB database.\n * For OPFS-based VFS, this deletes 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, delete the directory\n const dbPath = this.buildDatabasePath();\n const root = await navigator.storage.getDirectory();\n\n try {\n // Try to delete 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 // Delete the database file\n const filename = pathParts[pathParts.length - 1]!;\n await current.removeEntry(filename, { recursive: true });\n\n // Also try to delete 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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,YAAM,OAAO,MAAM,UAAU,QAAQ,aAAa;AAElD,UAAI;AAEA,cAAM,YAAY,OAAO,MAAM,GAAG,EAAE,OAAO,OAAO;AAClD,YAAI,UAAU;AAGd,iBAAS,IAAI,GAAG,IAAI,UAAU,SAAS,GAAG,KAAK;AAC3C,oBAAU,MAAM,QAAQ,mBAAmB,UAAU,CAAC,CAAE;AAAA,QAC5D;AAGA,cAAM,WAAW,UAAU,UAAU,SAAS,CAAC;AAC/C,cAAM,QAAQ,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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anfenn/dync",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "private": false,
5
5
  "description": "Write once, run IndexedDB & SQLite with sync anywhere - React, React Native, Expo, Capacitor, Electron & Node.js",
6
6
  "keywords": [],
@@ -120,19 +120,19 @@ export class StateManager implements StateHelpers {
120
120
  const action = change.action;
121
121
 
122
122
  if (queueItem) {
123
- if (queueItem.action === SyncAction.Remove) {
123
+ if (queueItem.action === SyncAction.Delete) {
124
124
  return Promise.resolve();
125
125
  }
126
126
 
127
127
  queueItem.version += 1;
128
128
 
129
- if (action === SyncAction.Remove) {
130
- queueItem.action = SyncAction.Remove;
129
+ if (action === SyncAction.Delete) {
130
+ queueItem.action = SyncAction.Delete;
131
131
  } else if (hasChanges) {
132
132
  queueItem.changes = { ...queueItem.changes, ...omittedChanges };
133
133
  queueItem.after = { ...queueItem.after, ...omittedAfter };
134
134
  }
135
- } else if (action === SyncAction.Remove || hasChanges) {
135
+ } else if (action === SyncAction.Delete || hasChanges) {
136
136
  next.pendingChanges = [...next.pendingChanges];
137
137
  next.pendingChanges.push({
138
138
  action,
@@ -162,7 +162,7 @@ async function processPullData(tableName: string, serverData: SyncedRecord[], si
162
162
  const pendingRemovalById = new Set(
163
163
  ctx.state
164
164
  .getState()
165
- .pendingChanges.filter((p) => p.tableName === tableName && p.action === SyncAction.Remove)
165
+ .pendingChanges.filter((p) => p.tableName === tableName && p.action === SyncAction.Delete)
166
166
  .map((p) => p.id),
167
167
  );
168
168
 
@@ -171,7 +171,7 @@ async function processPullData(tableName: string, serverData: SyncedRecord[], si
171
171
  if (remoteUpdated > newest) newest = remoteUpdated;
172
172
 
173
173
  if (pendingRemovalById.has(remote.id)) {
174
- ctx.logger.debug(`[dync] pull:skip-pending-remove tableName=${tableName} id=${remote.id}`);
174
+ ctx.logger.debug(`[dync] pull:skip-pending-delete tableName=${tableName} id=${remote.id}`);
175
175
  continue;
176
176
  }
177
177
 
@@ -180,7 +180,7 @@ async function processPullData(tableName: string, serverData: SyncedRecord[], si
180
180
  if (remote.deleted) {
181
181
  if (localItem) {
182
182
  await txTable.raw.delete(localItem._localId);
183
- ctx.logger.debug(`[dync] pull:remove tableName=${tableName} id=${remote.id}`);
183
+ ctx.logger.debug(`[dync] pull:delete tableName=${tableName} id=${remote.id}`);
184
184
  hasChanges = true;
185
185
  }
186
186
  continue;
@@ -22,9 +22,9 @@ export interface PushAllBatchContext extends PushContext {
22
22
  batchSync: BatchSync;
23
23
  }
24
24
 
25
- async function handleRemoveSuccess(change: PendingChange, ctx: PushContext): Promise<void> {
25
+ async function handleDeleteSuccess(change: PendingChange, ctx: PushContext): Promise<void> {
26
26
  const { tableName, localId, id } = change;
27
- ctx.logger.debug(`[dync] push:remove:success tableName=${tableName} localId=${localId} id=${id}`);
27
+ ctx.logger.debug(`[dync] push:delete:success tableName=${tableName} localId=${localId} id=${id}`);
28
28
  await ctx.state.removePendingChange(localId, tableName);
29
29
  }
30
30
 
@@ -49,9 +49,9 @@ async function handleCreateSuccess(change: PendingChange, serverResult: { id: un
49
49
  if (wasChanged && ctx.state.samePendingVersion(tableName, localId, version)) {
50
50
  await ctx.state.removePendingChange(localId, tableName);
51
51
  } else {
52
- const nextAction = wasChanged ? SyncAction.Update : SyncAction.Remove;
52
+ const nextAction = wasChanged ? SyncAction.Update : SyncAction.Delete;
53
53
  await ctx.state.updatePendingChange(tableName, localId, nextAction, serverResult.id);
54
- if (nextAction === SyncAction.Remove) return;
54
+ if (nextAction === SyncAction.Delete) return;
55
55
  }
56
56
  });
57
57
 
@@ -83,14 +83,14 @@ async function pushOne(change: PendingChange, ctx: PushAllContext): Promise<void
83
83
  const { action, tableName, localId, id, changes, after } = change;
84
84
 
85
85
  switch (action) {
86
- case SyncAction.Remove:
86
+ case SyncAction.Delete:
87
87
  if (!id) {
88
- ctx.logger.warn(`[dync] push:remove:no-id tableName=${tableName} localId=${localId}`);
88
+ ctx.logger.warn(`[dync] push:delete:no-id tableName=${tableName} localId=${localId}`);
89
89
  await ctx.state.removePendingChange(localId, tableName);
90
90
  return;
91
91
  }
92
- await api.remove(id);
93
- await handleRemoveSuccess(change, ctx);
92
+ await api.delete(id);
93
+ await handleDeleteSuccess(change, ctx);
94
94
  break;
95
95
 
96
96
  case SyncAction.Update: {
@@ -216,10 +216,10 @@ export async function pushAllBatch(ctx: PushAllBatchContext): Promise<Error | un
216
216
  // Build batch payload
217
217
  const payloads: BatchPushPayload[] = changesToPush.map((change) => ({
218
218
  table: change.tableName,
219
- action: change.action === SyncAction.Create ? 'add' : change.action === SyncAction.Update ? 'update' : 'remove',
219
+ action: change.action === SyncAction.Create ? 'add' : change.action === SyncAction.Update ? 'update' : 'delete',
220
220
  localId: change.localId,
221
221
  id: change.id,
222
- data: change.action === SyncAction.Remove ? undefined : change.changes,
222
+ data: change.action === SyncAction.Delete ? undefined : change.changes,
223
223
  }));
224
224
 
225
225
  ctx.logger.debug(`[dync] push:batch:start count=${payloads.length}`);
@@ -270,12 +270,12 @@ async function processBatchPushResult(change: PendingChange, result: BatchPushRe
270
270
  }
271
271
 
272
272
  switch (action) {
273
- case SyncAction.Remove:
274
- handleRemoveSuccess(change, ctx);
273
+ case SyncAction.Delete:
274
+ await handleDeleteSuccess(change, ctx);
275
275
  break;
276
276
 
277
277
  case SyncAction.Update:
278
- handleUpdateSuccess(change, ctx);
278
+ await handleUpdateSuccess(change, ctx);
279
279
  break;
280
280
 
281
281
  case SyncAction.Create: {
@@ -233,7 +233,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
233
233
  if (record) {
234
234
  deletedLocalId = record._localId;
235
235
  await state.addPendingChange({
236
- action: SyncAction.Remove,
236
+ action: SyncAction.Delete,
237
237
  tableName,
238
238
  localId: record._localId,
239
239
  id: record.id,
@@ -397,7 +397,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
397
397
  if (record) {
398
398
  deletedLocalIds.push(record._localId);
399
399
  await state.addPendingChange({
400
- action: SyncAction.Remove,
400
+ action: SyncAction.Delete,
401
401
  tableName,
402
402
  localId: record._localId,
403
403
  id: record.id,
@@ -427,7 +427,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
427
427
  if (record._localId) {
428
428
  deletedLocalIds.push(record._localId);
429
429
  await state.addPendingChange({
430
- action: SyncAction.Remove,
430
+ action: SyncAction.Delete,
431
431
  tableName,
432
432
  localId: record._localId,
433
433
  id: record.id,
package/src/helpers.ts CHANGED
@@ -53,7 +53,7 @@ export function orderFor(a: SyncAction): number {
53
53
  return 1;
54
54
  case SyncAction.Update:
55
55
  return 2;
56
- case SyncAction.Remove:
56
+ case SyncAction.Delete:
57
57
  return 3;
58
58
  }
59
59
  }
@@ -476,9 +476,9 @@ export class WaSqliteDriver implements SQLiteDatabaseDriver {
476
476
 
477
477
  /**
478
478
  * Delete the database.
479
- * This will close the database if open and remove all persisted data.
479
+ * This will close the database if open and delete all persisted data.
480
480
  * For IndexedDB-based VFS, this deletes the IndexedDB database.
481
- * For OPFS-based VFS, this removes the files from OPFS.
481
+ * For OPFS-based VFS, this deletes the files from OPFS.
482
482
  */
483
483
  async delete(): Promise<void> {
484
484
  // Close if open
@@ -499,12 +499,12 @@ export class WaSqliteDriver implements SQLiteDatabaseDriver {
499
499
  };
500
500
  });
501
501
  } else {
502
- // For OPFS-based VFS, remove the directory
502
+ // For OPFS-based VFS, delete the directory
503
503
  const dbPath = this.buildDatabasePath();
504
504
  const root = await navigator.storage.getDirectory();
505
505
 
506
506
  try {
507
- // Try to remove the file/directory
507
+ // Try to delete the file/directory
508
508
  const pathParts = dbPath.split('/').filter(Boolean);
509
509
  let current = root;
510
510
 
@@ -513,11 +513,11 @@ export class WaSqliteDriver implements SQLiteDatabaseDriver {
513
513
  current = await current.getDirectoryHandle(pathParts[i]!);
514
514
  }
515
515
 
516
- // Remove the database file
516
+ // Delete the database file
517
517
  const filename = pathParts[pathParts.length - 1]!;
518
518
  await current.removeEntry(filename, { recursive: true });
519
519
 
520
- // Also try to remove associated journal/wal files
520
+ // Also try to delete associated journal/wal files
521
521
  const associatedFiles = [`${filename}-journal`, `${filename}-wal`, `${filename}-shm`];
522
522
  for (const file of associatedFiles) {
523
523
  try {
package/src/types.ts CHANGED
@@ -15,7 +15,7 @@ export interface SyncedRecord {
15
15
  export interface ApiFunctions {
16
16
  add: (item: any) => Promise<any | undefined>;
17
17
  update: (id: any, changes: any, item: any) => Promise<boolean>;
18
- remove: (id: any) => Promise<void>;
18
+ delete: (id: any) => Promise<void>;
19
19
  list: (lastUpdatedAt: Date) => Promise<any[]>;
20
20
  firstLoad?: (lastId: any) => Promise<any[]>;
21
21
  }
@@ -29,9 +29,9 @@ export interface ApiFunctions {
29
29
  */
30
30
  export interface BatchPushPayload {
31
31
  table: string;
32
- action: 'add' | 'update' | 'remove';
32
+ action: 'add' | 'update' | 'delete';
33
33
  localId: string;
34
- // Server-assigned ID (for update/remove)
34
+ // Server-assigned ID (for update/delete)
35
35
  id?: any;
36
36
  // The data to sync (for add/update)
37
37
  data?: any;
@@ -152,7 +152,7 @@ export interface SyncState extends PersistedSyncState {
152
152
  export enum SyncAction {
153
153
  Create = 'create',
154
154
  Update = 'update',
155
- Remove = 'remove', // Remote removes are a noop if no record found
155
+ Delete = 'delete', // Remote deletes are a noop if no record found
156
156
  }
157
157
 
158
158
  export interface PendingChange {