{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/adapters/indexeddb.cjs","../../src/adapters/indexeddb-persistence-scheduler.ts","../../src/adapters/indexeddb-adapter.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACE;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B,iCAA8B;AAC9B;AACA;ACxCA,IAAM,oBAAA,EAAsB,GAAA;AA4BrB,IAAM,8BAAA,YAAN,MAAoC;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,iBACT,MAAA,EAA8C,KAAA;AAAA,kBAC9C,SAAA,EAAiC,KAAA;AAAA,kBACjC,SAAA,EAAW,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAMX,oBAAA,EAAsB,EAAA;AAAA,kBACtB,oBAAA,EAAsB,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAMtB,iBAAA,EAAmB,EAAA;AAAA;AAAA,kBAEnB,eAAA,EAA0B,KAAA;AAAA;AAAA,kBAE1B,iBAAA,EAAmE,CAAC,EAAA;AAAA,EAC3D;AAAA,EAEjB,WAAA,CAAY,OAAA,EAA+C;AAC1D,IAAA,IAAA,CAAK,WAAA,mBAAa,OAAA,CAAQ,UAAA,UAAc,qBAAA;AACxC,IAAA,IAAA,CAAK,MAAA,EAAQ,OAAA,CAAQ,KAAA;AACrB,IAAA,IAAA,CAAK,QAAA,EAAU,OAAA,CAAQ,OAAA;AACvB,IAAA,IAAA,CAAK,mBAAA,EAAqB,CAAA,EAAA,GAAM;AAC/B,MAAA,GAAA,CAAI,OAAO,SAAA,IA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G9B,sBAAA;AAC2B,MAAA;AAC3B,MAAA;AAKkB,QAAA;AACoC,QAAA;AACzB,QAAA;AACD,QAAA;AACxC,MAAA;AAC8D,MAAA;AAC9D,IAAA;AACW,IAAA;AACwE,MAAA;AACrE,QAAA;AACP,QAAA;AACN,MAAA;AACF,IAAA;AACO,IAAA;AACN,MAAA;AACsE,MAAA;AACvE,IAAA;AACD,EAAA;AACD;AAG0B;AAMF;AAEqC;AACtC,EAAA;AACrB,IAAA;AACgB,IAAA;AACjB,EAAA;AACqB,EAAA;AACtB;AAE4F;AACH,EAAA;AAChD,EAAA;AACzC;AAQuB;AAC0D;AACE;AAM7B;AAM1B;AAoBiB;AAc5C;AAE4D;AAGzD,EAAA;AACuE,EAAA;AAC3E;AAEwE;AAC7B,EAAA;AAC3C;AAE+E;AAC7C,EAAA;AACmB,EAAA;AACrD;AAEkE;AAGhC,EAAA;AACf,EAAA;AACnB;AAO4F;AACrC,EAAA;AACL,EAAA;AACkC,EAAA;AACpF;AAQ+F;AAC7D,EAAA;AACoB,EAAA;AACyC,EAAA;AAC7F,IAAA;AACA,IAAA;AACA,EAAA;AACF;AAEgC;AACA,EAAA;AACQ,EAAA;AACuC,EAAA;AAC/E;AAE0D;AACoB,EAAA;AAC9E;AASmE;AACS,EAAA;AAMzE,EAAA;AACM,IAAA;AACR,EAAA;AACO,EAAA;AACR;AAE4D;AACK,EAAA;AACjE;AFvI8L;AACA;AACA","file":"/home/runner/work/kora/kora/packages/store/dist/adapters/indexeddb.cjs","sourcesContent":[null,"/// <reference lib=\"dom\" />\n\nimport { PersistenceError } from '../errors'\n\nconst DEFAULT_DEBOUNCE_MS = 500\n\n/** What a snapshot write is told about the snapshot it takes. */\nexport interface IndexedDbFlushOptions {\n\t/** A barrier snapshot: IndexedDB durability `strict`. */\n\tstrict: boolean\n\t/**\n\t * Call at the moment the snapshot reads the database (inside the export transaction,\n\t * which no write can interleave with). Writes scheduled until then are in the snapshot,\n\t * so barriers that arrive before it share it instead of waiting for another one. A flush\n\t * that never calls it covers the writes scheduled when it started.\n\t */\n\treadPoint: () => void\n}\n\nexport interface IndexedDbPersistenceSchedulerOptions {\n\t/** Debounce interval before writing a snapshot. Defaults to 500ms. */\n\tdebounceMs?: number\n\t/** Persist the in-memory database to IndexedDB. */\n\tflush: (options: IndexedDbFlushOptions) => Promise<void>\n\t/** Called when persistence fails (mutation already committed in memory). */\n\tonError?: (error: unknown) => void\n}\n\n/**\n * Coalesces IndexedDB snapshot writes: debounces rapid mutations and flushes\n * immediately on tab hide (`visibilitychange`) or explicit {@link flushNow}.\n */\nexport class IndexedDbPersistenceScheduler {\n\tprivate readonly debounceMs: number\n\tprivate readonly flush: (options: IndexedDbFlushOptions) => Promise<void>\n\tprivate readonly onError: ((error: unknown) => void) | undefined\n\tprivate timer: ReturnType<typeof setTimeout> | null = null\n\tprivate inFlight: Promise<void> | null = null\n\tprivate disposed = false\n\t/**\n\t * Mutation generations (RT-35): `scheduled` counts schedule() calls (one per committed\n\t * write), `persisted` is the generation the last SUCCESSFUL snapshot covered. A\n\t * snapshot covers every generation scheduled before it started.\n\t */\n\tprivate scheduledGeneration = 0\n\tprivate persistedGeneration = 0\n\t/**\n\t * Generation covered by the last successful STRICT snapshot (IndexedDB durability\n\t * `strict`: `complete` fires after the data reached disk). Barriers wait on this one;\n\t * debounced background snapshots stay `relaxed` and only advance `persistedGeneration`.\n\t */\n\tprivate strictGeneration = 0\n\t/** Error of the last snapshot attempt, cleared by the next success. */\n\tprivate lastFlushError: unknown = null\n\t/** Callers waiting for a snapshot to cover a generation ({@link whenPersisted}). */\n\tprivate persistedWaiters: Array<{ target: number; resolve: () => void }> = []\n\tprivate readonly onVisibilityChange: () => void\n\n\tconstructor(options: IndexedDbPersistenceSchedulerOptions) {\n\t\tthis.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS\n\t\tthis.flush = options.flush\n\t\tthis.onError = options.onError\n\t\tthis.onVisibilityChange = () => {\n\t\t\tif (typeof document !== 'undefined' && document.visibilityState === 'hidden') {\n\t\t\t\tvoid this.flushNow()\n\t\t\t}\n\t\t}\n\t\tif (typeof document !== 'undefined') {\n\t\t\tdocument.addEventListener('visibilitychange', this.onVisibilityChange)\n\t\t}\n\t}\n\n\t/** Schedule a debounced snapshot write. */\n\tschedule(): void {\n\t\tif (this.disposed) return\n\t\tthis.scheduledGeneration++\n\t\tif (this.debounceMs <= 0) {\n\t\t\tvoid this.flushNow()\n\t\t\treturn\n\t\t}\n\t\tif (this.timer !== null) {\n\t\t\tclearTimeout(this.timer)\n\t\t}\n\t\tthis.timer = setTimeout(() => {\n\t\t\tthis.timer = null\n\t\t\tvoid this.flushNow()\n\t\t}, this.debounceMs)\n\t}\n\n\t/**\n\t * Cancel any pending debounce and persist immediately. Resolves only when a snapshot\n\t * taken after every write scheduled so far was written (STORE-7): a snapshot already in\n\t * flight may predate the latest writes, so the call waits for it and then writes again\n\t * while anything is still dirty. A failed snapshot ends the loop (the failure is\n\t * reported through `onError`; {@link flushBarrier} is the variant that rejects).\n\t */\n\tasync flushNow(): Promise<void> {\n\t\tif (this.disposed) return\n\t\tif (this.timer !== null) {\n\t\t\tclearTimeout(this.timer)\n\t\t\tthis.timer = null\n\t\t}\n\t\t// With nothing in flight, \"persist immediately\" writes one snapshot even when no\n\t\t// write was scheduled (callers use it to force the first snapshot).\n\t\tlet mustRun = this.inFlight === null\n\t\tfor (;;) {\n\t\t\tif (this.inFlight) {\n\t\t\t\tawait this.inFlight\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (!mustRun && this.persistedGeneration >= this.scheduledGeneration) return\n\t\t\tmustRun = false\n\t\t\tthis.inFlight = this.runFlush()\n\t\t\ttry {\n\t\t\t\tawait this.inFlight\n\t\t\t} finally {\n\t\t\t\tthis.inFlight = null\n\t\t\t}\n\t\t\tif (this.lastFlushError !== null) return\n\t\t}\n\t}\n\n\t/**\n\t * Resolve once a successful snapshot covers every write scheduled so far. Unlike\n\t * {@link flushBarrier} it forces nothing: it waits for the debounced snapshot, so it adds\n\t * no snapshot of its own. Never settles if the scheduler is disposed first.\n\t */\n\twhenPersisted(): Promise<void> {\n\t\tconst target = this.scheduledGeneration\n\t\tif (this.persistedGeneration >= target) return Promise.resolve()\n\t\treturn new Promise<void>((resolve) => {\n\t\t\tthis.persistedWaiters.push({ target, resolve })\n\t\t})\n\t}\n\n\t/** Whether a snapshot write is in flight. */\n\tisFlushing(): boolean {\n\t\treturn this.inFlight !== null\n\t}\n\n\t/** Whether a write was scheduled that no successful snapshot covers yet. */\n\tisDirty(): boolean {\n\t\treturn this.persistedGeneration < this.scheduledGeneration\n\t}\n\n\t/**\n\t * Durability barrier (RT-35): resolve once every write scheduled before this call is\n\t * in a snapshot persisted to IndexedDB. A snapshot already in flight may predate the\n\t * latest write, so the barrier waits for it and then writes a fresh one when needed.\n\t * Rejects when the snapshot cannot be written: the caller must treat the writes as\n\t * not durable (for example, not upload them yet).\n\t */\n\tasync flushBarrier(): Promise<void> {\n\t\tconst target = this.scheduledGeneration\n\t\tif (this.strictGeneration >= target) return\n\t\tif (this.disposed) {\n\t\t\tthrow new PersistenceError(\n\t\t\t\t'IndexedDB persistence was disposed before the writes were persisted',\n\t\t\t)\n\t\t}\n\t\tif (this.timer !== null) {\n\t\t\tclearTimeout(this.timer)\n\t\t\tthis.timer = null\n\t\t}\n\t\t// Group commit: concurrent barriers share the snapshot in flight and the next one.\n\t\t// Snapshots already in flight (relaxed background ones, or strict ones that may predate\n\t\t// `target`) are waited out however many there are: a busy app keeps starting them, and\n\t\t// that is not a failure. The barrier ends when a strict snapshot covers `target`, or\n\t\t// fails when the strict snapshot it started itself fails (or the scheduler is disposed).\n\t\twhile (this.strictGeneration < target) {\n\t\t\tif (this.disposed) {\n\t\t\t\tthrow new PersistenceError(\n\t\t\t\t\t'IndexedDB persistence was disposed before the writes were persisted',\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (this.inFlight) {\n\t\t\t\tawait this.inFlight\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tthis.inFlight = this.runFlush(true)\n\t\t\ttry {\n\t\t\t\tawait this.inFlight\n\t\t\t} finally {\n\t\t\t\tthis.inFlight = null\n\t\t\t}\n\t\t\t// A strict snapshot started after `target` covers it unless it failed.\n\t\t\tif (this.strictGeneration < target) {\n\t\t\t\tthrow this.lastFlushError instanceof Error\n\t\t\t\t\t? this.lastFlushError\n\t\t\t\t\t: new PersistenceError('IndexedDB snapshot was not persisted')\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Durability barrier for writes this scheduler was never told about: another tab's\n\t * writes, committed in the database this tab's worker holds, before a follower asked\n\t * for a snapshot. Counts as one scheduled write, so the barrier waits for a strict\n\t * snapshot STARTED after the request (one already in flight may predate the follower's\n\t * write) and shares it with every other barrier waiting here, this tab's own included.\n\t */\n\tflushBarrierForPeer(): Promise<void> {\n\t\tthis.scheduledGeneration++\n\t\treturn this.flushBarrier()\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true\n\t\tif (this.timer !== null) {\n\t\t\tclearTimeout(this.timer)\n\t\t\tthis.timer = null\n\t\t}\n\t\tif (typeof document !== 'undefined') {\n\t\t\tdocument.removeEventListener('visibilitychange', this.onVisibilityChange)\n\t\t}\n\t}\n\n\tprivate async runFlush(strict = false): Promise<void> {\n\t\tlet generation = this.scheduledGeneration\n\t\tconst readPoint = (): void => {\n\t\t\tgeneration = Math.max(generation, this.scheduledGeneration)\n\t\t}\n\t\ttry {\n\t\t\tawait this.flush({ strict, readPoint })\n\t\t\tthis.persistedGeneration = Math.max(this.persistedGeneration, generation)\n\t\t\tif (strict) this.strictGeneration = Math.max(this.strictGeneration, generation)\n\t\t\tthis.lastFlushError = null\n\t\t\tconst ready = this.persistedWaiters.filter((w) => w.target <= this.persistedGeneration)\n\t\t\tthis.persistedWaiters = this.persistedWaiters.filter(\n\t\t\t\t(w) => w.target > this.persistedGeneration,\n\t\t\t)\n\t\t\tfor (const waiter of ready) waiter.resolve()\n\t\t} catch (error) {\n\t\t\tthis.lastFlushError = error\n\t\t\tthis.onError?.(error)\n\t\t}\n\t}\n}\n","import type { KoraEventEmitter, SchemaDefinition } from '@korajs/core'\nimport {\n\tAdapterError,\n\tBridgeTerminatedError,\n\tNoLeaderError,\n\tPersistenceError,\n\tSchemaVersionAheadError,\n\tStorageBackendMismatchError,\n\tStoreNotOpenError,\n\tWorkerTimeoutError,\n} from '../errors'\nimport { STORED_SCHEMA_VERSION_SQL, storedSchemaVersion } from '../migrations/schema-ceiling'\nimport { serveSnapshotBarriers } from '../multi-tab/tab-storage'\nimport { type SupersededInfo, VersionGate } from '../multi-tab/version-gate'\nimport { WriteGate } from '../multi-tab/write-gate'\nimport type { MigrationPlan, StorageAdapter, StorageOpenState, Transaction } from '../types'\nimport { type DatabaseDump, exportDump, restoreDumpStatements } from './database-dump'\nimport { IndexedDbPersistenceScheduler } from './indexeddb-persistence-scheduler'\nimport { SqliteWasmAdapter } from './sqlite-wasm-adapter'\nimport type { WorkerBridge, WorkerResponse } from './sqlite-wasm-channel'\nimport {\n\tSNAPSHOT_SUPERSEDED,\n\ttype SnapshotAncestor,\n\ttype SnapshotSaveResult,\n\ttype SnapshotVersion,\n\ttype StartedSnapshotLineage,\n\tisIndexedDbQuotaError,\n\tloadSnapshotVersionRecord,\n\tsaveSnapshotToIndexedDB,\n\tsetSnapshotLineagePins,\n\tstartSnapshotLineage,\n} from './sqlite-wasm-persistence'\nimport { StorageEvidence, readFoundStorageEvidence } from './storage-evidence'\nimport { isManifestAvailable, readManifestRecord, recordDatabase } from './storage-manifest'\n\n/**\n * Options for creating an IndexedDbAdapter.\n */\nexport interface IndexedDbAdapterOptions {\n\t/**\n\t * Database name used as the IndexedDB key for persistence.\n\t * Defaults to 'kora-db'.\n\t */\n\tdbName?: string\n\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 * 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 * Debounce interval (ms) before writing snapshots to IndexedDB. Defaults to 500.\n\t */\n\tpersistenceDebounceMs?: number\n\n\t/**\n\t * When set, persistence failures and quota errors are emitted on this emitter.\n\t */\n\temitter?: KoraEventEmitter\n\n\t/**\n\t * The version gate of this database (one build writes it at a time). In a browser\n\t * (worker path) the adapter creates one when omitted; `false` disables it.\n\t */\n\tversionGate?: VersionGate | false\n\n\t/** Build id for the version gate the adapter creates. */\n\tbuild?: string\n\n\t/** Open single-tab in a browser without Web Locks (test environments). */\n\tallowUncoordinatedTabs?: boolean\n\n\t/**\n\t * Broadcast channel on which this adapter, as the storage leader, answers followers'\n\t * durability-barrier requests. Browsers need not set it: the adapter serves on the\n\t * database's storage channel whenever its tab leads. Tests that give the adapter an\n\t * injected bridge set it on the adapter that stands for the leader tab.\n\t */\n\tsnapshotBarrierChannel?: string\n\n\t/**\n\t * Keep storage-loss evidence (manifest epoch, \\`localStorage\\` marker) for this database.\n\t * On by default in browsers (a real worker); tests with an injected bridge opt in.\n\t */\n\tstorageEvidence?: boolean\n}\n\n/**\n * IndexedDB-backed adapter that uses SQLite WASM in-memory and serializes\n * the entire database to IndexedDB after mutations (coalesced/debounced).\n *\n * This is the fallback adapter for browsers where OPFS is not available.\n * It provides the same SQL interface as SqliteWasmAdapter, but persists by\n * serializing the full SQLite database to a single IndexedDB blob.\n *\n * @example\n * ```typescript\n * const adapter = new IndexedDbAdapter({ workerUrl: '/sqlite-wasm-worker.js' })\n * ```\n */\nexport class IndexedDbAdapter implements StorageAdapter {\n\tprivate inner: SqliteWasmAdapter\n\tprivate readonly dbName: string\n\tprivate readonly emitter: KoraEventEmitter | undefined\n\tprivate readonly scheduler: IndexedDbPersistenceScheduler\n\tprivate storageOpenState: StorageOpenState | null = null\n\t/** What survived outside the database when it was opened (null: not tracked). */\n\tprivate evidence: StorageEvidence | null = null\n\tprivate readonly options: IndexedDbAdapterOptions\n\t/** True in browsers (a real worker), where the backend choice is recorded. */\n\tprivate readonly usesRealWorker: boolean\n\t/**\n\t * This tab's writes not yet in a saved snapshot, per worker database (lineage): the\n\t * highest commit count among them and the lineage's epoch. A write is durable only once\n\t * a snapshot of the SAME worker database at that count or later is saved.\n\t */\n\tprivate readonly unconfirmedWrites = new Map<string, { epoch: number; seq: number }>()\n\t/**\n\t * Worker databases this tab wrote to that were replaced (the storage leader changed)\n\t * before those writes were saved: the writes are gone. While one is listed, every\n\t * durability barrier of this tab rejects: each covers every write committed before it,\n\t * the lost ones included, so a retry never reports them saved. The list lives as long\n\t * as this adapter: a reload opens a new adapter (and the database in a new lineage), so\n\t * the loss is reported for this session and clears on reload.\n\t */\n\tprivate readonly lostLineages = new Set<string>()\n\t/** This adapter's id among the holders of lineage pins ({@link setSnapshotLineagePins}). */\n\tprivate readonly pinHolder = newLineageId()\n\t/** The lineages last pinned for this adapter (sorted, joined): skips unchanged updates. */\n\tprivate pinnedKey = ''\n\t/**\n\t * The lineage this tab last wrote in. It stays pinned after its writes are saved, so the\n\t * pin record is written once per lineage (once per leader change), not after every save.\n\t */\n\tprivate currentLineage: string | null = null\n\t/** Pin updates run one at a time, in order. */\n\tprivate pinUpdate: Promise<void> = Promise.resolve()\n\t/** The version gate of this database, or null where it does not apply. */\n\tprivate readonly versionGate: VersionGate | null\n\t/** Admits this adapter's writes until the tab retires (version gate, section 5). */\n\tprivate readonly writes = new WriteGate()\n\t/** Page lifecycle: suspended while frozen or in the back/forward cache. */\n\tprivate lifecycle: 'running' | 'suspended' = 'running'\n\tprivate removeLifecycleListeners: (() => void) | null = null\n\t/** Set once this tab retired: no snapshot of this build is ever written again. */\n\tprivate retired = false\n\t/** Set once {@link close} began: the tab stops answering followers' barriers. */\n\tprivate closing = false\n\t/** Stops answering followers' durability barriers (this tab leads), or null. */\n\tprivate stopBarrierServer: (() => void) | null = null\n\n\tconstructor(options: IndexedDbAdapterOptions = {}) {\n\t\tthis.options = options\n\t\tthis.dbName = options.dbName ?? 'kora-db'\n\t\tthis.emitter = options.emitter\n\t\tthis.usesRealWorker = !options.bridge && options.workerUrl !== undefined\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(this.usesRealWorker && typeof window !== 'undefined' && typeof document !== 'undefined'\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\tthis.inner = new SqliteWasmAdapter({\n\t\t\t// The inner adapter checks the gate before it leads and gives up its storage roles\n\t\t\t// when the tab retires; this adapter opens the gate, seals its own writes, makes\n\t\t\t// them durable and drives the page lifecycle.\n\t\t\tversionGate: gate ?? false,\n\t\t\t...(gate ? { versionGateManagedByParent: true, releaseOnFreeze: false } : {}),\n\t\t\tbridge: options.bridge,\n\t\t\tworkerUrl: options.workerUrl,\n\t\t\tdbName: this.dbName,\n\t\t\tworkerResponseTimeoutMs: options.workerResponseTimeoutMs,\n\t\t\t// The inner SQLite database is in memory by design: this adapter makes it\n\t\t\t// durable by persisting snapshots to IndexedDB, so the inner adapter must\n\t\t\t// not refuse writes as non-durable, and must never touch OPFS (which would\n\t\t\t// create a second, disjoint copy of the data).\n\t\t\tallowNonDurable: true,\n\t\t\tstorage: 'memory',\n\t\t\tskipBackendRecord: true,\n\t\t\t// A browser leader restores the snapshot into its own fresh worker database\n\t\t\t// before serving other tabs (first open and promotion, STORE-6).\n\t\t\tonLeaderWorkerOpened: (tx) => this.restoreDumpIfFresh(tx),\n\t\t\t// Followers' barriers are answered here, where the snapshot scheduler lives.\n\t\t\tonLeaderServing: (channelName) => this.serveBarriers(channelName),\n\t\t})\n\t\tthis.scheduler = new IndexedDbPersistenceScheduler({\n\t\t\tdebounceMs: options.persistenceDebounceMs,\n\t\t\tflush: ({ strict, readPoint }) => this.writeSnapshot(strict, readPoint),\n\t\t\tonError: (error) => this.handlePersistenceError(error),\n\t\t})\n\t\tif (gate) {\n\t\t\tgate.addRetireStep('durability', (info) => this.retireDurably(info))\n\t\t\tgate.setRecoveryExporter(() => this.exportRecoveryDump())\n\t\t\tgate.setCloseCheck(() => this.saveBeforeClose())\n\t\t}\n\t}\n\n\t/** The version gate this adapter's tab declares (null where it does not apply). */\n\tgetVersionGate(): VersionGate | null {\n\t\treturn this.versionGate\n\t}\n\n\t/**\n\t * Version gate, steps 3 and 4 for the IndexedDB fallback: refuse new writes, wait for\n\t * every started one, then make everything this tab committed durable. A failed barrier\n\t * keeps the gate closed: the tab keeps its tab lock and retries (backoff, the user's\n\t * Retry, `visibilitychange`) until a snapshot holds every committed write, reporting\n\t * `store:persistence-error` and `unsaved-writes`. `SNAPSHOT_SUPERSEDED` (this tab's\n\t * lineage was replaced; its lost writes already rejected) does not hold it.\n\t *\n\t * When no snapshot can be taken (storage full, or no storage worker left: the leader\n\t * this tab relayed to closed), the tab's writes are settled against the snapshot\n\t * IndexedDB holds, read without a worker: when another tab's save holds them all (or\n\t * they are known lost, already reported), retirement continues.\n\t */\n\tprivate async retireDurably(info: SupersededInfo): Promise<void> {\n\t\tthis.writes.close({ currentBuild: info.current.build, newerBuild: info.newer.build })\n\t\tawait this.writes.drain()\n\t\tconst gate = this.versionGate\n\t\tconst onVisible = (): void => {\n\t\t\tif (typeof document !== 'undefined' && document.visibilityState === 'visible') {\n\t\t\t\tgate?.retryNow()\n\t\t\t}\n\t\t}\n\t\tif (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisible)\n\t\ttry {\n\t\t\tfor (let attempt = 0; ; attempt += 1) {\n\t\t\t\t// Closed meanwhile (the app closed this tab's database): nothing to hand over.\n\t\t\t\tif (gate?.getState() === 'closed') return\n\t\t\t\t// A snapshot another tab stored may already hold every unsaved write of this tab (a\n\t\t\t\t// follower whose leader saved on close): settled without a worker, which this tab\n\t\t\t\t// may no longer have.\n\t\t\t\tif (this.unconfirmedWrites.size > 0 && (await this.settleAgainstStoredSnapshot())) break\n\t\t\t\ttry {\n\t\t\t\t\tawait this.ensureDurable()\n\t\t\t\t\tbreak\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof PersistenceError && error.context?.code === SNAPSHOT_SUPERSEDED) {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif (this.unconfirmedWrites.size > 0 && (await this.settleAgainstStoredSnapshot())) break\n\t\t\t\t\tconst code = unsavedWritesCode(error)\n\t\t\t\t\tconst because =\n\t\t\t\t\t\tcode === 'QUOTA_EXCEEDED'\n\t\t\t\t\t\t\t? ' (storage is full)'\n\t\t\t\t\t\t\t: code === 'STORAGE_UNAVAILABLE'\n\t\t\t\t\t\t\t\t? ' (this tab has no storage worker left to save them from)'\n\t\t\t\t\t\t\t\t: ''\n\t\t\t\t\tthis.emitter?.emit({\n\t\t\t\t\t\ttype: 'store:persistence-error',\n\t\t\t\t\t\tdbName: this.dbName,\n\t\t\t\t\t\tmessage: `Your latest changes to \"${this.dbName}\" are not saved yet${because}; this tab keeps them until they are saved. ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\tcode,\n\t\t\t\t\t})\n\t\t\t\t\tgate?.reportUnsavedWrites(true)\n\t\t\t\t\tif (!gate) break\n\t\t\t\t\tawait gate.waitForRetry(attempt)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tif (typeof document !== 'undefined') {\n\t\t\t\tdocument.removeEventListener('visibilitychange', onVisible)\n\t\t\t}\n\t\t}\n\t\tgate?.reportUnsavedWrites(false)\n\t\t// No snapshot of this build is written after this point.\n\t\tthis.retired = true\n\t\tthis.scheduler.dispose()\n\t\tthis.removeLifecycleListeners?.()\n\t\tthis.removeLifecycleListeners = null\n\t}\n\n\t/**\n\t * A close while this tab retires: wait for every write it admitted, then make them durable\n\t * with the throwing barrier (not the close path's best-effort flush). Writes another tab's\n\t * stored snapshot already holds, or known lost (reported), do not hold the close.\n\t *\n\t * @throws The gate's `UNSAVED_WRITES` refusal when they cannot be saved\n\t */\n\tprivate async saveBeforeClose(): Promise<void> {\n\t\tif (this.retired) return\n\t\tawait this.writes.drain()\n\t\tif (this.unconfirmedWrites.size > 0 && (await this.settleAgainstStoredSnapshot())) return\n\t\ttry {\n\t\t\tawait this.ensureDurable()\n\t\t} catch (error) {\n\t\t\tif (error instanceof PersistenceError && error.context?.code === SNAPSHOT_SUPERSEDED) return\n\t\t\tthrow this.versionGate?.closeRefusal(error) ?? error\n\t\t}\n\t}\n\n\t/**\n\t * Settle this tab's unsaved writes against the snapshot version IndexedDB holds (and its\n\t * ancestors), read without a worker. True when none is left unsettled: each is in a\n\t * stored snapshot, or known lost (reported by `markLost`, as a refused save would).\n\t */\n\tprivate async settleAgainstStoredSnapshot(): Promise<boolean> {\n\t\ttry {\n\t\t\tconst { stored, ancestors } = await loadSnapshotVersionRecord(this.dbName)\n\t\t\tthis.settleWrites(stored, ancestors, null)\n\t\t\tawait this.syncPins()\n\t\t} catch (error) {\n\t\t\tconsole.warn(`[kora] Could not read the stored snapshot version of \"${this.dbName}\":`, error)\n\t\t\treturn false\n\t\t}\n\t\treturn this.unconfirmedWrites.size === 0\n\t}\n\n\t/**\n\t * The explicit recovery path while a failed barrier holds retirement (storage full): a\n\t * dump of the database as this tab's worker holds it, for the prompt's Export button.\n\t */\n\tasync exportRecoveryDump(): Promise<DatabaseDump> {\n\t\tlet dump: DatabaseDump = { tables: [] }\n\t\tawait this.inner.transaction(async (tx) => {\n\t\t\tdump = await exportDump((sql, params) => tx.query(sql, params))\n\t\t})\n\t\treturn dump\n\t}\n\n\t/**\n\t * Page lifecycle (`freeze`, bfcache `pagehide`), as before the version gate: a frozen page\n\t * cannot finish a snapshot, so it never keeps other tabs waiting on its storage. The\n\t * storage roles are released at once (the snapshot scheduler already flushed when the\n\t * page was hidden); writes made after the last stored snapshot stay only in this tab's\n\t * worker database and are lost if another tab takes over (reported as\n\t * `SNAPSHOT_SUPERSEDED`). No write a stored snapshot confirmed is ever lost.\n\t *\n\t * The tab lock is released only when the storage roles were: a tab still opening,\n\t * promoting or closing keeps both, so a newer build never opens behind its worker.\n\t */\n\tprivate suspendForLifecycle(): void {\n\t\t// A retiring tab keeps its storage until its retirement steps release it.\n\t\tif (this.lifecycle !== 'running' || this.retired || this.versionGate?.isSuperseded()) return\n\t\tif (!this.inner.suspendForLifecycle()) return\n\t\tthis.lifecycle = 'suspended'\n\t\tthis.versionGate?.suspend()\n\t}\n\n\tprivate async resumeFromLifecycle(): Promise<void> {\n\t\tif (this.lifecycle !== 'suspended') return\n\t\tthis.lifecycle = 'running'\n\t\tconst gate = this.versionGate\n\t\tif (gate) {\n\t\t\t// A failure other than supersession keeps this tab suspended (no tab lock held,\n\t\t\t// the inner adapter detached) and retries; it never holds the lock without a worker.\n\t\t\tconst mayResume = await gate.resumeWithRetry()\n\t\t\tif (!mayResume) {\n\t\t\t\t// A newer build opened meanwhile: never re-attach. Requests queued behind the\n\t\t\t\t// suspension fail retriably, so the retirement's drain completes (as on OPFS).\n\t\t\t\tthis.inner.abandonLifecycleSuspension()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tawait this.inner.resumeForLifecycle()\n\t}\n\n\tprivate installLifecycleListeners(): void {\n\t\tif (!this.versionGate || this.removeLifecycleListeners) return\n\t\tif (typeof addEventListener !== 'function' || typeof document === 'undefined') return\n\t\tconst onSuspend = (): void => this.suspendForLifecycle()\n\t\tconst onResume = (): void => {\n\t\t\tvoid this.resumeFromLifecycle()\n\t\t}\n\t\tconst onPageShow = (event: Event): void => {\n\t\t\tif ((event as PageTransitionEvent).persisted) onResume()\n\t\t}\n\t\tdocument.addEventListener('freeze', onSuspend)\n\t\tdocument.addEventListener('resume', onResume)\n\t\taddEventListener('pagehide', onSuspend)\n\t\taddEventListener('pageshow', onPageShow)\n\t\tthis.removeLifecycleListeners = () => {\n\t\t\tdocument.removeEventListener('freeze', onSuspend)\n\t\t\tdocument.removeEventListener('resume', onResume)\n\t\t\tremoveEventListener('pagehide', onSuspend)\n\t\t\tremoveEventListener('pageshow', onPageShow)\n\t\t}\n\t}\n\n\t/** @internal Tests: the page lifecycle events this adapter handles. */\n\thandleLifecycleEvent(event: 'freeze' | 'resume'): Promise<void> {\n\t\tif (event === 'freeze') {\n\t\t\tthis.suspendForLifecycle()\n\t\t\treturn Promise.resolve()\n\t\t}\n\t\treturn this.resumeFromLifecycle()\n\t}\n\n\tasync open(schema: SchemaDefinition): Promise<void> {\n\t\t// The backend choice is recorded per database. If OPFS holds the\n\t\t// authoritative copy, carry it over explicitly before this session starts,\n\t\t// so OPFS and IndexedDB never hold two disjoint copies (NEW-STORE-5).\n\t\tconst gate = this.versionGate\n\t\tif (gate) {\n\t\t\t// Storage open waits for the version gate (rule 3): no restore, DDL or migration of\n\t\t\t// this build while a tab of another build may still write the database.\n\t\t\tgate.useSchemaFingerprint(schema)\n\t\t\tawait gate.open()\n\t\t}\n\t\ttry {\n\t\t\tawait this.openStorage(schema)\n\t\t\t// After the storage opened: a freeze during the open keeps the tab lock (the\n\t\t\t// storage roles cannot be released mid-open either).\n\t\t\tthis.installLifecycleListeners()\n\t\t} catch (error) {\n\t\t\t// A failed open (format or schema ahead, OPFS carry-over, a worker error) releases\n\t\t\t// everything it took, the tab lock last, so no other tab waits on a tab that never\n\t\t\t// opened.\n\t\t\tthis.removeLifecycleListeners?.()\n\t\t\tthis.removeLifecycleListeners = null\n\t\t\tthis.scheduler.dispose()\n\t\t\tawait this.inner.close().catch(() => undefined)\n\t\t\tgate?.close()\n\t\t\tthrow error\n\t\t}\n\t}\n\n\tprivate async openStorage(schema: SchemaDefinition): Promise<void> {\n\t\tconst tracksBackend = this.usesRealWorker && isManifestAvailable()\n\t\t// Read before anything below refreshes the manifest: this is what a vanished database\n\t\t// left behind (offline-readiness design, section 6.1).\n\t\tthis.evidence =\n\t\t\t(this.usesRealWorker || this.options.storageEvidence === true) && isManifestAvailable()\n\t\t\t\t? new StorageEvidence({\n\t\t\t\t\t\tdbName: this.dbName,\n\t\t\t\t\t\tbackend: 'indexeddb',\n\t\t\t\t\t\tfound: await readFoundStorageEvidence(this.dbName),\n\t\t\t\t\t})\n\t\t\t\t: null\n\t\tconst recorded = tracksBackend ? await readManifestRecord(this.dbName).catch(() => null) : null\n\t\tconst carried = recorded?.backend === 'opfs' ? await this.readOpfsCopy(schema) : null\n\n\t\tawait this.inner.open(schema)\n\t\tthis.storageOpenState = { persistent: true, mode: 'indexeddb' }\n\t\t// An adapter with an injected bridge has no worker to start serving from (tests):\n\t\t// the leader tab's barrier channel is named by the option instead.\n\t\tconst barrierChannel = this.options.snapshotBarrierChannel\n\t\tif (barrierChannel !== undefined && this.options.bridge && this.inner.isLeader()) {\n\t\t\tthis.serveBarriers(barrierChannel)\n\t\t}\n\n\t\tif (carried && this.inner.isLeader()) {\n\t\t\t// The fresh worker database is marked restored, then receives the OPFS copy. It\n\t\t\t// starts a new snapshot lineage, so its snapshot replaces any older IndexedDB copy.\n\t\t\t// Its data comes from OPFS, so it claims none of the IndexedDB snapshot's writes.\n\t\t\tconst lineage = newLineageId()\n\t\t\tconst { epoch } = await startSnapshotLineage(this.dbName, lineage, 'replace')\n\t\t\tlet counted: CommitCount = NO_WRITE\n\t\t\t// One transaction: the lineage, the data and its count land in the same worker\n\t\t\t// database, or none of them does.\n\t\t\tawait this.inner.transaction(async (tx) => {\n\t\t\t\tawait markRestored(tx, epoch, lineage)\n\t\t\t\tfor (const statement of restoreDumpStatements(carried)) {\n\t\t\t\t\tawait tx.execute(statement.sql, statement.params)\n\t\t\t\t}\n\t\t\t\tcounted = await countCommit(tx, null)\n\t\t\t})\n\t\t\tthis.recordWrite(counted.counted)\n\t\t\tawait this.scheduler.flushNow()\n\t\t\tawait this.syncPins()\n\t\t\tawait recordDatabase({ dbName: this.dbName, backend: 'indexeddb' })\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: 'opfs',\n\t\t\t\tto: 'indexeddb',\n\t\t\t\tmessage: `Database \"${this.dbName}\" moved from OPFS into IndexedDB because OPFS is not usable in this session.`,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\n\t\t// Only the storage leader restores, and only into a database no snapshot was\n\t\t// restored into yet: a follower tab (or a second adapter on the same worker)\n\t\t// opening must never rewrite the leader's live database (STORE-6).\n\t\tif (this.inner.isLeader()) {\n\t\t\tawait this.restoreIfFresh()\n\t\t}\n\t\t// A snapshot a newer build migrated (RT-109): refuse it before anything writes, and\n\t\t// without the snapshot a close() would write (the in-memory copy ran this build's\n\t\t// DDL before the restore).\n\t\tconst stored = storedSchemaVersion(\n\t\t\tawait this.inner.query<{ value: unknown }>(STORED_SCHEMA_VERSION_SQL),\n\t\t)\n\t\tif (stored > schema.version) {\n\t\t\tthis.scheduler.dispose()\n\t\t\tawait this.inner.close().catch(() => undefined)\n\t\t\tthrow new SchemaVersionAheadError(this.dbName, stored, schema.version)\n\t\t}\n\t\tif (tracksBackend) {\n\t\t\tawait recordDatabase({ dbName: this.dbName, backend: 'indexeddb' }).catch((error: unknown) =>\n\t\t\t\tconsole.warn(`[kora] Could not record the storage backend of \"${this.dbName}\":`, error),\n\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Read the OPFS copy of this database through a short-lived SQLite WASM\n\t * adapter (as leader, or as a follower of a tab that has it open). Refuses\n\t * loudly when OPFS cannot be read, instead of starting an empty copy.\n\t */\n\tprivate async readOpfsCopy(schema: SchemaDefinition): Promise<DatabaseDump> {\n\t\tconst reader = new SqliteWasmAdapter({\n\t\t\tdbName: this.dbName,\n\t\t\tworkerUrl: this.options.workerUrl,\n\t\t\tworkerResponseTimeoutMs: this.options.workerResponseTimeoutMs,\n\t\t\tskipBackendRecord: true,\n\t\t\treleaseOnFreeze: false,\n\t\t\t// A short-lived reader inside this tab's open, not a tab of its own.\n\t\t\tversionGate: false,\n\t\t})\n\t\ttry {\n\t\t\tawait reader.open(schema)\n\t\t\tif (reader.getStorageOpenState()?.persistent !== true) {\n\t\t\t\tthrow new StorageBackendMismatchError(\n\t\t\t\t\tthis.dbName,\n\t\t\t\t\t'OPFS',\n\t\t\t\t\t'IndexedDB',\n\t\t\t\t\t`OPFS reported ${reader.getStorageOpenState()?.fallbackReason ?? 'no durable storage'}`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tlet dump: DatabaseDump = { tables: [] }\n\t\t\tawait reader.transaction(async (tx) => {\n\t\t\t\tdump = await exportDump((sql, params) => tx.query(sql, params))\n\t\t\t})\n\t\t\treturn dump\n\t\t} catch (error) {\n\t\t\tif (error instanceof StorageBackendMismatchError) throw error\n\t\t\tthrow new StorageBackendMismatchError(\n\t\t\t\tthis.dbName,\n\t\t\t\t'OPFS',\n\t\t\t\t'IndexedDB',\n\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t)\n\t\t} finally {\n\t\t\tawait reader.close().catch(() => undefined)\n\t\t}\n\t}\n\n\tasync close(): Promise<void> {\n\t\t// Retiring: closing would release the tab lock and let the newer build open without\n\t\t// this tab's unsaved writes. Saved first, or refused (surfaced, never silent); the\n\t\t// prompt's Retry and Export keep working.\n\t\tif (!this.retired) await this.versionGate?.assertClosable()\n\t\t// A follower asking for a barrier meanwhile is told to fall back at once, not left to\n\t\t// notice a silent leader.\n\t\tthis.closing = true\n\t\tthis.removeLifecycleListeners?.()\n\t\tthis.removeLifecycleListeners = null\n\t\tif (!this.retired) await this.scheduler.flushNow()\n\t\tthis.scheduler.dispose()\n\t\t// Writes still unsaved now can never be asked about again: release their pins.\n\t\tthis.unconfirmedWrites.clear()\n\t\tthis.currentLineage = null\n\t\tawait this.syncPins()\n\t\ttry {\n\t\t\tawait this.inner.close()\n\t\t} finally {\n\t\t\tthis.stopBarrierServer?.()\n\t\t\t// The tab lock last, after the inner adapter released the leader lock.\n\t\t\tthis.versionGate?.close()\n\t\t}\n\t}\n\n\texecute(sql: string, params?: unknown[]): Promise<void> {\n\t\treturn this.writes.run({ operation: 'execute' }, () => this.executeNow(sql, params))\n\t}\n\n\tprivate async executeNow(sql: string, params?: unknown[]): Promise<void> {\n\t\tif (OUTSIDE_TRANSACTION.test(sql)) {\n\t\t\t// A statement that cannot run in a transaction (PRAGMA foreign_keys is a silent\n\t\t\t// no-op inside one) changes connection settings, not the rows a snapshot holds.\n\t\t\tawait this.inner.execute(sql, params)\n\t\t\tthis.scheduler.schedule()\n\t\t\treturn\n\t\t}\n\t\t// The write and its count run in one transaction span, which the multi-tab layer binds\n\t\t// to the worker that answered BEGIN: if the storage leader changes in between, the\n\t\t// span fails with a retriable BridgeTerminatedError (nothing applied or counted on the\n\t\t// new worker) instead of counting the write under a database it never reached.\n\t\tlet counted: CommitCount = NO_WRITE\n\t\tawait this.inner.transaction(async (tx) => {\n\t\t\tconst before = await readWriteMark(tx)\n\t\t\tawait tx.execute(sql, params)\n\t\t\tcounted = await countCommit(tx, before)\n\t\t})\n\t\tawait this.recordCommit(counted)\n\t}\n\n\tasync query<T>(sql: string, params?: unknown[]): Promise<T[]> {\n\t\treturn this.inner.query<T>(sql, params)\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\t// Only a transaction that changed the database is a write: a read-only one (a backup\n\t\t// snapshot, a fold-state read) gets no count, so it never needs a saved snapshot and\n\t\t// can never be reported lost when the storage leader changes.\n\t\tlet counted: CommitCount = NO_WRITE\n\t\tawait this.inner.transaction(async (tx) => {\n\t\t\tconst before = await readWriteMark(tx)\n\t\t\tawait fn(tx)\n\t\t\tcounted = await countCommit(tx, before)\n\t\t})\n\t\tawait this.recordCommit(counted)\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\t// The migration and its count commit in one span on one worker database (as in\n\t\t// `execute`), so the count is the migration's own.\n\t\tlet counted: CommitCount = NO_WRITE\n\t\ttry {\n\t\t\tawait this.inner.transaction(async (tx) => {\n\t\t\t\tconst before = await readWriteMark(tx)\n\t\t\t\tfor (const sql of migration.statements) {\n\t\t\t\t\tawait tx.execute(sql)\n\t\t\t\t}\n\t\t\t\tcounted = await countCommit(tx, before)\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tif (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 instanceof Error ? error.message : String(error)}`,\n\t\t\t\t{ from, to },\n\t\t\t)\n\t\t}\n\t\tawait this.recordCommit(counted)\n\t}\n\n\tgetStorageOpenState(): StorageOpenState | null {\n\t\treturn this.storageOpenState\n\t}\n\n\tgetStorageEvidence(): StorageEvidence | null {\n\t\treturn this.evidence\n\t}\n\n\t/**\n\t * Force an immediate snapshot write to IndexedDB (skips debounce).\n\t * Useful before tab unload or in tests.\n\t */\n\tasync flushPersistence(): Promise<void> {\n\t\tawait this.scheduler.flushNow()\n\t}\n\n\t/** Resolves once a persisted snapshot holds every write committed so far (forces none). */\n\twhenPersisted(): Promise<void> {\n\t\treturn this.scheduler.whenPersisted()\n\t}\n\n\t/**\n\t * Durability barrier (RT-35): resolves once every write committed before the call is\n\t * in a snapshot persisted to IndexedDB, and rejects when the snapshot cannot be\n\t * written. Sync calls it before an operation leaves the device, so the server never\n\t * holds an operation this device could lose on reload.\n\t *\n\t * A write counts as persisted only when a snapshot of the worker database it was made\n\t * in is saved. When that database was replaced first (the storage leader changed and\n\t * the new leader restored an older snapshot), the write is gone and the barrier rejects\n\t * with a {@link PersistenceError} (`context.code` `SNAPSHOT_SUPERSEDED`, `context.lineages`)\n\t * instead of resolving on a snapshot of the new database.\n\t *\n\t * A lost write stays lost for the rest of this tab's session: every later barrier also\n\t * covers it and rejects the same way, so a retry never reports it saved (the snapshot is\n\t * still written first, so later writes keep being persisted). Sync then uploads in its\n\t * degraded mode (`localDurability: 'degraded'`, RT-49), so the server keeps a copy. A\n\t * reload opens the database in a new lineage with a new adapter: the loss is cleared\n\t * there, and sync starts durable again.\n\t */\n\tasync ensureDurable(): Promise<void> {\n\t\tconst needed = [...this.unconfirmedWrites.keys()]\n\t\tawait this.scheduler.flushBarrier()\n\t\tif (this.lostLineages.size > 0) {\n\t\t\tthrow new PersistenceError(\n\t\t\t\t`Writes to database \"${this.dbName}\" were lost before they were saved: the copy of the database they were made in was replaced (the storage leader tab changed). They are not in the database any more and must not be treated as saved. Every durability barrier of this tab reports it until the page is reloaded.`,\n\t\t\t\t{ dbName: this.dbName, code: SNAPSHOT_SUPERSEDED, lineages: [...this.lostLineages] },\n\t\t\t)\n\t\t}\n\t\tlet unsaved = needed.filter((lineage) => this.unconfirmedWrites.has(lineage))\n\t\tif (unsaved.length > 0) {\n\t\t\t// A snapshot the scheduler counted may have been taken just before a write's count\n\t\t\t// was read back: take one more, then decide.\n\t\t\tawait this.scheduler.flushNow()\n\t\t\tunsaved = needed.filter((lineage) => this.unconfirmedWrites.has(lineage))\n\t\t}\n\t\tif (unsaved.length > 0) {\n\t\t\tthrow new PersistenceError(\n\t\t\t\t`Writes to database \"${this.dbName}\" are not in a saved snapshot yet`,\n\t\t\t\t{ dbName: this.dbName, code: 'SNAPSHOT_PENDING', lineages: unsaved },\n\t\t\t)\n\t\t}\n\t}\n\n\t/** After a committed transaction: remember it and schedule a snapshot, if it wrote. */\n\tprivate async recordCommit(commit: CommitCount): Promise<void> {\n\t\tif (!commit.wrote) return\n\t\tthis.recordWrite(commit.counted)\n\t\tthis.scheduler.schedule()\n\t\t// Pinned before the write returns, so no later lineage can drop its ancestry entry.\n\t\t// Only a change of the pinned set writes the pin record (the first write in a new\n\t\t// lineage, i.e. after a leader change); every other write finds it unchanged.\n\t\tawait this.syncPins()\n\t}\n\n\t/**\n\t * Pin the lineages this tab has unsaved writes in, so their ancestry entries survive any\n\t * number of leader changes until this tab settles them (see `MAX_ANCESTORS`), and the\n\t * lineage it writes in now (see `currentLineage`). A tab that dies leaves at most those\n\t * behind, and only the most recent holders' pins are kept. A failed\n\t * update is reported, not thrown: the write it follows is committed, and without the pin\n\t * a lineage beyond the recent ancestry is judged by its epoch, as before.\n\t */\n\tprivate syncPins(): Promise<void> {\n\t\tconst run = async (): Promise<void> => {\n\t\t\tconst pinned = new Set(this.unconfirmedWrites.keys())\n\t\t\tif (this.currentLineage !== null) pinned.add(this.currentLineage)\n\t\t\tconst lineages = [...pinned].sort()\n\t\t\tconst key = lineages.join(',')\n\t\t\tif (key === this.pinnedKey) return\n\t\t\ttry {\n\t\t\t\tawait setSnapshotLineagePins(this.dbName, this.pinHolder, lineages)\n\t\t\t\tthis.pinnedKey = key\n\t\t\t} catch (error) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[kora] Could not pin the unsaved snapshot lineages of \"${this.dbName}\":`,\n\t\t\t\t\terror,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tthis.pinUpdate = this.pinUpdate.then(run, run)\n\t\treturn this.pinUpdate\n\t}\n\n\t/** Remember a write this tab committed, by the worker database and count it got. */\n\tprivate recordWrite(counted: CountedWrite | undefined): void {\n\t\t// No row: a worker database opened by an earlier build, which has no lineage until\n\t\t// its first snapshot from this build; such writes are covered as before.\n\t\tif (!counted) return\n\t\tthis.currentLineage = counted.lineage\n\t\tconst previous = this.unconfirmedWrites.get(counted.lineage)\n\t\tif (!previous || counted.seq > previous.seq) {\n\t\t\tthis.unconfirmedWrites.set(counted.lineage, { epoch: counted.epoch, seq: counted.seq })\n\t\t}\n\t}\n\n\t/**\n\t * Settle this tab's unsaved writes against the snapshot IndexedDB now holds (`stored`,\n\t * and the worker databases it descends from, `ancestors`). A write is durable when the\n\t * stored snapshot, or the snapshot an ancestor was saved at before it was replaced,\n\t * holds its commit count. A write in a worker database that was replaced before a\n\t * snapshot holding it was saved is lost: no snapshot can hold it any more (later saves\n\t * of that database are refused). `refused` is the lineage whose save was just refused.\n\t */\n\tprivate settleWrites(\n\t\tstored: SnapshotVersion | null,\n\t\tancestors: SnapshotAncestor[],\n\t\trefused: string | null,\n\t): void {\n\t\tfor (const [lineage, pending] of this.unconfirmedWrites) {\n\t\t\tif (stored && lineage === stored.lineage && lineage !== refused) {\n\t\t\t\tif (pending.seq <= stored.seq) this.unconfirmedWrites.delete(lineage)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst ancestor = ancestors.find((entry) => entry.lineage === lineage)\n\t\t\tif (ancestor) {\n\t\t\t\tif (pending.seq <= ancestor.seq) this.unconfirmedWrites.delete(lineage)\n\t\t\t\telse this.markLost(lineage)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Not in the ancestry, which keeps every lineage this tab pinned (unless the pin\n\t\t\t// could not be recorded): replaced when a later database started.\n\t\t\tif (lineage === refused || stored === null || pending.epoch < stored.epoch) {\n\t\t\t\tthis.markLost(lineage)\n\t\t\t}\n\t\t}\n\t}\n\n\t/** This tab's unsaved writes in `lineage` are gone; barriers report it until reload. */\n\tprivate markLost(lineage: string): void {\n\t\tif (!this.unconfirmedWrites.delete(lineage)) return\n\t\tthis.lostLineages.add(lineage)\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:persistence-error',\n\t\t\tdbName: this.dbName,\n\t\t\tmessage: `Writes to database \"${this.dbName}\" were lost before they were saved: the copy of the database they were made in was replaced when the storage leader tab changed.`,\n\t\t\tcode: SNAPSHOT_SUPERSEDED,\n\t\t})\n\t}\n\n\t/**\n\t * Save a snapshot of the worker database. Every tab's adapter snapshots the same worker\n\t * database (a follower's export runs on the leader's worker), so two tabs' saves can\n\t * reach IndexedDB in either order. Each snapshot carries the version it was read at,\n\t * and the save is a compare-and-put that never lets an older snapshot replace a newer\n\t * one; a save the stored snapshot already covers succeeds without writing.\n\t */\n\tprivate async writeSnapshot(strict = false, readPoint?: () => void): Promise<void> {\n\t\t// A follower's barrier snapshot is taken by the leader tab: one RPC, answered by the\n\t\t// leader's scheduler (which shares it with every barrier waiting there), instead of\n\t\t// exporting the whole database over the broadcast channel.\n\t\tif (strict && (await this.snapshotThroughLeader())) return\n\t\tconst { dump, version } = await this.exportDump(readPoint)\n\n\t\tlet data: Uint8Array | null = null\n\t\ttry {\n\t\t\tdata = await this.inner.exportDatabase()\n\t\t} catch (error) {\n\t\t\tif (!isUnsupportedWorkerExport(error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t}\n\t\tif (data !== null) {\n\t\t\t// The binary image is a separate request, so another tab may have committed in\n\t\t\t// between. Keep it only when no write was counted since the dump, so the image a\n\t\t\t// restore prefers holds the same counted writes as the dump stored with it;\n\t\t\t// otherwise store the dump alone (it restores fully).\n\t\t\tconst after = (await this.inner.query<SnapshotStateRow>(SNAPSHOT_STATE_SQL))[0]\n\t\t\tif (after?.lineage !== version.lineage || after.seq !== version.seq) {\n\t\t\t\tdata = null\n\t\t\t}\n\t\t}\n\n\t\tlet saved: SnapshotSaveResult\n\t\ttry {\n\t\t\tsaved = await saveSnapshotToIndexedDB(this.dbName, { dump, data, version }, { strict })\n\t\t} catch (error) {\n\t\t\tif (error instanceof PersistenceError && error.context?.code === SNAPSHOT_SUPERSEDED) {\n\t\t\t\t// This snapshot's worker database was replaced: settle this tab's writes against\n\t\t\t\t// what IndexedDB holds (an earlier save by another tab may hold them).\n\t\t\t\tconst stored = error.context.stored as SnapshotVersion | null\n\t\t\t\tconst ancestors = (error.context.storedAncestors as SnapshotAncestor[] | undefined) ?? []\n\t\t\t\tthis.settleWrites(stored, ancestors, version.lineage)\n\t\t\t\tawait this.syncPins()\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t\tthis.settleWrites(version, saved.ancestors, null)\n\t\tawait this.syncPins()\n\t}\n\n\t/**\n\t * Answer followers' durability barriers (this tab leads): one strict snapshot, shared\n\t * with every barrier waiting in this tab's scheduler. Returns the function that stops.\n\t */\n\tprivate serveBarriers(channelName: string): () => void {\n\t\tthis.stopBarrierServer?.()\n\t\tconst stop = serveSnapshotBarriers(channelName, () => this.answerPeerBarrier())\n\t\tconst stopOnce = (): void => {\n\t\t\tstop()\n\t\t\tif (this.stopBarrierServer === stopOnce) this.stopBarrierServer = null\n\t\t}\n\t\tthis.stopBarrierServer = stopOnce\n\t\treturn stopOnce\n\t}\n\n\tprivate async answerPeerBarrier(): Promise<void> {\n\t\t// Not the leader any more (closing, retiring for a newer build): the follower takes\n\t\t// its snapshot itself, through whichever tab leads next.\n\t\tif (this.retired || this.closing) {\n\t\t\tthrow new PersistenceError(`The leader tab of database \"${this.dbName}\" is going away`, {\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tcode: LEADER_GOING_AWAY,\n\t\t\t})\n\t\t}\n\t\tawait this.scheduler.flushBarrierForPeer()\n\t}\n\n\t/**\n\t * Follower: have the leader tab save the strict snapshot that covers this tab's writes.\n\t * True once the leader's snapshot is stored (the writes are then settled against it). False\n\t * when this tab leads, or the leader cannot answer (killed, frozen, hung, closing, or this\n\t * tab was promoted meanwhile): the caller then snapshots through whichever worker serves\n\t * now. That is the barrier re-issued to the new leader: its database holds this tab's\n\t * writes only if a stored snapshot did, and the settlement reports them lost otherwise\n\t * (`SNAPSHOT_SUPERSEDED`), never durable.\n\t *\n\t * @throws {PersistenceError} When the leader's snapshot failed (storage full, broken\n\t * IndexedDB): the barrier rejects, the writes stay in memory and are not durable\n\t */\n\tprivate async snapshotThroughLeader(): Promise<boolean> {\n\t\tconst client = this.inner.snapshotBarrierClient()\n\t\tif (client === null) return false\n\t\tlet response: WorkerResponse\n\t\ttry {\n\t\t\tresponse = await client.requestSnapshotBarrier()\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof NoLeaderError ||\n\t\t\t\terror instanceof BridgeTerminatedError ||\n\t\t\t\terror instanceof WorkerTimeoutError\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tthrow error\n\t\t}\n\t\tif (response.type === 'error') {\n\t\t\tconst detail = response.context?.detail\n\t\t\tif (detail === LEADER_GOING_AWAY) return false\n\t\t\tthrow new PersistenceError(response.message, {\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tcode: typeof detail === 'string' ? detail : response.code,\n\t\t\t\t...(response.context?.quotaExceeded === true ? { quotaExceeded: true } : {}),\n\t\t\t\tviaLeader: true,\n\t\t\t})\n\t\t}\n\t\t// The leader stored a snapshot taken after this tab's writes committed: settle them\n\t\t// against it (the barrier re-checks and takes one more snapshot if any is left).\n\t\tawait this.settleAgainstStoredSnapshot()\n\t\treturn true\n\t}\n\n\tprivate handlePersistenceError(error: unknown): void {\n\t\tconst message = error instanceof Error ? error.message : 'IndexedDB persistence failed'\n\t\t// A refused snapshot save is reported with its own code (it is in the error's context:\n\t\t// `PersistenceError.code` is always PERSISTENCE_ERROR); other errors as before.\n\t\tconst detail = error instanceof PersistenceError ? error.context?.code : undefined\n\t\tconst code =\n\t\t\tdetail === SNAPSHOT_SUPERSEDED\n\t\t\t\t? SNAPSHOT_SUPERSEDED\n\t\t\t\t: error instanceof PersistenceError\n\t\t\t\t\t? error.code\n\t\t\t\t\t: 'PERSISTENCE_FAILED'\n\t\tconst quotaExceeded = isIndexedDbQuotaError(error)\n\n\t\tif (quotaExceeded) {\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:quota-exceeded',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tmessage,\n\t\t\t})\n\t\t}\n\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:persistence-error',\n\t\t\tdbName: this.dbName,\n\t\t\tmessage,\n\t\t\tcode: quotaExceeded ? 'QUOTA_EXCEEDED' : code,\n\t\t})\n\t}\n\n\t/**\n\t * Restore the persisted snapshot into the worker database unless one was restored\n\t * into it already (this adapter or another one sharing the worker). The binary\n\t * snapshot (Node / test workers that support export) is imported whole; the JSON dump\n\t * (browsers) is restored in one transaction.\n\t */\n\tprivate async restoreIfFresh(): Promise<void> {\n\t\tconst fresh = { value: false }\n\t\tawait this.inner.transaction(async (tx) => {\n\t\t\tfresh.value = !(await isRestored(tx))\n\t\t})\n\t\tif (!fresh.value) return\n\t\t// One IndexedDB transaction claims the new lineage's epoch, reads the snapshot to\n\t\t// restore (binary image, dump) and fences it: no save of an older worker database\n\t\t// can land between what is restored here and this lineage's first save.\n\t\tconst lineage = newLineageId()\n\t\tconst started = await startSnapshotLineage<DatabaseDump>(this.dbName, lineage)\n\t\tif (started.data) {\n\t\t\ttry {\n\t\t\t\tawait this.inner.importDatabase(started.data)\n\t\t\t\tawait this.inner.transaction((tx) => markRestored(tx, started.epoch, lineage))\n\t\t\t\treturn\n\t\t\t} catch {\n\t\t\t\t// Fall through to the JSON dump.\n\t\t\t}\n\t\t}\n\t\tawait this.inner.transaction((tx) => this.restoreDumpIfFresh(tx, { lineage, started }))\n\t}\n\n\t/**\n\t * In `tx`: restore the JSON dump when no snapshot was restored into this database,\n\t * starting its lineage first (or with the one `restoreIfFresh` started).\n\t */\n\tprivate async restoreDumpIfFresh(\n\t\ttx: Transaction,\n\t\tbegun?: { lineage: string; started: StartedSnapshotLineage<DatabaseDump> },\n\t): Promise<void> {\n\t\tif (await isRestored(tx)) return\n\t\tconst lineage = begun?.lineage ?? newLineageId()\n\t\tconst started =\n\t\t\tbegun?.started ?? (await startSnapshotLineage<DatabaseDump>(this.dbName, lineage))\n\t\tawait markRestored(tx, started.epoch, lineage)\n\t\tif (!started.dump) return\n\t\tfor (const statement of restoreDumpStatements(started.dump)) {\n\t\t\tawait tx.execute(statement.sql, statement.params)\n\t\t}\n\t}\n\n\t/**\n\t * A consistent snapshot: every table and the snapshot version are read inside one\n\t * transaction (STORE-7), so the version names exactly the counted writes the dump holds.\n\t */\n\tprivate async exportDump(\n\t\treadPoint?: () => void,\n\t): Promise<{ dump: DatabaseDump; version: SnapshotVersion }> {\n\t\tlet dump: DatabaseDump = { tables: [] }\n\t\tlet state: SnapshotStateRow | undefined\n\t\tawait this.inner.transaction(async (tx) => {\n\t\t\t// No write can commit between here and the end of this transaction, and every write\n\t\t\t// scheduled so far has committed: barriers that arrive from now on need another snapshot.\n\t\t\treadPoint?.()\n\t\t\tstate = (await readSnapshotState(tx))[0]\n\t\t\tif (!state) {\n\t\t\t\t// A worker database opened by an earlier build (a tab still running it leads):\n\t\t\t\t// start a lineage for it, newer than the stored snapshot, since this live\n\t\t\t\t// database holds the latest writes. Inside this transaction, which holds the\n\t\t\t\t// worker for every tab, so only one tab starts it.\n\t\t\t\tconst lineage = newLineageId()\n\t\t\t\tconst { epoch } = await startSnapshotLineage(this.dbName, lineage)\n\t\t\t\tawait setLineageState(tx, epoch, lineage)\n\t\t\t\tstate = (await readSnapshotState(tx))[0]\n\t\t\t}\n\t\t\tdump = await exportDump((sql, params) => tx.query(sql, params))\n\t\t})\n\t\tif (!state) {\n\t\t\tthrow new PersistenceError(`Snapshot of database \"${this.dbName}\" has no version`, {\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tcode: 'SNAPSHOT_UNVERSIONED',\n\t\t\t})\n\t\t}\n\t\treturn {\n\t\t\tdump,\n\t\t\tversion: { epoch: state.epoch, lineage: state.lineage, seq: state.seq },\n\t\t}\n\t}\n}\n\n/** Detail code of a leader that answers a barrier with \"snapshot through someone else\". */\nconst LEADER_GOING_AWAY = 'LEADER_GOING_AWAY'\n\n/**\n * Connection-local marker (a TEMP table: never part of the database file or of a dump)\n * recording that a snapshot was restored into this worker database (STORE-6).\n */\nconst RESTORED_MARKER = '_kora_idb_restored'\n\nasync function isRestored(tx: Transaction): Promise<boolean> {\n\tconst rows = await tx.query<{ name: string }>(\n\t\t\"SELECT name FROM sqlite_temp_master WHERE type = 'table' AND name = ?\",\n\t\t[RESTORED_MARKER],\n\t)\n\treturn rows.length > 0\n}\n\nasync function markRestored(tx: Transaction, epoch: number, lineage: string): Promise<void> {\n\tawait tx.execute(`CREATE TEMP TABLE IF NOT EXISTS ${RESTORED_MARKER} (restored INTEGER)`)\n\tawait setLineageState(tx, epoch, lineage)\n}\n\n/**\n * Connection-local snapshot version of the worker database (a TEMP table, like the\n * marker: never part of a dump or a binary image), shared by every tab using the worker.\n * `lineage` identifies this in-memory database, `epoch` was claimed for it by\n * {@link startSnapshotLineage}, and `seq` counts the write transactions committed in it.\n */\nconst SNAPSHOT_STATE = '_kora_idb_snapshot_state'\nconst SNAPSHOT_STATE_SQL = `SELECT epoch, lineage, seq FROM temp.${SNAPSHOT_STATE}`\nconst CREATE_SNAPSHOT_STATE_SQL = `CREATE TEMP TABLE IF NOT EXISTS ${SNAPSHOT_STATE} (epoch INTEGER NOT NULL, lineage TEXT NOT NULL, seq INTEGER NOT NULL)`\n/**\n * Counts one committed write and returns the count it got. A no-op while the worker\n * database has no state row (a database opened by an earlier build: its first snapshot\n * from this build starts a lineage).\n */\nconst COUNT_COMMIT_SQL = `UPDATE temp.${SNAPSHOT_STATE} SET seq = seq + 1 RETURNING epoch, lineage, seq`\n\n/**\n * Statements `execute` runs outside a transaction: SQLite refuses them in one, or (PRAGMA\n * foreign_keys) silently ignores them there. None changes the rows a snapshot holds.\n */\nconst OUTSIDE_TRANSACTION = /^\\s*(PRAGMA|VACUUM|ATTACH|DETACH)\\b/i\n\ninterface SnapshotStateRow {\n\tepoch: number\n\tlineage: string\n\tseq: number\n}\n\n/** The worker database and commit count a write was counted in. */\ntype CountedWrite = SnapshotStateRow\n\n/**\n * What a committed transaction did: `wrote` when it changed the database, and the count it\n * got then (undefined in a worker database opened by an earlier build, which has no state).\n */\ninterface CommitCount {\n\twrote: boolean\n\tcounted?: CountedWrite\n}\n\nconst NO_WRITE: CommitCount = { wrote: false }\n\n/**\n * Where the connection stood when a transaction began: its total change count, the main\n * schema's version and its user_version, as one string. Every tab's request goes through\n * one serialized worker connection, and a transaction span holds it, so a difference at\n * the end is this transaction's own write: rows (by any statement, `query` with RETURNING\n * included), schema (which `total_changes()` does not count) or the user_version header.\n * Changes to TEMP tables count too; they can only make a transaction count as a write,\n * never hide one.\n */\ntype WriteMark = string\n\nconst WRITE_MARK_SQL =\n\t'SELECT total_changes() AS changes, (SELECT schema_version FROM pragma_schema_version) AS schema, (SELECT user_version FROM pragma_user_version) AS user'\n\nasync function readMark(tx: Transaction): Promise<WriteMark> {\n\tconst row = (\n\t\tawait tx.query<{ changes: unknown; schema: unknown; user: unknown }>(WRITE_MARK_SQL)\n\t)[0]\n\treturn `${String(row?.changes)}:${String(row?.schema)}:${String(row?.user)}`\n}\n\nasync function ensureSnapshotStateTable(tx: Transaction): Promise<void> {\n\tawait tx.execute(CREATE_SNAPSHOT_STATE_SQL)\n}\n\nasync function readSnapshotState(tx: Transaction): Promise<SnapshotStateRow[]> {\n\tawait ensureSnapshotStateTable(tx)\n\treturn tx.query<SnapshotStateRow>(SNAPSHOT_STATE_SQL)\n}\n\nasync function readWriteMark(tx: Transaction): Promise<WriteMark> {\n\t// The TEMP state table is created here, before the mark, so creating it is never\n\t// mistaken for this transaction's write (TEMP DDL changes no main schema version anyway).\n\tawait ensureSnapshotStateTable(tx)\n\treturn readMark(tx)\n}\n\n/**\n * Count the transaction's commit when it wrote since `before` (null: count it regardless).\n * The count is taken only then, so a read-only transaction leaves the commit count as it\n * was and claims no write a snapshot must hold.\n */\nasync function countCommit(tx: Transaction, before: WriteMark | null): Promise<CommitCount> {\n\tif (before === null) await ensureSnapshotStateTable(tx)\n\telse if ((await readMark(tx)) === before) return NO_WRITE\n\treturn { wrote: true, counted: (await tx.query<CountedWrite>(COUNT_COMMIT_SQL))[0] }\n}\n\n/**\n * Give this worker database the lineage {@link startSnapshotLineage} started for it (an\n * epoch higher than every one before), so its snapshots replace the one it was restored\n * from, and a snapshot of any older worker database (a tab that still relays to one) can\n * never replace them.\n */\nasync function setLineageState(tx: Transaction, epoch: number, lineage: string): Promise<void> {\n\tawait ensureSnapshotStateTable(tx)\n\tawait tx.execute(`DELETE FROM temp.${SNAPSHOT_STATE}`)\n\tawait tx.execute(`INSERT INTO temp.${SNAPSHOT_STATE} (epoch, lineage, seq) VALUES (?, ?, 0)`, [\n\t\tepoch,\n\t\tlineage,\n\t])\n}\n\nfunction newLineageId(): string {\n\tconst bytes = new Uint8Array(16)\n\tglobalThis.crypto.getRandomValues(bytes)\n\treturn Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\nfunction isQuotaPersistenceError(error: unknown): boolean {\n\treturn error instanceof PersistenceError && error.context?.quotaExceeded === true\n}\n\n/**\n * Why a retiring tab's snapshot failed, as the `store:persistence-error` code its prompt\n * names: storage full, no storage worker left (the leader it relayed to closed, or it gave\n * up its roles), or another persistence failure.\n */\nfunction unsavedWritesCode(\n\terror: unknown,\n): 'QUOTA_EXCEEDED' | 'STORAGE_UNAVAILABLE' | 'PERSISTENCE_FAILED' {\n\tif (isIndexedDbQuotaError(error) || isQuotaPersistenceError(error)) return 'QUOTA_EXCEEDED'\n\tif (\n\t\terror instanceof StoreNotOpenError ||\n\t\terror instanceof NoLeaderError ||\n\t\terror instanceof BridgeTerminatedError ||\n\t\t(error instanceof Error && (error as { code?: unknown }).code === 'BUILD_SUPERSEDED')\n\t) {\n\t\treturn 'STORAGE_UNAVAILABLE'\n\t}\n\treturn 'PERSISTENCE_FAILED'\n}\n\nfunction isUnsupportedWorkerExport(error: unknown): boolean {\n\treturn error instanceof AdapterError && error.context?.code === 'EXPORT_NOT_SUPPORTED'\n}\n"]}