{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/restore-32D3DPGP.cjs","../src/backup/restore.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B,gCAA6B;AAC7B;AACA;ACvBA,oCAA+C;AAyD/C,MAAA,SAAsB,YAAA,CACrB,IAAA,EACA,MAAA,EACA,QAAA,EACyB;AACzB,EAAA,MAAM,wBAAA,CAAyB,IAAA,CAAK,OAAA,EAAS,MAAM,CAAA;AACnD,EAAA,IAAI,SAAA,EAAW,CAAA;AACf,EAAA,IAAI,QAAA,EAAU,CAAA;AACd,EAAA,MAAM,UAAA,EAAY,CAAC,MAAA,EAAA,oCAA4B,IAAA,mBAAK,iBAAA,0BAAA,CAAoB,MAAM,GAAA,UAAK,OAAA;AACnF,EAAA,IAAA,CAAA,MAAW,UAAA,GAAa,MAAA,CAAO,UAAA,EAAY;AAC1C,IAAA,GAAA,CAAI,CAAC,IAAA,CAAK,MAAA,CAAO,WAAA,CAAY,SAAA,CAAU,UAAU,CAAA,EAAG,QAAA;AAKpD,IAAA,GAAA,CAAI,SAAA,CAAU,SAAA,CAAU,MAAM,CAAA,EAAG;AAChC,MAAA,OAAA,EAAA;AACA,MAAA,QAAA;AAAA,IACD;AACA,IAAA,GAAA,CAAK,MAAM,IAAA,CAAK,cAAA,CAAe,SAAS,EAAA,IAAO,SAAA,EAAW,QAAA,EAAA;AAAA,EAC3D;AACA,EAAA,GAAA,CAAI,CAAC,SAAA,GAAY,MAAA,CAAO,aAAA,CAAc,KAAA,EAAO,CAAA,EAAG;AAE/C,IAAA,MAAM,IAAA,CAAK,OAAA,CAAQ,WAAA,CAAY,MAAA,CAAO,EAAA,EAAA,GAAO;AAC5C,MAAA,IAAA,CAAA,MAAW,CAAC,MAAA,EAAQ,QAAQ,EAAA,GAAK,MAAA,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ACA,MAAA;AACS,MAAA;AACV,IAAA;AACA,IAAA;AACD,EAAA;AACS,EAAA;AACY,IAAA;AACpB,IAAA;AACK,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACL,IAAA;AACD,EAAA;AACD;AAE2F;AACjF,EAAA;AACR,IAAA;AAAA,wGAAA;AAEiB,IAAA;AAClB,EAAA;AACD;AAMmB;AACJ,EAAA;AACwB,EAAA;AACf,IAAA;AAC+B,MAAA;AAC7C,MAAA;AACR,IAAA;AAC2C,IAAA;AAC5C,EAAA;AACO,EAAA;AACR;AASgC;AAC0B,EAAA;AAClB,EAAA;AACb,EAAA;AAC8B,IAAA;AACF,IAAA;AACtD,EAAA;AACO,EAAA;AACR;AAEoF;AACxD,EAAA;AAC1B,IAAA;AACK,IAAA;AACN,EAAA;AACqB,EAAA;AACtB;AAE6C;AACO,EAAA;AACX,EAAA;AACgB,EAAA;AACjD,EAAA;AACR;AAGqC;AAE4C;AAClE,EAAA;AACsC,IAAA;AACpD,EAAA;AACD;AAWC;AAE0D,EAAA;AAC5B,EAAA;AACuB,IAAA;AACrD,EAAA;AACc,EAAA;AACe,EAAA;AACV,IAAA;AACG,MAAA;AACd,MAAA;AACP,IAAA;AACqD,IAAA;AACtD,EAAA;AAC8C,EAAA;AACvC,EAAA;AACR;ADxI4D;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/kora/kora/packages/store/dist/restore-32D3DPGP.cjs","sourcesContent":[null,"import { HybridLogicalClock, quoteIdent } from '@korajs/core'\nimport type { Operation, SchemaDefinition } from '@korajs/core'\nimport {\n\tCOMPACTED_THROUGH_TABLE,\n\tFOLD_BASE_TABLE,\n\tFOLD_MATERIALIZATION_META_KEY,\n\tFOLD_SNAPSHOT_TABLE,\n\tFOLD_STATE_TABLE,\n\tPROVISIONAL_OPS_TABLE,\n} from '../fold/record-folder'\nimport { deserializeOperationWithCollection, serializeOperation } from '../serialization/serializer'\nimport { SEQ_CONFLICTS_TABLE, insertConflictRow } from '../store/sequence-repair'\nimport {\n\ttype LocalNodeRecord,\n\tTERMINAL_REJECTIONS_TABLE,\n\tensureLocalSyncRecordTables,\n} from '../sync/local-sync-records'\nimport { loadOwnAckedThrough } from '../sync/sync-durability'\nimport {\n\tDELIVERY_WATERMARK_META_KEY,\n\tDELTA_CURSOR_META_KEY,\n\tloadLastAckedServerVector,\n} from '../sync/sync-state'\nimport type { ApplyResult, OperationRow, StorageAdapter, Transaction } from '../types'\nimport type { ParsedBackup } from './backup'\n\n/** What a restore needs from the store it restores into. */\nexport interface RestoreHost {\n\treadonly adapter: StorageAdapter\n\treadonly schema: SchemaDefinition\n\t/** The normal remote-apply path (sync's): dedup by id, per-field merge, version vector. */\n\tapplyOperation(operation: Operation): Promise<ApplyResult>\n\t/** This database's own nodes (RT-38/40), never taken from a backup. */\n\tlistLocalNodes(): Promise<LocalNodeRecord[]>\n\t/**\n\t * Whether a node's writes would be authoritative here (Kora's reserved `kora:`\n\t * nodes, and the explicit server authorities this device learned). A merge import\n\t * never applies their operations: only the sync server delivers them.\n\t */\n\tisServerAuthority?(nodeId: string): boolean\n}\n\n/** Outcome counts of a restore. */\nexport interface RestoreCounts {\n\toperationsRestored: number\n\trecordsRestored: number\n\tunsyncedWritesKept: number\n\t/** Merge mode: operations of server-authority nodes left out (see `RestoreHost.isServerAuthority`). */\n\tserverOperationsSkipped?: number\n}\n\n/**\n * Merge a backup into the database (STORE-5): every operation goes through the normal\n * remote-apply path in HLC (causal) order, the version vector advances by MAX, the\n * terminal-rejection markers are added. Never imported: the node id, node tokens, local\n * node registry and principal bindings, sync watermarks, acknowledged prefixes.\n */\nexport async function restoreMerge(\n\thost: RestoreHost,\n\tbackup: ParsedBackup,\n\tfiltered: boolean,\n): Promise<RestoreCounts> {\n\tawait importTerminalRejections(host.adapter, backup)\n\tlet restored = 0\n\tlet skipped = 0\n\tconst authority = (nodeId: string): boolean => host.isServerAuthority?.(nodeId) ?? false\n\tfor (const operation of backup.operations) {\n\t\tif (!host.schema.collections[operation.collection]) continue\n\t\t// A server decision is applied only as the sync server delivers it: from a file,\n\t\t// an operation under a server node would win `merge('server-authoritative')`\n\t\t// fields on this device (and is never uploaded to be checked). One the server\n\t\t// already delivered is in the log anyway; the rest arrive by sync.\n\t\tif (authority(operation.nodeId)) {\n\t\t\tskipped++\n\t\t\tcontinue\n\t\t}\n\t\tif ((await host.applyOperation(operation)) === 'applied') restored++\n\t}\n\tif (!filtered && backup.versionVector.size > 0) {\n\t\t// With a collection filter the vector would claim other collections' operations.\n\t\tawait host.adapter.transaction(async (tx) => {\n\t\t\tfor (const [nodeId, sequence] of backup.versionVector) {\n\t\t\t\tif (authority(nodeId)) continue\n\t\t\t\tawait maxVector(tx, nodeId, sequence)\n\t\t\t}\n\t\t})\n\t}\n\treturn {\n\t\toperationsRestored: restored,\n\t\trecordsRestored: 0,\n\t\tunsyncedWritesKept: 0,\n\t\tserverOperationsSkipped: skipped,\n\t}\n}\n\n/**\n * Replace the database's data with a backup's (STORE-5), keeping this device's\n * identity:\n *\n * - The node id, node tokens, local node registry, principal bindings and acknowledged\n *   prefixes are untouched; the exporting device's are never imported.\n * - This database's own nodes never move their sequence counters backwards (numbers the\n *   server may hold are never reused). A node the server never accepted, whose unsynced\n *   writes are not kept, restarts after its highest restored number (its numbers never\n *   left the device), so its log stays contiguous.\n * - Unacknowledged writes of an accepted node, and with `keepUnsyncedWrites` every\n *   unsynced own write, are re-applied on top of the restored data.\n * - Delivery watermarks restart at 0 and the delta cursor is dropped, so the sync server\n *   re-sends everything in scope (deduplicated by id).\n * - Rows, operations, version vector and sync bookkeeping change in one transaction;\n *   re-applied writes (and a backup without records, materialized through the\n *   remote-apply path) follow it.\n */\nexport async function restoreReplace(\n\thost: RestoreHost,\n\tbackup: ParsedBackup,\n\toptions: { collections: string[] | null; keepUnsyncedWrites: boolean },\n): Promise<RestoreCounts> {\n\tconst { adapter, schema } = host\n\tconst targets = Object.keys(schema.collections).filter(\n\t\t(name) => !options.collections || options.collections.includes(name),\n\t)\n\tconst rawRecords = backup.manifest.includesRecords\n\tconst localNodes = await host.listLocalNodes()\n\tconst localIds = new Set(localNodes.map((node) => node.nodeId))\n\tconst acked = await loadAckedThrough(adapter, localNodes)\n\n\t// Writes that exist only on this device: re-applied after the replace.\n\tconst kept: Operation[] = []\n\tconst keptRows = new Map<string, { collection: string; row: OperationRow }>()\n\tconst dropped = new Set<string>()\n\tfor (const node of localNodes) {\n\t\tconst keep = node.accepted || options.keepUnsyncedWrites\n\t\tconst floor = acked.get(node.nodeId) ?? 0\n\t\tfor (const collection of targets) {\n\t\t\tconst rows = await adapter.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE node_id = ? AND sequence_number > ?`,\n\t\t\t\t[node.nodeId, floor],\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tif (keep) {\n\t\t\t\t\tconst operation = deserializeOperationWithCollection(row, collection)\n\t\t\t\t\tkept.push(operation)\n\t\t\t\t\tkeptRows.set(operation.id, { collection, row })\n\t\t\t\t} else dropped.add(node.nodeId)\n\t\t\t}\n\t\t}\n\t}\n\tkept.sort((a, b) => HybridLogicalClock.compare(a.timestamp, b.timestamp))\n\t// Counters that may restart: nodes the server never accepted whose writes are dropped.\n\tconst restartable = new Set(\n\t\tlocalNodes\n\t\t\t.filter((node) => !node.accepted && !options.keepUnsyncedWrites)\n\t\t\t.map((node) => node.nodeId),\n\t)\n\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait ensureRestorePendingTable(adapter)\n\tlet recordsRestored = 0\n\tconst hasConflicts = await tableExists(adapter, SEQ_CONFLICTS_TABLE)\n\tawait adapter.transaction(async (tx) => {\n\t\tfor (const collection of targets) {\n\t\t\tawait tx.execute(`DELETE FROM ${quoteIdent(`_kora_ops_${collection}`)}`)\n\t\t\tawait tx.execute(`DELETE FROM ${quoteIdent(collection)}`)\n\t\t\tawait tx.execute('DELETE FROM _kora_scope_retractions WHERE collection = ?', [collection])\n\t\t\t// W7: the records' fold states go with their rows and log; the store\n\t\t\t// re-materializes the restored collections afterwards.\n\t\t\tawait tx.execute(`DELETE FROM ${FOLD_STATE_TABLE} WHERE collection = ?`, [collection])\n\t\t\tawait tx.execute(`DELETE FROM ${FOLD_BASE_TABLE} WHERE collection = ?`, [collection])\n\t\t\tawait tx.execute(`DELETE FROM ${FOLD_SNAPSHOT_TABLE} WHERE collection = ?`, [collection])\n\t\t\tawait tx.execute(`DELETE FROM ${PROVISIONAL_OPS_TABLE} WHERE collection = ?`, [collection])\n\t\t\tif (hasConflicts) {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`DELETE FROM ${SEQ_CONFLICTS_TABLE} WHERE collection = ? AND reemitted_as IS NULL`,\n\t\t\t\t\t[collection],\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// The kept writes leave the log here and are applied again after this transaction:\n\t\t// journal them in it, so a crash in between replays them on the next open.\n\t\tawait tx.execute(`DELETE FROM ${RESTORE_PENDING_TABLE}`)\n\t\tfor (const [position, operation] of kept.entries()) {\n\t\t\tconst entry = keptRows.get(operation.id)\n\t\t\tif (!entry) continue\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT INTO ${RESTORE_PENDING_TABLE} (position, collection, row) VALUES (?, ?, ?)`,\n\t\t\t\t[position, entry.collection, JSON.stringify(entry.row)],\n\t\t\t)\n\t\t}\n\t\t// The fold states of the restored collections are deleted above: the next open must\n\t\t// rebuild them even if this restore stops before the store does.\n\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [FOLD_MATERIALIZATION_META_KEY])\n\n\t\t// Version vector. Without a collection filter, remote nodes take the backup's\n\t\t// values; this database's own nodes never go backwards. With a filter, MAX only.\n\t\tconst current = await tx.query<{ node_id: string; sequence_number: number }>(\n\t\t\t'SELECT node_id, sequence_number FROM _kora_version_vector',\n\t\t)\n\t\tif (!options.collections) {\n\t\t\tfor (const row of current) {\n\t\t\t\tif (!localIds.has(row.node_id)) {\n\t\t\t\t\tawait tx.execute('DELETE FROM _kora_version_vector WHERE node_id = ?', [row.node_id])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const [nodeId, sequence] of backup.versionVector) {\n\t\t\tif (restartable.has(nodeId)) continue\n\t\t\tawait maxVector(tx, nodeId, sequence)\n\t\t}\n\n\t\t// The server must re-send everything in scope: this database no longer holds what\n\t\t// it delivered before.\n\t\tawait tx.execute('UPDATE _kora_meta SET value = ? WHERE key = ? OR key LIKE ?', [\n\t\t\t'0',\n\t\t\tDELIVERY_WATERMARK_META_KEY,\n\t\t\t`${DELIVERY_WATERMARK_META_KEY}:%`,\n\t\t])\n\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [DELTA_CURSOR_META_KEY])\n\t\t// Writes the journal recorded as applied landed in the state this restore replaces: a\n\t\t// leftover journal entry must apply again, not be skipped as done.\n\t\tawait tx.execute('DELETE FROM _kora_journal_applied')\n\n\t\tfor (const entry of backup.terminalRejections) {\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT OR IGNORE INTO ${TERMINAL_REJECTIONS_TABLE} (operation_id, node_id, sequence_number, code, rejected_at) VALUES (?, ?, ?, ?, ?)`,\n\t\t\t\t[entry.operationId, entry.nodeId, entry.sequenceNumber, entry.code, entry.rejectedAt],\n\t\t\t)\n\t\t}\n\n\t\t// W7 (RT-66): the exporting device's compacted history (base states), its row\n\t\t// snapshots and compacted prefixes, so records rebuild from base + log exactly.\n\t\tfor (const row of backup.foldBases) {\n\t\t\tif (!targets.includes(row.collection)) continue\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT OR REPLACE INTO ${FOLD_BASE_TABLE} (collection, record_id, state) VALUES (?, ?, ?)`,\n\t\t\t\t[row.collection, row.recordId, row.state],\n\t\t\t)\n\t\t}\n\t\tfor (const row of backup.foldSnapshots) {\n\t\t\tif (!targets.includes(row.collection)) continue\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT OR REPLACE INTO ${FOLD_SNAPSHOT_TABLE} (collection, record_id, state) VALUES (?, ?, ?)`,\n\t\t\t\t[row.collection, row.recordId, row.state],\n\t\t\t)\n\t\t}\n\t\tif (!options.collections) {\n\t\t\t// Per node and global; a collection filter would claim other collections' ops.\n\t\t\tawait tx.execute(`DELETE FROM ${COMPACTED_THROUGH_TABLE}`)\n\t\t\tfor (const [nodeId, sequence] of backup.compactedThrough) {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`INSERT INTO ${COMPACTED_THROUGH_TABLE} (node_id, sequence_number) VALUES (?, ?)`,\n\t\t\t\t\t[nodeId, sequence],\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tif (rawRecords) {\n\t\t\tfor (const operation of backup.operations) {\n\t\t\t\tif (!targets.includes(operation.collection)) continue\n\t\t\t\tawait insertOperationRow(tx, operation)\n\t\t\t}\n\t\t\tfor (const collection of targets) {\n\t\t\t\tconst rows = backup.records.get(collection) ?? []\n\t\t\t\tif (rows.length === 0) continue\n\t\t\t\tconst columns = new Set(\n\t\t\t\t\t(await tx.query<{ name: string }>(`PRAGMA table_info(${quoteIdent(collection)})`)).map(\n\t\t\t\t\t\t(column) => column.name,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tconst keys = Object.keys(row).filter((key) => columns.has(key))\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t`INSERT OR REPLACE INTO ${quoteIdent(collection)} (${keys.map((k) => quoteIdent(k)).join(', ')}) VALUES (${keys.map(() => '?').join(', ')})`,\n\t\t\t\t\t\tkeys.map((key) => toSqlValue(row[key])),\n\t\t\t\t\t)\n\t\t\t\t\trecordsRestored++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\tlet restored = rawRecords\n\t\t? backup.operations.filter((operation) => targets.includes(operation.collection)).length\n\t\t: 0\n\tif (!rawRecords) {\n\t\t// No materialized rows in the backup: the remote-apply path rebuilds them.\n\t\tfor (const operation of backup.operations) {\n\t\t\tif (!targets.includes(operation.collection)) continue\n\t\t\tif ((await host.applyOperation(operation)) === 'applied') restored++\n\t\t}\n\t}\n\tlet unsyncedWritesKept = 0\n\tfor (const operation of kept) {\n\t\tif ((await host.applyOperation(operation)) === 'applied') unsyncedWritesKept++\n\t}\n\n\tawait adapter.transaction(async (tx) => {\n\t\tawait tx.execute(`DELETE FROM ${RESTORE_PENDING_TABLE}`)\n\t\t// Restartable counters continue after the highest number now in the log.\n\t\tfor (const nodeId of restartable) {\n\t\t\tconst highest = await highestSequence(tx, targets, nodeId)\n\t\t\tawait tx.execute('DELETE FROM _kora_version_vector WHERE node_id = ?', [nodeId])\n\t\t\tif (highest > 0) {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t'INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)',\n\t\t\t\t\t[nodeId, highest],\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\t// Nothing dropped may still wait to upload.\n\t\tif (dropped.size > 0 || !options.keepUnsyncedWrites) {\n\t\t\tconst union = targets\n\t\t\t\t.map((c) => `SELECT id FROM ${quoteIdent(`_kora_ops_${c}`)}`)\n\t\t\t\t.join(' UNION ')\n\t\t\tif (union) {\n\t\t\t\tawait tx.execute(`DELETE FROM _kora_sync_queue WHERE id NOT IN (${union})`)\n\t\t\t}\n\t\t}\n\t})\n\n\treturn { operationsRestored: restored, recordsRestored, unsyncedWritesKept }\n}\n\nasync function importTerminalRejections(\n\tadapter: StorageAdapter,\n\tbackup: ParsedBackup,\n): Promise<void> {\n\tif (backup.terminalRejections.length === 0) return\n\tawait ensureLocalSyncRecordTables(adapter)\n\tawait adapter.transaction(async (tx) => {\n\t\tfor (const entry of backup.terminalRejections) {\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT OR IGNORE INTO ${TERMINAL_REJECTIONS_TABLE} (operation_id, node_id, sequence_number, code, rejected_at) VALUES (?, ?, ?, ?, ?)`,\n\t\t\t\t[entry.operationId, entry.nodeId, entry.sequenceNumber, entry.code, entry.rejectedAt],\n\t\t\t)\n\t\t}\n\t})\n}\n\n/** Append a canonical operation row; a taken `(node, sequence)` goes to the conflicts table. */\nasync function insertOperationRow(tx: Transaction, operation: Operation): Promise<void> {\n\tconst table = quoteIdent(`_kora_ops_${operation.collection}`)\n\tconst row = serializeOperation(operation)\n\tconst existing = await tx.query<{ id: string }>(`SELECT id FROM ${table} WHERE id = ?`, [row.id])\n\tif (existing.length > 0) return\n\tconst holder = await tx.query<{ id: string }>(\n\t\t`SELECT id FROM ${table} WHERE node_id = ? AND sequence_number = ?`,\n\t\t[row.node_id, row.sequence_number],\n\t)\n\tif (holder.length > 0) {\n\t\tawait insertConflictRow(\n\t\t\ttx,\n\t\t\toperation.collection,\n\t\t\trow,\n\t\t\t'backup-sequence-conflict',\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tDate.now(),\n\t\t)\n\t\treturn\n\t}\n\tawait tx.execute(\n\t\t`INSERT INTO ${table} (id, node_id, type, record_id, data, previous_data, timestamp, sequence_number, causal_deps, schema_version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t[\n\t\t\trow.id,\n\t\t\trow.node_id,\n\t\t\trow.type,\n\t\t\trow.record_id,\n\t\t\trow.data,\n\t\t\trow.previous_data,\n\t\t\trow.timestamp,\n\t\t\trow.sequence_number,\n\t\t\trow.causal_deps,\n\t\t\trow.schema_version,\n\t\t],\n\t)\n}\n\nasync function maxVector(tx: Transaction, nodeId: string, sequence: number): Promise<void> {\n\tawait tx.execute(\n\t\t`INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, ?)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t[nodeId, sequence],\n\t)\n}\n\nasync function highestSequence(\n\ttx: Transaction,\n\tcollections: string[],\n\tnodeId: string,\n): Promise<number> {\n\tlet highest = 0\n\tfor (const collection of collections) {\n\t\tconst rows = await tx.query<{ m: number | null }>(\n\t\t\t`SELECT MAX(sequence_number) AS m FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE node_id = ?`,\n\t\t\t[nodeId],\n\t\t)\n\t\thighest = Math.max(highest, rows[0]?.m ?? 0)\n\t}\n\treturn highest\n}\n\n/**\n * Per own node, how far the sync server acknowledged its operations: the W3 contiguous\n * acknowledged prefix, else the last acknowledged server vector, else 0.\n */\nasync function loadAckedThrough(\n\tadapter: StorageAdapter,\n\tnodes: readonly LocalNodeRecord[],\n): Promise<Map<string, number>> {\n\tconst lastAcked = await loadLastAckedServerVector(adapter)\n\tconst result = new Map<string, number>()\n\tfor (const node of nodes) {\n\t\tconst prefix = await loadOwnAckedThrough(adapter, node.nodeId)\n\t\tresult.set(node.nodeId, prefix ?? lastAcked.get(node.nodeId) ?? 0)\n\t}\n\treturn result\n}\n\nasync function tableExists(adapter: StorageAdapter, name: string): Promise<boolean> {\n\tconst rows = await adapter.query<{ name: string }>(\n\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?\",\n\t\t[name],\n\t)\n\treturn rows.length > 0\n}\n\nfunction toSqlValue(value: unknown): unknown {\n\tif (typeof value === 'boolean') return value ? 1 : 0\n\tif (value instanceof Uint8Array) return value\n\tif (value !== null && typeof value === 'object') return JSON.stringify(value)\n\treturn value\n}\n\n/** The unsynced writes a replace restore applies again once its transaction commits. */\nexport const RESTORE_PENDING_TABLE = '_kora_restore_pending'\n\nasync function ensureRestorePendingTable(adapter: StorageAdapter): Promise<void> {\n\tawait adapter.execute(\n\t\t`CREATE TABLE IF NOT EXISTS ${RESTORE_PENDING_TABLE} (position INTEGER PRIMARY KEY, collection TEXT NOT NULL, row TEXT NOT NULL)`,\n\t)\n}\n\n/**\n * Apply the writes an interrupted replace restore journaled and did not apply again (the\n * store opens with them). The apply path deduplicates by operation id, so writes the restore\n * did re-apply before it stopped are skipped.\n *\n * @returns How many writes were applied\n */\nexport async function replayInterruptedRestore(\n\tadapter: StorageAdapter,\n\tapplyOperation: (operation: Operation) => Promise<ApplyResult>,\n): Promise<number> {\n\tif (!(await tableExists(adapter, RESTORE_PENDING_TABLE))) return 0\n\tconst pending = await adapter.query<{ collection: string; row: string }>(\n\t\t`SELECT collection, row FROM ${RESTORE_PENDING_TABLE} ORDER BY position`,\n\t)\n\tlet applied = 0\n\tfor (const entry of pending) {\n\t\tconst operation = deserializeOperationWithCollection(\n\t\t\tJSON.parse(entry.row) as OperationRow,\n\t\t\tentry.collection,\n\t\t)\n\t\tif ((await applyOperation(operation)) === 'applied') applied++\n\t}\n\tif (pending.length > 0) await adapter.execute(`DELETE FROM ${RESTORE_PENDING_TABLE}`)\n\treturn applied\n}\n"]}