{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/chunk-VIOEUPMS.cjs","../src/adapters/sqlite-wasm-adapter.ts","../src/adapters/database-dump.ts","../src/adapters/sqlite-wasm-persistence.ts","../src/adapters/storage-manifest.ts","../src/adapters/storage-evidence.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;AC7BA,oCAAgC;AD+BhC;AACA;AEhCA;AA+BO,SAAS,oBAAA,CAAqB,UAAA,EAA4B;AAChE,EAAA,GAAA,CAAI,CAAC,iBAAA,CAAkB,IAAA,CAAK,UAAU,CAAA,EAAG;AACxC,IAAA,MAAM,IAAI,uCAAA,CAAiB,CAAA,uBAAA,EAA0B,UAAU,CAAA,CAAA;AACxD,MAAA;AACN,MAAA;AACA,IAAA;AACF,EAAA;AACO,EAAA;AACR;AAMwE;AAC/C,EAAA;AACvB,IAAA;AACD,EAAA;AACwC,EAAA;AACN,EAAA;AACmB,IAAA;AAC0B,IAAA;AACU,IAAA;AAC5E,IAAA;AACL,MAAA;AACyD,MAAA;AACnB,MAAA;AAC5C,MAAA;AACA,IAAA;AACF,EAAA;AACgB,EAAA;AACjB;AAiBmB;AACmB,EAAA;AACJ,EAAA;AACwB,IAAA;AACG,IAAA;AAC/C,IAAA;AACoB,MAAA;AACzB,IAAA;AACmD,MAAA;AAC/B,MAAA;AACoC,MAAA;AAC/D,IAAA;AAC8C,IAAA;AAChB,IAAA;AACC,MAAA;AACmB,QAAA;AACjD,MAAA;AAC0B,MAAA;AAEG,MAAA;AAEb,MAAA;AACwC,QAAA;AACZ,QAAA;AAC3C,MAAA;AACF,IAAA;AACD,EAAA;AACO,EAAA;AACR;AAM2F;AACjC,EAAA;AAC3C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AA;AAAA;AAAA;AAMmF,EAAA;AACpC,IAAA;AACgB,IAAA;AAC/D,EAAA;AACD;AASiB;AACsE,EAAA;AAC3C,IAAA;AACX,IAAA;AACgC,MAAA;AAC9C,QAAA;AAC8C,QAAA;AAC7D,MAAA;AACF,IAAA;AACO,IAAA;AACR,EAAA;AAC4C,EAAA;AACxC,EAAA;AACM,IAAA;AACwB,MAAA;AACqB,QAAA;AACrD,MAAA;AACmE,MAAA;AACT,QAAA;AACI,QAAA;AAC9D,MAAA;AACA,IAAA;AAC6C,IAAA;AAC/B,EAAA;AAC4C,IAAA;AACrD,IAAA;AACP,EAAA;AACD;AAG8F;AAC3B,EAAA;AACnE;AAEuE;AACvB,EAAA;AACvC,IAAA;AACR,EAAA;AACa,EAAA;AAM6B,EAAA;AAClC,IAAA;AACR,EAAA;AACO,EAAA;AACW,IAAA;AACgB,IAAA;AAC+B,IAAA;AACP,IAAA;AACM,IAAA;AAChE,EAAA;AACD;ADkOoE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/kora/kora/packages/store/dist/chunk-VIOEUPMS.cjs","sourcesContent":[null,"import { generateFullDDL } from '@korajs/core'\nimport type { KoraEventEmitter, SchemaDefinition } from '@korajs/core'\nimport {\n\tAdapterError,\n\tBridgeTerminatedError,\n\tBuildSupersededError,\n\tStorageDurabilityError,\n\tStoreNotOpenError,\n\tVersionGateClosedError,\n} from '../errors'\nimport {\n\tFollowerBroadcastBridge,\n\ttype SnapshotBarrierClient,\n\ttype TabStorageSession,\n\tacquireTabStorageSession,\n\tisMultiTabStorageSupported,\n\tisSnapshotBarrierClient,\n} from '../multi-tab/tab-storage'\nimport { type SupersededInfo, VersionGate } from '../multi-tab/version-gate'\nimport { WriteGate } from '../multi-tab/write-gate'\nimport type {\n\tMigrationPlan,\n\tStorageAdapter,\n\tStorageFallbackReason,\n\tStorageOpenState,\n\tTransaction,\n\tTransactionStatement,\n} from '../types'\nimport { restoreDumpStatements } from './database-dump'\nimport type { DatabaseDump } from './database-dump'\nimport { storageChannelName as storageChannelNameFor } from './opfs-names'\nimport { Mutex } from './sqlite-wasm-channel'\nimport type {\n\tWebWorkerBridge,\n\tWorkerBridge,\n\tWorkerRequest,\n\tWorkerResponse,\n\tWorkerSendOptions,\n\tWorkerStatusEvent,\n} from './sqlite-wasm-channel'\nimport { deleteFromIndexedDB, loadDumpFromIndexedDB } from './sqlite-wasm-persistence'\nimport { StorageEvidence, readFoundStorageEvidence } from './storage-evidence'\nimport { isManifestAvailable, recordDatabase } from './storage-manifest'\n\ntype WorkerSuccessResponse = Extract<WorkerResponse, { type: 'success' }>\n\n/** Per-request options for {@link SqliteWasmAdapter.execute} and `query`. */\nexport interface StorageRequestOptions {\n\t/**\n\t * Stop waiting for the response. The leader may still apply a write that\n\t * already reached it; retry with the same `requestId` to stay idempotent.\n\t */\n\tsignal?: AbortSignal\n\t/**\n\t * Stable id for this request. A follower tab's retry with the same id is\n\t * answered from the leader's response cache instead of being applied twice.\n\t */\n\trequestId?: string\n}\n\n/**\n * Options for creating a SqliteWasmAdapter.\n */\nexport interface SqliteWasmAdapterOptions {\n\t/**\n\t * Injected WorkerBridge for testing. If omitted, a WebWorkerBridge is created\n\t * in browser environments.\n\t */\n\tbridge?: WorkerBridge\n\n\t/**\n\t * Database name for persistence. Each database gets its own OPFS pool.\n\t */\n\tdbName?: string\n\n\t/**\n\t * URL to the sqlite-wasm-worker script. Required in browsers if no bridge is provided.\n\t */\n\tworkerUrl?: string | URL\n\n\t/** Timeout for worker / follower RPC responses. Defaults to 30000ms. */\n\tworkerResponseTimeoutMs?: number\n\n\t/**\n\t * When false, the adapter records a non-persistent open without emitting\n\t * `store:opfs-unavailable`. `createApp()` uses this while it promotes the store\n\t * to durable IndexedDB; direct adapter users keep the diagnostic by default.\n\t */\n\temitNonPersistentDiagnostic?: boolean\n\n\t/**\n\t * Accept writes when durable OPFS storage could not be obtained and the\n\t * database runs in memory. Defaults to false: a non-durable open or promotion\n\t * emits the blocking `store:durability-lost` event and every write is refused\n\t * with {@link StorageDurabilityError}, so data is never accepted and then lost\n\t * on reload. Set true only for apps that can tolerate losing local writes.\n\t */\n\tallowNonDurable?: boolean\n\n\t/**\n\t * For `createApp()`: skip the durability check at open only, because the caller\n\t * inspects {@link SqliteWasmAdapter.getStorageOpenState} right after open and\n\t * switches to a durable backend itself. A later leader promotion that loses\n\t * durable storage is still enforced.\n\t */\n\tdeferOpenDurabilityCheck?: boolean\n\n\t/**\n\t * Release storage ownership when the page is frozen or hidden into the\n\t * back/forward cache (`freeze` / `pagehide`), so a visible tab can take over\n\t * instead of waiting on a tab that cannot run; ownership is re-acquired on\n\t * `resume` / `pageshow`. Defaults to true.\n\t */\n\treleaseOnFreeze?: boolean\n\n\t/**\n\t * When set, storage diagnostics are emitted here: `store:opfs-unavailable`,\n\t * `store:durability-lost`, `store:storage-blocked` (another holder has the\n\t * storage; the open waits), `store:storage-migrated` and\n\t * `store:db-name-collision`.\n\t */\n\temitter?: KoraEventEmitter\n\n\t/**\n\t * @internal Used by the IndexedDB adapter: open an in-memory database that\n\t * never touches OPFS (the IndexedDB adapter persists snapshots itself).\n\t */\n\tstorage?: 'opfs' | 'memory'\n\n\t/**\n\t * Creates the bridge of a scratch in-memory database for staged replication (tests and\n\t * embedders with their own worker). Without it, a browser adapter starts one more\n\t * dedicated worker from {@link workerUrl}; an adapter with an injected bridge and no\n\t * factory has no staging database.\n\t */\n\tstagingBridgeFactory?: () => WorkerBridge | Promise<WorkerBridge>\n\n\t/**\n\t * @internal Do not read or write the storage manifest (the IndexedDB adapter's\n\t * inner database and its one-shot OPFS reader manage the manifest themselves).\n\t */\n\tskipBackendRecord?: boolean\n\n\t/**\n\t * @internal Used by the IndexedDB adapter (STORE-6): runs in one transaction on this\n\t * tab's OWN worker right after it opened the database as storage leader (first open\n\t * or promotion), before the worker serves any other tab. The IndexedDB adapter\n\t * restores its persisted snapshot here, so a snapshot is only ever restored into a\n\t * freshly created worker database and never over a leader's live one. Throwing fails\n\t * the open (or the promotion, which then refuses writes).\n\t */\n\tonLeaderWorkerOpened?: (tx: Transaction) => Promise<void>\n\n\t/**\n\t * @internal Used by the IndexedDB adapter: called with the storage channel name each\n\t * time this tab's own worker starts serving other tabs (first open and promotion).\n\t * Returns the function that stops what it started; it is called when this tab stops\n\t * leading (close, freeze, retirement) or before the next call. The IndexedDB adapter\n\t * answers followers' durability barriers here, because only the leader tab holds the\n\t * snapshot scheduler.\n\t */\n\tonLeaderServing?: (channelName: string) => () => void\n\n\t/**\n\t * The version gate of this database (`docs/design/version-gate.md`): one build of the\n\t * app writes it at a time. In a browser (worker path) the adapter creates one when this\n\t * is omitted, with `build` (or a schema fingerprint when no build is given). `false`\n\t * disables it (a short-lived reader that is not a tab of its own).\n\t */\n\tversionGate?: VersionGate | false\n\n\t/** Build id for the version gate the adapter creates (ignored with `versionGate`). */\n\tbuild?: string\n\n\t/**\n\t * Open single-tab in a browser without Web Locks instead of refusing\n\t * (`TabCoordinationUnavailableError`). For test environments (jsdom, happy-dom).\n\t */\n\tallowUncoordinatedTabs?: boolean\n\n\t/**\n\t * @internal Used by the IndexedDB adapter: it opens the version gate, drives the page\n\t * lifecycle and seals its own writes; this adapter only gives up its storage roles when\n\t * the tab retires and checks the gate before it leads.\n\t */\n\tversionGateManagedByParent?: boolean\n}\n\n/** Whether a SQL statement only reads (a retired tab still serves such reads). */\nfunction isReadOnlySql(sql: string): boolean {\n\tconst text = sql.trimStart()\n\tif (/^SELECT\\b/i.test(text)) return true\n\tif (/^WITH\\b/i.test(text)) return !/\\b(INSERT|UPDATE|DELETE|REPLACE)\\b/i.test(text)\n\tif (/^PRAGMA\\b/i.test(text)) return !text.includes('=')\n\treturn false\n}\n\n/** Whether this runtime is a browser page (where the version gate applies). */\nfunction isBrowserPage(): boolean {\n\treturn typeof window !== 'undefined' && typeof document !== 'undefined'\n}\n\ninterface Gate {\n\tpromise: Promise<void>\n\topen(): void\n}\n\nfunction createGate(): Gate {\n\tlet open: () => void = () => {}\n\tconst promise = new Promise<void>((resolve) => {\n\t\topen = resolve\n\t})\n\treturn { promise, open }\n}\n\n/**\n * SQLite WASM adapter that communicates with a SQLite instance through a WorkerBridge.\n *\n * In browsers, one tab per database (the leader) runs a dedicated worker that\n * owns the database's OPFS pool; other tabs reach that worker over a\n * BroadcastChannel. In Node.js tests, the bridge is backed by MockWorkerBridge\n * wrapping better-sqlite3.\n *\n * Storage is durable or loud, never silently in memory (W8a): another holder of\n * the storage makes the open wait (reported with `store:storage-blocked`); only a\n * runtime without OPFS SAH support gets a non-durable database, which refuses\n * writes unless the app opted in with `allowNonDurable`.\n *\n * @example\n * ```typescript\n * // Browser usage\n * const adapter = new SqliteWasmAdapter({ workerUrl: '/sqlite-wasm-worker.js' })\n *\n * // Test usage with MockWorkerBridge\n * import { MockWorkerBridge } from './sqlite-wasm-mock-bridge'\n * const adapter = new SqliteWasmAdapter({ bridge: new MockWorkerBridge() })\n * ```\n */\nexport class SqliteWasmAdapter implements StorageAdapter {\n\tprivate bridge: WorkerBridge | null = null\n\t/** The dedicated worker this tab runs while it is the database's leader. */\n\tprivate ownWorker: WebWorkerBridge | null = null\n\tprivate opened = false\n\tprivate readonly mutex = new Mutex()\n\t/**\n\t * Bridges whose worker announced the `batch` request in its open response. Only\n\t * those get batches: a leader worker from an older build (another tab still on\n\t * the previous deploy) gets the statements one `execute` at a time, as before.\n\t */\n\tprivate readonly batchCapable = new WeakSet<WorkerBridge>()\n\tprivate readonly injectedBridge: WorkerBridge | undefined\n\tprivate readonly stagingBridgeFactory: (() => WorkerBridge | Promise<WorkerBridge>) | undefined\n\tprivate readonly workerUrl: string | URL | undefined\n\tprivate readonly workerResponseTimeoutMs: number\n\tprivate readonly dbName: string\n\tprivate readonly emitter: KoraEventEmitter | undefined\n\tprivate tabSession: TabStorageSession | null = null\n\tprivate readonly emitNonPersistentDiagnostic: boolean\n\tprivate storageOpenState: StorageOpenState | null = null\n\t/** What survived outside the database when this leader opened it (null: not tracked). */\n\tprivate evidence: StorageEvidence | null = null\n\t/** Retained so a follower promoted to leader can re-open its own worker. */\n\tprivate schema: SchemaDefinition | null = null\n\tprivate promoting = false\n\tprivate closing = false\n\tprivate suspended = false\n\t/** Requests wait here while leadership changes hands (promotion, resume). */\n\tprivate gate: Gate | null = null\n\tprivate removeLifecycleListeners: (() => void) | null = null\n\tprivate readonly allowNonDurable: boolean\n\tprivate readonly deferOpenDurabilityCheck: boolean\n\tprivate readonly releaseOnFreeze: boolean\n\tprivate readonly storage: 'opfs' | 'memory'\n\tprivate readonly skipBackendRecord: boolean\n\t/** Set when this adapter lost (or never had) durable storage; writes are refused. */\n\tprivate durabilityLoss: { phase: 'open' | 'promotion'; reason: string } | null = null\n\tprivate readonly onLeaderWorkerOpened: ((tx: Transaction) => Promise<void>) | undefined\n\tprivate readonly onLeaderServing: ((channelName: string) => () => void) | undefined\n\t/** Stops what {@link onLeaderServing} started for the current leader worker. */\n\tprivate stopLeaderServing: (() => void) | null = null\n\t/** The version gate of this database, or null where it does not apply. */\n\tprivate readonly versionGate: VersionGate | null\n\tprivate readonly gateManagedByParent: boolean\n\t/** Admits this adapter's writes until the tab retires (version gate, section 5). */\n\tprivate readonly writes = new WriteGate()\n\t/** Set once this tab gave up its storage roles for a newer build: reads only. */\n\tprivate retiredStorage = false\n\n\tconstructor(options: SqliteWasmAdapterOptions = {}) {\n\t\tthis.injectedBridge = options.bridge\n\t\tthis.stagingBridgeFactory = options.stagingBridgeFactory\n\t\tthis.workerUrl = options.workerUrl\n\t\tthis.workerResponseTimeoutMs = options.workerResponseTimeoutMs ?? 30_000\n\t\tthis.dbName = options.dbName ?? 'kora-db'\n\t\tthis.emitter = options.emitter\n\t\tthis.emitNonPersistentDiagnostic = options.emitNonPersistentDiagnostic ?? true\n\t\tthis.allowNonDurable = options.allowNonDurable ?? false\n\t\tthis.deferOpenDurabilityCheck = options.deferOpenDurabilityCheck ?? false\n\t\tthis.releaseOnFreeze = options.releaseOnFreeze ?? true\n\t\tthis.storage = options.storage ?? 'opfs'\n\t\tthis.skipBackendRecord = options.skipBackendRecord ?? false\n\t\tthis.onLeaderWorkerOpened = options.onLeaderWorkerOpened\n\t\tthis.onLeaderServing = options.onLeaderServing\n\t\tthis.gateManagedByParent = options.versionGateManagedByParent === true\n\t\tthis.versionGate =\n\t\t\toptions.versionGate === false\n\t\t\t\t? null\n\t\t\t\t: (options.versionGate ??\n\t\t\t\t\t(options.workerUrl !== undefined && !options.bridge && isBrowserPage()\n\t\t\t\t\t\t? new VersionGate({\n\t\t\t\t\t\t\t\tdbName: this.dbName,\n\t\t\t\t\t\t\t\t...(options.build !== undefined ? { build: options.build } : {}),\n\t\t\t\t\t\t\t\t...(options.emitter ? { emitter: options.emitter } : {}),\n\t\t\t\t\t\t\t\t...(options.allowUncoordinatedTabs ? { allowUncoordinatedTabs: true } : {}),\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: null))\n\t\tconst gate = this.versionGate\n\t\tif (gate) {\n\t\t\tif (!this.gateManagedByParent) {\n\t\t\t\t// Step 3/4 for this adapter: refuse new writes and wait for every started one.\n\t\t\t\t// OPFS needs no barrier: a committed write is durable.\n\t\t\t\tgate.addRetireStep('durability', async (info) => {\n\t\t\t\t\tthis.writes.close(supersededBuilds(info))\n\t\t\t\t\tawait this.writes.drain()\n\t\t\t\t})\n\t\t\t}\n\t\t\tgate.addRetireStep('roles', (info) => this.giveUpStorageRoles(info))\n\t\t}\n\t}\n\n\t/**\n\t * The version gate this adapter's tab declares, for the store and the app (which\n\t * register their own retirement steps). Null when the gate does not apply here, or when\n\t * a parent adapter owns it.\n\t */\n\tgetVersionGate(): VersionGate | null {\n\t\treturn this.gateManagedByParent ? null : this.versionGate\n\t}\n\n\tasync open(schema: SchemaDefinition): Promise<void> {\n\t\tif (this.opened) return\n\n\t\tconst versionGate = this.versionGate\n\t\tif (versionGate && !this.gateManagedByParent) {\n\t\t\t// Storage open waits for the version gate (rule 3): this build never opens, migrates\n\t\t\t// or writes the database while a tab of another build may still write it.\n\t\t\tversionGate.useSchemaFingerprint(schema)\n\t\t\tawait versionGate.open()\n\t\t}\n\n\t\tconst ddlStatements = generateFullDDL(schema)\n\t\tif (this.injectedBridge) {\n\t\t\tthis.bridge = this.injectedBridge\n\t\t\tconst response = await this.openCurrentBridge(ddlStatements)\n\t\t\tthis.reportStorageMode(response.data)\n\t\t\tthis.enforceDurability('open')\n\t\t\tthis.opened = true\n\t\t\treturn\n\t\t}\n\t\tif (this.workerUrl) {\n\t\t\tthis.schema = schema\n\t\t\ttry {\n\t\t\t\tconst response = await this.attachAndOpen(ddlStatements)\n\t\t\t\tthis.reportStorageMode(response.data)\n\t\t\t\tthis.enforceDurability('open')\n\t\t\t\tawait this.afterLeaderOpen(response.data)\n\t\t\t\tthis.opened = true\n\t\t\t} catch (error) {\n\t\t\t\t// A failed open must not keep the worker, the OPFS pool or the leader\n\t\t\t\t// lock for the rest of the page's life (NEW-STORE-8).\n\t\t\t\tawait this.teardown()\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tthrow new AdapterError(\n\t\t\t'SqliteWasmAdapter requires either a bridge (for testing) or a workerUrl (for browsers). ' +\n\t\t\t\t'Pass { bridge: new MockWorkerBridge() } for tests, or { workerUrl: \"/worker.js\" } for browsers.',\n\t\t)\n\t}\n\n\t/**\n\t * Join the database as leader (own worker) or follower (RPC to the leader's\n\t * worker), then open it. The open waits, without a timeout, while another\n\t * holder still has the storage; the worker reports that as a blocking state.\n\t */\n\tprivate async attachAndOpen(ddlStatements: string[]): Promise<WorkerSuccessResponse> {\n\t\tconst workerUrl = this.workerUrl\n\t\tif (!workerUrl) {\n\t\t\tthrow new AdapterError('Durable SQLite WASM storage requires workerUrl.')\n\t\t}\n\t\tconst session = await acquireTabStorageSession(this.dbName, {\n\t\t\tonPromote: () => {\n\t\t\t\tvoid this.promoteToLeader()\n\t\t\t},\n\t\t\tmarkGatedLeader: this.versionGate !== null,\n\t\t\tgatedLeaderIdentity: () => this.versionGate?.getIdentity() ?? null,\n\t\t})\n\t\tthis.tabSession = session\n\n\t\tif (session.role === 'leader') {\n\t\t\tif (this.versionGate && !(await this.versionGate.mayLead())) {\n\t\t\t\t// A tab of a newer build appeared: never open a worker of this build (rule 4).\n\t\t\t\tthis.tabSession = null\n\t\t\t\tawait session.releaseLock?.()\n\t\t\t\tthrow (\n\t\t\t\t\tthis.workerStartRefusal() ??\n\t\t\t\t\tnew BuildSupersededError(\n\t\t\t\t\t\t{ operation: 'open' },\n\t\t\t\t\t\tthis.versionGate.supersededInfo() ?? {\n\t\t\t\t\t\t\tcurrentBuild: 'unknown',\n\t\t\t\t\t\t\tnewerBuild: 'unknown',\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst { WebWorkerBridge } = await import('./sqlite-wasm-channel')\n\t\t\t// The import yielded: a newer build may have retired this tab (its roles step took\n\t\t\t// the session) or the adapter closed. Release without starting a worker (rule 4).\n\t\t\tconst stopped = this.workerStartRefusal()\n\t\t\tif (stopped || this.tabSession !== session) {\n\t\t\t\tif (this.tabSession === session) this.tabSession = null\n\t\t\t\tawait session.releaseLock?.()\n\t\t\t\tthrow (\n\t\t\t\t\tstopped ??\n\t\t\t\t\tnew BuildSupersededError(\n\t\t\t\t\t\t{ operation: 'open' },\n\t\t\t\t\t\tthis.versionGate?.supersededInfo() ?? {\n\t\t\t\t\t\t\tcurrentBuild: 'unknown',\n\t\t\t\t\t\t\tnewerBuild: 'unknown',\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst worker: WebWorkerBridge = new WebWorkerBridge(workerUrl, this.workerResponseTimeoutMs, {\n\t\t\t\tonEvent: (event) => this.onWorkerEvent(event, worker),\n\t\t\t})\n\t\t\tthis.ownWorker = worker\n\t\t\tthis.bridge = worker\n\t\t\tconst response = await this.openLeaderWorker(worker, ddlStatements)\n\t\t\tthis.installLifecycleListeners()\n\t\t\treturn response\n\t\t}\n\n\t\tconst followerBridge = new FollowerBroadcastBridge(\n\t\t\tsession.channelName,\n\t\t\tthis.workerResponseTimeoutMs,\n\t\t)\n\t\tthis.bridge = followerBridge\n\t\t// Another runtime on this origin already owns this database name. That is\n\t\t// expected for multiple tabs of the same app (they share one leader),\n\t\t// but a bug if these are logically separate apps, so surface it so the\n\t\t// developer can give them distinct store names.\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:db-name-collision',\n\t\t\tdbName: this.dbName,\n\t\t\tmessage: `Another runtime on this origin is already using database \"${this.dbName}\"; this runtime is sharing it as a follower. If these are separate apps, give each a distinct store name.`,\n\t\t})\n\t\t// Readiness handshake: give the leader relay a moment to answer before the\n\t\t// first RPC, so a follower opened during a leader's startup race retries the\n\t\t// handshake instead of firing into the void.\n\t\tawait followerBridge.waitForLeader()\n\t\tthis.installLifecycleListeners()\n\t\treturn this.checkedOpen(followerBridge, ddlStatements)\n\t}\n\n\t/** Open the database in this tab's own worker and start serving followers. */\n\tprivate async openLeaderWorker(\n\t\tworker: WebWorkerBridge,\n\t\tddlStatements: string[],\n\t): Promise<WorkerSuccessResponse> {\n\t\tconst hook = this.onLeaderWorkerOpened\n\t\tconst identity = this.versionGate?.getIdentity() ?? null\n\t\tconst serve: WorkerRequest = {\n\t\t\tid: 0,\n\t\t\ttype: 'serve',\n\t\t\tchannelName: this.tabSession?.channelName ?? '',\n\t\t\t// Heartbeats carry this tab's identity, so other tabs of another build learn of it.\n\t\t\t...(identity ? { identity } : {}),\n\t\t}\n\t\tif (!hook) {\n\t\t\tconst pending = this.checkedOpen(worker, ddlStatements)\n\t\t\t// Posted after the open so follower requests queue behind it in the worker.\n\t\t\tworker.post(serve)\n\t\t\tthis.startLeaderServing()\n\t\t\treturn pending\n\t\t}\n\t\tconst response = await this.checkedOpen(worker, ddlStatements)\n\t\t// The hook (snapshot restore, STORE-6) runs before the worker serves other tabs,\n\t\t// so no follower ever reads or writes the database before it holds its data.\n\t\tawait runWorkerTransaction(worker, hook)\n\t\tworker.post(serve)\n\t\tthis.startLeaderServing()\n\t\treturn response\n\t}\n\n\t/** Start what the owner serves to followers beside the worker's relay (see the option). */\n\tprivate startLeaderServing(): void {\n\t\tthis.stopServing()\n\t\tconst channelName = this.tabSession?.channelName\n\t\tif (!this.onLeaderServing || !channelName) return\n\t\tthis.stopLeaderServing = this.onLeaderServing(channelName)\n\t}\n\n\t/** Stop answering followers on the owner's behalf (this tab no longer leads). */\n\tprivate stopServing(): void {\n\t\tconst stop = this.stopLeaderServing\n\t\tthis.stopLeaderServing = null\n\t\tstop?.()\n\t}\n\n\t/**\n\t * The link this tab uses to route a durability barrier to the leader tab, or null when\n\t * it leads itself or has no follower link (suspended, retired, closed).\n\t */\n\tsnapshotBarrierClient(): SnapshotBarrierClient | null {\n\t\treturn isSnapshotBarrierClient(this.bridge) ? this.bridge : null\n\t}\n\n\t/**\n\t * Whether this runtime owns the database's worker: the storage leader in a browser,\n\t * or any adapter with an injected bridge (tests, Node). A follower tab relays every\n\t * request to the leader's worker (STORE-6).\n\t */\n\tisLeader(): boolean {\n\t\tif (this.injectedBridge) return true\n\t\treturn this.tabSession?.role === 'leader'\n\t}\n\n\tprivate async checkedOpen(\n\t\tbridge: WorkerBridge,\n\t\tddlStatements: string[],\n\t): Promise<WorkerSuccessResponse> {\n\t\tconst response = await bridge.send(\n\t\t\t{\n\t\t\t\tid: 0,\n\t\t\t\ttype: 'open',\n\t\t\t\tddlStatements,\n\t\t\t\tdbName: this.dbName,\n\t\t\t\t...(this.storage === 'memory' ? { storage: 'memory' as const } : {}),\n\t\t\t},\n\t\t\tundefined,\n\t\t\t{ timeoutMs: Number.POSITIVE_INFINITY },\n\t\t)\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Failed to open database: ${response.message}`, {\n\t\t\t\tcode: response.code,\n\t\t\t\tdbName: this.dbName,\n\t\t\t\t...(response.context ?? {}),\n\t\t\t})\n\t\t}\n\t\tconst data = response.data as { batch?: unknown } | undefined\n\t\tif (data?.batch === true) this.batchCapable.add(bridge)\n\t\telse this.batchCapable.delete(bridge)\n\t\treturn response\n\t}\n\n\tprivate async openCurrentBridge(ddlStatements: string[]): Promise<WorkerSuccessResponse> {\n\t\tconst bridge = this.bridge\n\t\tif (!bridge) throw new StoreNotOpenError()\n\t\treturn this.checkedOpen(bridge, ddlStatements)\n\t}\n\n\tprivate onWorkerEvent(event: WorkerStatusEvent, worker: WebWorkerBridge): void {\n\t\tif (event.kind === 'worker-broken') {\n\t\t\tvoid this.replaceBrokenWorker(worker, event.reason)\n\t\t\treturn\n\t\t}\n\t\tif (!this.emitter) return\n\t\tconst holder =\n\t\t\tevent.resource === 'legacy-pool'\n\t\t\t\t? 'the shared OPFS pool used by older Kora versions (a tab running an older version of this app may still be open)'\n\t\t\t\t: 'another tab or worker that is still releasing it'\n\t\tif (event.kind === 'storage-blocked') {\n\t\t\tthis.emitter.emit({\n\t\t\t\ttype: 'store:storage-blocked',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tresource: event.resource,\n\t\t\t\tstate: 'waiting',\n\t\t\t\tmessage: `Database \"${this.dbName}\" is waiting for ${holder}. Close other tabs of this app if this persists; Kora will not fall back to non-durable storage.`,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tthis.emitter.emit({\n\t\t\ttype: 'store:storage-blocked',\n\t\t\tdbName: this.dbName,\n\t\t\tresource: event.resource,\n\t\t\tstate: 'resolved',\n\t\t\twaitedMs: event.waitedMs,\n\t\t\tmessage: `Database \"${this.dbName}\" obtained its storage after waiting ${event.waitedMs}ms.`,\n\t\t})\n\t}\n\n\t/**\n\t * Leader-only bookkeeping after a durable open: report a legacy-pool\n\t * migration, move an IndexedDB-held copy into OPFS explicitly (never two\n\t * disjoint copies), and record OPFS as this database's backend.\n\t */\n\tprivate async afterLeaderOpen(data: unknown): Promise<void> {\n\t\tif (!this.ownWorker || this.skipBackendRecord || this.storageOpenState?.persistent !== true) {\n\t\t\treturn\n\t\t}\n\t\tconst info = (typeof data === 'object' && data !== null ? data : {}) as {\n\t\t\tmigratedFromLegacy?: boolean\n\t\t}\n\t\tif (info.migratedFromLegacy === true) {\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:storage-migrated',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tfrom: 'legacy-opfs-pool',\n\t\t\t\tto: 'opfs',\n\t\t\t\tmessage: `Database \"${this.dbName}\" moved from the shared pre-1.0 OPFS pool into its own pool.`,\n\t\t\t})\n\t\t}\n\t\tif (!isManifestAvailable()) return\n\n\t\t// Read before the manifest is refreshed below: what a vanished database left behind\n\t\t// (offline-readiness design, section 6.1).\n\t\tconst found = await readFoundStorageEvidence(this.dbName)\n\t\tthis.evidence = new StorageEvidence({ dbName: this.dbName, backend: 'opfs', found })\n\t\tconst recordedBackend: string | null = found.manifest?.backend ?? null\n\t\tif (recordedBackend === 'indexeddb') {\n\t\t\t// The authoritative copy is in IndexedDB (an earlier session ran without\n\t\t\t// OPFS). Move it here before anything reads or writes; a failure fails\n\t\t\t// the open instead of showing the older OPFS copy.\n\t\t\tconst dump = await loadDumpFromIndexedDB<DatabaseDump>(this.dbName)\n\t\t\tif (dump) {\n\t\t\t\tawait this.applyDumpThroughWorker(this.ownWorker, dump)\n\t\t\t}\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:storage-migrated',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tfrom: 'indexeddb',\n\t\t\t\tto: 'opfs',\n\t\t\t\tmessage: `Database \"${this.dbName}\" moved from IndexedDB into OPFS.`,\n\t\t\t})\n\t\t}\n\t\ttry {\n\t\t\tawait recordDatabase({\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tbackend: 'opfs',\n\t\t\t\t...(this.storageOpenState.poolName ? { poolName: this.storageOpenState.poolName } : {}),\n\t\t\t})\n\t\t\tif (recordedBackend === 'indexeddb') {\n\t\t\t\tawait deleteFromIndexedDB(this.dbName)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[kora] Could not update the storage manifest for \"${this.dbName}\":`, error)\n\t\t}\n\t}\n\n\tprivate async applyDumpThroughWorker(worker: WorkerBridge, dump: DatabaseDump): Promise<void> {\n\t\tconst check = async (request: WorkerRequest, what: string): Promise<void> => {\n\t\t\tconst response = await worker.send(request)\n\t\t\tif (response.type === 'error') {\n\t\t\t\tthrow new AdapterError(`${what} failed: ${response.message}`, { dbName: this.dbName })\n\t\t\t}\n\t\t}\n\t\tawait check({ id: 0, type: 'begin' }, 'BEGIN IndexedDB import')\n\t\ttry {\n\t\t\tfor (const statement of restoreDumpStatements(dump)) {\n\t\t\t\tawait check(\n\t\t\t\t\t{ id: 0, type: 'execute', sql: statement.sql, params: statement.params },\n\t\t\t\t\t'IndexedDB import',\n\t\t\t\t)\n\t\t\t}\n\t\t\tawait check({ id: 0, type: 'commit' }, 'COMMIT IndexedDB import')\n\t\t} catch (error) {\n\t\t\tawait worker.send({ id: 0, type: 'rollback' }).catch(() => undefined)\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t/**\n\t * Surface a `store:opfs-unavailable` diagnostic when the worker reported that\n\t * persistence silently degraded to an in-memory database, so a data-loss\n\t * condition is observable instead of failing silently. A persistent open (or a\n\t * bridge that does not report a mode, e.g. the Node mock) emits nothing.\n\t */\n\tprivate reportStorageMode(data: unknown): void {\n\t\tthis.storageOpenState = parseStorageOpenState(data)\n\t\tif (!this.emitNonPersistentDiagnostic || !this.emitter || !this.storageOpenState) {\n\t\t\treturn\n\t\t}\n\t\tif (this.storageOpenState.persistent === false && this.storage === 'opfs') {\n\t\t\tconst reason = this.storageOpenState.fallbackReason ?? 'unsupported'\n\t\t\tthis.emitter.emit({\n\t\t\t\ttype: 'store:opfs-unavailable',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\treason,\n\t\t\t\tmessage: `OPFS persistence is unavailable (${reason}) for database \"${this.dbName}\"; the store is running in memory and data will not survive a reload.`,\n\t\t\t})\n\t\t}\n\t}\n\n\tgetStorageOpenState(): StorageOpenState | null {\n\t\treturn this.storageOpenState\n\t}\n\n\t/**\n\t * A scratch in-memory database in a worker of its own, for staged replication (see\n\t * `StorageAdapter.createStagingAdapter`). It never touches OPFS, the tab storage session\n\t * or the version gate, so another tab cannot adopt it as a follower and it leaves nothing\n\t * behind: closing the adapter terminates the worker, and so does the page.\n\t */\n\tasync createStagingAdapter(): Promise<StorageAdapter | null> {\n\t\t// Only a durable browser database replicates through staging: an in-memory main\n\t\t// database gains nothing from a second in-memory one.\n\t\tif (this.storage !== 'opfs' || this.storageOpenState?.persistent === false) return null\n\t\tlet bridge: WorkerBridge\n\t\tif (this.stagingBridgeFactory) {\n\t\t\tbridge = await this.stagingBridgeFactory()\n\t\t} else if (this.workerUrl && !this.injectedBridge && typeof Worker !== 'undefined') {\n\t\t\tconst { WebWorkerBridge } = await import('./sqlite-wasm-channel')\n\t\t\tbridge = new WebWorkerBridge(this.workerUrl, this.workerResponseTimeoutMs)\n\t\t} else {\n\t\t\treturn null\n\t\t}\n\t\treturn new SqliteWasmAdapter({\n\t\t\tbridge,\n\t\t\tstorage: 'memory',\n\t\t\tdbName: `${this.dbName}__staging`,\n\t\t\tallowNonDurable: true,\n\t\t\temitNonPersistentDiagnostic: false,\n\t\t\tskipBackendRecord: true,\n\t\t\tversionGate: false,\n\t\t\tworkerResponseTimeoutMs: this.workerResponseTimeoutMs,\n\t\t})\n\t}\n\n\tgetStorageEvidence(): StorageEvidence | null {\n\t\treturn this.evidence\n\t}\n\n\t/**\n\t * Durable or loud, never silent (NEW-STORE-6). When the open or a promotion\n\t * ended on non-persistent storage and the app did not opt into that, emit the\n\t * blocking `store:durability-lost` event and refuse every later write. A\n\t * bridge that reports no mode (the Node mock) is not judged.\n\t */\n\tprivate enforceDurability(\n\t\tphase: 'open' | 'promotion',\n\t\tfailure?: { reason: 'open-failed'; message: string },\n\t): void {\n\t\tif (this.allowNonDurable) return\n\t\tif (phase === 'open' && this.deferOpenDurabilityCheck && !failure) return\n\t\tlet reason: 'lock-conflict' | 'timeout' | 'unsupported' | 'open-failed'\n\t\tif (failure) {\n\t\t\treason = failure.reason\n\t\t} else if (this.storageOpenState?.persistent === false) {\n\t\t\treason = this.storageOpenState.fallbackReason ?? 'unsupported'\n\t\t} else {\n\t\t\tthis.durabilityLoss = null\n\t\t\treturn\n\t\t}\n\t\tthis.durabilityLoss = { phase, reason }\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:durability-lost',\n\t\t\tdbName: this.dbName,\n\t\t\tphase,\n\t\t\treason,\n\t\t\tmessage:\n\t\t\t\t`Database \"${this.dbName}\" has no durable storage (${reason} during ${phase}); ` +\n\t\t\t\t`writes are refused until the app reloads with durable storage.${failure ? ` ${failure.message}` : ''}`,\n\t\t})\n\t}\n\n\t/** True while writes are refused for lack of durable storage (see {@link StorageAdapter.refusesWrites}). */\n\trefusesWrites(): boolean {\n\t\treturn this.durabilityLoss !== null\n\t}\n\n\tprivate guardDurableWrite(): void {\n\t\tif (this.durabilityLoss) {\n\t\t\tthrow new StorageDurabilityError(\n\t\t\t\tthis.dbName,\n\t\t\t\tthis.durabilityLoss.phase,\n\t\t\t\tthis.durabilityLoss.reason,\n\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Close the database. A leader closes the database file and releases the OPFS\n\t * pool inside its worker, terminates the worker, and only then releases the\n\t * tab leader lock, so the next leader never races a still-running worker for\n\t * the file handles (NEW-STORE-10). A follower just leaves.\n\t */\n\tasync close(): Promise<void> {\n\t\tif (!this.bridge && !this.tabSession) {\n\t\t\t// Nothing opened yet (the open may still wait on the version gate): closing the gate\n\t\t\t// makes that open fail instead of opening storage after close.\n\t\t\tif (this.versionGate && !this.gateManagedByParent) this.versionGate.close()\n\t\t\treturn\n\t\t}\n\t\tthis.closing = true\n\t\ttry {\n\t\t\tif (this.injectedBridge && this.bridge) {\n\t\t\t\tawait this.bridge.send({ id: 0, type: 'close' })\n\t\t\t} else if (this.ownWorker && !this.ownWorker.isTerminated()) {\n\t\t\t\tconst response = await this.ownWorker\n\t\t\t\t\t.send({ id: 0, type: 'close' }, undefined, { timeoutMs: 5000 })\n\t\t\t\t\t.catch((error: unknown) => ({\n\t\t\t\t\t\tid: 0,\n\t\t\t\t\t\ttype: 'error' as const,\n\t\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\tcode: 'CLOSE_FAILED',\n\t\t\t\t\t}))\n\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\t// Terminating the worker below still releases the pool.\n\t\t\t\t\tconsole.warn(`[kora] Closing \"${this.dbName}\" in its worker failed:`, response.message)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tawait this.teardown()\n\t\t\tthis.closing = false\n\t\t}\n\t}\n\n\t/**\n\t * Release everything this adapter holds, in ownership order: lifecycle\n\t * listeners, then the worker (which holds the OPFS pool and its Web Lock),\n\t * then the tab leader lock or queued promotion request.\n\t */\n\tprivate async teardown(): Promise<void> {\n\t\tthis.removeLifecycleListeners?.()\n\t\tthis.removeLifecycleListeners = null\n\t\tconst session = this.tabSession\n\t\tthis.tabSession = null\n\t\tthis.stopServing()\n\t\tthis.bridge?.terminate()\n\t\tthis.bridge = null\n\t\tthis.ownWorker = null\n\t\tif (session) {\n\t\t\tif (session.releaseLock) {\n\t\t\t\tawait session.releaseLock()\n\t\t\t}\n\t\t\tsession.cancelPromotionWatch?.()\n\t\t}\n\t\t// The tab lock last: the leader lock (and the worker's pool) are released first.\n\t\tif (this.versionGate && !this.gateManagedByParent) this.versionGate.close()\n\t\tthis.opened = false\n\t\tthis.suspended = false\n\t\tconst gate = this.gate\n\t\tthis.gate = null\n\t\tgate?.open()\n\t}\n\n\t/**\n\t * Promotes a follower to leader after the previous leader released the storage\n\t * lock (its tab closed, crashed, or suspended on freeze). The new worker waits\n\t * on the pool's Web Lock and handles, so it never races the previous worker.\n\t * Requests issued during the hand-off wait for it; requests that were in\n\t * flight to the old leader fail with a retriable `BridgeTerminatedError`.\n\t */\n\tprivate async promoteToLeader(): Promise<void> {\n\t\tif (\n\t\t\tthis.promoting ||\n\t\t\tthis.closing ||\n\t\t\t!this.opened ||\n\t\t\tthis.workerUrl === undefined ||\n\t\t\tthis.schema === null\n\t\t) {\n\t\t\treturn\n\t\t}\n\t\tthis.promoting = true\n\t\tconst gate = createGate()\n\t\tthis.gate = gate\n\n\t\ttry {\n\t\t\tif (this.versionGate && !(await this.versionGate.mayLead())) {\n\t\t\t\t// Granted the leader lock while a tab of a newer build exists (or while this tab\n\t\t\t\t// retires): release it unopened, so no worker of this build starts (rule 4).\n\t\t\t\tthis.tabSession?.cancelPromotionWatch?.()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst { WebWorkerBridge } = await import('./sqlite-wasm-channel')\n\t\t\tif (this.closing || !this.opened) return\n\t\t\t// Retiring (or closed) since mayLead(): give the leader lock back unopened.\n\t\t\tif (this.workerStartRefusal()) {\n\t\t\t\tthis.tabSession?.cancelPromotionWatch?.()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst worker: WebWorkerBridge = new WebWorkerBridge(\n\t\t\t\tthis.workerUrl,\n\t\t\t\tthis.workerResponseTimeoutMs,\n\t\t\t\t{ onEvent: (event) => this.onWorkerEvent(event, worker) },\n\t\t\t)\n\t\t\tconst previousBridge = this.bridge\n\t\t\tthis.bridge = worker\n\t\t\tthis.ownWorker = worker\n\t\t\tif (this.tabSession) {\n\t\t\t\tthis.tabSession.role = 'leader'\n\t\t\t}\n\t\t\tpreviousBridge?.terminate()\n\n\t\t\t// Re-open against our own worker. DDL is idempotent, and the OPFS data the\n\t\t\t// old leader persisted is readable once its worker is gone.\n\t\t\tconst ddlStatements = generateFullDDL(this.schema)\n\t\t\tlet response: WorkerSuccessResponse\n\t\t\ttry {\n\t\t\t\tresponse = await this.openLeaderWorker(worker, ddlStatements)\n\t\t\t} catch (error) {\n\t\t\t\t// The promoted worker could not obtain durable storage. Never let it\n\t\t\t\t// run silently in memory.\n\t\t\t\tthis.storageOpenState = { persistent: false, mode: 'memory' }\n\t\t\t\tthis.enforceDurability('promotion', {\n\t\t\t\t\treason: 'open-failed',\n\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.storageOpenState = parseStorageOpenState(response.data) ?? this.storageOpenState\n\t\t\tthis.enforceDurability('promotion')\n\t\t\ttry {\n\t\t\t\tawait this.afterLeaderOpen(response.data)\n\t\t\t} catch (error) {\n\t\t\t\tthis.enforceDurability('promotion', {\n\t\t\t\t\treason: 'open-failed',\n\t\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t\t})\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.promoting = false\n\t\t\tif (this.gate === gate) this.gate = null\n\t\t\tgate.open()\n\t\t}\n\t}\n\n\t/**\n\t * Page Lifecycle: a frozen or bfcached page cannot run, so it must not keep\n\t * other tabs waiting on its storage. Leaders terminate their worker (freeing\n\t * the OPFS pool) and then release the leader lock, so a visible tab is\n\t * promoted; followers withdraw their queued lock request so a frozen tab is\n\t * never granted leadership it cannot use. Never uses Web Locks `steal`.\n\t */\n\tprivate installLifecycleListeners(): void {\n\t\tif (!this.releaseOnFreeze || this.removeLifecycleListeners) return\n\t\tif (typeof addEventListener !== 'function' || typeof document === 'undefined') return\n\t\tconst onFreeze = (): void => {\n\t\t\tthis.suspend()\n\t\t}\n\t\tconst onPageHide = (): void => {\n\t\t\tthis.suspend()\n\t\t}\n\t\tconst onResume = (): void => {\n\t\t\tvoid this.resume()\n\t\t}\n\t\tconst onPageShow = (event: Event): void => {\n\t\t\tif ((event as PageTransitionEvent).persisted) void this.resume()\n\t\t}\n\t\tdocument.addEventListener('freeze', onFreeze)\n\t\tdocument.addEventListener('resume', onResume)\n\t\taddEventListener('pagehide', onPageHide)\n\t\taddEventListener('pageshow', onPageShow)\n\t\tthis.removeLifecycleListeners = () => {\n\t\t\tdocument.removeEventListener('freeze', onFreeze)\n\t\t\tdocument.removeEventListener('resume', onResume)\n\t\t\tremoveEventListener('pagehide', onPageHide)\n\t\t\tremoveEventListener('pageshow', onPageShow)\n\t\t}\n\t}\n\n\t/**\n\t * The leader worker stopped serving because its transaction state is unknown.\n\t * Replace it through the suspend/resume path: terminate it (which discards any\n\t * open transaction and frees the pool), release the leader lock, re-attach. The\n\t * broken worker never runs another request in the meantime.\n\t */\n\tprivate async replaceBrokenWorker(worker: WebWorkerBridge, reason: string): Promise<void> {\n\t\tconsole.warn(`[kora] Replacing the storage worker of \"${this.dbName}\": ${reason}`)\n\t\twhile (this.gate) {\n\t\t\tawait this.gate.promise\n\t\t}\n\t\tif (this.ownWorker !== worker || this.closing || !this.opened) return\n\t\t// Not a page lifecycle event: the tab keeps its version gate tab lock.\n\t\tthis.suspend(false)\n\t\tawait this.resume(false)\n\t}\n\n\t/**\n\t * @internal The page is being frozen or hidden into the back/forward cache: release the\n\t * storage roles (and, unless a parent adapter manages it, the version gate tab lock).\n\t * The IndexedDB adapter calls this once its snapshot holds every committed write.\n\t */\n\tsuspendForLifecycle(): boolean {\n\t\treturn this.suspend(true)\n\t}\n\n\t/**\n\t * @internal The page resumed but a newer build opened meanwhile (the version gate did not\n\t * let this tab resume): never re-attach, and let the requests queued behind the suspension\n\t * fail (retriably, {@link BuildSupersededError}) so the retirement's drain completes.\n\t */\n\tabandonLifecycleSuspension(): void {\n\t\tif (!this.suspended) return\n\t\tconst gate = this.gate\n\t\tthis.suspended = false\n\t\tif (this.gate === gate) this.gate = null\n\t\tgate?.open()\n\t}\n\n\t/** @internal The page is running again: re-attach (see {@link suspendForLifecycle}). */\n\tresumeForLifecycle(): Promise<void> {\n\t\treturn this.resume(true)\n\t}\n\n\t/**\n\t * Synchronous by necessity: a `freeze` handler gets no further turns. Returns whether the\n\t * storage roles were released: not while opening, promoting, closing or retiring, where\n\t * the tab keeps them (and so must keep its version gate tab lock too).\n\t */\n\tprivate suspend(lifecycle = true): boolean {\n\t\tif (!this.opened || this.suspended || this.closing || this.promoting) return false\n\t\tif (this.retiredStorage) return false\n\t\t// A retiring tab keeps its storage until its retirement steps release it.\n\t\tif (lifecycle && this.versionGate?.isSuperseded()) return false\n\t\tthis.suspended = true\n\t\tthis.gate = createGate()\n\t\tconst session = this.tabSession\n\t\tthis.tabSession = null\n\t\tthis.stopServing()\n\t\t// Worker (pool holder) first, then the leader lock (NEW-STORE-10).\n\t\tthis.bridge?.terminate()\n\t\tthis.bridge = null\n\t\tthis.ownWorker = null\n\t\tif (session) {\n\t\t\tvoid session.releaseLock?.()\n\t\t\tsession.cancelPromotionWatch?.()\n\t\t}\n\t\t// The version gate tab lock after the leader lock (both released in this task, in\n\t\t// this order), so a newer build's tab never finds the leader lock still held by a tab\n\t\t// it no longer sees. OPFS: every committed write is durable, so release at once.\n\t\tif (lifecycle && this.versionGate && !this.gateManagedByParent) this.versionGate.suspend()\n\t\treturn true\n\t}\n\n\tprivate async resume(lifecycle = true): Promise<void> {\n\t\tif (!this.suspended || this.closing || this.schema === null) return\n\t\tconst gate = this.gate\n\t\tif (lifecycle && this.versionGate && !this.gateManagedByParent) {\n\t\t\t// Re-acquire the tab lock and run discovery before anything else (rule 5). A failure\n\t\t\t// other than supersession keeps this tab suspended (no tab lock held) and retries.\n\t\t\tconst mayResume = await this.versionGate.resumeWithRetry()\n\t\t\tif (!mayResume) {\n\t\t\t\t// Superseded while suspended: the retirement steps finish; never re-attach.\n\t\t\t\tthis.suspended = false\n\t\t\t\tif (this.gate === gate) this.gate = null\n\t\t\t\tgate?.open()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconst response = await this.attachAndOpen(generateFullDDL(this.schema))\n\t\t\tthis.reportStorageMode(response.data)\n\t\t\tthis.enforceDurability('promotion')\n\t\t\tawait this.afterLeaderOpen(response.data)\n\t\t} catch (error) {\n\t\t\tthis.enforceDurability('promotion', {\n\t\t\t\treason: 'open-failed',\n\t\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t\t})\n\t\t} finally {\n\t\t\tthis.suspended = false\n\t\t\tif (this.gate === gate) this.gate = null\n\t\t\tgate?.open()\n\t\t}\n\t}\n\n\t/**\n\t * Non-transactional write. Takes the same mutex as {@link transaction}, so it\n\t * never lands inside this tab's open transaction and is never rolled back\n\t * with it (STORE-8). Inside a transaction callback, use the `tx` handle.\n\t */\n\texecute(sql: string, params?: unknown[], options?: StorageRequestOptions): Promise<void> {\n\t\treturn this.writes.run({ operation: 'execute' }, () => this.executeNow(sql, params, options))\n\t}\n\n\tprivate async executeNow(\n\t\tsql: string,\n\t\tparams?: unknown[],\n\t\toptions?: StorageRequestOptions,\n\t): Promise<void> {\n\t\tthis.guardOpen()\n\t\tthis.guardDurableWrite()\n\t\tconst release = await this.mutex.acquire()\n\t\ttry {\n\t\t\tconst response = await this.sendRequest(\n\t\t\t\t{\n\t\t\t\t\tid: 0,\n\t\t\t\t\ttype: 'execute',\n\t\t\t\t\tsql,\n\t\t\t\t\tparams,\n\t\t\t\t\t...(options?.requestId ? { requestId: options.requestId } : {}),\n\t\t\t\t},\n\t\t\t\toptions?.signal ? { signal: options.signal } : undefined,\n\t\t\t)\n\t\t\tif (response.type === 'error') {\n\t\t\t\tthrow new AdapterError(`Execute failed: ${response.message}`, { sql, params })\n\t\t\t}\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\t/**\n\t * Non-transactional read. Waits for this tab's open transaction to finish, so\n\t * it never observes uncommitted (possibly rolled-back) rows (STORE-8).\n\t */\n\tasync query<T>(sql: string, params?: unknown[], options?: StorageRequestOptions): Promise<T[]> {\n\t\tthis.guardOpen()\n\t\tif (this.retiredStorage && !isReadOnlySql(sql)) {\n\t\t\t// A retired tab reads through the newer build's leader; it never writes there.\n\t\t\tthis.writes.assertOpen({ operation: 'query' })\n\t\t}\n\t\tconst release = await this.mutex.acquire()\n\t\ttry {\n\t\t\tconst response = await this.sendRequest(\n\t\t\t\t{\n\t\t\t\t\tid: 0,\n\t\t\t\t\ttype: 'query',\n\t\t\t\t\tsql,\n\t\t\t\t\tparams,\n\t\t\t\t\t...(options?.requestId ? { requestId: options.requestId } : {}),\n\t\t\t\t},\n\t\t\t\toptions?.signal ? { signal: options.signal } : undefined,\n\t\t\t)\n\t\t\tif (response.type === 'error') {\n\t\t\t\tthrow new AdapterError(`Query failed: ${response.message}`, { sql, params })\n\t\t\t}\n\t\t\treturn (response.data as T[]) ?? []\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\ttransaction(fn: (tx: Transaction) => Promise<void>): Promise<void> {\n\t\treturn this.writes.run({ operation: 'transaction' }, () => this.transactionNow(fn))\n\t}\n\n\tprivate async transactionNow(fn: (tx: Transaction) => Promise<void>): Promise<void> {\n\t\tthis.guardOpen()\n\t\tthis.guardDurableWrite()\n\n\t\tconst release = await this.mutex.acquire()\n\t\tlet txBridge: WorkerBridge | null = null\n\t\t// Every statement of the span must reach the worker that ran BEGIN. If\n\t\t// leadership changed hands mid-transaction, the old worker rolled it back\n\t\t// (or is gone); sending the rest to the new worker would autocommit a\n\t\t// partial transaction, so fail with a retriable error instead.\n\t\tconst sendInSpan = async (request: WorkerRequest): Promise<WorkerResponse> => {\n\t\t\tif (txBridge === null || this.bridge !== txBridge) {\n\t\t\t\tthrow new BridgeTerminatedError(request.type, 'storage leader changed during transaction')\n\t\t\t}\n\t\t\treturn txBridge.send(request)\n\t\t}\n\t\ttry {\n\t\t\twhile (this.gate) {\n\t\t\t\tawait this.gate.promise\n\t\t\t}\n\t\t\ttxBridge = this.bridge\n\t\t\tif (!txBridge) throw this.noBridgeError('transaction')\n\t\t\tconst begin = await sendInSpan({ id: 0, type: 'begin' })\n\t\t\tif (begin.type === 'error') {\n\t\t\t\tthrow new AdapterError(`BEGIN transaction failed: ${begin.message}`)\n\t\t\t}\n\n\t\t\tconst tx: Transaction = {\n\t\t\t\texecute: async (sql: string, params?: unknown[]): Promise<void> => {\n\t\t\t\t\tconst response = await sendInSpan({ id: 0, type: 'execute', sql, params })\n\t\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\t\tthrow new AdapterError(`Transaction execute failed: ${response.message}`, {\n\t\t\t\t\t\t\tsql,\n\t\t\t\t\t\t\tparams,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tquery: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {\n\t\t\t\t\tconst response = await sendInSpan({ id: 0, type: 'query', sql, params })\n\t\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\t\tthrow new AdapterError(`Transaction query failed: ${response.message}`, { sql, params })\n\t\t\t\t\t}\n\t\t\t\t\treturn (response.data as T[]) ?? []\n\t\t\t\t},\n\t\t\t\texecuteBatch: async (statements: readonly TransactionStatement[]): Promise<void> => {\n\t\t\t\t\tif (statements.length === 0) return\n\t\t\t\t\tif (txBridge === null || !this.batchCapable.has(txBridge)) {\n\t\t\t\t\t\tfor (const statement of statements) {\n\t\t\t\t\t\t\tawait tx.execute(statement.sql, statement.params)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tconst response = await sendInSpan({\n\t\t\t\t\t\tid: 0,\n\t\t\t\t\t\ttype: 'batch',\n\t\t\t\t\t\tstatements: statements.map((s) =>\n\t\t\t\t\t\t\ts.params === undefined ? { sql: s.sql } : { sql: s.sql, params: s.params },\n\t\t\t\t\t\t),\n\t\t\t\t\t})\n\t\t\t\t\tif (response.type === 'success') return\n\t\t\t\t\tif (response.code === 'UNKNOWN_REQUEST') {\n\t\t\t\t\t\t// The worker announced `batch` at open, but the storage leader has since\n\t\t\t\t\t\t// changed to a tab on an older build. Its worker ran nothing of the batch,\n\t\t\t\t\t\t// but it may already have ended this transaction's span (an error ends\n\t\t\t\t\t\t// it), so the transaction is not continued: it rolls back and the write\n\t\t\t\t\t\t// fails retriably; the retry sends statements one by one.\n\t\t\t\t\t\tthis.batchCapable.delete(txBridge)\n\t\t\t\t\t\tthrow new BridgeTerminatedError('batch', 'storage leader runs an older Kora build')\n\t\t\t\t\t}\n\t\t\t\t\tconst index = response.context?.index\n\t\t\t\t\tconst failed = typeof index === 'number' ? statements[index] : undefined\n\t\t\t\t\tthrow new AdapterError(`Transaction execute failed: ${response.message}`, {\n\t\t\t\t\t\t...(failed ? { sql: failed.sql, params: failed.params } : {}),\n\t\t\t\t\t\tbatchIndex: index,\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tawait fn(tx)\n\t\t\tconst commit = await sendInSpan({ id: 0, type: 'commit' })\n\t\t\tif (commit.type === 'error') {\n\t\t\t\tthrow new AdapterError(`COMMIT transaction failed: ${commit.message}`)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Attempt rollback on the worker that ran BEGIN, but don't mask the\n\t\t\t// original error.\n\t\t\ttry {\n\t\t\t\tif (txBridge && this.bridge === txBridge) {\n\t\t\t\t\tawait txBridge.send({ id: 0, type: 'rollback' })\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Rollback failure is secondary to the original error\n\t\t\t}\n\t\t\tthrow error\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\tmigrate(from: number, to: number, migration: MigrationPlan): Promise<void> {\n\t\treturn this.writes.run({ operation: 'migrate' }, () => this.migrateNow(from, to, migration))\n\t}\n\n\tprivate async migrateNow(from: number, to: number, migration: MigrationPlan): Promise<void> {\n\t\tthis.guardOpen()\n\t\tthis.guardDurableWrite()\n\n\t\tconst release = await this.mutex.acquire()\n\t\t// Like `transaction`, every statement must reach the worker that ran BEGIN: a\n\t\t// leadership change (suspend and resume, promotion) between two statements\n\t\t// would otherwise send the rest to a new worker, where each autocommits.\n\t\tlet spanBridge: WorkerBridge | null = null\n\t\tconst sendInSpan = async (request: WorkerRequest): Promise<WorkerResponse> => {\n\t\t\tif (spanBridge === null || this.bridge !== spanBridge) {\n\t\t\t\tthrow new BridgeTerminatedError(request.type, 'storage leader changed during migration')\n\t\t\t}\n\t\t\treturn spanBridge.send(request)\n\t\t}\n\t\ttry {\n\t\t\twhile (this.gate) {\n\t\t\t\tawait this.gate.promise\n\t\t\t}\n\t\t\tspanBridge = this.bridge\n\t\t\tif (!spanBridge) throw this.noBridgeError('migrate')\n\t\t\tconst begin = await sendInSpan({ id: 0, type: 'begin' })\n\t\t\tif (begin.type === 'error') {\n\t\t\t\tthrow new AdapterError(`BEGIN migration failed: ${begin.message}`)\n\t\t\t}\n\n\t\t\tfor (const sql of migration.statements) {\n\t\t\t\tconst response = await sendInSpan({ id: 0, type: 'execute', sql })\n\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\tthrow new AdapterError(`Migration from v${from} to v${to} failed: ${response.message}`, {\n\t\t\t\t\t\tfrom,\n\t\t\t\t\t\tto,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst commit = await sendInSpan({ id: 0, type: 'commit' })\n\t\t\tif (commit.type === 'error') {\n\t\t\t\tthrow new AdapterError(`COMMIT migration failed: ${commit.message}`)\n\t\t\t}\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tif (spanBridge && this.bridge === spanBridge) {\n\t\t\t\t\tawait spanBridge.send({ id: 0, type: 'rollback' })\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Rollback failure is secondary\n\t\t\t}\n\t\t\tif (error instanceof AdapterError || error instanceof BridgeTerminatedError) throw error\n\t\t\tthrow new AdapterError(\n\t\t\t\t`Migration from v${from} to v${to} failed: ${(error as Error).message}`,\n\t\t\t\t{ from, to },\n\t\t\t)\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\t/**\n\t * Export the database as a Uint8Array (for IndexedDB persistence).\n\t * Only available when the database is open.\n\t */\n\tasync exportDatabase(): Promise<Uint8Array> {\n\t\tthis.guardOpen()\n\t\tconst release = await this.mutex.acquire()\n\t\ttry {\n\t\t\tconst response = await this.sendRequest({ id: 0, type: 'export' })\n\t\t\tif (response.type === 'error') {\n\t\t\t\tthrow new AdapterError(`Export failed: ${response.message}`, {\n\t\t\t\t\tcode: response.code,\n\t\t\t\t\tcontext: response.context,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn response.data as Uint8Array\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\t/**\n\t * Import a serialized database snapshot.\n\t */\n\timportDatabase(data: Uint8Array): Promise<void> {\n\t\treturn this.writes.run({ operation: 'import' }, () => this.importDatabaseNow(data))\n\t}\n\n\tprivate async importDatabaseNow(data: Uint8Array): Promise<void> {\n\t\tthis.guardOpen()\n\t\tthis.guardDurableWrite()\n\t\tconst release = await this.mutex.acquire()\n\t\ttry {\n\t\t\tconst response = await this.sendRequest({ id: 0, type: 'import', data })\n\t\t\tif (response.type === 'error') {\n\t\t\t\tthrow new AdapterError(`Import failed: ${response.message}`)\n\t\t\t}\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\t/**\n\t * Version gate, step 6: give up this tab's storage roles for a newer build. A leader\n\t * first waits for every other retiring tab to finish (their retirement may still need\n\t * this worker), then terminates its worker and releases the leader lock; a follower\n\t * withdraws its queued promotion. The tab then reads through the newer build's leader\n\t * and never writes again.\n\t */\n\tprivate async giveUpStorageRoles(info: SupersededInfo): Promise<void> {\n\t\tthis.writes.close(supersededBuilds(info))\n\t\tif (this.injectedBridge) {\n\t\t\tthis.retiredStorage = true\n\t\t\treturn\n\t\t}\n\t\tif (this.ownWorker && this.versionGate) {\n\t\t\tawait this.versionGate.waitForPeersToRetire()\n\t\t}\n\t\tthis.removeLifecycleListeners?.()\n\t\tthis.removeLifecycleListeners = null\n\t\tconst session = this.tabSession\n\t\tthis.tabSession = null\n\t\tthis.stopServing()\n\t\t// Worker (pool holder) first, then the leader lock (NEW-STORE-10). After the drain no\n\t\t// write of this tab is in flight; a follower span cut here fails retriably (#59).\n\t\tthis.bridge?.terminate()\n\t\tthis.bridge = null\n\t\tthis.ownWorker = null\n\t\tif (session) {\n\t\t\tif (session.releaseLock) await session.releaseLock()\n\t\t\tsession.cancelPromotionWatch?.()\n\t\t}\n\t\tthis.retiredStorage = true\n\t\tif (this.opened && isMultiTabStorageSupported()) {\n\t\t\t// Reads keep working where they can, as a follower that never asks to lead.\n\t\t\tthis.bridge = new FollowerBroadcastBridge(\n\t\t\t\tstorageChannelNameFor(this.dbName),\n\t\t\t\tthis.workerResponseTimeoutMs,\n\t\t\t)\n\t\t}\n\t\tconst handOff = this.gate\n\t\tthis.gate = null\n\t\tthis.suspended = false\n\t\thandOff?.open()\n\t}\n\n\t/**\n\t * Why this tab may not start a worker of its build now (closing, retired, or its version\n\t * gate superseded or closed), or null. Checked after every await before a worker starts.\n\t */\n\tprivate workerStartRefusal(): Error | null {\n\t\tconst gate = this.versionGate\n\t\tconst info = gate?.supersededInfo() ?? null\n\t\tif (info) return new BuildSupersededError({ operation: 'open' }, info)\n\t\tif (gate?.getState() === 'closed') return new VersionGateClosedError(this.dbName)\n\t\tif (this.closing || this.retiredStorage) return new StoreNotOpenError()\n\t\treturn null\n\t}\n\n\tprivate guardOpen(): void {\n\t\tif (!this.opened || (!this.bridge && !this.gate)) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t}\n\n\tprivate async sendRequest(\n\t\trequest: WorkerRequest,\n\t\toptions?: WorkerSendOptions,\n\t): Promise<WorkerResponse> {\n\t\t// While leadership changes hands, wait for the new bridge instead of\n\t\t// sending into a torn-down one.\n\t\twhile (this.gate) {\n\t\t\tawait this.gate.promise\n\t\t}\n\t\tconst bridge = this.bridge\n\t\tif (!bridge) {\n\t\t\tthrow this.noBridgeError(request.type)\n\t\t}\n\t\treturn bridge.send(request, undefined, options)\n\t}\n\n\t/**\n\t * No worker to send to: a tab retiring for a newer build (between abandoning a lifecycle\n\t * suspension and its roles step) refuses retriably; otherwise the store is not open.\n\t */\n\tprivate noBridgeError(operation: string): BuildSupersededError | StoreNotOpenError {\n\t\tconst info = this.versionGate?.supersededInfo()\n\t\treturn info ? new BuildSupersededError({ operation }, info) : new StoreNotOpenError()\n\t}\n}\n\n/**\n * Run `fn` in one transaction sent straight to `worker`, bypassing the adapter's mutex\n * and leadership gate (the caller is the leader opening its own worker).\n */\nasync function runWorkerTransaction(\n\tworker: WorkerBridge,\n\tfn: (tx: Transaction) => Promise<void>,\n): Promise<void> {\n\tconst send = async (request: WorkerRequest, what: string): Promise<WorkerResponse> => {\n\t\tconst response = await worker.send(request)\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`${what} failed: ${response.message}`, {\n\t\t\t\tcode: response.code,\n\t\t\t\t...(request.type === 'execute' || request.type === 'query' ? { sql: request.sql } : {}),\n\t\t\t})\n\t\t}\n\t\treturn response\n\t}\n\tawait send({ id: 0, type: 'begin' }, 'BEGIN')\n\ttry {\n\t\tawait fn({\n\t\t\texecute: async (sql, params) => {\n\t\t\t\tawait send({ id: 0, type: 'execute', sql, params }, 'Leader open execute')\n\t\t\t},\n\t\t\tquery: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {\n\t\t\t\tconst response = await send({ id: 0, type: 'query', sql, params }, 'Leader open query')\n\t\t\t\treturn ((response as WorkerSuccessResponse).data as T[]) ?? []\n\t\t\t},\n\t\t})\n\t\tawait send({ id: 0, type: 'commit' }, 'COMMIT')\n\t} catch (error) {\n\t\tawait worker.send({ id: 0, type: 'rollback' }).catch(() => undefined)\n\t\tthrow error\n\t}\n}\n\n/** The builds of a supersession, as {@link BuildSupersededError} names them. */\nfunction supersededBuilds(info: SupersededInfo): { currentBuild: string; newerBuild: string } {\n\treturn { currentBuild: info.current.build, newerBuild: info.newer.build }\n}\n\nfunction parseStorageOpenState(data: unknown): StorageOpenState | null {\n\tif (typeof data !== 'object' || data === null) {\n\t\treturn null\n\t}\n\tconst mode = data as {\n\t\tpersistent?: boolean\n\t\tfallbackReason?: StorageFallbackReason\n\t\tpoolName?: string\n\t\tjournalMode?: string\n\t}\n\tif (typeof mode.persistent !== 'boolean') {\n\t\treturn null\n\t}\n\treturn {\n\t\tpersistent: mode.persistent,\n\t\tmode: mode.persistent ? 'opfs' : 'memory',\n\t\t...(mode.fallbackReason ? { fallbackReason: mode.fallbackReason } : {}),\n\t\t...(typeof mode.poolName === 'string' ? { poolName: mode.poolName } : {}),\n\t\t...(typeof mode.journalMode === 'string' ? { journalMode: mode.journalMode } : {}),\n\t}\n}\n","import { quoteIdent } from '@korajs/core'\nimport { PersistenceError } from '../errors'\n\n/**\n * Logical copy of every user table of a SQLite database. Used to move a\n * database between storage backends (OPFS <-> IndexedDB) explicitly, and as the\n * IndexedDB adapter's durable snapshot format.\n */\nexport interface DatabaseDump {\n\ttables: Array<{\n\t\tname: string\n\t\t/**\n\t\t * The table's `CREATE TABLE` statement (from `sqlite_master`), so a restore can\n\t\t * recreate a table the target database does not have yet with its constraints.\n\t\t * Absent in dumps written before it was recorded.\n\t\t */\n\t\tsql?: string\n\t\tcolumns: string[]\n\t\trows: Array<Record<string, unknown>>\n\t}>\n}\n\n/** A parameterized SQL statement. */\nexport interface DumpStatement {\n\tsql: string\n\tparams?: unknown[]\n}\n\ntype QueryFn = <T>(sql: string, params?: unknown[]) => Promise<T[]>\n\n/** Throws unless `identifier` is a plain SQL identifier (dump data is untrusted). */\nexport function ensureSafeIdentifier(identifier: string): string {\n\tif (!/^[a-zA-Z0-9_]+$/.test(identifier)) {\n\t\tthrow new PersistenceError(`Unsafe SQL identifier: ${identifier}`, {\n\t\t\tcode: 'UNSAFE_IDENTIFIER',\n\t\t\tidentifier,\n\t\t})\n\t}\n\treturn identifier\n}\n\n/**\n * Read every user table through `query`. Pass a transaction's `query` to get a\n * consistent snapshot.\n */\nexport async function exportDump(query: QueryFn): Promise<DatabaseDump> {\n\tconst tableRows = await query<{ name: string; sql: string | null }>(\n\t\t\"SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\",\n\t)\n\tconst tables: DatabaseDump['tables'] = []\n\tfor (const tableRow of tableRows) {\n\t\tconst tableName = ensureSafeIdentifier(tableRow.name)\n\t\tconst columns = await query<{ name: string }>(`PRAGMA table_info(${quoteIdent(tableName)})`)\n\t\tconst rows = await query<Record<string, unknown>>(`SELECT * FROM ${quoteIdent(tableName)}`)\n\t\ttables.push({\n\t\t\tname: tableName,\n\t\t\t...(typeof tableRow.sql === 'string' ? { sql: tableRow.sql } : {}),\n\t\t\tcolumns: columns.map((column) => column.name),\n\t\t\trows,\n\t\t})\n\t}\n\treturn { tables }\n}\n\n/**\n * Statements that replace the contents of each dumped table with the dump's\n * rows. Run them inside one transaction so a failure leaves the target as it was.\n *\n * A table the target does not have yet (the store creates some of its bookkeeping\n * tables after the schema DDL) is created first from the dump's recorded `CREATE TABLE`\n * statement, constraints included. A dump written before statements were recorded\n * creates it untyped, so its rows are still restored.\n *\n * @param createMissingTables - Kept for callers that restore into scratch databases\n *   with no schema; missing tables are always created now.\n */\nexport function restoreDumpStatements(\n\tdump: DatabaseDump,\n\t_createMissingTables = true,\n): DumpStatement[] {\n\tconst statements: DumpStatement[] = []\n\tfor (const table of dump.tables) {\n\t\tconst name = quoteIdent(ensureSafeIdentifier(table.name))\n\t\tconst create = createTableIfNotExists(table.name, table.sql)\n\t\tif (create) {\n\t\t\tstatements.push({ sql: create })\n\t\t} else {\n\t\t\tconst columns = table.columns.map((column) => quoteIdent(ensureSafeIdentifier(column)))\n\t\t\tif (columns.length === 0) continue\n\t\t\tstatements.push({ sql: `CREATE TABLE IF NOT EXISTS ${name} (${columns.join(', ')})` })\n\t\t}\n\t\tstatements.push({ sql: `DELETE FROM ${name}` })\n\t\tfor (const row of table.rows) {\n\t\t\tconst columns = table.columns.filter((column) =>\n\t\t\t\tObject.prototype.hasOwnProperty.call(row, column),\n\t\t\t)\n\t\t\tif (columns.length === 0) continue\n\t\t\tconst quotedColumns = columns\n\t\t\t\t.map((column) => quoteIdent(ensureSafeIdentifier(column)))\n\t\t\t\t.join(', ')\n\t\t\tstatements.push({\n\t\t\t\tsql: `INSERT INTO ${name} (${quotedColumns}) VALUES (${columns.map(() => '?').join(', ')})`,\n\t\t\t\tparams: columns.map((column) => row[column]),\n\t\t\t})\n\t\t}\n\t}\n\treturn statements\n}\n\n/**\n * The recorded `CREATE TABLE` statement made idempotent, or null when there is none or\n * it is not a single plain `CREATE TABLE` of exactly this table (dump data is untrusted).\n */\nfunction createTableIfNotExists(tableName: string, sql: string | undefined): string | null {\n\tif (typeof sql !== 'string' || sql.includes(';')) return null\n\tconst match = /^\\s*CREATE\\s+TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(\"?)([A-Za-z0-9_]+)\\1\\s*\\(/i.exec(\n\t\tsql,\n\t)\n\tif (!match || match[2] !== tableName) return null\n\treturn `CREATE TABLE IF NOT EXISTS ${quoteIdent(tableName)} ${sql.slice(match[0].length - 1)}`\n}\n","/// <reference lib=\"dom\" />\nimport { KORA_STORAGE_FORMAT } from '@korajs/core'\nimport { PersistenceError, StorageFormatAheadError } from '../errors'\n\nconst IDB_DATABASE_NAME = 'kora-persistence'\nconst IDB_STORE_NAME = 'databases'\nconst IDB_VERSION = 1\n\nconst DUMP_SUFFIX = '::dump'\nconst VERSION_SUFFIX = '::version'\nconst EPOCH_SUFFIX = '::epoch'\nconst PINS_SUFFIX = '::pins'\n\n/**\n * Identifies the database state a snapshot was taken from. `lineage` is one in-memory\n * worker database (a fresh one is created on every restore from IndexedDB), `epoch` is\n * claimed for it when it starts ({@link startSnapshotLineage}), and `seq` counts the write\n * transactions committed in that worker database. Within one lineage a higher `seq`\n * contains every write of a lower one, so snapshots can be ordered no matter which tab\n * saves them. A stored `seq` of -1 is a fence: the lineage started, nothing saved yet.\n */\nexport interface SnapshotVersion {\n\tepoch: number\n\tlineage: string\n\tseq: number\n}\n\n/**\n * A worker database a lineage descends from, and the commit count of the snapshot it\n * restored from (every write of that lineage up to `seq` is in the descendant). -1: that\n * lineage never saved a snapshot.\n */\nexport interface SnapshotAncestor {\n\tlineage: string\n\tseq: number\n}\n\n/**\n * How many of the most recent ancestors a stored version always keeps. An older ancestor\n * is kept only while it is pinned ({@link setSnapshotLineagePins}): a tab still holding\n * unsaved writes in it needs it to tell whether another tab saved them. Without the pin\n * it is dropped, since no tab can ask about it any more.\n */\nconst MAX_ANCESTORS = 32\n\n/** The result of {@link saveSnapshotToIndexedDB}. */\nexport interface SnapshotSaveResult {\n\t/** `written`, or `covered` when the stored snapshot already held this one's writes. */\n\toutcome: 'written' | 'covered'\n\t/** Lineages the stored snapshot descends from (newest first). */\n\tancestors: SnapshotAncestor[]\n}\n\n/** A full snapshot: the JSON dump, the binary image when the worker can export one. */\nexport interface SnapshotRecord<TDump = unknown> {\n\tdump: TDump\n\t/** Binary SQLite image taken at the same `version`, or null (browser workers). */\n\tdata: Uint8Array | null\n\tversion: SnapshotVersion\n}\n\n/** `context.code` of the {@link PersistenceError} a refused snapshot save rejects with. */\nexport const SNAPSHOT_SUPERSEDED = 'SNAPSHOT_SUPERSEDED'\n\n/**\n * What saving a snapshot over `stored` must do:\n * - `write`: the snapshot is from the same worker database and newer, or from a database\n *   that started later (higher epoch);\n * - `covered`: the stored snapshot is from the same worker database and at least as new,\n *   so it already holds every write this one holds;\n * - `superseded`: the stored snapshot comes from a database that started later, or no\n *   version is stored at all. Every lineage writes a fence version before its first save\n *   ({@link startSnapshotLineage}), so a missing version means the database was deleted\n *   after this snapshot's lineage started: saving it would bring deleted data back.\n */\nexport function compareSnapshotVersions(\n\tstored: SnapshotVersion | null,\n\tincoming: SnapshotVersion,\n): 'write' | 'covered' | 'superseded' {\n\tif (stored === null) return 'superseded'\n\tif (incoming.lineage === stored.lineage) {\n\t\treturn incoming.seq > stored.seq ? 'write' : 'covered'\n\t}\n\treturn incoming.epoch > stored.epoch ? 'write' : 'superseded'\n}\n\nfunction asSnapshotVersion(value: unknown): SnapshotVersion | null {\n\tif (typeof value !== 'object' || value === null) return null\n\tconst candidate = value as Record<string, unknown>\n\tif (\n\t\ttypeof candidate.epoch !== 'number' ||\n\t\t!Number.isSafeInteger(candidate.epoch) ||\n\t\ttypeof candidate.lineage !== 'string' ||\n\t\ttypeof candidate.seq !== 'number' ||\n\t\t!Number.isSafeInteger(candidate.seq)\n\t) {\n\t\treturn null\n\t}\n\treturn { epoch: candidate.epoch, lineage: candidate.lineage, seq: candidate.seq }\n}\n\n/**\n * The Kora storage format a version record was written under (version gate): absent in\n * records written before the gate (format 0).\n */\nfunction storedFormatOf(value: unknown): number {\n\tif (typeof value !== 'object' || value === null) return 0\n\tconst format = (value as Record<string, unknown>).format\n\treturn typeof format === 'number' && Number.isSafeInteger(format) ? format : 0\n}\n\nfunction asAncestors(value: unknown): SnapshotAncestor[] {\n\tif (typeof value !== 'object' || value === null) return []\n\tconst list = (value as Record<string, unknown>).ancestors\n\tif (!Array.isArray(list)) return []\n\tconst ancestors: SnapshotAncestor[] = []\n\tfor (const entry of list) {\n\t\tif (typeof entry !== 'object' || entry === null) continue\n\t\tconst candidate = entry as Record<string, unknown>\n\t\tif (typeof candidate.lineage === 'string' && Number.isSafeInteger(candidate.seq)) {\n\t\t\tancestors.push({ lineage: candidate.lineage, seq: candidate.seq as number })\n\t\t}\n\t}\n\treturn ancestors\n}\n\n/**\n * `stored` and its ancestors, as the ancestors of a lineage that replaces it: the\n * {@link MAX_ANCESTORS} most recent, and every older one still `pinned`.\n */\nfunction descendFrom(\n\tstored: SnapshotVersion | null,\n\tancestors: SnapshotAncestor[],\n\tpinned: ReadonlySet<string>,\n): SnapshotAncestor[] {\n\tconst all = stored ? [{ lineage: stored.lineage, seq: stored.seq }, ...ancestors] : ancestors\n\treturn all.filter((entry, index) => index < MAX_ANCESTORS || pinned.has(entry.lineage))\n}\n\n/**\n * Pins per holder (one adapter): the lineages it still has unsaved writes in, least\n * recently updated holder first.\n */\ntype LineagePins = Record<string, string[]>\n\n/**\n * How many holders' pins are kept. A tab that crashed with unsaved writes never removes\n * its pins; beyond this many holders the least recently updated are dropped, so the\n * pinned ancestry stays bounded. A live holder re-pins on every change of its lineages.\n */\nconst MAX_PIN_HOLDERS = 64\n\nfunction asPins(value: unknown): LineagePins {\n\tif (typeof value !== 'object' || value === null) return {}\n\tconst pins: LineagePins = {}\n\tfor (const [holder, lineages] of Object.entries(value as Record<string, unknown>)) {\n\t\tif (Array.isArray(lineages)) {\n\t\t\tpins[holder] = lineages.filter((lineage): lineage is string => typeof lineage === 'string')\n\t\t}\n\t}\n\treturn pins\n}\n\nfunction pinnedLineages(value: unknown): Set<string> {\n\treturn new Set(Object.values(asPins(value)).flat())\n}\n\nfunction toUint8Array(value: unknown): Uint8Array | null {\n\tif (value instanceof Uint8Array) return value\n\tif (value) return new Uint8Array(value as ArrayBuffer)\n\treturn null\n}\n\n/**\n * Returns true when an IndexedDB error indicates storage quota was exceeded.\n */\nexport function isIndexedDbQuotaError(error: unknown): boolean {\n\tif (error instanceof DOMException && error.name === 'QuotaExceededError') {\n\t\treturn true\n\t}\n\tif (error instanceof PersistenceError && error.context?.quotaExceeded === true) {\n\t\treturn true\n\t}\n\tif (error instanceof Error && /quota/i.test(error.message)) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n/**\n * Settle `tx`: resolve on `complete`, reject with a {@link PersistenceError} on `error`\n * or `abort`. A commit can fail with no request error (a quota failure while writing the\n * data to disk aborts the transaction and fires only `abort`); without the `abort`\n * handler the promise would never settle and every later flush would wait on it.\n */\nfunction settleTransaction(\n\ttx: IDBTransaction,\n\tresolve: () => void,\n\treject: (reason: unknown) => void,\n\tmessage: string,\n\tcontext: Record<string, unknown>,\n): void {\n\tlet settled = false\n\tconst fail = (event: Event): void => {\n\t\tif (settled) return\n\t\tsettled = true\n\t\tconst error = (event.target as IDBRequest | IDBTransaction | undefined)?.error ?? tx.error\n\t\tif (error && isIndexedDbQuotaError(error)) {\n\t\t\treject(\n\t\t\t\tnew PersistenceError(message, { ...context, quotaExceeded: true, cause: error.message }),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\treject(\n\t\t\tnew PersistenceError(message, {\n\t\t\t\t...context,\n\t\t\t\t...(error ? { cause: error.message } : { cause: 'transaction aborted' }),\n\t\t\t}),\n\t\t)\n\t}\n\ttx.oncomplete = () => {\n\t\tif (settled) return\n\t\tsettled = true\n\t\tresolve()\n\t}\n\ttx.onerror = fail\n\ttx.onabort = fail\n}\n\n/**\n * Open the IndexedDB database used for SQLite persistence.\n * Creates the object store on first access.\n */\nfunction openIdb(): Promise<IDBDatabase> {\n\treturn new Promise<IDBDatabase>((resolve, reject) => {\n\t\tconst request = indexedDB.open(IDB_DATABASE_NAME, IDB_VERSION)\n\t\trequest.onupgradeneeded = () => {\n\t\t\tconst db = request.result\n\t\t\tif (!db.objectStoreNames.contains(IDB_STORE_NAME)) {\n\t\t\t\tdb.createObjectStore(IDB_STORE_NAME)\n\t\t\t}\n\t\t}\n\t\trequest.onsuccess = () => resolve(request.result)\n\t\trequest.onerror = () =>\n\t\t\treject(\n\t\t\t\tnew PersistenceError(\n\t\t\t\t\t`Failed to open IndexedDB: ${request.error?.message ?? 'unknown error'}`,\n\t\t\t\t\t{ database: IDB_DATABASE_NAME },\n\t\t\t\t),\n\t\t\t)\n\t})\n}\n\n/**\n * Save a serialized SQLite database to IndexedDB.\n *\n * @param dbName - Key under which to store the data\n * @param data - Serialized database as Uint8Array\n */\nexport async function saveToIndexedDB(dbName: string, data: Uint8Array): Promise<void> {\n\tconst idb = await openIdb()\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = idb.transaction(IDB_STORE_NAME, 'readwrite')\n\t\t\tconst store = tx.objectStore(IDB_STORE_NAME)\n\t\t\tstore.put(data, dbName)\n\t\t\tsettleTransaction(tx, resolve, reject, `Failed to save database \"${dbName}\" to IndexedDB`, {\n\t\t\t\tdbName,\n\t\t\t})\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n\n/**\n * Save a logical SQL dump payload to IndexedDB for import-fallback restore.\n */\nexport async function saveDumpToIndexedDB(dbName: string, dump: unknown): Promise<void> {\n\tconst idb = await openIdb()\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = idb.transaction(IDB_STORE_NAME, 'readwrite')\n\t\t\tconst store = tx.objectStore(IDB_STORE_NAME)\n\t\t\tstore.put(dump, `${dbName}${DUMP_SUFFIX}`)\n\t\t\tsettleTransaction(tx, resolve, reject, `Failed to save dump for database \"${dbName}\"`, {\n\t\t\t\tdbName,\n\t\t\t})\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n\n/**\n * Save a snapshot with compare-and-put: in ONE IndexedDB `readwrite` transaction, read the\n * stored snapshot's version and, only when this snapshot is newer\n * ({@link compareSnapshotVersions}), write the JSON dump, the binary image (or delete a\n * stale one) and the version together. An older snapshot never replaces a newer one, and\n * the binary image and the dump can never come from different versions.\n *\n * @param options - `strict` opens the transaction with IndexedDB durability `strict`\n * @returns whether it was written or already covered, and the stored snapshot's ancestors\n * @throws PersistenceError when the stored snapshot comes from a later worker database\n */\nexport async function saveSnapshotToIndexedDB(\n\tdbName: string,\n\tsnapshot: SnapshotRecord,\n\toptions: { strict?: boolean } = {},\n): Promise<SnapshotSaveResult> {\n\tconst idb = await openIdb()\n\ttry {\n\t\treturn await new Promise<SnapshotSaveResult>((resolve, reject) => {\n\t\t\t// Barrier snapshots are strict: Chrome's default `relaxed` can fire `complete` before the\n\t\t\t// data reaches disk, which a durable-write promise must not rely on.\n\t\t\tconst tx = options.strict\n\t\t\t\t? idb.transaction(IDB_STORE_NAME, 'readwrite', { durability: 'strict' })\n\t\t\t\t: idb.transaction(IDB_STORE_NAME, 'readwrite')\n\t\t\tconst store = tx.objectStore(IDB_STORE_NAME)\n\t\t\tlet outcome: 'written' | 'covered' = 'written'\n\t\t\tlet ancestors: SnapshotAncestor[] = []\n\t\t\tlet refusal: PersistenceError | null = null\n\t\t\tsettleTransaction(\n\t\t\t\ttx,\n\t\t\t\t() => {\n\t\t\t\t\tif (refusal) reject(refusal)\n\t\t\t\t\telse resolve({ outcome, ancestors })\n\t\t\t\t},\n\t\t\t\treject,\n\t\t\t\t`Failed to save snapshot of database \"${dbName}\" to IndexedDB`,\n\t\t\t\t{ dbName },\n\t\t\t)\n\t\t\tconst pins = store.get(`${dbName}${PINS_SUFFIX}`)\n\t\t\tconst read = store.get(`${dbName}${VERSION_SUFFIX}`)\n\t\t\tread.onsuccess = () => {\n\t\t\t\tconst stored = asSnapshotVersion(read.result)\n\t\t\t\tconst storedAncestors = asAncestors(read.result)\n\t\t\t\t// A record a build with a newer storage format wrote is never overwritten by\n\t\t\t\t// this code (version gate): treated as a newer copy.\n\t\t\t\tconst decision =\n\t\t\t\t\tstoredFormatOf(read.result) > KORA_STORAGE_FORMAT\n\t\t\t\t\t\t? 'superseded'\n\t\t\t\t\t\t: compareSnapshotVersions(stored, snapshot.version)\n\t\t\t\tancestors =\n\t\t\t\t\tstored && stored.lineage !== snapshot.version.lineage\n\t\t\t\t\t\t? descendFrom(stored, storedAncestors, pinnedLineages(pins.result))\n\t\t\t\t\t\t: storedAncestors\n\t\t\t\tif (decision === 'write') {\n\t\t\t\t\tstore.put(snapshot.dump, `${dbName}${DUMP_SUFFIX}`)\n\t\t\t\t\tif (snapshot.data) {\n\t\t\t\t\t\tstore.put(snapshot.data, dbName)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstore.delete(dbName)\n\t\t\t\t\t}\n\t\t\t\t\tstore.put(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tepoch: snapshot.version.epoch,\n\t\t\t\t\t\t\tlineage: snapshot.version.lineage,\n\t\t\t\t\t\t\tseq: snapshot.version.seq,\n\t\t\t\t\t\t\tancestors,\n\t\t\t\t\t\t\tformat: KORA_STORAGE_FORMAT,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t`${dbName}${VERSION_SUFFIX}`,\n\t\t\t\t\t)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (decision === 'covered') {\n\t\t\t\t\toutcome = 'covered'\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trefusal = new PersistenceError(\n\t\t\t\t\tstored === null\n\t\t\t\t\t\t? `Snapshot of database \"${dbName}\" was not saved: the database was deleted from IndexedDB after this copy of it was opened`\n\t\t\t\t\t\t: `Snapshot of database \"${dbName}\" was not saved: IndexedDB holds a newer copy of the database (another tab restored it), and an older copy must never replace it. Writes made only in this copy are lost.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tdbName,\n\t\t\t\t\t\tcode: SNAPSHOT_SUPERSEDED,\n\t\t\t\t\t\tstored,\n\t\t\t\t\t\tstoredAncestors,\n\t\t\t\t\t\tattempted: snapshot.version,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n\n/** The stored snapshot a new lineage starts from, and the epoch claimed for it. */\nexport interface StartedSnapshotLineage<TDump> {\n\tepoch: number\n\tdata: Uint8Array | null\n\tdump: TDump | null\n}\n\n/**\n * Start a snapshot lineage (a worker database about to receive this database's data), in\n * ONE IndexedDB `readwrite` transaction: claim an epoch from the database's epoch counter\n * (higher than every epoch claimed or stored before, so a lineage started later always\n * outranks an earlier one), read the stored snapshot the lineage restores from, and store\n * the fence version `{ epoch, lineage, seq: -1 }`. From then on a save from any older\n * lineage is refused ({@link SNAPSHOT_SUPERSEDED}) instead of being accepted and later\n * overwritten by this lineage's first save, which never saw it.\n *\n * `replace` is for a lineage whose data comes from elsewhere (the OPFS copy carried over):\n * its fence claims no ancestor, since it holds none of the stored snapshot's writes.\n *\n * When the stored version already belongs to `lineage` (a lineage started for a worker\n * database another tab is starting at the same time), it is left as is: the fence never\n * lowers a saved `seq`. Opening writes only these two small records, never a copy of the\n * data.\n */\nexport async function startSnapshotLineage<TDump>(\n\tdbName: string,\n\tlineage: string,\n\tmode: 'restore' | 'replace' = 'restore',\n): Promise<StartedSnapshotLineage<TDump>> {\n\tconst idb = await openIdb()\n\ttry {\n\t\treturn await new Promise<StartedSnapshotLineage<TDump>>((resolve, reject) => {\n\t\t\tconst tx = idb.transaction(IDB_STORE_NAME, 'readwrite')\n\t\t\tconst store = tx.objectStore(IDB_STORE_NAME)\n\t\t\tlet epoch = 0\n\t\t\tconst counter = store.get(`${dbName}${EPOCH_SUFFIX}`)\n\t\t\tconst data = store.get(dbName)\n\t\t\tconst dump = store.get(`${dbName}${DUMP_SUFFIX}`)\n\t\t\tconst pins = store.get(`${dbName}${PINS_SUFFIX}`)\n\t\t\tconst version = store.get(`${dbName}${VERSION_SUFFIX}`)\n\t\t\tlet formatAhead: StorageFormatAheadError | null = null\n\t\t\tversion.onsuccess = () => {\n\t\t\t\tconst storedFormat = storedFormatOf(version.result)\n\t\t\t\tif (storedFormat > KORA_STORAGE_FORMAT) {\n\t\t\t\t\t// A build with a newer storage format wrote this database: refuse it before\n\t\t\t\t\t// anything (not even the fence) is written (version gate, section 3).\n\t\t\t\t\tformatAhead = new StorageFormatAheadError(dbName, storedFormat, KORA_STORAGE_FORMAT)\n\t\t\t\t\ttx.abort()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst stored = asSnapshotVersion(version.result)\n\t\t\t\tif (stored?.lineage === lineage) {\n\t\t\t\t\tepoch = stored.epoch\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst last = typeof counter.result === 'number' ? counter.result : 0\n\t\t\t\tepoch = Math.max(last, stored?.epoch ?? 0) + 1\n\t\t\t\tstore.put(epoch, `${dbName}${EPOCH_SUFFIX}`)\n\t\t\t\t// The fence. It records what this lineage restores from, so a tab whose writes\n\t\t\t\t// were in an ancestor (saved there by another tab) can tell they survived.\n\t\t\t\tconst ancestors =\n\t\t\t\t\tmode === 'replace'\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: descendFrom(stored, asAncestors(version.result), pinnedLineages(pins.result))\n\t\t\t\tstore.put(\n\t\t\t\t\t{ epoch, lineage, seq: -1, ancestors, format: KORA_STORAGE_FORMAT },\n\t\t\t\t\t`${dbName}${VERSION_SUFFIX}`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tsettleTransaction(\n\t\t\t\ttx,\n\t\t\t\t() =>\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tepoch,\n\t\t\t\t\t\tdata: toUint8Array(data.result),\n\t\t\t\t\t\tdump: (dump.result as TDump | undefined) ?? null,\n\t\t\t\t\t}),\n\t\t\t\t(error) => reject(formatAhead ?? error),\n\t\t\t\t`Failed to start a snapshot lineage for database \"${dbName}\"`,\n\t\t\t\t{ dbName },\n\t\t\t)\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n\n/**\n * Record the lineages `holder` (one adapter) still has unsaved writes in, replacing what it\n * recorded before (an empty list removes the holder). A pinned lineage stays in the\n * ancestry of every later lineage however many leader changes follow, so the holder can\n * still learn whether another tab saved its writes there before it was replaced.\n */\nexport async function setSnapshotLineagePins(\n\tdbName: string,\n\tholder: string,\n\tlineages: string[],\n): Promise<void> {\n\tconst idb = await openIdb()\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = idb.transaction(IDB_STORE_NAME, 'readwrite')\n\t\t\tconst store = tx.objectStore(IDB_STORE_NAME)\n\t\t\tconst read = store.get(`${dbName}${PINS_SUFFIX}`)\n\t\t\tread.onsuccess = () => {\n\t\t\t\tconst pins = asPins(read.result)\n\t\t\t\t// Re-inserted last: the most recently updated holder is dropped last.\n\t\t\t\tdelete pins[holder]\n\t\t\t\tif (lineages.length > 0) pins[holder] = [...lineages]\n\t\t\t\tconst holders = Object.keys(pins)\n\t\t\t\tfor (const stale of holders.slice(0, Math.max(0, holders.length - MAX_PIN_HOLDERS))) {\n\t\t\t\t\tdelete pins[stale]\n\t\t\t\t}\n\t\t\t\tif (Object.keys(pins).length > 0) store.put(pins, `${dbName}${PINS_SUFFIX}`)\n\t\t\t\telse store.delete(`${dbName}${PINS_SUFFIX}`)\n\t\t\t}\n\t\t\tsettleTransaction(\n\t\t\t\ttx,\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t\t`Failed to record the unsaved snapshot lineages of database \"${dbName}\"`,\n\t\t\t\t{ dbName },\n\t\t\t)\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n\n/**\n * The stored snapshot's version record (`<db>::version`) and the lineages it descends from,\n * read straight from IndexedDB with no worker. A tab with no storage worker left (its\n * leader closed while it retires) settles its unsaved writes against it.\n */\nexport async function loadSnapshotVersionRecord(\n\tdbName: string,\n): Promise<{ stored: SnapshotVersion | null; ancestors: SnapshotAncestor[] }> {\n\tconst idb = await openIdb()\n\ttry {\n\t\treturn await new Promise((resolve, reject) => {\n\t\t\tconst tx = idb.transaction(IDB_STORE_NAME, 'readonly')\n\t\t\tconst read = tx.objectStore(IDB_STORE_NAME).get(`${dbName}${VERSION_SUFFIX}`)\n\t\t\tsettleTransaction(\n\t\t\t\ttx,\n\t\t\t\t() =>\n\t\t\t\t\tresolve({ stored: asSnapshotVersion(read.result), ancestors: asAncestors(read.result) }),\n\t\t\t\treject,\n\t\t\t\t`Failed to read the snapshot version of database \"${dbName}\" from IndexedDB`,\n\t\t\t\t{ dbName },\n\t\t\t)\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n\n/**\n * Load the stored snapshot (binary image, JSON dump and version) in one IndexedDB\n * transaction. `version` is null for snapshots written before versions were recorded.\n */\nexport async function loadSnapshotFromIndexedDB<TDump>(dbName: string): Promise<{\n\tdata: Uint8Array | null\n\tdump: TDump | null\n\tversion: SnapshotVersion | null\n}> {\n\tconst idb = await openIdb()\n\ttry {\n\t\treturn await new Promise((resolve, reject) => {\n\t\t\tconst tx = idb.transaction(IDB_STORE_NAME, 'readonly')\n\t\t\tconst store = tx.objectStore(IDB_STORE_NAME)\n\t\t\tconst data = store.get(dbName)\n\t\t\tconst dump = store.get(`${dbName}${DUMP_SUFFIX}`)\n\t\t\tconst version = store.get(`${dbName}${VERSION_SUFFIX}`)\n\t\t\tsettleTransaction(\n\t\t\t\ttx,\n\t\t\t\t() =>\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tdata: toUint8Array(data.result),\n\t\t\t\t\t\tdump: (dump.result as TDump | undefined) ?? null,\n\t\t\t\t\t\tversion: asSnapshotVersion(version.result),\n\t\t\t\t\t}),\n\t\t\t\treject,\n\t\t\t\t`Failed to load snapshot of database \"${dbName}\" from IndexedDB`,\n\t\t\t\t{ dbName },\n\t\t\t)\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n\n/**\n * Load a serialized SQLite database from IndexedDB.\n *\n * @param dbName - Key under which the data was stored\n * @returns The serialized database, or null if not found\n */\nexport async function loadFromIndexedDB(dbName: string): Promise<Uint8Array | null> {\n\tconst idb = await openIdb()\n\ttry {\n\t\treturn await new Promise<Uint8Array | null>((resolve, reject) => {\n\t\t\tconst tx = idb.transaction(IDB_STORE_NAME, 'readonly')\n\t\t\tconst store = tx.objectStore(IDB_STORE_NAME)\n\t\t\tconst request = store.get(dbName)\n\t\t\trequest.onsuccess = () => {\n\t\t\t\tconst result = request.result\n\t\t\t\tif (result instanceof Uint8Array) {\n\t\t\t\t\tresolve(result)\n\t\t\t\t} else if (result) {\n\t\t\t\t\t// Handle ArrayBuffer or other typed array forms\n\t\t\t\t\tresolve(new Uint8Array(result as ArrayBuffer))\n\t\t\t\t} else {\n\t\t\t\t\tresolve(null)\n\t\t\t\t}\n\t\t\t}\n\t\t\trequest.onerror = () =>\n\t\t\t\treject(\n\t\t\t\t\tnew PersistenceError(`Failed to load database \"${dbName}\" from IndexedDB`, { dbName }),\n\t\t\t\t)\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n\n/**\n * Load a logical SQL dump payload from IndexedDB.\n */\nexport async function loadDumpFromIndexedDB<T>(dbName: string): Promise<T | null> {\n\tconst idb = await openIdb()\n\ttry {\n\t\treturn await new Promise<T | null>((resolve, reject) => {\n\t\t\tconst tx = idb.transaction(IDB_STORE_NAME, 'readonly')\n\t\t\tconst store = tx.objectStore(IDB_STORE_NAME)\n\t\t\tconst request = store.get(`${dbName}${DUMP_SUFFIX}`)\n\t\t\trequest.onsuccess = () => {\n\t\t\t\tresolve((request.result as T | undefined) ?? null)\n\t\t\t}\n\t\t\trequest.onerror = () =>\n\t\t\t\treject(\n\t\t\t\t\tnew PersistenceError(`Failed to load dump for database \"${dbName}\" from IndexedDB`, {\n\t\t\t\t\t\tdbName,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n\n/**\n * Delete a serialized SQLite database from IndexedDB.\n *\n * The epoch counter is kept: a lineage started before the delete (a suspended tab that\n * resumes) must never outrank a database created after it, and with no stored version\n * its saves are refused ({@link compareSnapshotVersions}).\n *\n * @param dbName - Key to delete\n */\nexport async function deleteFromIndexedDB(dbName: string): Promise<void> {\n\tconst idb = await openIdb()\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tconst tx = idb.transaction(IDB_STORE_NAME, 'readwrite')\n\t\t\tconst store = tx.objectStore(IDB_STORE_NAME)\n\t\t\tstore.delete(dbName)\n\t\t\tstore.delete(`${dbName}${DUMP_SUFFIX}`)\n\t\t\tstore.delete(`${dbName}${VERSION_SUFFIX}`)\n\t\t\tstore.delete(`${dbName}${PINS_SUFFIX}`)\n\t\t\tsettleTransaction(\n\t\t\t\ttx,\n\t\t\t\tresolve,\n\t\t\t\treject,\n\t\t\t\t`Failed to delete database \"${dbName}\" from IndexedDB`,\n\t\t\t\t{ dbName },\n\t\t\t)\n\t\t})\n\t} finally {\n\t\tidb.close()\n\t}\n}\n","/// <reference lib=\"dom\" />\n/**\n * Kora-owned manifest of the local databases this origin created (W8a).\n *\n * One record per database name, kept in its own IndexedDB database so it is\n * readable from any tab without opening the OPFS pools. It records which backend\n * holds the database's data, which is how Kora keeps OPFS and IndexedDB from\n * ever holding two disjoint copies: a backend switch is a recorded, explicit\n * migration, never a silent fresh start (NEW-STORE-5, LMS-5c).\n *\n * The manifest is advisory for listing and authoritative for the backend\n * choice. Nothing is ever evicted automatically; deletion is the explicit\n * `deleteDatabase()` API.\n */\n\nconst MANIFEST_DB_NAME = 'kora-manifest'\nconst MANIFEST_STORE = 'databases'\nconst MANIFEST_VERSION = 1\n\n/** Where a database's data lives. */\nexport type LocalDatabaseBackend = 'opfs' | 'indexeddb'\n\n/** One manifest entry, as returned by `listDatabases()`. */\nexport interface LocalDatabaseRecord {\n\t/** The store name (`store.name`, plus the per-user suffix if namespaced). */\n\tdbName: string\n\t/** The backend that holds the authoritative copy. */\n\tbackend: LocalDatabaseBackend\n\t/** OPFS pool holding the file (opfs backend only). */\n\tpoolName?: string\n\t/** Wall-clock milliseconds; informational only, never used for ordering. */\n\tcreatedAt: number\n\t/** Wall-clock milliseconds of the last durable open; informational only. */\n\tlastOpenedAt: number\n\t/**\n\t * Random id of this database's life (also `_kora_meta.db_epoch`), written once the\n\t * first durable open completed. A record without one may belong to a database whose\n\t * creation never finished, so it is weak evidence of eviction (see storage-evidence).\n\t */\n\tepoch?: string\n\t/** Unsynced writes at `unsyncedAt` (offline-readiness: what a vanished database lost). */\n\tunsynced?: number\n\t/** Wall-clock milliseconds `unsynced` was recorded; informational only. */\n\tunsyncedAt?: number\n\t/** True when no write followed the recording of `unsynced` (it is exact, not stale). */\n\tunsyncedExact?: boolean\n}\n\n/** True when this runtime can keep a manifest (browsers; not Node tests). */\nexport function isManifestAvailable(): boolean {\n\treturn typeof indexedDB !== 'undefined'\n}\n\nfunction openManifest(): Promise<IDBDatabase> {\n\treturn new Promise<IDBDatabase>((resolve, reject) => {\n\t\tconst request = indexedDB.open(MANIFEST_DB_NAME, MANIFEST_VERSION)\n\t\trequest.onupgradeneeded = () => {\n\t\t\tconst db = request.result\n\t\t\tif (!db.objectStoreNames.contains(MANIFEST_STORE)) {\n\t\t\t\tdb.createObjectStore(MANIFEST_STORE, { keyPath: 'dbName' })\n\t\t\t}\n\t\t}\n\t\trequest.onsuccess = () => resolve(request.result)\n\t\trequest.onerror = () =>\n\t\t\treject(request.error ?? new Error('Failed to open the Kora storage manifest'))\n\t})\n}\n\nasync function withStore<T>(\n\tmode: IDBTransactionMode,\n\trun: (store: IDBObjectStore) => IDBRequest<T> | null,\n): Promise<T | undefined> {\n\tconst db = await openManifest()\n\ttry {\n\t\treturn await new Promise<T | undefined>((resolve, reject) => {\n\t\t\tconst tx = db.transaction(MANIFEST_STORE, mode)\n\t\t\tconst request = run(tx.objectStore(MANIFEST_STORE))\n\t\t\tlet result: T | undefined\n\t\t\tif (request) {\n\t\t\t\trequest.onsuccess = () => {\n\t\t\t\t\tresult = request.result\n\t\t\t\t}\n\t\t\t}\n\t\t\ttx.oncomplete = () => resolve(result)\n\t\t\ttx.onerror = () => reject(tx.error ?? new Error('Kora storage manifest transaction failed'))\n\t\t\ttx.onabort = () => reject(tx.error ?? new Error('Kora storage manifest transaction aborted'))\n\t\t})\n\t} finally {\n\t\tdb.close()\n\t}\n}\n\nfunction isRecord(value: unknown): value is LocalDatabaseRecord {\n\tif (typeof value !== 'object' || value === null) return false\n\tconst record = value as Partial<LocalDatabaseRecord>\n\treturn (\n\t\ttypeof record.dbName === 'string' &&\n\t\t(record.backend === 'opfs' || record.backend === 'indexeddb')\n\t)\n}\n\n/** Read the manifest entry for a database, or null when Kora never recorded it. */\nexport async function readManifestRecord(dbName: string): Promise<LocalDatabaseRecord | null> {\n\tif (!isManifestAvailable()) return null\n\tconst value = await withStore<unknown>('readonly', (store) => store.get(dbName))\n\treturn isRecord(value) ? value : null\n}\n\n/** Every database Kora recorded on this origin, sorted by name. */\nexport async function listManifestRecords(): Promise<LocalDatabaseRecord[]> {\n\tif (!isManifestAvailable()) return []\n\tconst values = await withStore<unknown[]>('readonly', (store) => store.getAll())\n\treturn (values ?? []).filter(isRecord).sort((a, b) => (a.dbName < b.dbName ? -1 : 1))\n}\n\n/**\n * Record (or refresh) which backend holds a database after a durable open,\n * keeping the original creation time.\n */\nexport async function recordDatabase(entry: {\n\tdbName: string\n\tbackend: LocalDatabaseBackend\n\tpoolName?: string\n}): Promise<void> {\n\tif (!isManifestAvailable()) return\n\tconst existing = await readManifestRecord(entry.dbName)\n\tconst now = Date.now()\n\t// The fields other writers own (epoch, unsynced*) survive a refresh of the backend; a\n\t// pool name belongs to the backend that reported it, so it is never carried over.\n\tconst { poolName: _previousPool, ...kept } = existing ?? ({} as Partial<LocalDatabaseRecord>)\n\tconst record: LocalDatabaseRecord = {\n\t\t...kept,\n\t\tdbName: entry.dbName,\n\t\tbackend: entry.backend,\n\t\t...(entry.poolName ? { poolName: entry.poolName } : {}),\n\t\tcreatedAt: existing?.createdAt ?? now,\n\t\tlastOpenedAt: now,\n\t}\n\tawait withStore('readwrite', (store) => store.put(record))\n}\n\n/**\n * Merge `patch` into a database's manifest entry, creating the entry when Kora never\n * recorded the database (adapters that do not track their backend still keep evidence).\n */\nexport async function patchManifestRecord(\n\tdbName: string,\n\tbackend: LocalDatabaseBackend,\n\tpatch: Partial<Pick<LocalDatabaseRecord, 'epoch' | 'unsynced' | 'unsyncedAt' | 'unsyncedExact'>>,\n): Promise<void> {\n\tif (!isManifestAvailable()) return\n\tconst existing = await readManifestRecord(dbName)\n\tconst now = Date.now()\n\tconst record: LocalDatabaseRecord = {\n\t\t...(existing ?? { dbName, backend, createdAt: now, lastOpenedAt: now }),\n\t\t...patch,\n\t}\n\tawait withStore('readwrite', (store) => store.put(record))\n}\n\n/** Remove a database's manifest entry (after its data was deleted). */\nexport async function deleteManifestRecord(dbName: string): Promise<void> {\n\tif (!isManifestAvailable()) return\n\tawait withStore('readwrite', (store) => store.delete(dbName))\n}\n","/// <reference lib=\"dom\" />\n/**\n * Evidence that a database existed on this device, kept OUTSIDE the database (A1 of the\n * offline-readiness design, section 6).\n *\n * A database whose OPFS pool or IndexedDB copy vanished reopens empty, and an empty\n * database looks exactly like a first visit. Two independent records tell the two apart:\n *\n * 1. the storage manifest (IndexedDB `kora-manifest`), extended with the database's\n *    `epoch` and its last known unsynced-write count;\n * 2. `localStorage['kora:db:<name>']`, which survives the loss of the IndexedDB copy the\n *    manifest shares a backend with, and carries the backend itself.\n *\n * Both are written only after a database finished its first durable open, so a crash\n * during creation never leaves evidence of a database that never existed.\n */\n\nimport {\n\ttype LocalDatabaseBackend,\n\ttype LocalDatabaseRecord,\n\tisManifestAvailable,\n\tpatchManifestRecord,\n\treadManifestRecord,\n} from './storage-manifest'\n\nconst MARKER_PREFIX = 'kora:db:'\nconst MARKER_VERSION = 1\n\n/** The `localStorage` marker of a database. */\nexport interface StorageMarker {\n\tv: 1\n\tepoch: string\n\tbackend: LocalDatabaseBackend\n}\n\n/** What survived outside the database at the time it was opened. */\nexport interface FoundStorageEvidence {\n\tmanifest: LocalDatabaseRecord | null\n\tmarker: StorageMarker | null\n}\n\n/**\n * A database that existed and vanished (`store:storage-evicted`, `storage.evicted`).\n */\nexport interface StorageEviction {\n\tdbName: string\n\t/** Wall-clock milliseconds the loss was detected. */\n\tdetectedAt: number\n\t/** Wall-clock milliseconds of the vanished database's last durable open, when known. */\n\tlastOpenedAt: number | null\n\t/** Which independent records named the vanished database. */\n\tevidence: Array<'manifest' | 'localStorage'>\n\t/**\n\t * Unsynced writes the vanished database held when it was last recorded. `certain` is\n\t * true when no write followed that recording; otherwise the count may be too low.\n\t */\n\tlostWrites: { count: number; certain: boolean }\n}\n\n/** The `localStorage` key of a database's marker. */\nexport function storageMarkerKey(dbName: string): string {\n\treturn `${MARKER_PREFIX}${dbName}`\n}\n\nfunction markerStorage(): Storage | null {\n\ttry {\n\t\tconst storage = (globalThis as { localStorage?: Storage }).localStorage\n\t\treturn storage ?? null\n\t} catch {\n\t\t// Access can throw (blocked site data, sandboxed frames): no marker is kept.\n\t\treturn null\n\t}\n}\n\n/**\n * Read a database's marker. A marker without a backend (malformed, or written by a future\n * format this build does not read) is ignored, never reported.\n */\nexport function readStorageMarker(dbName: string): StorageMarker | null {\n\ttry {\n\t\tconst raw = markerStorage()?.getItem(storageMarkerKey(dbName))\n\t\tif (!raw) return null\n\t\tconst parsed = JSON.parse(raw) as Partial<StorageMarker> | null\n\t\tif (\n\t\t\tparsed === null ||\n\t\t\ttypeof parsed !== 'object' ||\n\t\t\tparsed.v !== MARKER_VERSION ||\n\t\t\ttypeof parsed.epoch !== 'string' ||\n\t\t\t(parsed.backend !== 'opfs' && parsed.backend !== 'indexeddb')\n\t\t) {\n\t\t\treturn null\n\t\t}\n\t\treturn { v: MARKER_VERSION, epoch: parsed.epoch, backend: parsed.backend }\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/** Write a database's marker; failures are ignored (the manifest remains). */\nexport function writeStorageMarker(dbName: string, marker: StorageMarker): void {\n\ttry {\n\t\tmarkerStorage()?.setItem(storageMarkerKey(dbName), JSON.stringify(marker))\n\t} catch {\n\t\t// Quota or blocked storage: the manifest is still evidence.\n\t}\n}\n\n/** Remove a database's marker (an explicit deletion is not an eviction). */\nexport function clearStorageMarker(dbName: string): void {\n\ttry {\n\t\tmarkerStorage()?.removeItem(storageMarkerKey(dbName))\n\t} catch {\n\t\t// Nothing to clear.\n\t}\n}\n\n/** Read what survived outside the database, before any open refreshes it. */\nexport async function readFoundStorageEvidence(dbName: string): Promise<FoundStorageEvidence> {\n\tlet manifest: LocalDatabaseRecord | null = null\n\tif (isManifestAvailable()) {\n\t\ttry {\n\t\t\tmanifest = await readManifestRecord(dbName)\n\t\t} catch {\n\t\t\t// An unreadable manifest is no evidence; the marker may still be.\n\t\t}\n\t}\n\treturn { manifest, marker: readStorageMarker(dbName) }\n}\n\n/**\n * Evidence kept for one open database: what was found at open, and the writers that keep\n * the records current. Adapters that persist durably create one per open.\n */\nexport class StorageEvidence {\n\treadonly dbName: string\n\treadonly backend: LocalDatabaseBackend\n\tprivate readonly found: FoundStorageEvidence\n\n\tconstructor(options: {\n\t\tdbName: string\n\t\tbackend: LocalDatabaseBackend\n\t\tfound: FoundStorageEvidence\n\t}) {\n\t\tthis.dbName = options.dbName\n\t\tthis.backend = options.backend\n\t\tthis.found = options.found\n\t}\n\n\t/**\n\t * The eviction these records prove, or null. Only meaningful for a database that was\n\t * just created (the caller checks); a record for ANOTHER backend is never evidence (the\n\t * explicit IndexedDB/OPFS migration or `StorageBackendMismatchError` governs that case,\n\t * and this holds with the `localStorage` marker alone).\n\t */\n\tdetectEviction(now: number = Date.now()): StorageEviction | null {\n\t\tconst evidence: Array<'manifest' | 'localStorage'> = []\n\t\tconst manifest = this.found.manifest\n\t\t// DECISION: a manifest record counts when it has an epoch (the first durable open\n\t\t// finished), or - for records written before epochs existed - when the database was\n\t\t// opened at least twice. A record without an epoch from a single open could belong to a\n\t\t// database whose creation crashed before it held anything, and reporting that as a loss\n\t\t// would be a false positive.\n\t\tif (\n\t\t\tmanifest !== null &&\n\t\t\tmanifest.backend === this.backend &&\n\t\t\t(manifest.epoch !== undefined || manifest.lastOpenedAt > manifest.createdAt)\n\t\t) {\n\t\t\tevidence.push('manifest')\n\t\t}\n\t\tif (this.found.marker !== null && this.found.marker.backend === this.backend) {\n\t\t\tevidence.push('localStorage')\n\t\t}\n\t\tif (evidence.length === 0) return null\n\t\tconst count = evidence.includes('manifest') ? (manifest?.unsynced ?? 0) : 0\n\t\treturn {\n\t\t\tdbName: this.dbName,\n\t\t\tdetectedAt: now,\n\t\t\tlastOpenedAt: evidence.includes('manifest') ? (manifest?.lastOpenedAt ?? null) : null,\n\t\t\tevidence,\n\t\t\tlostWrites: {\n\t\t\t\tcount,\n\t\t\t\t// Exact only when a manifest recorded it as such; a marker alone knows nothing.\n\t\t\t\tcertain: evidence.includes('manifest') && manifest?.unsyncedExact === true,\n\t\t\t},\n\t\t}\n\t}\n\n\t/**\n\t * Record the database's epoch after its first durable open completed. `fresh` marks a\n\t * database that was just created (including after an eviction): its unsynced count\n\t * restarts at zero, exactly.\n\t */\n\tasync recordEpoch(epoch: string, fresh: boolean): Promise<void> {\n\t\tconst { manifest, marker } = this.found\n\t\tif (marker?.epoch !== epoch || marker.backend !== this.backend) {\n\t\t\twriteStorageMarker(this.dbName, { v: MARKER_VERSION, epoch, backend: this.backend })\n\t\t}\n\t\tif (!isManifestAvailable()) return\n\t\tif (!fresh && manifest?.epoch === epoch && manifest.backend === this.backend) return\n\t\tawait patchManifestRecord(this.dbName, this.backend, {\n\t\t\tepoch,\n\t\t\t...(fresh ? { unsynced: 0, unsyncedAt: Date.now(), unsyncedExact: true } : {}),\n\t\t})\n\t}\n\n\t/**\n\t * Record how many writes only this device holds. Written when the count crosses zero\n\t * and when the page is hidden, so it is cheap and at worst stale (`exact` false).\n\t */\n\tasync recordUnsynced(count: number, exact: boolean): Promise<void> {\n\t\tif (!isManifestAvailable()) return\n\t\tawait patchManifestRecord(this.dbName, this.backend, {\n\t\t\tunsynced: count,\n\t\t\tunsyncedAt: Date.now(),\n\t\t\tunsyncedExact: exact,\n\t\t})\n\t}\n}\n"]}