import { KoraEventEmitter, SchemaDefinition } from '@korajs/core'; import { a as WorkerSendOptions, b as WorkerResponse, W as WorkerBridge } from '../sqlite-wasm-channel-8-TlaBEp.js'; export { c as WebWorkerBridge, d as WorkerRequest, e as WorkerStatusEvent } from '../sqlite-wasm-channel-8-TlaBEp.js'; import { S as StorageAdapter, T as Transaction, V as VersionGate, b as StorageOpenState, c as StorageEvidence, M as MigrationPlan, L as LocalDatabaseRecord } from '../types-BVVjCckP.js'; export { d as LocalDatabaseBackend } from '../types-BVVjCckP.js'; import '@korajs/core/lite'; /** * Async mutex for serializing access to a resource across `await` boundaries. * * This exists because an adapter's `transaction()` is async (its callback may * await), but the underlying database transaction (BEGIN…COMMIT) is not * reentrant: starting a second transaction while one is open is an error. When * a client applies a relayed remote operation while a local write is in flight, * the two `transaction()` calls interleave at their `await` points, and without * serialization the second `BEGIN` collides with the first, silently dropping * the operation. Serializing every transaction through this mutex guarantees at * most one is active at a time. */ declare class Mutex { private locked; private readonly waiters; /** * Acquire the mutex. Resolves with a release function once the lock is held. * If the mutex is already held, the caller waits (FIFO) until it is released. */ acquire(): Promise<() => void>; private createRelease; } /** * Multi-tab SQLite storage coordination via `navigator.locks` and `BroadcastChannel`. * * One tab holds the exclusive `kora-leader-${dbName}` lock and owns the SQLite * worker. Other tabs send worker RPC over a named broadcast channel. In browsers * the leader's WORKER answers that channel itself ({@link startWorkerRpcRelay}), * so a hung leader main thread never blocks other tabs, and it pushes heartbeats * (also from inside long statements) that followers use to detect a hung or * frozen leader (NEW-STORE-9). */ /** * What a follower needs to route its durability barrier to the leader tab: implemented * by {@link FollowerBroadcastBridge}. */ interface SnapshotBarrierClient { requestSnapshotBarrier(options?: WorkerSendOptions): Promise; } /** Per-request options for {@link SqliteWasmAdapter.execute} and `query`. */ interface StorageRequestOptions { /** * Stop waiting for the response. The leader may still apply a write that * already reached it; retry with the same `requestId` to stay idempotent. */ signal?: AbortSignal; /** * Stable id for this request. A follower tab's retry with the same id is * answered from the leader's response cache instead of being applied twice. */ requestId?: string; } /** * Options for creating a SqliteWasmAdapter. */ interface SqliteWasmAdapterOptions { /** * Injected WorkerBridge for testing. If omitted, a WebWorkerBridge is created * in browser environments. */ bridge?: WorkerBridge; /** * Database name for persistence. Each database gets its own OPFS pool. */ dbName?: string; /** * URL to the sqlite-wasm-worker script. Required in browsers if no bridge is provided. */ workerUrl?: string | URL; /** Timeout for worker / follower RPC responses. Defaults to 30000ms. */ workerResponseTimeoutMs?: number; /** * When false, the adapter records a non-persistent open without emitting * `store:opfs-unavailable`. `createApp()` uses this while it promotes the store * to durable IndexedDB; direct adapter users keep the diagnostic by default. */ emitNonPersistentDiagnostic?: boolean; /** * Accept writes when durable OPFS storage could not be obtained and the * database runs in memory. Defaults to false: a non-durable open or promotion * emits the blocking `store:durability-lost` event and every write is refused * with {@link StorageDurabilityError}, so data is never accepted and then lost * on reload. Set true only for apps that can tolerate losing local writes. */ allowNonDurable?: boolean; /** * For `createApp()`: skip the durability check at open only, because the caller * inspects {@link SqliteWasmAdapter.getStorageOpenState} right after open and * switches to a durable backend itself. A later leader promotion that loses * durable storage is still enforced. */ deferOpenDurabilityCheck?: boolean; /** * Release storage ownership when the page is frozen or hidden into the * back/forward cache (`freeze` / `pagehide`), so a visible tab can take over * instead of waiting on a tab that cannot run; ownership is re-acquired on * `resume` / `pageshow`. Defaults to true. */ releaseOnFreeze?: boolean; /** * When set, storage diagnostics are emitted here: `store:opfs-unavailable`, * `store:durability-lost`, `store:storage-blocked` (another holder has the * storage; the open waits), `store:storage-migrated` and * `store:db-name-collision`. */ emitter?: KoraEventEmitter; /** * @internal Used by the IndexedDB adapter: open an in-memory database that * never touches OPFS (the IndexedDB adapter persists snapshots itself). */ storage?: 'opfs' | 'memory'; /** * Creates the bridge of a scratch in-memory database for staged replication (tests and * embedders with their own worker). Without it, a browser adapter starts one more * dedicated worker from {@link workerUrl}; an adapter with an injected bridge and no * factory has no staging database. */ stagingBridgeFactory?: () => WorkerBridge | Promise; /** * @internal Do not read or write the storage manifest (the IndexedDB adapter's * inner database and its one-shot OPFS reader manage the manifest themselves). */ skipBackendRecord?: boolean; /** * @internal Used by the IndexedDB adapter (STORE-6): runs in one transaction on this * tab's OWN worker right after it opened the database as storage leader (first open * or promotion), before the worker serves any other tab. The IndexedDB adapter * restores its persisted snapshot here, so a snapshot is only ever restored into a * freshly created worker database and never over a leader's live one. Throwing fails * the open (or the promotion, which then refuses writes). */ onLeaderWorkerOpened?: (tx: Transaction) => Promise; /** * @internal Used by the IndexedDB adapter: called with the storage channel name each * time this tab's own worker starts serving other tabs (first open and promotion). * Returns the function that stops what it started; it is called when this tab stops * leading (close, freeze, retirement) or before the next call. The IndexedDB adapter * answers followers' durability barriers here, because only the leader tab holds the * snapshot scheduler. */ onLeaderServing?: (channelName: string) => () => void; /** * The version gate of this database (`docs/design/version-gate.md`): one build of the * app writes it at a time. In a browser (worker path) the adapter creates one when this * is omitted, with `build` (or a schema fingerprint when no build is given). `false` * disables it (a short-lived reader that is not a tab of its own). */ versionGate?: VersionGate | false; /** Build id for the version gate the adapter creates (ignored with `versionGate`). */ build?: string; /** * Open single-tab in a browser without Web Locks instead of refusing * (`TabCoordinationUnavailableError`). For test environments (jsdom, happy-dom). */ allowUncoordinatedTabs?: boolean; /** * @internal Used by the IndexedDB adapter: it opens the version gate, drives the page * lifecycle and seals its own writes; this adapter only gives up its storage roles when * the tab retires and checks the gate before it leads. */ versionGateManagedByParent?: boolean; } /** * SQLite WASM adapter that communicates with a SQLite instance through a WorkerBridge. * * In browsers, one tab per database (the leader) runs a dedicated worker that * owns the database's OPFS pool; other tabs reach that worker over a * BroadcastChannel. In Node.js tests, the bridge is backed by MockWorkerBridge * wrapping better-sqlite3. * * Storage is durable or loud, never silently in memory (W8a): another holder of * the storage makes the open wait (reported with `store:storage-blocked`); only a * runtime without OPFS SAH support gets a non-durable database, which refuses * writes unless the app opted in with `allowNonDurable`. * * @example * ```typescript * // Browser usage * const adapter = new SqliteWasmAdapter({ workerUrl: '/sqlite-wasm-worker.js' }) * * // Test usage with MockWorkerBridge * import { MockWorkerBridge } from './sqlite-wasm-mock-bridge' * const adapter = new SqliteWasmAdapter({ bridge: new MockWorkerBridge() }) * ``` */ declare class SqliteWasmAdapter implements StorageAdapter { private bridge; /** The dedicated worker this tab runs while it is the database's leader. */ private ownWorker; private opened; private readonly mutex; /** * Bridges whose worker announced the `batch` request in its open response. Only * those get batches: a leader worker from an older build (another tab still on * the previous deploy) gets the statements one `execute` at a time, as before. */ private readonly batchCapable; private readonly injectedBridge; private readonly stagingBridgeFactory; private readonly workerUrl; private readonly workerResponseTimeoutMs; private readonly dbName; private readonly emitter; private tabSession; private readonly emitNonPersistentDiagnostic; private storageOpenState; /** What survived outside the database when this leader opened it (null: not tracked). */ private evidence; /** Retained so a follower promoted to leader can re-open its own worker. */ private schema; private promoting; private closing; private suspended; /** Requests wait here while leadership changes hands (promotion, resume). */ private gate; private removeLifecycleListeners; private readonly allowNonDurable; private readonly deferOpenDurabilityCheck; private readonly releaseOnFreeze; private readonly storage; private readonly skipBackendRecord; /** Set when this adapter lost (or never had) durable storage; writes are refused. */ private durabilityLoss; private readonly onLeaderWorkerOpened; private readonly onLeaderServing; /** Stops what {@link onLeaderServing} started for the current leader worker. */ private stopLeaderServing; /** The version gate of this database, or null where it does not apply. */ private readonly versionGate; private readonly gateManagedByParent; /** Admits this adapter's writes until the tab retires (version gate, section 5). */ private readonly writes; /** Set once this tab gave up its storage roles for a newer build: reads only. */ private retiredStorage; constructor(options?: SqliteWasmAdapterOptions); /** * The version gate this adapter's tab declares, for the store and the app (which * register their own retirement steps). Null when the gate does not apply here, or when * a parent adapter owns it. */ getVersionGate(): VersionGate | null; open(schema: SchemaDefinition): Promise; /** * Join the database as leader (own worker) or follower (RPC to the leader's * worker), then open it. The open waits, without a timeout, while another * holder still has the storage; the worker reports that as a blocking state. */ private attachAndOpen; /** Open the database in this tab's own worker and start serving followers. */ private openLeaderWorker; /** Start what the owner serves to followers beside the worker's relay (see the option). */ private startLeaderServing; /** Stop answering followers on the owner's behalf (this tab no longer leads). */ private stopServing; /** * The link this tab uses to route a durability barrier to the leader tab, or null when * it leads itself or has no follower link (suspended, retired, closed). */ snapshotBarrierClient(): SnapshotBarrierClient | null; /** * Whether this runtime owns the database's worker: the storage leader in a browser, * or any adapter with an injected bridge (tests, Node). A follower tab relays every * request to the leader's worker (STORE-6). */ isLeader(): boolean; private checkedOpen; private openCurrentBridge; private onWorkerEvent; /** * Leader-only bookkeeping after a durable open: report a legacy-pool * migration, move an IndexedDB-held copy into OPFS explicitly (never two * disjoint copies), and record OPFS as this database's backend. */ private afterLeaderOpen; private applyDumpThroughWorker; /** * Surface a `store:opfs-unavailable` diagnostic when the worker reported that * persistence silently degraded to an in-memory database, so a data-loss * condition is observable instead of failing silently. A persistent open (or a * bridge that does not report a mode, e.g. the Node mock) emits nothing. */ private reportStorageMode; getStorageOpenState(): StorageOpenState | null; /** * A scratch in-memory database in a worker of its own, for staged replication (see * `StorageAdapter.createStagingAdapter`). It never touches OPFS, the tab storage session * or the version gate, so another tab cannot adopt it as a follower and it leaves nothing * behind: closing the adapter terminates the worker, and so does the page. */ createStagingAdapter(): Promise; getStorageEvidence(): StorageEvidence | null; /** * Durable or loud, never silent (NEW-STORE-6). When the open or a promotion * ended on non-persistent storage and the app did not opt into that, emit the * blocking `store:durability-lost` event and refuse every later write. A * bridge that reports no mode (the Node mock) is not judged. */ private enforceDurability; /** True while writes are refused for lack of durable storage (see {@link StorageAdapter.refusesWrites}). */ refusesWrites(): boolean; private guardDurableWrite; /** * Close the database. A leader closes the database file and releases the OPFS * pool inside its worker, terminates the worker, and only then releases the * tab leader lock, so the next leader never races a still-running worker for * the file handles (NEW-STORE-10). A follower just leaves. */ close(): Promise; /** * Release everything this adapter holds, in ownership order: lifecycle * listeners, then the worker (which holds the OPFS pool and its Web Lock), * then the tab leader lock or queued promotion request. */ private teardown; /** * Promotes a follower to leader after the previous leader released the storage * lock (its tab closed, crashed, or suspended on freeze). The new worker waits * on the pool's Web Lock and handles, so it never races the previous worker. * Requests issued during the hand-off wait for it; requests that were in * flight to the old leader fail with a retriable `BridgeTerminatedError`. */ private promoteToLeader; /** * Page Lifecycle: a frozen or bfcached page cannot run, so it must not keep * other tabs waiting on its storage. Leaders terminate their worker (freeing * the OPFS pool) and then release the leader lock, so a visible tab is * promoted; followers withdraw their queued lock request so a frozen tab is * never granted leadership it cannot use. Never uses Web Locks `steal`. */ private installLifecycleListeners; /** * The leader worker stopped serving because its transaction state is unknown. * Replace it through the suspend/resume path: terminate it (which discards any * open transaction and frees the pool), release the leader lock, re-attach. The * broken worker never runs another request in the meantime. */ private replaceBrokenWorker; /** * @internal The page is being frozen or hidden into the back/forward cache: release the * storage roles (and, unless a parent adapter manages it, the version gate tab lock). * The IndexedDB adapter calls this once its snapshot holds every committed write. */ suspendForLifecycle(): boolean; /** * @internal The page resumed but a newer build opened meanwhile (the version gate did not * let this tab resume): never re-attach, and let the requests queued behind the suspension * fail (retriably, {@link BuildSupersededError}) so the retirement's drain completes. */ abandonLifecycleSuspension(): void; /** @internal The page is running again: re-attach (see {@link suspendForLifecycle}). */ resumeForLifecycle(): Promise; /** * Synchronous by necessity: a `freeze` handler gets no further turns. Returns whether the * storage roles were released: not while opening, promoting, closing or retiring, where * the tab keeps them (and so must keep its version gate tab lock too). */ private suspend; private resume; /** * Non-transactional write. Takes the same mutex as {@link transaction}, so it * never lands inside this tab's open transaction and is never rolled back * with it (STORE-8). Inside a transaction callback, use the `tx` handle. */ execute(sql: string, params?: unknown[], options?: StorageRequestOptions): Promise; private executeNow; /** * Non-transactional read. Waits for this tab's open transaction to finish, so * it never observes uncommitted (possibly rolled-back) rows (STORE-8). */ query(sql: string, params?: unknown[], options?: StorageRequestOptions): Promise; transaction(fn: (tx: Transaction) => Promise): Promise; private transactionNow; migrate(from: number, to: number, migration: MigrationPlan): Promise; private migrateNow; /** * Export the database as a Uint8Array (for IndexedDB persistence). * Only available when the database is open. */ exportDatabase(): Promise; /** * Import a serialized database snapshot. */ importDatabase(data: Uint8Array): Promise; private importDatabaseNow; /** * Version gate, step 6: give up this tab's storage roles for a newer build. A leader * first waits for every other retiring tab to finish (their retirement may still need * this worker), then terminates its worker and releases the leader lock; a follower * withdraws its queued promotion. The tab then reads through the newer build's leader * and never writes again. */ private giveUpStorageRoles; /** * Why this tab may not start a worker of its build now (closing, retired, or its version * gate superseded or closed), or null. Checked after every await before a worker starts. */ private workerStartRefusal; private guardOpen; private sendRequest; /** * No worker to send to: a tab retiring for a newer build (between abandoning a lifecycle * suspension and its roles step) refuses retriably; otherwise the store is not open. */ private noBridgeError; } /** * Explicit management of the local databases on this origin (W8a, NEW-STORE-7). * * Kora never evicts a database on its own: a full pool is prevented by * per-database pools and capacity reservation, and removing data is always an * explicit call that refuses while the database is open or still holds * operations the server has not acknowledged. */ /** Read-only access to a database handed to the unsynced-data check. */ interface LocalDatabaseReader { dbName: string; query(sql: string, params?: unknown[]): Promise; } /** Options for {@link deleteLocalDatabase}. */ interface DeleteLocalDatabaseOptions { /** URL of the Kora SQLite worker (the same one the app's store uses). */ workerUrl: string | URL; /** * Decides whether the database still holds operations the server never * acknowledged. Injected by the app layer, which knows its sync setup. * When it returns true the delete is refused with {@link UnsyncedDataError}. */ hasUnsyncedOperations?: (db: LocalDatabaseReader) => Promise; /** Delete even when unsynced operations exist (they are lost). */ force?: boolean; /** Worker response timeout. Defaults to 30000ms. */ workerResponseTimeoutMs?: number; } /** Options for {@link exportLocalDatabase}. */ interface ExportLocalDatabaseOptions { /** URL of the Kora SQLite worker (the same one the app's store uses). */ workerUrl: string | URL; /** Worker response timeout. Defaults to 30000ms; the export itself has no timeout. */ workerResponseTimeoutMs?: number; } /** * Databases Kora has recorded on this origin (created or opened since W8a). * A database still in the pre-W8a shared pool appears after its first open. */ declare function listLocalDatabases(): Promise; /** * Export a closed local database as a standard SQLite file. * * The authoritative backend is selected from Kora's storage manifest. The * database leader lock is held for the entire read, so the returned bytes are a * consistent committed snapshot and no tab can write concurrently. This method * never migrates, verifies, deletes, or otherwise changes the source database. * * @throws {@link StorageInUseError} when a tab has the database open. * @throws {@link LocalDatabaseNotFoundError} when no authoritative copy exists. */ declare function exportLocalDatabase(dbName: string, options: ExportLocalDatabaseOptions): Promise; /** * Permanently delete a local database and its OPFS pool or IndexedDB copy. * * Refuses with {@link StorageInUseError} while any tab has the database open, * and with {@link UnsyncedDataError} while `hasUnsyncedOperations` reports * unsynced operations (unless `force`). Never touches any other database. * * @returns true when something was deleted, false when the database did not exist */ declare function deleteLocalDatabase(dbName: string, options: DeleteLocalDatabaseOptions): Promise; /** * The OPFS SAH pool that owns `dbName`. Database names that are already safe * map to `kora-opfs-`; anything sanitized or truncated gets a hash suffix * so two distinct names can never share a pool. * * @example opfsPoolNameFor('school__user_alice') === 'kora-opfs-school__user_alice' */ declare function opfsPoolNameFor(dbName: string): string; export { type DeleteLocalDatabaseOptions, type ExportLocalDatabaseOptions, type LocalDatabaseReader, LocalDatabaseRecord, Mutex, SqliteWasmAdapter, type SqliteWasmAdapterOptions, type StorageRequestOptions, WorkerBridge, WorkerResponse, WorkerSendOptions, deleteLocalDatabase, exportLocalDatabase, listLocalDatabases, opfsPoolNameFor };