{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/adapters/sqlite-wasm-worker.cjs","../../src/adapters/opfs-pool-ownership.ts","../../src/adapters/sqlite-wasm-loader.ts","../../src/adapters/sqlite-wasm-worker-core.ts","../../src/adapters/sqlite-wasm-worker.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACA;ACiEA,IAAM,mBAAA,EAAqB,CAAA;AAG3B,IAAM,wBAAA,EAA0B,GAAA;AAGhC,IAAM,sBAAA,EAAwB,EAAA;AAG9B,IAAM,qBAAA,EAAuB,GAAA;AAE7B,IAAM,gBAAA,EAAkB,SAAA;AAGjB,IAAM,qBAAA,EAAN,MAAA,QAAmC,MAAM;AAAA,EAC/C,WAAA,CACC,OAAA,EACS,MAAA,EACR;AACD,IAAA,KAAA,CAAM,OAAO,CAAA;AAFJ,IAAA,IAAA,CAAA,OAAA,EAAA,MAAA;AAGT,IAAA,IAAA,CAAK,KAAA,EAAO,sBAAA;AAAA,EACb;AAAA,EAJU;AAKX,CAAA;AAGO,SAAS,gBAAA,CAAiB,OAAA,EAA8B;AAC9D,EAAA,MAAM,EAAA,EAAI,UAAA;AACV,EAAA,MAAM,WAAA,EAAa,CAAA,CAAE,oBAAA;AACrB,EAAA,OACC,OAAO,OAAA,CAAQ,sBAAA,IAA0B,WAAA,GACzC,OAAO,CAAA,CAAE,0BAAA,IAA8B,YAAA,GACvC,uBAAO,UAAA,6BAAY,SAAA,6BAAW,yBAAA,IAA2B,WAAA,GACzD,OAAO,UAAA,IAAc,YAAA,GACrB,uBAAO,SAAA,qBAAU,OAAA,6BAAS,eAAA,IAAiB,UAAA;AAE7C;AAEA,SAAS,KAAA,CAAM,EAAA,EA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"/home/runner/work/kora/kora/packages/store/dist/adapters/sqlite-wasm-worker.cjs","sourcesContent":[null,"/// <reference lib=\"webworker\" />\n/**\n * Worker-side OPFS pool ownership (W8a, NEW-STORE-5/7/8/10).\n *\n * Durable storage on the web is a protocol between tabs, workers and the\n * SyncAccessHandle (SAH) pool, not a single open call:\n *\n * - One pool per database ({@link opfsPoolNameFor}); the tab leader lock already\n *   makes one tab the owner of each database.\n * - The worker that installs a pool holds the Web Lock named after it for the\n *   pool's whole life. Termination of that worker releases both the lock and the\n *   file handles, so the next owner waits on the lock instead of racing.\n * - The lock can be released a few milliseconds before the browser finishes\n *   closing the old worker's handles (measured ~90ms). Before installing, the\n *   new owner therefore probes every pool file for a free handle and waits.\n *   This matters for correctness, not just speed: when sqlite-wasm's install\n *   fails half-way it calls `removeVfs()`, which recursively deletes the pool\n *   directory's files that are not locked. Installing only once every handle is\n *   free keeps that path unreachable.\n * - Contention with a live holder is a wait plus a reported blocking state,\n *   never a fallback to non-durable storage.\n *\n * This file runs inside the dedicated SQLite worker; it is exercised by the\n * real-browser suite (tests/repro/browser), not by Node unit tests.\n */\n\nimport { LEGACY_OPFS_POOL_NAME, opfsPoolDirectory, opfsPoolLockName } from './opfs-names'\n\n/** The subset of sqlite-wasm's oo1.DB the worker uses. */\nexport interface SqliteDb {\n\texec(opts: {\n\t\tsql: string\n\t\tbind?: unknown[]\n\t\treturnValue?: string\n\t\trowMode?: string\n\t\tcallback?: (row: Record<string, unknown>) => void\n\t}): unknown\n\tclose(): void\n\tpointer?: number\n\tdeserialize?: (data: Uint8Array) => void\n\t/** sqlite-wasm oo1: compile one statement (the worker caches its batch statements). */\n\tprepare?: (sql: string) => SqliteStmt\n}\n\n/** The subset of sqlite-wasm's oo1 `Stmt` the worker uses. */\nexport interface SqliteStmt {\n\tbind(values: unknown[]): SqliteStmt\n\tstep(): boolean\n\treset(alsoClearBindings?: boolean): SqliteStmt\n\tfinalize(): unknown\n}\n\n/** The subset of sqlite-wasm's OpfsSAHPoolUtil the worker uses. */\nexport interface OpfsPool {\n\tOpfsSAHPoolDb: new (filename: string) => SqliteDb\n\tgetFileCount(): number\n\tgetFileNames(): string[]\n\tgetCapacity(): number\n\treserveMinimumCapacity(min: number): Promise<number>\n\texportFile(name: string): Uint8Array\n\timportDb(name: string, bytes: Uint8Array): number | Promise<number>\n\tunlink(name: string): boolean\n\tremoveVfs(): Promise<boolean>\n\tpauseVfs(): unknown\n\tunpauseVfs(): Promise<unknown>\n\tisPaused(): boolean\n}\n\n/** The subset of the sqlite3 namespace the worker uses. */\nexport interface Sqlite3Api {\n\too1: { DB: new (opts: { filename: string }) => SqliteDb }\n\tinstallOpfsSAHPoolVfs?: (opts: {\n\t\tname: string\n\t\tforceReinitIfPreviouslyFailed?: boolean\n\t}) => Promise<OpfsPool>\n\tcapi?: {\n\t\tsqlite3_deserialize?: unknown\n\t\tsqlite3_js_db_export?: (dbPointer: number) => Uint8Array\n\t\tsqlite3_progress_handler?: (\n\t\t\tdb: number,\n\t\t\tnOps: number,\n\t\t\thandler: (() => number) | 0,\n\t\t\tctx: number,\n\t\t) => void\n\t}\n}\n\n/** Reports the start and end of a wait on another holder. */\nexport interface BlockingReporter {\n\tblocked(): void\n\tunblocked(waitedMs: number): void\n}\n\n/** Free slots kept beyond the database being opened (other journals, imports). */\nconst OPFS_POOL_HEADROOM = 2\n\n/** How long a wait stays silent before it is reported as a blocking state. */\nconst BLOCKED_REPORT_AFTER_MS = 750\n\n/** Install attempts after the handle probe said \"free\" (covers the release race). */\nconst INSTALL_RACE_ATTEMPTS = 20\n\n/** Headless browsers and some profiles hang on OPFS VFS install. */\nconst OPFS_INIT_TIMEOUT_MS = 10_000\n\nconst OPAQUE_DIR_NAME = '.opaque'\n\n/** Why a durable pool could not be obtained. Contention is never a reason: it waits. */\nexport class PoolUnavailableError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\treadonly reason: 'unsupported' | 'timeout' | 'lock-conflict',\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'PoolUnavailableError'\n\t}\n}\n\n/** True when this worker has every API the SAH pool needs. */\nexport function opfsSahSupported(sqlite3: Sqlite3Api): boolean {\n\tconst g = globalThis as Record<string, unknown>\n\tconst fileHandle = g.FileSystemFileHandle as { prototype?: Record<string, unknown> } | undefined\n\treturn (\n\t\ttypeof sqlite3.installOpfsSAHPoolVfs === 'function' &&\n\t\ttypeof g.FileSystemDirectoryHandle !== 'undefined' &&\n\t\ttypeof fileHandle?.prototype?.createSyncAccessHandle === 'function' &&\n\t\ttypeof navigator !== 'undefined' &&\n\t\ttypeof navigator.storage?.getDirectory === 'function'\n\t)\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n\tlet timer: ReturnType<typeof setTimeout> | undefined\n\ttry {\n\t\treturn await Promise.race([\n\t\t\tpromise,\n\t\t\tnew Promise<T>((_, reject) => {\n\t\t\t\ttimer = setTimeout(\n\t\t\t\t\t() =>\n\t\t\t\t\t\treject(new PoolUnavailableError(`${label} timed out after ${timeoutMs}ms`, 'timeout')),\n\t\t\t\t\ttimeoutMs,\n\t\t\t\t)\n\t\t\t}),\n\t\t])\n\t} finally {\n\t\tif (timer !== undefined) clearTimeout(timer)\n\t}\n}\n\n/**\n * Acquire an exclusive Web Lock and hold it until the returned release function\n * is called (or this worker terminates). Waits for a live holder, reporting the\n * wait once it lasts long enough to matter. Without the Web Locks API (very old\n * engines that also lack the SAH pool) it returns a no-op release.\n */\nexport async function holdExclusiveLock(\n\tname: string,\n\treporter?: BlockingReporter,\n): Promise<() => void> {\n\tconst locks = typeof navigator !== 'undefined' ? navigator.locks : undefined\n\tif (!locks || typeof locks.request !== 'function') {\n\t\treturn () => {}\n\t}\n\tconst grab = (ifAvailable: boolean): Promise<(() => void) | null> =>\n\t\tnew Promise<(() => void) | null>((resolve, reject) => {\n\t\t\tlocks\n\t\t\t\t.request(name, { mode: 'exclusive', ifAvailable }, (lock) => {\n\t\t\t\t\tif (lock === null) {\n\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\treturn undefined\n\t\t\t\t\t}\n\t\t\t\t\treturn new Promise<void>((release) => {\n\t\t\t\t\t\tresolve(() => release())\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t\t.catch(reject)\n\t\t})\n\n\tconst immediate = await grab(true)\n\tif (immediate) return immediate\n\tconst start = Date.now()\n\treporter?.blocked()\n\tconst release = await grab(false)\n\tif (!release) {\n\t\tthrow new PoolUnavailableError(`Web Lock \"${name}\" was not granted`, 'lock-conflict')\n\t}\n\treporter?.unblocked(Date.now() - start)\n\treturn release\n}\n\ninterface DirHandle {\n\tgetDirectoryHandle(name: string, options?: { create?: boolean }): Promise<DirHandle>\n\tremoveEntry(name: string, options?: { recursive?: boolean }): Promise<void>\n\tentries(): AsyncIterable<[string, { kind: string }]>\n}\n\ninterface FileHandleWithSah {\n\tkind: 'file'\n\tcreateSyncAccessHandle(): Promise<{ close(): void }>\n}\n\nasync function opfsRoot(): Promise<DirHandle> {\n\treturn (await navigator.storage.getDirectory()) as unknown as DirHandle\n}\n\nasync function childDirectory(parent: DirHandle, name: string): Promise<DirHandle | null> {\n\ttry {\n\t\treturn await parent.getDirectoryHandle(name)\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/** Whether a pool's directory exists in OPFS (it may still be empty). */\nexport async function poolDirectoryExists(poolName: string): Promise<boolean> {\n\treturn (await childDirectory(await opfsRoot(), opfsPoolDirectory(poolName))) !== null\n}\n\nfunction isHandleBusy(error: unknown): boolean {\n\tconst name = (error as { name?: string } | null)?.name\n\treturn name === 'NoModificationAllowedError' || name === 'InvalidStateError'\n}\n\n/**\n * True when some file of the pool still has an open SyncAccessHandle elsewhere\n * (a live owner, or a terminated owner whose handles are still being released).\n */\nasync function poolHandlesBusy(poolName: string): Promise<boolean> {\n\tconst dir = await childDirectory(await opfsRoot(), opfsPoolDirectory(poolName))\n\tif (!dir) return false\n\tconst opaque = await childDirectory(dir, OPAQUE_DIR_NAME)\n\tif (!opaque) return false\n\tfor await (const [, handle] of opaque.entries()) {\n\t\tif (handle.kind !== 'file') continue\n\t\ttry {\n\t\t\tconst access = await (handle as unknown as FileHandleWithSah).createSyncAccessHandle()\n\t\t\taccess.close()\n\t\t} catch (error) {\n\t\t\tif (isHandleBusy(error)) return true\n\t\t\tthrow error\n\t\t}\n\t}\n\treturn false\n}\n\n/**\n * Wait until every file in the pool can be opened by this worker. Waits as long\n * as a holder exists (a beta.12 tab that never takes the pool lock, or a raw\n * user of the pool), reporting the blocking state; never gives up and falls back.\n */\nasync function waitForPoolHandles(poolName: string, reporter?: BlockingReporter): Promise<void> {\n\tconst start = Date.now()\n\tlet reported = false\n\tlet delay = 15\n\twhile (await poolHandlesBusy(poolName)) {\n\t\tif (!reported && Date.now() - start >= BLOCKED_REPORT_AFTER_MS) {\n\t\t\treported = true\n\t\t\treporter?.blocked()\n\t\t}\n\t\tawait sleep(delay)\n\t\tdelay = Math.min(delay * 2, 500)\n\t}\n\tif (reported) reporter?.unblocked(Date.now() - start)\n}\n\n/**\n * Install (or resume) a pool this worker already holds the pool lock for. The\n * bounded retry with `forceReinitIfPreviouslyFailed` covers only the residual\n * handle-release window; sqlite-wasm otherwise caches a failed install forever.\n */\nexport async function installPool(\n\tsqlite3: Sqlite3Api,\n\tpoolName: string,\n\treporter?: BlockingReporter,\n): Promise<OpfsPool> {\n\tconst install = sqlite3.installOpfsSAHPoolVfs\n\tif (!install || !opfsSahSupported(sqlite3)) {\n\t\tthrow new PoolUnavailableError('OPFS SyncAccessHandle pool is not supported', 'unsupported')\n\t}\n\tlet lastError: unknown = null\n\tfor (let attempt = 0; attempt < INSTALL_RACE_ATTEMPTS; attempt += 1) {\n\t\tawait waitForPoolHandles(poolName, reporter)\n\t\ttry {\n\t\t\tconst pool = await withTimeout(\n\t\t\t\tinstall({ name: poolName, forceReinitIfPreviouslyFailed: true }),\n\t\t\t\tOPFS_INIT_TIMEOUT_MS,\n\t\t\t\t'OPFS VFS install',\n\t\t\t)\n\t\t\tif (pool.isPaused()) {\n\t\t\t\tawait pool.unpauseVfs()\n\t\t\t}\n\t\t\treturn pool\n\t\t} catch (error) {\n\t\t\tif (error instanceof PoolUnavailableError) throw error\n\t\t\tlastError = error\n\t\t\tif (!isHandleBusy(error)) break\n\t\t\tawait sleep(Math.min(25 * 2 ** attempt, 250))\n\t\t}\n\t}\n\tconst message = lastError instanceof Error ? lastError.message : String(lastError)\n\tif (isHandleBusy(lastError)) {\n\t\tthrow new PoolUnavailableError(\n\t\t\t`OPFS pool \"${poolName}\" stayed busy: ${message}`,\n\t\t\t'lock-conflict',\n\t\t)\n\t}\n\tthrow new PoolUnavailableError(\n\t\t`OPFS pool \"${poolName}\" could not be installed: ${message}`,\n\t\t'unsupported',\n\t)\n}\n\n/**\n * Grow the pool to fit the database about to be opened plus its journal before\n * opening it (NEW-STORE-7). Slots are empty pre-allocated files, so this is\n * cheap; files are never evicted.\n */\nexport async function ensurePoolCapacity(pool: OpfsPool): Promise<void> {\n\tawait pool.reserveMinimumCapacity(pool.getFileCount() + 2 + OPFS_POOL_HEADROOM)\n}\n\n/** Runs `PRAGMA quick_check` and throws unless the database reports `ok`. */\nexport function assertDatabaseHealthy(db: SqliteDb, label: string): void {\n\tconst rows = db.exec({\n\t\tsql: 'PRAGMA quick_check',\n\t\treturnValue: 'resultRows',\n\t\trowMode: 'array',\n\t}) as unknown[][]\n\tconst verdict = rows?.[0]?.[0]\n\tif (verdict !== 'ok') {\n\t\tthrow new Error(`${label} failed integrity check: ${String(verdict)}`)\n\t}\n}\n\n/** Release the pool's handles (database files must already be closed). */\nexport function pausePool(pool: OpfsPool): void {\n\tif (!pool.isPaused()) {\n\t\tpool.pauseVfs()\n\t}\n}\n\n/**\n * Move a database file from the origin-wide beta.12 pool (`kora-opfs`) into its\n * own pool, the first time the database opens under W8a.\n *\n * - Runs only when the legacy pool directory exists. Holders of the legacy pool\n *   (another migrating worker, or a beta.12 tab still open) are waited for, never\n *   raced: a beta.12 tab keeps the new tab in the reported blocking state.\n * - Opening the legacy file first lets SQLite roll back a hot journal, so the\n *   exported image is consistent. The imported copy must pass `quick_check`\n *   before the legacy copy is removed.\n * - The legacy pool is kept while it still holds other databases and removed\n *   once its last one has moved.\n *\n * @returns true when this call moved the database.\n */\nexport async function migrateFromLegacyPool(\n\tsqlite3: Sqlite3Api,\n\ttarget: OpfsPool,\n\tpoolPath: string,\n\treporter?: BlockingReporter,\n): Promise<boolean> {\n\tif (!(await poolDirectoryExists(LEGACY_OPFS_POOL_NAME))) {\n\t\treturn false\n\t}\n\tconst releaseLegacyLock = await holdExclusiveLock(\n\t\topfsPoolLockName(LEGACY_OPFS_POOL_NAME),\n\t\treporter,\n\t)\n\ttry {\n\t\t// Another worker may have finished the last migration while we waited.\n\t\tif (!(await poolDirectoryExists(LEGACY_OPFS_POOL_NAME))) {\n\t\t\treturn false\n\t\t}\n\t\tconst legacy = await installPool(sqlite3, LEGACY_OPFS_POOL_NAME, reporter)\n\t\ttry {\n\t\t\tif (!legacy.getFileNames().includes(poolPath)) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tconst legacyDb = new legacy.OpfsSAHPoolDb(poolPath)\n\t\t\ttry {\n\t\t\t\tassertDatabaseHealthy(legacyDb, `Legacy database ${poolPath}`)\n\t\t\t} finally {\n\t\t\t\tlegacyDb.close()\n\t\t\t}\n\t\t\tconst bytes = legacy.exportFile(poolPath)\n\t\t\tif (bytes.byteLength === 0) {\n\t\t\t\t// An empty file left by a failed beta.12 open holds no data.\n\t\t\t\tlegacy.unlink(poolPath)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tawait ensurePoolCapacity(target)\n\t\t\tawait target.importDb(poolPath, bytes)\n\t\t\tlet migratedDb: SqliteDb | null = null\n\t\t\ttry {\n\t\t\t\tmigratedDb = new target.OpfsSAHPoolDb(poolPath)\n\t\t\t\tassertDatabaseHealthy(migratedDb, `Migrated database ${poolPath}`)\n\t\t\t} catch (error) {\n\t\t\t\tmigratedDb?.close()\n\t\t\t\tmigratedDb = null\n\t\t\t\t// Keep the legacy copy as the source of truth; drop the bad import.\n\t\t\t\ttarget.unlink(poolPath)\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tmigratedDb.close()\n\t\t\tlegacy.unlink(poolPath)\n\t\t\tlegacy.unlink(`${poolPath}-journal`)\n\t\t\treturn true\n\t\t} finally {\n\t\t\tif (legacy.getFileCount() === 0) {\n\t\t\t\tawait legacy.removeVfs()\n\t\t\t} else {\n\t\t\t\tpausePool(legacy)\n\t\t\t}\n\t\t}\n\t} finally {\n\t\treleaseLegacyLock()\n\t}\n}\n","import { WorkerInitError } from '../errors'\n\n/** How long SQLite WASM may take to initialize before the open fails. */\nexport const SQLITE_INIT_TIMEOUT_MS = 60_000\n\n/** Subscribes to unhandled promise rejections; returns the unsubscribe function. */\nexport type UnhandledRejectionSource = (listener: (reason: unknown) => void) => () => void\n\n/** Options for {@link loadSqliteModule}. */\nexport interface LoadSqliteModuleOptions {\n\t/** Options passed to the module's init function (Emscripten module arguments). */\n\tinitOptions?: Record<string, unknown>\n\t/** Where unhandled rejections are observed. Defaults to the global scope's event. */\n\tunhandledRejections?: UnhandledRejectionSource\n\t/** Init timeout in milliseconds. Defaults to {@link SQLITE_INIT_TIMEOUT_MS}. */\n\ttimeoutMs?: number\n}\n\n/**\n * Initialize the SQLite WASM module, failing fast when the `.wasm` cannot be fetched\n * or compiled (F15).\n *\n * The sqlite-wasm build installs its own `instantiateWasm` hook, which fetches and\n * compiles the binary but drops the resulting promise: when the fetch fails (the\n * device is offline before the binary was ever cached) or the response is not WASM\n * (a 404 page), that rejection is unhandled and the module's init promise never\n * settles. Waiting for the init timeout then holds the app for a full minute. While\n * init runs, an unhandled fetch or WebAssembly error is therefore taken as the init's\n * failure and rejects at once.\n *\n * @param init - The module's init function (`@sqlite.org/sqlite-wasm`'s default export)\n * @param options - Init options, the rejection source (tests) and the timeout\n * @returns The initialized module\n * @throws {WorkerInitError} When the binary cannot be loaded, or init times out\n */\nexport async function loadSqliteModule<T>(\n\tinit: (options?: Record<string, unknown>) => Promise<unknown>,\n\toptions: LoadSqliteModuleOptions = {},\n): Promise<T> {\n\tconst timeoutMs = options.timeoutMs ?? SQLITE_INIT_TIMEOUT_MS\n\tconst source = options.unhandledRejections ?? globalUnhandledRejections\n\tlet timer: ReturnType<typeof setTimeout> | undefined\n\tlet unsubscribe: (() => void) | undefined\n\ttry {\n\t\treturn (await Promise.race([\n\t\t\tinit(options.initOptions),\n\t\t\tnew Promise<never>((_, reject) => {\n\t\t\t\tunsubscribe = source((reason) => {\n\t\t\t\t\tif (!isWasmLoadFailure(reason)) return\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew WorkerInitError(\n\t\t\t\t\t\t\t`could not load the SQLite WebAssembly binary (sqlite3.wasm): ${describe(reason)}. The device may be offline before the app was cached, or the file is not served (check the URL and the application/wasm MIME type).`,\n\t\t\t\t\t\t\t{ cause: describe(reason) },\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t})\n\t\t\t\ttimer = setTimeout(\n\t\t\t\t\t() =>\n\t\t\t\t\t\treject(\n\t\t\t\t\t\t\tnew WorkerInitError(`SQLite3 module init timed out after ${String(timeoutMs)}ms`),\n\t\t\t\t\t\t),\n\t\t\t\t\ttimeoutMs,\n\t\t\t\t)\n\t\t\t}),\n\t\t])) as T\n\t} finally {\n\t\tif (timer !== undefined) clearTimeout(timer)\n\t\tunsubscribe?.()\n\t}\n}\n\n/**\n * True for the errors a failed `.wasm` fetch or compile produces: `TypeError` from\n * `fetch` or `instantiateStreaming` (network failure, wrong MIME type) and the\n * WebAssembly compile, link and runtime errors.\n */\nfunction isWasmLoadFailure(reason: unknown): boolean {\n\tif (reason instanceof TypeError) return true\n\tconst wasm = (globalThis as { WebAssembly?: Record<string, unknown> }).WebAssembly\n\tif (!wasm) return false\n\tfor (const name of ['CompileError', 'LinkError', 'RuntimeError']) {\n\t\tconst ctor = wasm[name]\n\t\tif (typeof ctor === 'function' && reason instanceof (ctor as new () => Error)) return true\n\t}\n\treturn false\n}\n\nfunction describe(reason: unknown): string {\n\treturn reason instanceof Error ? reason.message : String(reason)\n}\n\n/** Unhandled rejections of the current global scope (a worker or a window). */\nconst globalUnhandledRejections: UnhandledRejectionSource = (listener) => {\n\tconst scope = globalThis as {\n\t\taddEventListener?: (type: string, handler: (event: { reason?: unknown }) => void) => void\n\t\tremoveEventListener?: (type: string, handler: (event: { reason?: unknown }) => void) => void\n\t}\n\tif (typeof scope.addEventListener !== 'function') return () => {}\n\tconst handler = (event: { reason?: unknown }): void => listener(event.reason)\n\tscope.addEventListener('unhandledrejection', handler)\n\treturn () => scope.removeEventListener?.('unhandledrejection', handler)\n}\n","/// <reference lib=\"webworker\" />\n/**\n * Reusable SQLite WASM core, decoupled from any specific worker global.\n *\n * The dedicated worker ({@link file://./sqlite-wasm-worker.ts}) wires one core to\n * `self.onmessage`/`self.postMessage`. Each worker serves exactly one database\n * and owns that database's OPFS SyncAccessHandle pool (one pool per database,\n * W8a). Pool ownership, the pool Web Lock and the beta.12 legacy-pool migration\n * live in {@link file://./opfs-pool-ownership.ts}.\n *\n * This file cannot be unit-tested in Node (no WASM/OPFS); it is exercised through\n * the real-browser suite.\n */\n\nimport {\n\tSTORED_FORMAT_SQL,\n\tSTORED_SCHEMA_VERSION_SQL,\n\tformatAheadMessage,\n\tparseFormatCeiling,\n\tparseSchemaCeiling,\n\tschemaAheadMessage,\n\tstoredSchemaVersion,\n} from '../migrations/schema-ceiling'\nimport { DDL_STATE_TABLE_SQL, ddlFingerprint } from './ddl-state'\nimport { opfsPoolLockName, opfsPoolNameFor, opfsPoolPath } from './opfs-names'\nimport {\n\ttype BlockingReporter,\n\ttype OpfsPool,\n\tPoolUnavailableError,\n\ttype Sqlite3Api,\n\ttype SqliteDb,\n\ttype SqliteStmt,\n\tensurePoolCapacity,\n\tholdExclusiveLock,\n\tinstallPool,\n\tmigrateFromLegacyPool,\n\topfsSahSupported,\n\tpausePool,\n} from './opfs-pool-ownership'\nimport type {\n\tBatchStatement,\n\tWorkerRequest,\n\tWorkerResponse,\n\tWorkerStatusEvent,\n} from './sqlite-wasm-channel'\nimport { loadSqliteModule } from './sqlite-wasm-loader'\n\n/** Minimum gap between progress heartbeats sent from inside a long statement. */\nconst PROGRESS_HEARTBEAT_MS = 500\n/** SQLite VM instructions between progress-handler callbacks. */\nconst PROGRESS_HANDLER_OPS = 20_000\n/** Page size of a newly created OPFS database (bytes). */\nconst OPFS_NEW_DATABASE_PAGE_SIZE = 16_384\n\nlet sqlite3Promise: Promise<Sqlite3Api> | null = null\n\nasync function loadSqlite3(): Promise<Sqlite3Api> {\n\tconst sqlite3InitModule = (await import('@sqlite.org/sqlite-wasm')).default\n\t// In production builds, Vite hashes asset filenames (e.g. sqlite3-[hash].wasm).\n\t// The sqlite3 module's default locateFile resolves the unhashed name, causing a\n\t// 404. The worker/host entry sets __KORA_SQLITE_WASM_URL via a `?url` import so\n\t// we can override locateFile with the correct hashed URL.\n\tconst wasmUrl = (globalThis as Record<string, unknown>).__KORA_SQLITE_WASM_URL as\n\t\t| string\n\t\t| undefined\n\tconst initOptions = wasmUrl\n\t\t? {\n\t\t\t\tlocateFile: (file: string): string => (file.endsWith('.wasm') ? wasmUrl : file),\n\t\t\t}\n\t\t: undefined\n\tconst initFn = sqlite3InitModule as unknown as (\n\t\topts?: Record<string, unknown>,\n\t) => Promise<unknown>\n\t// Fails fast when the .wasm cannot be fetched or compiled, instead of waiting out\n\t// the init timeout (F15).\n\treturn loadSqliteModule<Sqlite3Api>(initFn, initOptions ? { initOptions } : {})\n}\n\nfunction getSqlite3(): Promise<Sqlite3Api> {\n\tif (!sqlite3Promise) {\n\t\tconst loading = loadSqlite3()\n\t\tsqlite3Promise = loading\n\t\t// A failed load is not kept: the next open in this worker tries again (F15).\n\t\tloading.catch(() => {\n\t\t\tif (sqlite3Promise === loading) sqlite3Promise = null\n\t\t})\n\t}\n\treturn sqlite3Promise\n}\n\n/** Options for {@link createSqliteWasmCore}. */\nexport interface SqliteWasmCoreOptions {\n\t/** Posts unsolicited status (blocking state) to the tab that owns this worker. */\n\tpostEvent?: (event: WorkerStatusEvent) => void\n\t/**\n\t * Called from inside long-running statements (sqlite progress handler) so the\n\t * worker can keep announcing liveness to follower tabs while it is busy.\n\t */\n\tonProgress?: () => void\n}\n\n/** Handle to a single database, dispatching the worker protocol for it. */\nexport interface SqliteWasmCore {\n\thandle(request: WorkerRequest): Promise<WorkerResponse>\n}\n\n/**\n * Creates a core bound to one database. `handle` resolves with the response for\n * each request; the caller routes it back through the dedicated worker's\n * `postMessage`.\n */\nexport function createSqliteWasmCore(options: SqliteWasmCoreOptions = {}): SqliteWasmCore {\n\tlet db: SqliteDb | null = null\n\tlet sqlite3Api: Sqlite3Api | null = null\n\tlet persistent = false\n\tlet fallbackReason: 'timeout' | 'unsupported' | 'lock-conflict' | undefined\n\tlet pool: OpfsPool | null = null\n\tlet poolName: string | null = null\n\tlet openDbName: string | null = null\n\tlet releasePoolLock: (() => void) | null = null\n\tlet openInfo: { created: boolean; migratedFromLegacy: boolean } = {\n\t\tcreated: false,\n\t\tmigratedFromLegacy: false,\n\t}\n\tlet lastProgressBeat = 0\n\n\tfunction reporterFor(resource: 'pool' | 'legacy-pool', name: string): BlockingReporter {\n\t\treturn {\n\t\t\tblocked: () => options.postEvent?.({ kind: 'storage-blocked', resource, poolName: name }),\n\t\t\tunblocked: (waitedMs) =>\n\t\t\t\toptions.postEvent?.({ kind: 'storage-unblocked', resource, poolName: name, waitedMs }),\n\t\t}\n\t}\n\n\t/** Close the database and give the pool back: handles first, then the lock. */\n\tasync function releaseStorage(mode: 'pause' | 'remove'): Promise<void> {\n\t\tif (db) {\n\t\t\tdetachProgressHandler(db)\n\t\t\tdropStatementCache()\n\t\t\ttry {\n\t\t\t\tdb.close()\n\t\t\t} finally {\n\t\t\t\tdb = null\n\t\t\t}\n\t\t}\n\t\tif (pool) {\n\t\t\tif (mode === 'remove') {\n\t\t\t\tawait pool.removeVfs()\n\t\t\t} else {\n\t\t\t\tpausePool(pool)\n\t\t\t}\n\t\t\tpool = null\n\t\t}\n\t\treleasePoolLock?.()\n\t\treleasePoolLock = null\n\t}\n\n\tfunction attachProgressHandler(target: SqliteDb): void {\n\t\tconst register = sqlite3Api?.capi?.sqlite3_progress_handler\n\t\tif (!options.onProgress || typeof register !== 'function' || !target.pointer) return\n\t\tregister(\n\t\t\ttarget.pointer,\n\t\t\tPROGRESS_HANDLER_OPS,\n\t\t\t() => {\n\t\t\t\tconst now = Date.now()\n\t\t\t\tif (now - lastProgressBeat >= PROGRESS_HEARTBEAT_MS) {\n\t\t\t\t\tlastProgressBeat = now\n\t\t\t\t\toptions.onProgress?.()\n\t\t\t\t}\n\t\t\t\treturn 0\n\t\t\t},\n\t\t\t0,\n\t\t)\n\t}\n\n\tfunction detachProgressHandler(target: SqliteDb): void {\n\t\tconst register = sqlite3Api?.capi?.sqlite3_progress_handler\n\t\tif (typeof register !== 'function' || !target.pointer) return\n\t\ttry {\n\t\t\tregister(target.pointer, 0, 0, 0)\n\t\t} catch {\n\t\t\t// Closing the database releases the handler binding anyway.\n\t\t}\n\t}\n\n\tasync function openOpfs(\n\t\tsqlite3: Sqlite3Api,\n\t\tdbName: string,\n\t\tmustExist: boolean,\n\t): Promise<WorkerResponse | null> {\n\t\tconst name = opfsPoolNameFor(dbName)\n\t\tconst path = opfsPoolPath(dbName)\n\t\tpoolName = name\n\t\treleasePoolLock = await holdExclusiveLock(opfsPoolLockName(name), reporterFor('pool', name))\n\t\tpool = await installPool(sqlite3, name, reporterFor('pool', name))\n\n\t\tlet migratedFromLegacy = false\n\t\tif (!pool.getFileNames().includes(path)) {\n\t\t\tmigratedFromLegacy = await migrateFromLegacyPool(\n\t\t\t\tsqlite3,\n\t\t\t\tpool,\n\t\t\t\tpath,\n\t\t\t\treporterFor('legacy-pool', name),\n\t\t\t)\n\t\t}\n\t\tconst existedBefore = pool.getFileNames().includes(path)\n\t\tif (!existedBefore && mustExist) {\n\t\t\t// Do not leave behind the empty pool this probe just created.\n\t\t\tawait releaseStorage(pool.getFileCount() === 0 ? 'remove' : 'pause')\n\t\t\treturn { id: 0, type: 'error', message: `Database file ${path} not found`, code: 'NOT_FOUND' }\n\t\t}\n\t\tawait ensurePoolCapacity(pool)\n\t\ttry {\n\t\t\tdb = new pool.OpfsSAHPoolDb(path)\n\t\t} catch (error) {\n\t\t\tif (!existedBefore) pool.unlink(path)\n\t\t\tthrow error\n\t\t}\n\t\tpersistent = true\n\t\topenInfo = { created: !existedBefore, migratedFromLegacy }\n\t\treturn null\n\t}\n\n\tasync function open(\n\t\tid: number,\n\t\tddlStatements: string[],\n\t\tdbName: string,\n\t\tstorage: 'opfs' | 'memory',\n\t\tmustExist: boolean,\n\t): Promise<WorkerResponse> {\n\t\t// Re-run idempotent DDL on the existing handle rather than opening the\n\t\t// database a second time (a follower's open lands here on the leader).\n\t\tif (db) {\n\t\t\ttry {\n\t\t\t\tapplyDdlUnlessUnchanged(db, ddlStatements)\n\t\t\t\treturn { id, type: 'success', data: buildOpenData() }\n\t\t\t} catch (error) {\n\t\t\t\treturn { id, type: 'error', message: (error as Error).message, code: 'INIT_ERROR' }\n\t\t\t}\n\t\t}\n\n\t\tlet createdPath: string | null = null\n\t\ttry {\n\t\t\topenDbName = dbName\n\t\t\tconst sqlite3 = await getSqlite3()\n\t\t\tsqlite3Api = sqlite3\n\t\t\tif (storage === 'opfs' && opfsSahSupported(sqlite3)) {\n\t\t\t\ttry {\n\t\t\t\t\tconst early = await openOpfs(sqlite3, dbName, mustExist)\n\t\t\t\t\tif (early) return { ...early, id }\n\t\t\t\t\tif (openInfo.created) createdPath = opfsPoolPath(dbName)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof PoolUnavailableError) || error.reason === 'lock-conflict') {\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t\t// Only an unsupported or hung OPFS selects memory here; the adapter\n\t\t\t\t\t// then reports it (and refuses writes unless the app opted in).\n\t\t\t\t\tawait releaseStorage('pause')\n\t\t\t\t\tfallbackReason = error.reason\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfallbackReason = 'unsupported'\n\t\t\t}\n\t\t\tif (!db) {\n\t\t\t\tdb = new sqlite3.oo1.DB({ filename: ':memory:' })\n\t\t\t\tpersistent = false\n\t\t\t}\n\n\t\t\t// NEW-STORE-11: no `PRAGMA journal_mode = WAL` here. WAL needs the VFS's\n\t\t\t// shared-memory methods, which opfs-sahpool does not implement, so the pragma\n\t\t\t// was a silent no-op (the mode stayed `delete`). The OPFS database uses\n\t\t\t// SQLite's default rollback journal (DELETE), the in-memory fallback uses\n\t\t\t// `memory`; the actual mode is reported in the open result (`journalMode`).\n\t\t\tif (persistent && openInfo.created) {\n\t\t\t\t// C3: a new OPFS database uses 16 KiB pages (SQLite's default is 4 KiB). The\n\t\t\t\t// commit of a large write is dominated by OPFS writes per page (journal and\n\t\t\t\t// database); bigger pages make that 10,000-insert commit about 40% cheaper\n\t\t\t\t// while a one-row commit costs the same (measured in Chromium, see\n\t\t\t\t// docs/benchmarks/baseline.md). It only takes effect before the first table\n\t\t\t\t// exists, so existing databases keep their page size: converting them would\n\t\t\t\t// need a VACUUM of the whole file at open. Durability is unchanged: the\n\t\t\t\t// rollback journal still holds every page a transaction changes.\n\t\t\t\tdb.exec({ sql: `PRAGMA page_size = ${OPFS_NEW_DATABASE_PAGE_SIZE}` })\n\t\t\t}\n\t\t\tdb.exec({ sql: 'PRAGMA foreign_keys = ON' })\n\t\t\tapplyDdlUnlessUnchanged(db, ddlStatements)\n\t\t\tattachProgressHandler(db)\n\t\t\treturn { id, type: 'success', data: buildOpenData() }\n\t\t} catch (error) {\n\t\t\t// A failed open removes only the file this open created (never existing\n\t\t\t// or migrated data) and gives the pool and its lock back (NEW-STORE-8).\n\t\t\tconst currentPool = pool\n\t\t\tif (db) {\n\t\t\t\ttry {\n\t\t\t\t\tdb.close()\n\t\t\t\t} catch {\n\t\t\t\t\t// Already failing; the original error is what matters.\n\t\t\t\t}\n\t\t\t\tdb = null\n\t\t\t}\n\t\t\tif (createdPath && currentPool) {\n\t\t\t\ttry {\n\t\t\t\t\tcurrentPool.unlink(createdPath)\n\t\t\t\t\tcurrentPool.unlink(`${createdPath}-journal`)\n\t\t\t\t} catch {\n\t\t\t\t\t// Best effort: an empty leftover slot is harmless.\n\t\t\t\t}\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait releaseStorage('pause')\n\t\t\t} catch {\n\t\t\t\t// The worker is about to be terminated by the adapter anyway.\n\t\t\t}\n\t\t\tconst reason = error instanceof PoolUnavailableError ? error.reason : undefined\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: (error as Error).message,\n\t\t\t\tcode: 'INIT_ERROR',\n\t\t\t\tcontext: {\n\t\t\t\t\t...(reason ? { reason } : {}),\n\t\t\t\t\t...(createdPath ? { removedCreatedFile: createdPath } : {}),\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction readJournalMode(): string | undefined {\n\t\tif (!db) return undefined\n\t\ttry {\n\t\t\tlet mode: string | undefined\n\t\t\tdb.exec({\n\t\t\t\tsql: 'PRAGMA journal_mode',\n\t\t\t\trowMode: 'object',\n\t\t\t\tcallback: (row: Record<string, unknown>) => {\n\t\t\t\t\tif (typeof row.journal_mode === 'string') mode = row.journal_mode\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn mode\n\t\t} catch {\n\t\t\t// Diagnostic only: an unreadable mode must not fail the open.\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\tfunction buildOpenData(): Record<string, unknown> {\n\t\tconst journalMode = readJournalMode()\n\t\treturn {\n\t\t\t...(journalMode ? { journalMode } : {}),\n\t\t\tpersistent,\n\t\t\t...(persistent ? {} : { fallbackReason: fallbackReason ?? 'unsupported' }),\n\t\t\t...(poolName && persistent ? { poolName } : {}),\n\t\t\tcreated: openInfo.created,\n\t\t\tmigratedFromLegacy: openInfo.migratedFromLegacy,\n\t\t\t// This worker understands the `batch` request (C3).\n\t\t\tbatch: true,\n\t\t}\n\t}\n\n\t/**\n\t * Apply the schema DDL unless this exact DDL already ran on the database: its fingerprint\n\t * is stored after a successful run (`_kora_ddl_state`), so a warm open skips dozens of\n\t * idempotent statements. Identical statements carry identical schema and format\n\t * ceilings, so the newer-build checks below cannot be skipped for a database they would\n\t * refuse: a newer build's DDL differs, and the store clears the fingerprint before any\n\t * migration runs (a migration's table rebuild can drop indexes the next open re-creates).\n\t */\n\tfunction applyDdlUnlessUnchanged(target: SqliteDb, ddlStatements: string[]): void {\n\t\tconst fingerprint = ddlFingerprint(ddlStatements)\n\t\ttarget.exec({ sql: DDL_STATE_TABLE_SQL })\n\t\tlet stored: unknown = null\n\t\ttarget.exec({\n\t\t\tsql: \"SELECT value FROM _kora_ddl_state WHERE key = 'fingerprint'\",\n\t\t\trowMode: 'object',\n\t\t\tcallback: (row: Record<string, unknown>) => {\n\t\t\t\tstored = row.value\n\t\t\t},\n\t\t})\n\t\tif (stored === fingerprint) return\n\t\tapplyDdl(target, ddlStatements)\n\t\ttarget.exec({\n\t\t\tsql: \"INSERT OR REPLACE INTO _kora_ddl_state (key, value) VALUES ('fingerprint', ?)\",\n\t\t\tbind: [fingerprint],\n\t\t})\n\t}\n\n\tfunction applyDdl(target: SqliteDb, ddlStatements: string[]): void {\n\t\tfor (const sql of ddlStatements) {\n\t\t\tconst ceiling = parseSchemaCeiling(sql)\n\t\t\tif (ceiling !== null) {\n\t\t\t\t// A database a newer build migrated gets none of this build's DDL (RT-109).\n\t\t\t\tconst rows: Array<{ value: unknown }> = []\n\t\t\t\ttarget.exec({\n\t\t\t\t\tsql: STORED_SCHEMA_VERSION_SQL,\n\t\t\t\t\trowMode: 'object',\n\t\t\t\t\tcallback: (row: Record<string, unknown>) => {\n\t\t\t\t\t\trows.push({ value: row.value })\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tconst stored = storedSchemaVersion(rows)\n\t\t\t\tif (stored > ceiling) throw new Error(schemaAheadMessage(stored, ceiling))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst formatCeiling = parseFormatCeiling(sql)\n\t\t\tif (formatCeiling !== null) {\n\t\t\t\t// A database a build with a newer storage format opened gets none of this\n\t\t\t\t// build's DDL (version gate).\n\t\t\t\tconst rows: Array<{ value: unknown }> = []\n\t\t\t\ttarget.exec({\n\t\t\t\t\tsql: STORED_FORMAT_SQL,\n\t\t\t\t\trowMode: 'object',\n\t\t\t\t\tcallback: (row: Record<string, unknown>) => {\n\t\t\t\t\t\trows.push({ value: row.value })\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tconst stored = storedSchemaVersion(rows)\n\t\t\t\tif (stored > formatCeiling) throw new Error(formatAheadMessage(stored, formatCeiling))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (sql.startsWith('--kora:safe-alter')) {\n\t\t\t\ttry {\n\t\t\t\t\ttarget.exec({ sql: sql.replace('--kora:safe-alter\\n', '') })\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst msg = (error as Error).message || ''\n\t\t\t\t\tif (!msg.includes('duplicate column name')) {\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttarget.exec({ sql })\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction execute(id: number, sql: string, params?: unknown[]): WorkerResponse {\n\t\tif (!db) {\n\t\t\treturn { id, type: 'error', message: 'Database is not open', code: 'DB_NOT_OPEN' }\n\t\t}\n\t\ttry {\n\t\t\tdb.exec({ sql, bind: params })\n\t\t\treturn { id, type: 'success' }\n\t\t} catch (error) {\n\t\t\treturn { id, type: 'error', message: (error as Error).message, code: 'EXEC_ERROR' }\n\t\t}\n\t}\n\n\t/**\n\t * Prepared statements of `batch` requests, per open database. The local write\n\t * path repeats a handful of statements thousands of times in a large write, so\n\t * parsing each once saves most of SQLite's per-statement work. Statements are\n\t * reset after every use and finalized when the database closes.\n\t */\n\tlet statementCache: { owner: SqliteDb; statements: Map<string, SqliteStmt> } | null = null\n\tconst STATEMENT_CACHE_LIMIT = 64\n\tconst MAY_HOLD_SEVERAL_STATEMENTS = /;\\s*\\S/\n\n\tfunction cachedStatement(target: SqliteDb, sql: string): SqliteStmt | null {\n\t\tif (typeof target.prepare !== 'function') return null\n\t\t// `prepare` compiles only the FIRST statement of a string and drops the rest\n\t\t// silently; `exec` runs all of them. Anything that may hold a second statement\n\t\t// (a `;` followed by more text, even inside a literal) takes the `exec` path.\n\t\tif (MAY_HOLD_SEVERAL_STATEMENTS.test(sql)) return null\n\t\tif (statementCache?.owner !== target) {\n\t\t\tstatementCache = { owner: target, statements: new Map() }\n\t\t}\n\t\tconst statements = statementCache.statements\n\t\tlet statement = statements.get(sql)\n\t\tif (!statement) {\n\t\t\tif (statements.size >= STATEMENT_CACHE_LIMIT) {\n\t\t\t\tfor (const old of statements.values()) old.finalize()\n\t\t\t\tstatements.clear()\n\t\t\t}\n\t\t\tstatement = target.prepare(sql)\n\t\t\tstatements.set(sql, statement)\n\t\t}\n\t\treturn statement\n\t}\n\n\tfunction dropStatementCache(): void {\n\t\tif (!statementCache) return\n\t\tfor (const statement of statementCache.statements.values()) {\n\t\t\ttry {\n\t\t\t\tstatement.finalize()\n\t\t\t} catch {\n\t\t\t\t// Closing the database finalizes it anyway.\n\t\t\t}\n\t\t}\n\t\tstatementCache = null\n\t}\n\n\t/**\n\t * Run the write statements of an open transaction in order. Stops at the first\n\t * failure; `context.index` names the failing statement. Statements before it ran\n\t * inside the caller's transaction, which the caller rolls back.\n\t */\n\tfunction batch(id: number, statements: BatchStatement[]): WorkerResponse {\n\t\tif (!db) {\n\t\t\treturn { id, type: 'error', message: 'Database is not open', code: 'DB_NOT_OPEN' }\n\t\t}\n\t\tfor (let index = 0; index < statements.length; index++) {\n\t\t\tconst statement = statements[index]\n\t\t\tif (!statement) continue\n\t\t\ttry {\n\t\t\t\tconst prepared = cachedStatement(db, statement.sql)\n\t\t\t\tif (prepared === null) {\n\t\t\t\t\tdb.exec({ sql: statement.sql, bind: statement.params })\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tif (statement.params !== undefined && statement.params.length > 0) {\n\t\t\t\t\t\tprepared.bind(statement.params)\n\t\t\t\t\t}\n\t\t\t\t\tprepared.step()\n\t\t\t\t} finally {\n\t\t\t\t\tprepared.reset(true)\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tid,\n\t\t\t\t\ttype: 'error',\n\t\t\t\t\tmessage: (error as Error).message,\n\t\t\t\t\tcode: 'EXEC_ERROR',\n\t\t\t\t\tcontext: { index, sql: statement.sql },\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { id, type: 'success' }\n\t}\n\n\tfunction query(id: number, sql: string, params?: unknown[]): WorkerResponse {\n\t\tif (!db) {\n\t\t\treturn { id, type: 'error', message: 'Database is not open', code: 'DB_NOT_OPEN' }\n\t\t}\n\t\ttry {\n\t\t\tconst rows: Record<string, unknown>[] = []\n\t\t\tdb.exec({\n\t\t\t\tsql,\n\t\t\t\tbind: params,\n\t\t\t\trowMode: 'object',\n\t\t\t\tcallback: (row: Record<string, unknown>) => {\n\t\t\t\t\trows.push({ ...row })\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn { id, type: 'success', data: rows }\n\t\t} catch (error) {\n\t\t\treturn { id, type: 'error', message: (error as Error).message, code: 'QUERY_ERROR' }\n\t\t}\n\t}\n\n\tasync function close(id: number, mode: 'pause' | 'remove'): Promise<WorkerResponse> {\n\t\ttry {\n\t\t\tawait releaseStorage(mode)\n\t\t\treturn { id, type: 'success' }\n\t\t} catch (error) {\n\t\t\treturn { id, type: 'error', message: (error as Error).message, code: 'CLOSE_ERROR' }\n\t\t}\n\t}\n\n\tfunction migrate(id: number, statements: string[]): WorkerResponse {\n\t\tif (!db) {\n\t\t\treturn { id, type: 'error', message: 'Database is not open', code: 'DB_NOT_OPEN' }\n\t\t}\n\t\ttry {\n\t\t\tfor (const sql of statements) {\n\t\t\t\tdb.exec({ sql })\n\t\t\t}\n\t\t\treturn { id, type: 'success' }\n\t\t} catch (error) {\n\t\t\treturn { id, type: 'error', message: (error as Error).message, code: 'MIGRATE_ERROR' }\n\t\t}\n\t}\n\n\tfunction importData(id: number, data: Uint8Array): WorkerResponse {\n\t\tif (!db) {\n\t\t\treturn { id, type: 'error', message: 'Database is not open', code: 'DB_NOT_OPEN' }\n\t\t}\n\t\tif (typeof db.deserialize === 'function') {\n\t\t\tdropStatementCache()\n\t\t\ttry {\n\t\t\t\tdb.deserialize(data)\n\t\t\t\treturn { id, type: 'success' }\n\t\t\t} catch (error) {\n\t\t\t\treturn { id, type: 'error', message: (error as Error).message, code: 'IMPORT_ERROR' }\n\t\t\t}\n\t\t}\n\t\tif (!sqlite3Api || typeof sqlite3Api.capi?.sqlite3_deserialize === 'undefined') {\n\t\t\treturn {\n\t\t\t\tid,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: 'Import not supported in this SQLite WASM runtime',\n\t\t\t\tcode: 'IMPORT_NOT_SUPPORTED',\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tid,\n\t\t\ttype: 'error',\n\t\t\tmessage:\n\t\t\t\t'Import requires runtime-specific deserialize wiring and is unavailable in this worker build',\n\t\t\tcode: 'IMPORT_NOT_SUPPORTED',\n\t\t}\n\t}\n\n\tasync function handle(request: WorkerRequest): Promise<WorkerResponse> {\n\t\ttry {\n\t\t\tswitch (request.type) {\n\t\t\t\tcase 'open':\n\t\t\t\t\treturn await open(\n\t\t\t\t\t\trequest.id,\n\t\t\t\t\t\trequest.ddlStatements,\n\t\t\t\t\t\trequest.dbName ?? 'kora-db',\n\t\t\t\t\t\trequest.storage ?? 'opfs',\n\t\t\t\t\t\trequest.mustExist === true,\n\t\t\t\t\t)\n\t\t\t\tcase 'close':\n\t\t\t\t\treturn await close(request.id, 'pause')\n\t\t\t\tcase 'destroy':\n\t\t\t\t\treturn await close(request.id, 'remove')\n\t\t\t\tcase 'execute':\n\t\t\t\t\treturn execute(request.id, request.sql, request.params)\n\t\t\t\tcase 'query':\n\t\t\t\t\treturn query(request.id, request.sql, request.params)\n\t\t\t\tcase 'batch':\n\t\t\t\t\treturn batch(request.id, request.statements)\n\t\t\t\tcase 'begin':\n\t\t\t\t\treturn execute(request.id, 'BEGIN')\n\t\t\t\tcase 'commit':\n\t\t\t\t\treturn execute(request.id, 'COMMIT')\n\t\t\t\tcase 'rollback':\n\t\t\t\t\treturn execute(request.id, 'ROLLBACK')\n\t\t\t\tcase 'migrate':\n\t\t\t\t\treturn migrate(request.id, request.statements)\n\t\t\t\tcase 'import':\n\t\t\t\t\treturn importData(request.id, request.data)\n\t\t\t\tcase 'export':\n\t\t\t\t\tif (!db || !openDbName) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tid: request.id,\n\t\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\t\tmessage: 'Database is not open',\n\t\t\t\t\t\t\tcode: 'DB_NOT_OPEN',\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (persistent && pool) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tid: request.id,\n\t\t\t\t\t\t\ttype: 'success',\n\t\t\t\t\t\t\tdata: pool.exportFile(opfsPoolPath(openDbName)),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (db.pointer && sqlite3Api?.capi?.sqlite3_js_db_export) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tid: request.id,\n\t\t\t\t\t\t\ttype: 'success',\n\t\t\t\t\t\t\tdata: sqlite3Api.capi.sqlite3_js_db_export(db.pointer),\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid: request.id,\n\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\tmessage: 'SQLite binary export is unavailable in this runtime',\n\t\t\t\t\t\tcode: 'EXPORT_NOT_SUPPORTED',\n\t\t\t\t\t}\n\t\t\t\tcase 'serve':\n\t\t\t\t\t// Handled by the worker entry, which owns the BroadcastChannel.\n\t\t\t\t\treturn { id: request.id, type: 'success' }\n\t\t\t\tdefault:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tid: (request as WorkerRequest).id,\n\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\tmessage: 'Unknown request type',\n\t\t\t\t\t\tcode: 'UNKNOWN_REQUEST',\n\t\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tid: request.id,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: (error as Error).message,\n\t\t\t\tcode: 'WORKER_ERROR',\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { handle }\n}\n","/// <reference lib=\"webworker\" />\n/**\n * Web Worker script for running SQLite WASM in a dedicated worker.\n *\n * One worker serves one database. Requests from the owning (leader) tab arrive\n * by postMessage; requests from follower tabs arrive on the database's\n * BroadcastChannel once the leader sends `serve`. Both go through one\n * {@link TransactionSerializingWorkerBridge}, so transaction spans from different\n * tabs never interleave, and the leader tab's main thread is not on the\n * follower path at all.\n *\n * This script cannot be tested in Node.js; it is validated in browser suites.\n */\n\nimport { TransactionSerializingWorkerBridge, startWorkerRpcRelay } from '../multi-tab/tab-storage'\nimport type { WorkerRpcRelay } from '../multi-tab/tab-storage'\nimport type {\n\tWorkerEventMessage,\n\tWorkerInboundMessage,\n\tWorkerResponse,\n} from './sqlite-wasm-channel'\nimport { createSqliteWasmCore } from './sqlite-wasm-worker-core'\n\ndeclare const self: DedicatedWorkerGlobalScope\n\nlet relay: WorkerRpcRelay | null = null\n\nconst core = createSqliteWasmCore({\n\tpostEvent: (event) => {\n\t\tconst message: WorkerEventMessage = { id: -1, type: 'event', event }\n\t\tself.postMessage(message)\n\t},\n\t// Keep followers' watchdogs fed while a long statement blocks this worker.\n\tonProgress: () => relay?.beat(),\n})\n\nconst serializer = new TransactionSerializingWorkerBridge(\n\t{\n\t\tsend: (request) => core.handle(request),\n\t\tterminate: () => {},\n\t},\n\tundefined,\n\t{\n\t\t// The worker's transaction state is unknown: it never runs another request.\n\t\t// Followers get a retriable error for every request; the owning tab\n\t\t// terminates this worker (discarding any open transaction) and re-attaches.\n\t\tonBroken: (reason) => {\n\t\t\tconst message: WorkerEventMessage = {\n\t\t\t\tid: -1,\n\t\t\t\ttype: 'event',\n\t\t\t\tevent: { kind: 'worker-broken', reason },\n\t\t\t}\n\t\t\tself.postMessage(message)\n\t\t},\n\t},\n)\n\nself.onmessage = (event: MessageEvent<WorkerInboundMessage>): void => {\n\tconst { clientId, ...request } = event.data\n\tif (request.type === 'serve') {\n\t\tif (!relay) {\n\t\t\trelay = startWorkerRpcRelay(\n\t\t\t\trequest.channelName,\n\t\t\t\tserializer,\n\t\t\t\trequest.identity ? { identity: request.identity } : {},\n\t\t\t)\n\t\t}\n\t\tconst response: WorkerResponse = { id: request.id, type: 'success' }\n\t\tself.postMessage(response)\n\t\treturn\n\t}\n\tvoid serializer.send(request, clientId).then(\n\t\t(response) => {\n\t\t\tif (request.type === 'close' || request.type === 'destroy') {\n\t\t\t\t// The pool is released; stop answering followers for this database.\n\t\t\t\trelay?.stop()\n\t\t\t\trelay = null\n\t\t\t}\n\t\t\tself.postMessage(response)\n\t\t},\n\t\t(error: unknown) => {\n\t\t\tconst response: WorkerResponse = {\n\t\t\t\tid: request.id,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\tcode: errorCode(error) ?? 'WORKER_ERROR',\n\t\t\t}\n\t\t\tself.postMessage(response)\n\t\t},\n\t)\n}\n\nfunction errorCode(error: unknown): string | undefined {\n\tconst code = (error as { code?: unknown } | null)?.code\n\treturn typeof code === 'string' ? code : undefined\n}\n"]}