@korajs/store 1.0.0-beta.12 → 1.0.0-beta.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -37
- package/dist/adapters/better-sqlite3.cjs +90 -4
- package/dist/adapters/better-sqlite3.cjs.map +1 -1
- package/dist/adapters/better-sqlite3.d.cts +21 -12
- package/dist/adapters/better-sqlite3.d.ts +21 -12
- package/dist/adapters/better-sqlite3.js +69 -5
- package/dist/adapters/better-sqlite3.js.map +1 -1
- package/dist/adapters/indexeddb.cjs +1316 -610
- package/dist/adapters/indexeddb.cjs.map +1 -1
- package/dist/adapters/indexeddb.d.cts +29 -3
- package/dist/adapters/indexeddb.d.ts +29 -3
- package/dist/adapters/indexeddb.js +247 -221
- package/dist/adapters/indexeddb.js.map +1 -1
- package/dist/adapters/sqlite-wasm-worker.cjs +856 -63
- package/dist/adapters/sqlite-wasm-worker.cjs.map +1 -1
- package/dist/adapters/sqlite-wasm-worker.js +529 -63
- package/dist/adapters/sqlite-wasm-worker.js.map +1 -1
- package/dist/adapters/sqlite-wasm.cjs +1032 -344
- package/dist/adapters/sqlite-wasm.cjs.map +1 -1
- package/dist/adapters/sqlite-wasm.d.cts +239 -18
- package/dist/adapters/sqlite-wasm.d.ts +239 -18
- package/dist/adapters/sqlite-wasm.js +111 -5
- package/dist/adapters/sqlite-wasm.js.map +1 -1
- package/dist/backup-IHKVMUAM.js +25 -0
- package/dist/chunk-5AQSGMJV.js +5471 -0
- package/dist/chunk-5AQSGMJV.js.map +1 -0
- package/dist/chunk-5JMGMPUE.js +591 -0
- package/dist/chunk-5JMGMPUE.js.map +1 -0
- package/dist/{chunk-CYO3YKFL.js → chunk-5ZRRF6R2.js} +2 -2
- package/dist/chunk-A6GFH5IG.js +36 -0
- package/dist/chunk-A6GFH5IG.js.map +1 -0
- package/dist/chunk-BILSA6XZ.js +608 -0
- package/dist/chunk-BILSA6XZ.js.map +1 -0
- package/dist/chunk-BQSIL6TT.js +1095 -0
- package/dist/chunk-BQSIL6TT.js.map +1 -0
- package/dist/{chunk-GSJ7EEUC.js → chunk-J5AGXF3D.js} +58 -9
- package/dist/chunk-J5AGXF3D.js.map +1 -0
- package/dist/chunk-KK3GBONL.js +112 -0
- package/dist/chunk-KK3GBONL.js.map +1 -0
- package/dist/chunk-KTVNANUH.js +876 -0
- package/dist/chunk-KTVNANUH.js.map +1 -0
- package/dist/chunk-QW4UU7NG.js +1003 -0
- package/dist/chunk-QW4UU7NG.js.map +1 -0
- package/dist/chunk-SRHDJF5B.js +186 -0
- package/dist/chunk-SRHDJF5B.js.map +1 -0
- package/dist/chunk-UC2LGFPV.js +810 -0
- package/dist/chunk-UC2LGFPV.js.map +1 -0
- package/dist/{export-audit-ODGQTQIK.js → export-audit-J2QXRHD2.js} +3 -3
- package/dist/index.cjs +9533 -4246
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1143 -110
- package/dist/index.d.ts +1143 -110
- package/dist/index.js +298 -3191
- package/dist/index.js.map +1 -1
- package/dist/internal.cjs +581 -264
- package/dist/internal.cjs.map +1 -1
- package/dist/internal.d.cts +15 -85
- package/dist/internal.d.ts +15 -85
- package/dist/internal.js +10 -8
- package/dist/restore-MNDPR557.js +299 -0
- package/dist/restore-MNDPR557.js.map +1 -0
- package/dist/sql-builder-D0tC3sv9.d.cts +615 -0
- package/dist/sql-builder-D5UMzHEo.d.ts +615 -0
- package/dist/sqlite-wasm-channel-DVX93Uiq.d.cts +141 -0
- package/dist/sqlite-wasm-channel-DVX93Uiq.d.ts +141 -0
- package/dist/sqlite-wasm-channel-QCCNBYCU.js +12 -0
- package/dist/store-HNGX4KTT.js +16 -0
- package/dist/store-HNGX4KTT.js.map +1 -0
- package/dist/{types-BslDOTk0.d.ts → types-Dh-xyUjP.d.cts} +99 -26
- package/dist/{types-BslDOTk0.d.cts → types-Dh-xyUjP.d.ts} +99 -26
- package/package.json +3 -2
- package/dist/backup-5S7K2Z35.js +0 -14
- package/dist/chunk-GSJ7EEUC.js.map +0 -1
- package/dist/chunk-HS6DBMST.js +0 -383
- package/dist/chunk-HS6DBMST.js.map +0 -1
- package/dist/chunk-RJIEKEN4.js +0 -751
- package/dist/chunk-RJIEKEN4.js.map +0 -1
- package/dist/chunk-TUR7RGEP.js +0 -84
- package/dist/chunk-TUR7RGEP.js.map +0 -1
- package/dist/chunk-VDBJQ75K.js +0 -78
- package/dist/chunk-VDBJQ75K.js.map +0 -1
- package/dist/chunk-YT7MRFCP.js +0 -687
- package/dist/chunk-YT7MRFCP.js.map +0 -1
- package/dist/sqlite-wasm-channel-GGHA2BXU.js +0 -12
- package/dist/sqlite-wasm-channel-L6o3bWQK.d.cts +0 -92
- package/dist/sqlite-wasm-channel-L6o3bWQK.d.ts +0 -92
- package/dist/types-BOO9EPt1.d.ts +0 -170
- package/dist/types-C_GDavG-.d.cts +0 -170
- /package/dist/{backup-5S7K2Z35.js.map → backup-IHKVMUAM.js.map} +0 -0
- /package/dist/{chunk-CYO3YKFL.js.map → chunk-5ZRRF6R2.js.map} +0 -0
- /package/dist/{export-audit-ODGQTQIK.js.map → export-audit-J2QXRHD2.js.map} +0 -0
- /package/dist/{sqlite-wasm-channel-GGHA2BXU.js.map → sqlite-wasm-channel-QCCNBYCU.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/store/store.ts","../src/collection/collection.ts","../src/compaction/compact-operation-log.ts","../src/fold/compact-folded-log.ts","../src/fold/legacy-bodies.ts","../src/fold/rematerialize.ts","../src/migrations/run-migrations.ts","../src/query/query-builder.ts","../src/subscription/result-equality.ts","../src/query/pluralize.ts","../src/query/query-key.ts","../src/relations/relation-enforcer.ts","../src/relations/relation-lookup.ts","../src/replay/replay-to.ts","../src/sequences/sequence-manager.ts","../src/serialization/stored-text-migration.ts","../src/subscription/bloom-filter.ts","../src/subscription/subscription-manager.ts","../src/sync/rebase-unsynced-operations.ts","../src/sync/rotate-node-id.ts","../src/transaction/transaction-context.ts","../src/store/legacy-indexes.ts","../src/store/node-lock.ts","../src/store/relax-constraints.ts","../src/store/tab-node-id.ts"],"sourcesContent":["import {\n\tCausalTracker,\n\tHybridLogicalClock,\n\tKoraError,\n\tassertOperationTransformCoverage,\n\tcreateVersionVector,\n\tderiveSideEffectOpId,\n\tdeserializeFoldState,\n\texpandFieldVersionedOperations,\n\tfoldPlanFingerprints,\n\tgenerateUUIDv7,\n\tisReservedNodeId,\n\tisServerNodeId,\n\tmismatchedFoldFields,\n\toperationSchemaView,\n\tquoteIdent,\n\treplayOperationsForRecord,\n} from '@korajs/core'\nimport type {\n\tFoldState,\n\tHLCTimestamp,\n\tKoraEventEmitter,\n\tMergeTrace,\n\tOperation,\n\tOperationLog,\n\tOperationTransform,\n\tSchemaDefinition,\n\tSecretKeyProvider,\n\tVersionVector,\n} from '@korajs/core'\nimport { readBackupManifest as readManifest } from '../backup/backup'\nimport type { BackupManifest, BackupOptions, RestoreOptions, RestoreResult } from '../backup/types'\nimport { Collection } from '../collection/collection'\nimport { compactOperationLog } from '../compaction/compact-operation-log'\nimport type { CompactionResult, CompactionStrategy } from '../compaction/types'\nimport {\n\tNodeOwnedByAnotherUserError,\n\tOptimisticLockError,\n\tSchemaVersionAheadError,\n\tStoreNotOpenError,\n} from '../errors'\nimport { compactFoldedLog } from '../fold/compact-folded-log'\nimport { LEGACY_BODIES_META_KEY, canonicalizeLegacyLogBodies } from '../fold/legacy-bodies'\nimport {\n\tCOMPACTED_THROUGH_TABLE,\n\tFOLD_MATERIALIZATION_CURRENT,\n\tFOLD_MATERIALIZATION_LEGACY,\n\tFOLD_MATERIALIZATION_META_KEY,\n\tFOLD_STATE_TABLE,\n\tFOLD_TABLES_DDL,\n\tRecordFolder,\n\tisCompacted,\n} from '../fold/record-folder'\nimport {\n\ttype KeptRecords,\n\ttype RematerializationMode,\n\trematerializeDatabase,\n} from '../fold/rematerialize'\nimport {\n\tLOG_QUARANTINE_TABLE,\n\ttype LogIntegrityReport,\n\tscanLogIntegrity,\n} from '../log-integrity/log-integrity'\nimport {\n\ttype FieldVersions,\n\teffectiveFieldVersion,\n\tfieldVersionsForFields,\n\tparseFieldVersions,\n\tresolvePerFieldLww,\n\tserializeFieldVersions,\n} from '../lww/field-versions'\nimport { isIncomingNewerThanRow, serializeRowVersion } from '../lww/row-version'\nimport { runSchemaMigrations } from '../migrations/run-migrations'\nimport {\n\tSTORED_SCHEMA_VERSION_SQL,\n\tparseSchemaAhead,\n\tstoredSchemaVersion,\n} from '../migrations/schema-ceiling'\nimport type { LocalMutationContext } from '../mutations/types'\nimport { isStorageFullError } from '../mutations/write-context'\nimport { QueryBuilder } from '../query/query-builder'\nimport {\n\tbuildFieldFastForwardUpdateQuery,\n\tbuildInsertQuery,\n\tbuildLwwSoftDeleteQuery,\n\tbuildSoftDeleteQuery,\n} from '../query/sql-builder'\nimport { RelationEnforcer } from '../relations/relation-enforcer'\nimport { buildReplaySnapshot } from '../replay/replay-to'\nimport type { ReplaySnapshot } from '../replay/replay-to'\nimport { SequenceManager } from '../sequences/sequence-manager'\nimport {\n\tdeserializeOperationWithCollection,\n\tdeserializeRecord,\n\tserializeOperation,\n\tserializeRecord,\n} from '../serialization/serializer'\nimport { ensureStoredTextCodec } from '../serialization/stored-text-migration'\nimport {\n\ttype RecordsChangeListener,\n\tSubscriptionManager,\n} from '../subscription/subscription-manager'\nimport {\n\ttype AdoptionSchedule,\n\ttype LocalNodeRecord,\n\ttype TerminalRejection,\n\tassignLocalNodePrincipal,\n\tconfirmLocalNodePrincipal,\n\tdropLocalNode,\n\tfindTerminalRejections,\n\tforgetLocalNode,\n\tlistLocalNodes,\n\tloadAcceptedCycle,\n\tloadAdoptionSchedule,\n\tmarkLocalNodeAccepted,\n\tmarkLocalNodeRefused,\n\trecordLocalNodeRefusedFor,\n\trecordTerminalRejections,\n\tregisterLocalNode,\n\tsaveAdoptionSchedule,\n\tseedTerminalRejectionsOnce,\n\tsetLocalNodePrincipal,\n} from '../sync/local-sync-records'\nimport type { ClockRebaseResult } from '../sync/rebase-unsynced-operations'\nimport { rebaseUnsyncedOperationsInLog } from '../sync/rebase-unsynced-operations'\nimport { renumberOperationRow, rewriteDependentsInTx } from '../sync/rehash-operation'\nimport type { ResequenceResult } from '../sync/rehash-operation'\nimport type { NodeRotationResult } from '../sync/rotate-node-id'\nimport { rotateUnsyncedOperationsInLog } from '../sync/rotate-node-id'\nimport type { UnappliedOperation } from '../sync/sync-durability'\nimport {\n\tloadAcceptedDownlinkScope,\n\tloadOwnAckedThrough,\n\tloadUnappliedOperations,\n\tremoveUnappliedOperations,\n\tsaveAcceptedDownlinkScope,\n\tsaveOwnAckedThrough,\n\tsaveUnappliedOperations,\n} from '../sync/sync-durability'\nimport {\n\tDELIVERY_WATERMARK_META_KEY,\n\tDELTA_CURSOR_META_KEY,\n\tNODE_TOKEN_META_KEY,\n\tcollectOperationsAheadOfServer,\n\tdeleteDeliveryWatermark,\n\tloadAllDeliveryWatermarks,\n\tloadAuthoritativeNodeIds,\n\tloadDeliveryWatermark,\n\tloadDeltaCursor,\n\tloadLastAckedServerVector,\n\tloadNodeToken,\n\tloadRevokedAuthoritativeNodeIds,\n\tmergeVersionVectors,\n\tnodeTokenKey,\n\tsaveAuthoritativeNodeIds,\n\tsaveDeliveryWatermark,\n\tsaveDeltaCursor,\n\tsaveLastAckedServerVector,\n\tsaveNodeToken,\n\tsaveRevokedAuthoritativeNodeIds,\n} from '../sync/sync-state'\nimport { TransactionContext } from '../transaction/transaction-context'\nimport type {\n\tApplyRemoteOptions,\n\tApplyResult,\n\tLocalMutationHandler,\n\tMaterializedRowSnapshot,\n\tMetaRow,\n\tOperationRow,\n\tRawCollectionRow,\n\tRowVersionState,\n\tStorageAdapter,\n\tStoreConfig,\n\tStoreIsolation,\n\tTransaction,\n\tVersionVectorRow,\n} from '../types'\nimport { dropLegacyIndexes } from './legacy-indexes'\nimport { acquireNodeLock, isNodeLockHeld, nodeLockName, tryAcquireNodeLock } from './node-lock'\nimport { relaxValueDomainConstraints } from './relax-constraints'\nimport { allocateNextSequenceInTransaction } from './sequence-allocator'\nimport {\n\tSEQ_CONFLICTS_TABLE,\n\tinsertConflictRow,\n\tisOperationLogged,\n\tloadRetainedConflictRows,\n\trepairSequenceUniqueness,\n} from './sequence-repair'\nimport { savePerTabNodeId } from './tab-node-id'\nimport { resolvePerTabNodeId } from './tab-node-id'\n\n/**\n * Store is the main orchestrator. It owns a schema, a storage adapter,\n * a clock, and a subscription manager. It creates Collection instances\n * for each schema collection, and provides the sync contract via\n * applyRemoteOperation and getOperationRange.\n *\n * @example\n * ```typescript\n * const store = new Store({ schema, adapter })\n * await store.open()\n * const todo = await store.collection('todos').insert({ title: 'Hello' })\n * await store.close()\n * ```\n */\n/** `_kora_meta` key: per-collection fold plan fingerprints the rows were folded with (RT-63). */\nconst FOLD_PLAN_META_KEY = 'fold_plan_fingerprints'\n/** `_kora_meta` key: a full resync was requested to settle row snapshots (RT-68). */\nconst SNAPSHOT_RESYNC_META_KEY = 'fold_snapshot_resync'\n/**\n * Node id of provisional side effects (RT-69). In the reserved `kora:` namespace: no\n * device authors under it, and its effects never enter the log or the upload queue.\n */\nconst PROVISIONAL_NODE_ID = 'kora:provisional'\n\n/** A node id this client must never author under (RT-61): Kora's reserved namespace. */\nexport class ReservedNodeIdError extends KoraError {\n\tconstructor(nodeId: string, source: string) {\n\t\tsuper(\n\t\t\t`Node id \"${nodeId}\" (${source}) is in Kora's reserved \"kora:\" namespace; devices never author under it.`,\n\t\t\t'RESERVED_NODE_ID',\n\t\t\t{ nodeId, source, fix: 'Configure a node id that does not start with \"kora:\".' },\n\t\t)\n\t\tthis.name = 'ReservedNodeIdError'\n\t}\n}\n\n/**\n * Per collection, the record ids that own quarantined log rows (RT-68); a\n * quarantined row whose record id cannot be read keeps its whole collection.\n */\nasync function loadQuarantinedRecords(adapter: StorageAdapter): Promise<KeptRecords> {\n\tconst records = new Map<string, Set<string>>()\n\tconst collections = new Set<string>()\n\tconst exists = await adapter.query<{ name: string }>(\n\t\t\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?\",\n\t\t[LOG_QUARANTINE_TABLE],\n\t)\n\tif (exists.length === 0) return { records, collections }\n\tconst rows = await adapter.query<{ collection: string; row_json: string }>(\n\t\t`SELECT collection, row_json FROM ${LOG_QUARANTINE_TABLE}`,\n\t)\n\tfor (const row of rows) {\n\t\tlet recordId: unknown = null\n\t\ttry {\n\t\t\trecordId = (JSON.parse(row.row_json) as { record_id?: unknown }).record_id\n\t\t} catch {\n\t\t\trecordId = null\n\t\t}\n\t\tif (typeof recordId === 'string' && recordId.length > 0) {\n\t\t\tconst set = records.get(row.collection) ?? new Set<string>()\n\t\t\tset.add(recordId)\n\t\t\trecords.set(row.collection, set)\n\t\t} else {\n\t\t\tcollections.add(row.collection)\n\t\t}\n\t}\n\treturn { records, collections }\n}\n\n/** Collections whose stored fold states hold a field of another fold kind than the schema's. */\nasync function collectionsWithMismatchedStates(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n): Promise<string[]> {\n\tconst out: string[] = []\n\tfor (const collection of Object.keys(schema.collections)) {\n\t\tconst rows = await adapter.query<{ state: string }>(\n\t\t\t`SELECT state FROM ${FOLD_STATE_TABLE} WHERE collection = ?`,\n\t\t\t[collection],\n\t\t)\n\t\tfor (const row of rows) {\n\t\t\tlet state: FoldState\n\t\t\ttry {\n\t\t\t\tstate = deserializeFoldState(row.state)\n\t\t\t} catch {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (mismatchedFoldFields(state, schema).length > 0) {\n\t\t\t\tout.push(collection)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Make `nodeId` the database's node id (`_kora_meta.node_id`). The unkeyed legacy node\n * token belongs to the node id it replaces, so it moves to that node's own key first:\n * it must never be presented as the new node's token.\n */\nasync function moveDatabaseNodeId(tx: Transaction, nodeId: string): Promise<void> {\n\tconst meta = await tx.query<MetaRow>(\"SELECT value FROM _kora_meta WHERE key = 'node_id'\")\n\tconst previous = meta[0]?.value\n\tif (previous === nodeId) return\n\tconst legacy = await tx.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\tNODE_TOKEN_META_KEY,\n\t])\n\tif (legacy[0] && previous) {\n\t\tawait tx.execute('INSERT OR IGNORE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tnodeTokenKey(previous),\n\t\t\tlegacy[0].value,\n\t\t])\n\t}\n\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [NODE_TOKEN_META_KEY])\n\tawait tx.execute(\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('node_id', ?)\", [nodeId])\n}\n\n/** Result of {@link Store.bindPrincipal} (RT-42). */\nexport interface PrincipalBinding {\n\t/** The node id local writes use from now on. */\n\tnodeId: string\n\t/** The node id in use before the call. */\n\tpreviousNodeId: string\n\t/** The store moved to another node id. */\n\tswitched: boolean\n\t/** The node id is pinned and belongs to another user: nothing may upload it now. */\n\tconflict: boolean\n}\n\nexport class Store implements OperationLog {\n\tprivate opened = false\n\tprivate nodeId = ''\n\tprivate sequenceNumber = 0\n\tprivate versionVector: VersionVector = createVersionVector()\n\tprivate clock: HybridLogicalClock | null = null\n\tprivate collections = new Map<string, Collection>()\n\tprivate subscriptionManager: SubscriptionManager\n\tprivate sequenceManager: SequenceManager | null = null\n\n\tprivate readonly schema: SchemaDefinition\n\tprivate readonly adapter: StorageAdapter\n\tprivate readonly configNodeId: string | undefined\n\t/** The owner of the pinned node while it belongs to another user than the signed-in one (F9). */\n\tprivate pinnedNodeOwnedBy: string | null = null\n\t/** The sync server refused the pinned node as another user's (F9). */\n\tprivate pinnedNodeRefusedByServer = false\n\t/** The user of the last {@link bindPrincipal}. */\n\tprivate signedInPrincipal: string | null = null\n\tprivate readonly dbName: string\n\tprivate readonly isolation: StoreIsolation\n\tprivate readonly emitter: KoraEventEmitter | null\n\tprivate localMutationHandler: LocalMutationHandler | null\n\tprivate relationEnforcer: RelationEnforcer | null = null\n\tprivate causalTracker: CausalTracker | null = null\n\tprivate readonly secretKeyProvider: SecretKeyProvider | undefined\n\t/** Releases the per-tab node lock (RT-40); null when none is held. */\n\tprivate releaseNodeLock: (() => void) | null = null\n\t/** How rows are materialized ({@link StoreConfig.materialization}). */\n\tprivate readonly materialization: 'fold' | 'legacy'\n\t/** The W7 record fold; null under legacy materialization. */\n\tprivate readonly folder: RecordFolder | null\n\t/** True once every row of the database is a materialization of its fold state. */\n\tprivate foldActive = false\n\t/** Schema transforms applied at fold time (RT-84); never to stored operations. */\n\tprivate readonly operationTransforms: readonly OperationTransform[]\n\t/** Largest operation a local write may produce (RT-86); default in the write path. */\n\tprivate readonly maxOperationBytes: number | undefined\n\n\tconstructor(config: StoreConfig) {\n\t\tthis.materialization = config.materialization ?? 'fold'\n\t\tthis.operationTransforms = config.operationTransforms ?? []\n\t\tthis.maxOperationBytes = config.maxOperationBytes\n\t\tthis.folder =\n\t\t\tthis.materialization === 'fold'\n\t\t\t\t? new RecordFolder(config.schema, this.operationTransforms)\n\t\t\t\t: null\n\t\tthis.schema = config.schema\n\t\tthis.adapter = config.adapter\n\t\tthis.configNodeId = config.nodeId\n\t\tthis.dbName = config.dbName ?? 'kora-db'\n\t\tthis.isolation = config.isolation ?? 'shared'\n\t\tthis.emitter = config.emitter ?? null\n\t\tthis.localMutationHandler = config.localMutationHandler ?? null\n\t\tthis.secretKeyProvider = config.secretKeyProvider\n\t\tthis.subscriptionManager = new SubscriptionManager({\n\t\t\tonQuerySubscribed: config.onQuerySubscribed,\n\t\t\t// STORE-12: every subscription failure is observable (DevTools, app listeners).\n\t\t\tonQueryError: (failure) => {\n\t\t\t\tconst code =\n\t\t\t\t\tfailure.error instanceof KoraError ? failure.error.code : failure.error.name || 'Error'\n\t\t\t\tthis.emitter?.emit({\n\t\t\t\t\ttype: 'query:error',\n\t\t\t\t\tqueryId: failure.queryId,\n\t\t\t\t\tcollection: failure.collection,\n\t\t\t\t\tphase: failure.phase,\n\t\t\t\t\tcode,\n\t\t\t\t\tmessage: failure.error.message,\n\t\t\t\t})\n\t\t\t},\n\t\t})\n\t}\n\n\t/**\n\t * Open the store: initialize the database, load or generate a node ID,\n\t * restore the sequence number and version vector, and create Collection instances.\n\t */\n\tasync open(): Promise<void> {\n\t\ttry {\n\t\t\tawait this.adapter.open(this.schema)\n\t\t} catch (error) {\n\t\t\tconst ahead =\n\t\t\t\terror instanceof SchemaVersionAheadError\n\t\t\t\t\t? { stored: error.storedVersion, code: error.codeVersion }\n\t\t\t\t\t: parseSchemaAhead(error)\n\t\t\tif (ahead !== null) throw this.schemaAhead(ahead.stored)\n\t\t\tthrow error\n\t\t}\n\t\t// A database a newer build already migrated is refused before anything here writes\n\t\t// to it (RT-109). The DDL executors refuse it before their DDL; this also covers\n\t\t// adapters that restore their data after it (the IndexedDB fallback).\n\t\tconst stored = storedSchemaVersion(\n\t\t\tawait this.adapter.query<{ value: unknown }>(STORED_SCHEMA_VERSION_SQL),\n\t\t)\n\t\tif (stored > this.schema.version) {\n\t\t\tawait this.adapter.close().catch(() => undefined)\n\t\t\tthrow this.schemaAhead(stored)\n\t\t}\n\t\tawait this.adapter.execute(\n\t\t\t'CREATE TABLE IF NOT EXISTS _kora_scope_retractions (collection TEXT NOT NULL, record_id TEXT NOT NULL, PRIMARY KEY (collection, record_id))',\n\t\t)\n\t\tfor (const ddl of FOLD_TABLES_DDL) await this.adapter.execute(ddl)\n\t\tthis.foldActive = false\n\n\t\t// Tables created before beta.13 restate enum membership and requiredness as CHECK /\n\t\t// NOT NULL constraints that cannot evolve with the schema: rebuild them once without\n\t\t// (RT-101). Validation is the single authority for the value domain.\n\t\tawait relaxValueDomainConstraints(this.adapter, this.schema)\n\t\t// Indexes named under the old, colliding scheme are replaced (STORE-15).\n\t\tawait dropLegacyIndexes(this.adapter, this.schema)\n\n\t\t// Load or generate node ID\n\t\tconst persistedNodeId = await this.readPersistedNodeId()\n\t\tthis.nodeId = await this.loadOrGenerateNodeId()\n\t\t// Every node id this database authors under is registered (RT-38, RT-40).\n\t\tawait registerLocalNode(this.adapter, this.nodeId)\n\t\tawait this.registerUnregisteredAuthors(persistedNodeId)\n\n\t\t// Log integrity first (W8 step 0): repair rows an earlier release damaged and\n\t\t// quarantine the unrecoverable ones, before anything reads or folds the log.\n\t\tawait this.scanLog('quick')\n\n\t\t// (node_id, sequence_number) is unique in the operation log: repair any\n\t\t// duplicates an earlier version wrote, then enforce it with an index (W6).\n\t\tawait repairSequenceUniqueness(this.adapter, this.schema, this.nodeId)\n\t\t// The terminal rejections an earlier release kept only in the app's list become\n\t\t// durable markers (RT-36).\n\t\tawait seedTerminalRejectionsOnce(this.adapter)\n\t\t// Raw-string columns use the lossless stored-text codec (RT-65); rows written\n\t\t// before it get their U+FFFF re-encoded once, before anything reads them.\n\t\tawait ensureStoredTextCodec(this.adapter, this.schema)\n\t\tif (this.isolation === 'per-tab' && !this.configNodeId) {\n\t\t\t// A live tab holds its node's lock, so a later tab adopts the node's unsynced\n\t\t\t// writes only after this tab is gone (RT-40).\n\t\t\tthis.releaseNodeLock = acquireNodeLock(nodeLockName(this.dbName, this.nodeId))\n\t\t}\n\t\tthis.clock = new HybridLogicalClock(this.nodeId)\n\t\tthis.causalTracker = new CausalTracker()\n\n\t\t// The fold is active for writes as soon as the database's rows are known to be\n\t\t// fold materializations (W7); a pre-W7 database is re-materialized after its\n\t\t// schema migrations, whose backfills then write the legacy way.\n\t\tif (this.folder) {\n\t\t\tthis.folder.setAuthoritativeNodeIds((await loadAuthoritativeNodeIds(this.adapter)) ?? [])\n\t\t\tthis.foldActive =\n\t\t\t\t(await this.readMeta(FOLD_MATERIALIZATION_META_KEY)) === FOLD_MATERIALIZATION_CURRENT\n\t\t}\n\n\t\t// Run schema migrations if needed. Backfills write operations through the local\n\t\t// write path, so the node id and clock must exist first (STORE-13).\n\t\ttry {\n\t\t\t// Transforms that cannot read the stored log would fold those operations as\n\t\t\t// absent and erase them from their records: refuse to open instead (RT-103).\n\t\t\tawait this.assertTransformCoverage()\n\t\t\tawait this.runMigrationsIfNeeded()\n\t\t\tawait this.ensureLegacyBodiesCanonical()\n\t\t\tawait this.ensureMaterialization()\n\t\t} catch (error) {\n\t\t\tthis.releaseNodeLock?.()\n\t\t\tthis.releaseNodeLock = null\n\t\t\tthrow error\n\t\t}\n\n\t\t// Initialize sequence manager\n\t\tthis.sequenceManager = new SequenceManager(this.adapter, this.nodeId)\n\n\t\t// Load sequence number and version vector\n\t\tthis.sequenceNumber = await this.loadSequenceNumber()\n\t\tthis.versionVector = await this.loadVersionVector()\n\n\t\t// Create RelationEnforcer if the schema has relations.\n\t\t// The enforcer is shared across all Collection instances so that\n\t\t// cascading deletes can cross collection boundaries.\n\t\tconst hasRelations = Object.keys(this.schema.relations).length > 0\n\t\tthis.relationEnforcer = hasRelations ? new RelationEnforcer({ schema: this.schema }) : null\n\n\t\t// Create collection instances\n\t\tfor (const [name, definition] of Object.entries(this.schema.collections)) {\n\t\t\tconst col = new Collection(\n\t\t\t\tname,\n\t\t\t\tdefinition,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.adapter,\n\t\t\t\tthis.clock,\n\t\t\t\tthis.nodeId,\n\t\t\t\t(collectionName, operation) => this.publishLocalOperation(collectionName, operation),\n\t\t\t\tthis.relationEnforcer,\n\t\t\t\tthis.localMutationHandler,\n\t\t\t\tthis.causalTracker,\n\t\t\t\tthis.secretKeyProvider,\n\t\t\t\t(error) => this.reportStorageError(error),\n\t\t\t\t() => this.activeFold(),\n\t\t\t\tthis.maxOperationBytes,\n\t\t\t\t() => this.assertLocalWriteAllowed(),\n\t\t\t)\n\t\t\tthis.collections.set(name, col)\n\t\t}\n\n\t\tthis.opened = true\n\t}\n\n\t/**\n\t * Close the store: clear subscriptions and close the adapter.\n\t */\n\tasync close(): Promise<void> {\n\t\tthis.subscriptionManager.clear()\n\t\tthis.collections.clear()\n\t\tthis.opened = false\n\t\ttry {\n\t\t\tawait this.adapter.close()\n\t\t} finally {\n\t\t\tthis.releaseNodeLock?.()\n\t\t\tthis.releaseNodeLock = null\n\t\t}\n\t}\n\n\t/**\n\t * Check the operation log (W8 step 0): every row must round-trip through the\n\t * canonical operation serializer. Rows an earlier release damaged in a recoverable\n\t * way (a JSON-encoded timestamp written by a beta.12 backup restore) are repaired;\n\t * unrecoverable rows move to the quarantine table, where no fold reads them. Also\n\t * reports sequence gaps in this database's own nodes (compaction, a lost tail).\n\t *\n\t * The store runs a quick variant (SQL prefilter) on every open. Rebuilding state from\n\t * the log must only run on a `clean` report.\n\t *\n\t * @param options - `repair: false` only reports; `mode: 'quick'` checks only the rows\n\t * a SQL prefilter flags (default `'full'`: every row)\n\t * @returns The integrity report; emits `store:log-integrity` when rows changed\n\t */\n\tasync verifyLogIntegrity(options?: {\n\t\trepair?: boolean\n\t\tmode?: 'full' | 'quick'\n\t}): Promise<LogIntegrityReport> {\n\t\tthis.ensureOpen()\n\t\treturn this.scanLog(options?.mode ?? 'full', options?.repair ?? true)\n\t}\n\n\tprivate async scanLog(mode: 'full' | 'quick', repair = true): Promise<LogIntegrityReport> {\n\t\tconst localNodeIds = (await listLocalNodes(this.adapter)).map((node) => node.nodeId)\n\t\tconst report = await scanLogIntegrity(this.adapter, this.schema, {\n\t\t\tmode,\n\t\t\trepair,\n\t\t\tlocalNodeIds,\n\t\t})\n\t\tif (repair && (report.repaired.length > 0 || report.newlyQuarantined.length > 0)) {\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:log-integrity',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\trepaired: report.repaired.length,\n\t\t\t\tquarantined: report.newlyQuarantined.length,\n\t\t\t\tgaps: report.gaps.length,\n\t\t\t\tclean: report.clean,\n\t\t\t\tmessage: `Operation log of \"${this.dbName}\": ${report.repaired.length} row(s) repaired, ${report.newlyQuarantined.length} row(s) quarantined (${LOG_QUARANTINE_TABLE}).`,\n\t\t\t})\n\t\t}\n\t\treturn report\n\t}\n\n\t/**\n\t * Get a Collection instance for CRUD operations.\n\t * @throws {StoreNotOpenError} If the store is not open\n\t * @throws {Error} If the collection name is not in the schema\n\t */\n\tcollection(name: string): CollectionAccessor {\n\t\tthis.ensureOpen()\n\t\tconst col = this.collections.get(name)\n\t\tif (!col) {\n\t\t\tthrow new Error(\n\t\t\t\t`Unknown collection \"${name}\". Available: ${[...this.collections.keys()].join(', ')}`,\n\t\t\t)\n\t\t}\n\n\t\tconst definition = this.schema.collections[name]\n\t\tif (!definition) {\n\t\t\tthrow new Error(`Collection definition not found for \"${name}\"`)\n\t\t}\n\n\t\treturn {\n\t\t\tinsert: (data: Record<string, unknown>) => col.insert(data),\n\t\t\tfindById: (id: string) => col.findById(id),\n\t\t\tupdate: (id: string, data: Record<string, unknown>) => col.update(id, data),\n\t\t\tdelete: (id: string) => col.delete(id),\n\t\t\twhere: (conditions) =>\n\t\t\t\tnew QueryBuilder(\n\t\t\t\t\tname,\n\t\t\t\t\tdefinition,\n\t\t\t\t\tthis.adapter,\n\t\t\t\t\tthis.subscriptionManager,\n\t\t\t\t\tconditions,\n\t\t\t\t\tthis.schema,\n\t\t\t\t),\n\t\t}\n\t}\n\n\t/**\n\t * Get the current version vector.\n\t */\n\tgetVersionVector(): VersionVector {\n\t\tthis.ensureOpen()\n\t\treturn new Map(this.versionVector)\n\t}\n\n\t/**\n\t * Get the node ID for this store instance.\n\t */\n\t/**\n\t * Records the offset between server time and this device's clock\n\t * (serverTime - localTime), learned at sync handshake. Lets the store's HLC\n\t * validate remote timestamps correctly even when the local clock is wrong.\n\t */\n\tsetClockReferenceOffset(offsetMs: number): void {\n\t\tthis.clock?.setReferenceOffset(offsetMs)\n\t}\n\n\tgetNodeId(): string {\n\t\tthis.ensureOpen()\n\t\treturn this.nodeId\n\t}\n\n\t/** The schema transforms the fold applies (transforms at fold time, RT-84). */\n\tgetOperationTransforms(): readonly OperationTransform[] {\n\t\treturn this.operationTransforms\n\t}\n\n\t/**\n\t * Apply a remote operation received from sync.\n\t * Checks for duplicates, applies to the data table, persists the operation,\n\t * and updates the version vector.\n\t */\n\tasync applyRemoteOperation(\n\t\tstored: Operation,\n\t\toptions?: ApplyRemoteOptions,\n\t): Promise<ApplyResult> {\n\t\tthis.ensureOpen()\n\n\t\tconst collection = stored.collection\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition) {\n\t\t\treturn 'skipped'\n\t\t}\n\t\tconst fold = this.activeFold()\n\t\tif (fold) {\n\t\t\t// The fold reads the operation through the schema transforms itself (RT-84).\n\t\t\treturn this.applyRemoteFolded(stored, fold, options)\n\t\t}\n\t\t// Legacy materialization writes rows directly: it materializes the operation as\n\t\t// this schema reads it, and logs the operation exactly as written (RT-84).\n\t\tconst view = operationSchemaView(stored, this.schema.version, this.operationTransforms)\n\t\tif (view === null) return 'skipped'\n\t\tconst op = view\n\n\t\t// Materialization may use overridden data/timestamp (authoritative merge\n\t\t// results), but the LOG below always stores the canonical operation:\n\t\t// operations are immutable and content-addressed, so merged values must\n\t\t// never be persisted under the original operation's id.\n\t\tconst materializeTimestamp = options?.materializeTimestamp ?? op.timestamp\n\t\tconst remoteVersion = serializeRowVersion(materializeTimestamp)\n\t\tconst wallTime = materializeTimestamp.wallTime\n\t\tconst materializeSource = options?.materializeData ?? op.data\n\t\t// Duration is reported to DevTools only; it never orders anything.\n\t\tconst startedAt = Date.now()\n\t\tconst outcome = { duplicate: false, revived: false }\n\n\t\t// Apply the operation to the data table (LWW-guarded; op log always appended below)\n\t\ttry {\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\t// Content-addressed dedup INSIDE the write transaction: two concurrent\n\t\t\t\t// deliveries of one operation serialize here, and the second sees the\n\t\t\t\t// first's row instead of failing on the primary key (STORE-15).\n\t\t\t\tif (await isOperationLogged(tx, collection, op.id)) {\n\t\t\t\t\toutcome.duplicate = true\n\t\t\t\t\tconst retracted = await tx.query<{ record_id: string }>(\n\t\t\t\t\t\t'SELECT record_id FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t\t\t[collection, op.recordId],\n\t\t\t\t\t)\n\t\t\t\t\tif (retracted.length > 0) {\n\t\t\t\t\t\tawait tx.execute(`UPDATE ${quoteIdent(collection)} SET _deleted = 0 WHERE id = ?`, [\n\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t])\n\t\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t\t'DELETE FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t\t\t\t[collection, op.recordId],\n\t\t\t\t\t\t)\n\t\t\t\t\t\toutcome.revived = true\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// Advance the local HLC; severe clock drift throws ClockDriftError (surfaced as sync:apply-failed).\n\t\t\t\tif (this.clock) {\n\t\t\t\t\t// A scope entry's newest field version can be later than its timestamp (the\n\t\t\t\t\t// record's creation, RT-27): the clock must move past every version it carries.\n\t\t\t\t\tthis.clock.receive(op.fieldVersions ? newestFieldVersion(op) : op.timestamp)\n\t\t\t\t}\n\n\t\t\t\t// Optimistic-concurrency guard: if the caller computed its data from a\n\t\t\t\t// snapshot, verify the row hasn't changed since. Throwing rolls the\n\t\t\t\t// whole transaction back (nothing written, op NOT logged) so the caller\n\t\t\t\t// can recompute against fresh state and retry.\n\t\t\t\tconst checkGuard = (row: RawCollectionRow | undefined): void => {\n\t\t\t\t\tconst guard = options?.guardRowState\n\t\t\t\t\tif (!guard) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tconst version = typeof row?._version === 'string' ? row._version : null\n\t\t\t\t\tconst fieldVersions =\n\t\t\t\t\t\ttypeof row?._field_versions === 'string' ? row._field_versions : null\n\t\t\t\t\tif (version !== guard.version || fieldVersions !== guard.fieldVersions) {\n\t\t\t\t\t\tthrow new OptimisticLockError(collection, op.recordId)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (options?.logOnly) {\n\t\t\t\t\t// Append-only: the caller (after folding the record's log) determined\n\t\t\t\t\t// this op does not change the authoritative row. Persist it for future\n\t\t\t\t\t// folds but leave the row untouched. Fall through to op-log insert + VV.\n\t\t\t\t} else if (\n\t\t\t\t\top.type === 'insert' &&\n\t\t\t\t\top.data &&\n\t\t\t\t\top.fieldVersions &&\n\t\t\t\t\t!options?.materializeData &&\n\t\t\t\t\t!options?.forceMaterialize &&\n\t\t\t\t\t!options?.materializeTimestamp\n\t\t\t\t) {\n\t\t\t\t\t// Server scope-entry insert (RT-27): every field carries its own version.\n\t\t\t\t\tawait this.applyFieldVersionedInsert(tx, op, definition, op.data, checkGuard)\n\t\t\t\t} else if (op.type === 'insert' && materializeSource) {\n\t\t\t\t\tconst serializedData = serializeRecord(materializeSource, definition.fields)\n\t\t\t\t\tconst existing = await tx.query<RawCollectionRow>(\n\t\t\t\t\t\t`SELECT _updated_at, _version, _field_versions, _deleted FROM ${collection} WHERE id = ?`,\n\t\t\t\t\t\t[op.recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst row = existing[0]\n\t\t\t\t\tcheckGuard(row)\n\n\t\t\t\t\tif (!row) {\n\t\t\t\t\t\tconst record: Record<string, unknown> = {\n\t\t\t\t\t\t\tid: op.recordId,\n\t\t\t\t\t\t\t...serializedData,\n\t\t\t\t\t\t\t_created_at: wallTime,\n\t\t\t\t\t\t\t_updated_at: wallTime,\n\t\t\t\t\t\t\t_version: remoteVersion,\n\t\t\t\t\t\t\t// Stamp every inserted field so per-field LWW has a real baseline.\n\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(\n\t\t\t\t\t\t\t\tfieldVersionsForFields(Object.keys(serializedData), remoteVersion),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst insertQuery = buildInsertQuery(collection, record)\n\t\t\t\t\t\tawait tx.execute(insertQuery.sql, insertQuery.params)\n\n\t\t\t\t\t\t// Catch up on operations delivered BEFORE this insert (transports may\n\t\t\t\t\t\t// reorder): any update/delete already logged for this record was\n\t\t\t\t\t\t// applied while no row existed, so it never materialized. The row is\n\t\t\t\t\t\t// a fold of the log — fold the orphans now, in timestamp order,\n\t\t\t\t\t\t// inside this same transaction. Per-field LWW makes the result\n\t\t\t\t\t\t// identical to what an in-order device computed.\n\t\t\t\t\t\tawait this.foldOrphanedOperations(tx, collection, definition, op.recordId, op)\n\t\t\t\t\t} else if (\n\t\t\t\t\t\trow._deleted === 1 &&\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\tawait tx.query<{ record_id: string }>(\n\t\t\t\t\t\t\t\t'SELECT record_id FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t\t\t\t\t[collection, op.recordId],\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t).length > 0\n\t\t\t\t\t) {\n\t\t\t\t\t\t// The row is hidden by a scope retraction (a view change, not a domain\n\t\t\t\t\t\t// delete) and the record is entering the scope again, typically through\n\t\t\t\t\t\t// a server scope-entry insert (RT-19). Show it again and merge per field,\n\t\t\t\t\t\t// exactly like an insert collision on a live row: fields this device\n\t\t\t\t\t\t// holds newer versions of are kept.\n\t\t\t\t\t\tconst { winners, merged } = resolvePerFieldLww(\n\t\t\t\t\t\t\tparseFieldVersions(row._field_versions),\n\t\t\t\t\t\t\tObject.keys(serializedData),\n\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\ttypeof row._version === 'string' ? row._version : undefined,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tconst fieldChanges: Record<string, unknown> = {\n\t\t\t\t\t\t\t_deleted: 0,\n\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(merged),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const field of winners) {\n\t\t\t\t\t\t\tfieldChanges[field] = serializedData[field]\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// `_created_at` is left alone: the record was created long before it\n\t\t\t\t\t\t// re-entered this device's view.\n\t\t\t\t\t\tconst reactivate = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\tfieldChanges,\n\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tawait tx.execute(reactivate.sql, reactivate.params)\n\t\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t\t'DELETE FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t\t\t\t[collection, op.recordId],\n\t\t\t\t\t\t)\n\t\t\t\t\t} else if (row._deleted === 1) {\n\t\t\t\t\t\t// Insert vs tombstone: a strictly newer insert resurrects the record\n\t\t\t\t\t\t// with its full field set; an older one is stale (delete wins).\n\t\t\t\t\t\tif (isIncomingNewerThanRow(materializeTimestamp, row)) {\n\t\t\t\t\t\t\tconst fieldChanges: Record<string, unknown> = {\n\t\t\t\t\t\t\t\t...serializedData,\n\t\t\t\t\t\t\t\t_deleted: 0,\n\t\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(\n\t\t\t\t\t\t\t\t\tfieldVersionsForFields(Object.keys(serializedData), remoteVersion),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst upsert = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\t\tfieldChanges,\n\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t\t\t{ maxCreatedAt: wallTime },\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tawait tx.execute(upsert.sql, upsert.params)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Insert collision on a LIVE row (relayed insert racing a local one,\n\t\t\t\t\t\t// or an insert-vs-insert merge). A plain INSERT would violate the\n\t\t\t\t\t\t// primary key; resolve per-field instead, exactly like an update, so\n\t\t\t\t\t\t// every node converges no matter which insert (or interleaved\n\t\t\t\t\t\t// update) it saw first. `_created_at` converges to the max insert\n\t\t\t\t\t\t// wall time seen, applied even when every field loses.\n\t\t\t\t\t\tconst currentVersions = parseFieldVersions(row._field_versions)\n\t\t\t\t\t\tconst rowVersion = typeof row._version === 'string' ? row._version : undefined\n\t\t\t\t\t\tconst fieldChanges: Record<string, unknown> = {}\n\t\t\t\t\t\tlet fieldVersionsJson: string\n\t\t\t\t\t\tif (options?.forceMaterialize) {\n\t\t\t\t\t\t\t// Authoritative merged insert: every field is written.\n\t\t\t\t\t\t\tconst merged = { ...currentVersions }\n\t\t\t\t\t\t\tfor (const field of Object.keys(serializedData)) {\n\t\t\t\t\t\t\t\tfieldChanges[field] = serializedData[field]\n\t\t\t\t\t\t\t\tmerged[field] = remoteVersion\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfieldVersionsJson = serializeFieldVersions(merged)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconst { winners, merged } = resolvePerFieldLww(\n\t\t\t\t\t\t\t\tcurrentVersions,\n\t\t\t\t\t\t\t\tObject.keys(serializedData),\n\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\trowVersion,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tfor (const field of winners) {\n\t\t\t\t\t\t\t\tfieldChanges[field] = serializedData[field]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfieldVersionsJson = serializeFieldVersions(merged)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst upsert = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\t{ ...fieldChanges, _field_versions: fieldVersionsJson },\n\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t\t{ maxCreatedAt: wallTime },\n\t\t\t\t\t\t)\n\t\t\t\t\t\tawait tx.execute(upsert.sql, upsert.params)\n\t\t\t\t\t}\n\t\t\t\t} else if (op.type === 'update' && materializeSource) {\n\t\t\t\t\tconst serializedChanges = serializeRecord(materializeSource, definition.fields)\n\t\t\t\t\tconst changedFields = Object.keys(serializedChanges)\n\n\t\t\t\t\t// Read the current per-field versions INSIDE the transaction so the\n\t\t\t\t\t// resolve-then-write is atomic with respect to any concurrent local\n\t\t\t\t\t// mutation — this is what prevents a relayed remote op from clobbering\n\t\t\t\t\t// a newer local edit that lands between the read and the write.\n\t\t\t\t\tconst currentRows = await tx.query<RawCollectionRow>(\n\t\t\t\t\t\t`SELECT _version, _field_versions FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t\t\t\t[op.recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst currentRow = currentRows[0]\n\t\t\t\t\tcheckGuard(currentRow)\n\n\t\t\t\t\tif (currentRow) {\n\t\t\t\t\t\tconst currentVersions = parseFieldVersions(currentRow._field_versions)\n\t\t\t\t\t\tconst rowVersion =\n\t\t\t\t\t\t\ttypeof currentRow._version === 'string' ? currentRow._version : undefined\n\n\t\t\t\t\t\tif (options?.forceMaterialize) {\n\t\t\t\t\t\t\t// Authoritative merged result (richtext / add-wins-set / constraint\n\t\t\t\t\t\t\t// resolution computed by the merge engine): write every changed\n\t\t\t\t\t\t\t// field and stamp its per-field version to this op's version, while\n\t\t\t\t\t\t\t// advancing the row watermark monotonically.\n\t\t\t\t\t\t\tconst merged = { ...currentVersions }\n\t\t\t\t\t\t\tfor (const field of changedFields) {\n\t\t\t\t\t\t\t\tmerged[field] = remoteVersion\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst fieldChanges: Record<string, unknown> = {\n\t\t\t\t\t\t\t\t...serializedChanges,\n\t\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(merged),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (options?.reactivateIfDeleted) {\n\t\t\t\t\t\t\t\tfieldChanges._deleted = 0\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst forceQuery = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\t\tfieldChanges,\n\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tawait tx.execute(forceQuery.sql, forceQuery.params)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Deterministic field-level LWW: write only the fields this op\n\t\t\t\t\t\t\t// wins (strictly newer than the field's stored version). Same\n\t\t\t\t\t\t\t// result on every node regardless of arrival order.\n\t\t\t\t\t\t\tconst { winners, merged } = resolvePerFieldLww(\n\t\t\t\t\t\t\t\tcurrentVersions,\n\t\t\t\t\t\t\t\tchangedFields,\n\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\trowVersion,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tif (winners.length > 0 || options?.reactivateIfDeleted) {\n\t\t\t\t\t\t\t\tconst winningChanges: Record<string, unknown> = {\n\t\t\t\t\t\t\t\t\t_field_versions: serializeFieldVersions(merged),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfor (const field of winners) {\n\t\t\t\t\t\t\t\t\twinningChanges[field] = serializedChanges[field]\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (options?.reactivateIfDeleted) {\n\t\t\t\t\t\t\t\t\twinningChanges._deleted = 0\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst forceQuery = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\t\t\t\twinningChanges,\n\t\t\t\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t\t\t\t\twallTime,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\tawait tx.execute(forceQuery.sql, forceQuery.params)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// currentRow absent: nothing materialized to update (insert not yet\n\t\t\t\t\t// applied, or hard-absent). The op is still appended to the log below;\n\t\t\t\t\t// the pipeline handles tombstone reactivation separately.\n\t\t\t\t} else if (op.type === 'delete') {\n\t\t\t\t\tconst deleteQuery = buildLwwSoftDeleteQuery(\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\top.recordId,\n\t\t\t\t\t\twallTime,\n\t\t\t\t\t\tremoteVersion,\n\t\t\t\t\t)\n\t\t\t\t\tawait tx.execute(deleteQuery.sql, deleteQuery.params)\n\t\t\t\t}\n\n\t\t\t\t// Persist the operation\n\t\t\t\tawait this.appendRemoteOperationRow(tx, stored)\n\n\t\t\t\t// Version vector: MAX with the stored value, never a value computed outside\n\t\t\t\t// this transaction (another tab may have advanced it). The in-memory\n\t\t\t\t// vector is updated only after commit.\n\t\t\t\tawait tx.execute(\n\t\t\t\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\t\t\t[op.nodeId, op.sequenceNumber],\n\t\t\t\t)\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.reportStorageError(error)\n\t\t\tthrow error\n\t\t}\n\n\t\t// Committed. A duplicate still advances this runtime's vector and refreshes\n\t\t// its queries: another tab sharing the database may have applied the\n\t\t// operation first, and this tab must not stay blind to it (STORE-10).\n\t\tthis.recordOperationSequence(op)\n\t\tif (outcome.duplicate) {\n\t\t\tif (outcome.revived) {\n\t\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t\t} else {\n\t\t\t\tthis.subscriptionManager.notify(collection, op)\n\t\t\t}\n\t\t\treturn 'duplicate'\n\t\t}\n\n\t\tthis.subscriptionManager.notify(collection, op)\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'operation:applied',\n\t\t\toperation: op,\n\t\t\tduration: Date.now() - startedAt,\n\t\t})\n\n\t\treturn 'applied'\n\t}\n\n\t/**\n\t * W7 remote apply: append the operation, then merge it into its record's fold\n\t * state, which re-materializes the row, all in one write transaction. There is no\n\t * read-decide-write race to guard: the state is read and written inside the\n\t * transaction, and the merge does not depend on the order operations arrive in.\n\t */\n\tprivate async applyRemoteFolded(\n\t\top: Operation,\n\t\tfold: RecordFolder,\n\t\toptions: ApplyRemoteOptions | undefined,\n\t): Promise<ApplyResult> {\n\t\tconst collection = op.collection\n\t\tconst startedAt = Date.now()\n\t\tconst outcome = { duplicate: false, revived: false, traces: [] as MergeTrace[] }\n\t\ttry {\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tif ((await isOperationLogged(tx, collection, op.id)) || (await isCompacted(tx, op))) {\n\t\t\t\t\toutcome.duplicate = true\n\t\t\t\t\tconst retracted = await tx.query<{ record_id: string }>(\n\t\t\t\t\t\t'SELECT record_id FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t\t\t[collection, op.recordId],\n\t\t\t\t\t)\n\t\t\t\t\tif (retracted.length > 0) {\n\t\t\t\t\t\t// The record re-enters the scope: show it again with every field of\n\t\t\t\t\t\t// its state (writes merged while it was hidden included).\n\t\t\t\t\t\tconst state = await fold.loadState(tx, collection, op.recordId)\n\t\t\t\t\t\tif (state) {\n\t\t\t\t\t\t\tawait fold.materializeRow(tx, state, 'all', { clearRetraction: true })\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t\t\t'DELETE FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t\t\t\t\t[collection, op.recordId],\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutcome.revived = true\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (this.clock) {\n\t\t\t\t\t// A scope entry's newest field version can be later than its timestamp (the\n\t\t\t\t\t// record's creation, RT-27): the clock must move past every version it carries.\n\t\t\t\t\tthis.clock.receive(op.fieldVersions ? newestFieldVersion(op) : op.timestamp)\n\t\t\t\t}\n\t\t\t\tawait this.appendRemoteOperationRow(tx, op)\n\t\t\t\tconst applied = await fold.applyInTx(tx, op, 'remote')\n\t\t\t\toutcome.traces = applied.traces\n\t\t\t\tawait tx.execute(\n\t\t\t\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\t\t\t[op.nodeId, op.sequenceNumber],\n\t\t\t\t)\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.reportStorageError(error)\n\t\t\tthrow error\n\t\t}\n\n\t\tthis.recordOperationSequence(op)\n\t\tif (outcome.duplicate) {\n\t\t\tif (outcome.revived) {\n\t\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t\t} else {\n\t\t\t\tthis.subscriptionManager.notify(collection, op)\n\t\t\t}\n\t\t\treturn 'duplicate'\n\t\t}\n\t\tthis.subscriptionManager.notify(collection, op)\n\t\tthis.emitMergeTraces(op, outcome.traces)\n\t\toptions?.onMergeTraces?.(outcome.traces)\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'operation:applied',\n\t\t\toperation: op,\n\t\t\tduration: Date.now() - startedAt,\n\t\t})\n\t\treturn 'applied'\n\t}\n\n\t/** DevTools: every fold decision that was a conflict, plus one completion per merge. */\n\tprivate emitMergeTraces(op: Operation, traces: MergeTrace[]): void {\n\t\tif (!this.emitter || traces.length === 0) return\n\t\tconst first = traces[0] as MergeTrace\n\t\tthis.emitter.emit({ type: 'merge:started', operationA: first.operationA, operationB: op })\n\t\tfor (const trace of traces) this.emitter.emit({ type: 'merge:conflict', trace })\n\t\tthis.emitter.emit({ type: 'merge:completed', trace: first })\n\t}\n\n\t/** The record fold, once the database's rows are fold materializations. */\n\tprivate activeFold(): RecordFolder | undefined {\n\t\treturn this.foldActive && this.folder ? this.folder : undefined\n\t}\n\n\t/**\n\t * The record's W7 fold state (null under legacy materialization or when the\n\t * record has none). For DevTools, tests and the server-comparison harness.\n\t */\n\tasync getFoldState(collection: string, recordId: string): Promise<FoldState | null> {\n\t\tthis.ensureOpen()\n\t\tconst fold = this.activeFold()\n\t\tif (!fold) return null\n\t\tlet state: FoldState | null = null\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tstate = await fold.loadState(tx, collection, recordId)\n\t\t})\n\t\treturn state\n\t}\n\n\t/** Whether rows are materialized by the W7 fold (false under `materialization: 'legacy'`). */\n\tisFoldMaterialized(): boolean {\n\t\treturn this.activeFold() !== undefined\n\t}\n\n\tprivate async readMeta(key: string): Promise<string | null> {\n\t\tconst rows = await this.adapter.query<MetaRow>('SELECT value FROM _kora_meta WHERE key = ?', [\n\t\t\tkey,\n\t\t])\n\t\treturn rows[0]?.value ?? null\n\t}\n\n\tprivate async writeMeta(key: string, value: string): Promise<void> {\n\t\tawait this.adapter.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tkey,\n\t\t\tvalue,\n\t\t])\n\t}\n\n\t/**\n\t * Write every genuine beta.12 clear of the op log into its logged body, once per\n\t * database (RT-83, RT-85): the fold folds bodies as written, so the clear must be in\n\t * the body. Records already materialized by the fold are re-folded.\n\t */\n\tprivate async ensureLegacyBodiesCanonical(): Promise<void> {\n\t\tconst folder = this.folder\n\t\tif (!folder) return\n\t\tif ((await this.readMeta(LEGACY_BODIES_META_KEY)) !== null) return\n\t\tconst rewritten = await canonicalizeLegacyLogBodies(this.adapter, this.schema, this.nodeId)\n\t\tif (rewritten.length > 0 && this.foldActive) {\n\t\t\tconst seen = new Set<string>()\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tfor (const { collection, recordId } of rewritten) {\n\t\t\t\t\tconst key = `${collection}\\u0000${recordId}`\n\t\t\t\t\tif (seen.has(key)) continue\n\t\t\t\t\tseen.add(key)\n\t\t\t\t\tawait folder.refoldInTx(tx, collection, recordId)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tawait this.writeMeta(LEGACY_BODIES_META_KEY, String(rewritten.length))\n\t}\n\n\t/**\n\t * Make every row a materialization of its record's fold state (W7), once per\n\t * database and fold-state version. Runs after the W8 log-integrity scan: a\n\t * clean log is rebuilt with the fold; an incomplete (compacted) log rebuilds on\n\t * top of the rows as base snapshots; a log with quarantined rows is never\n\t * rebuilt from (rows are kept and become base snapshots), and\n\t * `store:rematerialized` reports which happened.\n\t */\n\tprivate async ensureMaterialization(forceSnapshot = false): Promise<void> {\n\t\tconst current = await this.readMeta(FOLD_MATERIALIZATION_META_KEY)\n\t\tif (!this.folder) {\n\t\t\tif (current !== FOLD_MATERIALIZATION_LEGACY) {\n\t\t\t\tawait this.writeMeta(FOLD_MATERIALIZATION_META_KEY, FOLD_MATERIALIZATION_LEGACY)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (current === FOLD_MATERIALIZATION_CURRENT) {\n\t\t\tthis.foldActive = true\n\t\t\tawait this.ensureFoldPlan()\n\t\t\treturn\n\t\t}\n\t\tconst report = await this.scanLog('full')\n\t\t// Only the records that own a quarantined row are kept as they are (RT-68); the\n\t\t// rest are rebuilt from a log that is complete for them unless it was compacted\n\t\t// or has holes.\n\t\tconst kept = await loadQuarantinedRecords(this.adapter)\n\t\t// A hole in an own node's sequence that a quarantined row explains belongs to\n\t\t// that row's record (kept above), not to the whole log.\n\t\tconst quarantinedSeqs = new Set(\n\t\t\treport.quarantined.map((row) => `${row.nodeId ?? ''}\\u0000${row.sequenceNumber ?? ''}`),\n\t\t)\n\t\tconst unexplainedGaps = report.gaps.filter((gap) => {\n\t\t\tfor (let s = gap.from; s <= gap.to; s++) {\n\t\t\t\tif (!quarantinedSeqs.has(`${gap.nodeId}\\u0000${s}`)) return true\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tconst mode: Exclude<RematerializationMode, 'kept'> =\n\t\t\t!forceSnapshot && unexplainedGaps.length === 0 && report.compactedAt === null\n\t\t\t\t? 'log'\n\t\t\t\t: 'snapshot+log'\n\t\tconst result = await rematerializeDatabase(this.adapter, this.schema, this.folder, mode, kept)\n\t\tawait this.writeMeta(FOLD_MATERIALIZATION_META_KEY, FOLD_MATERIALIZATION_CURRENT)\n\t\tawait this.writeMeta(\n\t\t\tFOLD_PLAN_META_KEY,\n\t\t\tJSON.stringify(foldPlanFingerprints(this.schema, this.operationTransforms)),\n\t\t)\n\t\tthis.foldActive = true\n\t\tif (result.snapshots > 0) await this.requestSnapshotResync()\n\t\tif (result.changedRows > 0) {\n\t\t\t// Other tabs on this database hear about it once the bus is wired (RT-98).\n\t\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t\t}\n\t\t}\n\t\tif (result.records > 0) {\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:rematerialized',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tmode: result.mode,\n\t\t\t\trecords: result.records,\n\t\t\t\tchangedRows: result.changedRows,\n\t\t\t\tmessage:\n\t\t\t\t\tresult.mode === 'kept'\n\t\t\t\t\t\t? `Operation log of \"${this.dbName}\" has quarantined rows: the records that own them were kept as they were (row snapshots); ${result.records} record(s) re-materialized, ${result.changedRows} row(s) changed.`\n\t\t\t\t\t\t: `Re-materialized ${result.records} record(s) of \"${this.dbName}\" with the per-field fold (${result.mode}); ${result.changedRows} row(s) changed.`,\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * Refuse to open when a schema version in the local operation log has no transform\n\t * path to the current schema (RT-103). Operations of a NEWER schema (authored by an\n\t * upgraded peer) are not checked: they are kept aside until this device upgrades.\n\t */\n\tprivate async assertTransformCoverage(): Promise<void> {\n\t\tconst transforms = this.operationTransforms\n\t\tif (transforms === undefined || transforms.length === 0) return\n\t\tconst versions = new Set<number>()\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tconst rows = await this.adapter.query<{ v: number }>(\n\t\t\t\t`SELECT DISTINCT schema_version AS v FROM ${quoteIdent(`_kora_ops_${collection}`)}`,\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst version = Number(row.v)\n\t\t\t\tif (version < this.schema.version) versions.add(version)\n\t\t\t}\n\t\t}\n\t\tassertOperationTransformCoverage(\n\t\t\tversions,\n\t\t\tthis.schema.version,\n\t\t\ttransforms,\n\t\t\t`local database \"${this.dbName}\"`,\n\t\t)\n\t}\n\n\t/**\n\t * Re-fold the records of every collection whose fold plan changed since the rows\n\t * were materialized (RT-63): a field that became `merge('counter')`, an array that\n\t * became append-only, a new or edited resolver. Their stored states hold fields of\n\t * the old kind, which the fold refuses (`FoldStateError`). Each record is rebuilt\n\t * from its log with the new plan; compacted bases and row snapshots are adapted\n\t * (a re-planned field restarts from its materialized value at its version). The\n\t * client's equivalent of the server stores' `fold_plan_fingerprint`.\n\t */\n\tprivate async ensureFoldPlan(): Promise<void> {\n\t\tconst folder = this.folder\n\t\tif (!folder) return\n\t\tconst current = foldPlanFingerprints(this.schema, this.operationTransforms)\n\t\tconst storedRaw = await this.readMeta(FOLD_PLAN_META_KEY)\n\t\tlet changed: string[]\n\t\tif (storedRaw === null) {\n\t\t\t// Materialized before the fingerprint was recorded: re-fold the collections\n\t\t\t// whose stored states actually hold a field of another kind.\n\t\t\tchanged = await collectionsWithMismatchedStates(this.adapter, this.schema)\n\t\t} else {\n\t\t\tlet stored: Record<string, unknown> = {}\n\t\t\ttry {\n\t\t\t\tstored = JSON.parse(storedRaw) as Record<string, unknown>\n\t\t\t} catch {\n\t\t\t\tstored = {}\n\t\t\t}\n\t\t\tchanged = Object.keys(current).filter((name) => stored[name] !== current[name])\n\t\t}\n\t\tif (changed.length > 0) {\n\t\t\tconst result = await rematerializeDatabase(\n\t\t\t\tthis.adapter,\n\t\t\t\tthis.schema,\n\t\t\t\tfolder,\n\t\t\t\t'log',\n\t\t\t\tundefined,\n\t\t\t\tchanged,\n\t\t\t)\n\t\t\tif (result.snapshots > 0) await this.requestSnapshotResync()\n\t\t\tfor (const collection of changed) this.subscriptionManager.invalidate(collection)\n\t\t\tthis.emitter?.emit({\n\t\t\t\ttype: 'store:rematerialized',\n\t\t\t\tdbName: this.dbName,\n\t\t\t\tmode: result.mode,\n\t\t\t\trecords: result.records,\n\t\t\t\tchangedRows: result.changedRows,\n\t\t\t\tmessage: `The fold plan of ${changed.map((name) => `\"${name}\"`).join(', ')} changed (schema): re-folded ${result.records} record(s) of \"${this.dbName}\"; ${result.changedRows} row(s) changed.`,\n\t\t\t})\n\t\t}\n\t\tawait this.writeMeta(FOLD_PLAN_META_KEY, JSON.stringify(current))\n\t}\n\n\t/**\n\t * Row snapshots were created (RT-68): ask the sync server for a full resync (the\n\t * delivery watermarks restart at 0, as after a restore), so each such record gets\n\t * its complete history back; {@link settleSnapshotRecords} then drops the\n\t * snapshots once the resync has caught up.\n\t */\n\tprivate async requestSnapshotResync(): Promise<void> {\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tawait tx.execute('UPDATE _kora_meta SET value = ? WHERE key = ? OR key LIKE ?', [\n\t\t\t\t'0',\n\t\t\t\tDELIVERY_WATERMARK_META_KEY,\n\t\t\t\t`${DELIVERY_WATERMARK_META_KEY}:%`,\n\t\t\t])\n\t\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [DELTA_CURSOR_META_KEY])\n\t\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\t\tSNAPSHOT_RESYNC_META_KEY,\n\t\t\t\t'pending',\n\t\t\t])\n\t\t})\n\t}\n\n\t/**\n\t * Records whose state still folds against a row snapshot (approximate: a late\n\t * concurrent write older than a field's version is not folded, RT-68).\n\t */\n\tasync getSnapshotRecords(): Promise<Array<{ collection: string; recordId: string }>> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.folder\n\t\tif (!folder) return []\n\t\tlet out: Array<{ collection: string; recordId: string }> = []\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tout = await folder.listSnapshotRecords(tx)\n\t\t})\n\t\treturn out\n\t}\n\n\t/**\n\t * Called by sync when a delivery stream has caught up (its final batch fully\n\t * applied). After the full resync {@link requestSnapshotResync} asked for, every\n\t * row-snapshot record whose insert is back in the log is re-folded from its\n\t * complete history and stops being approximate (RT-68). Also retires the\n\t * provisional cascades of remote deletes (RT-69): the server's own copies were\n\t * delivered by now, and any it did not derive must not stay applied locally.\n\t *\n\t * With `provisionalOnly` only the provisional cascades are retired (RT-93: a stream\n\t * batch from a server that derives no cascades, which is not the end of a resync).\n\t *\n\t * @param options - `provisionalOnly`: leave row snapshots for the next catch-up\n\t * @returns How many snapshots were dropped\n\t */\n\tasync settleAfterCatchUp(options: { provisionalOnly?: boolean } = {}): Promise<number> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.activeFold()\n\t\tif (!folder) return 0\n\t\tconst pending =\n\t\t\toptions.provisionalOnly !== true &&\n\t\t\t(await this.readMeta(SNAPSHOT_RESYNC_META_KEY)) === 'pending'\n\t\tlet settled = 0\n\t\tconst touched = new Set<string>()\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const { collection, recordId } of await folder.listProvisionalRecords(tx)) {\n\t\t\t\tawait folder.deleteProvisional(tx, collection, recordId, null)\n\t\t\t\tawait folder.refoldInTx(tx, collection, recordId)\n\t\t\t\ttouched.add(collection)\n\t\t\t}\n\t\t\tif (pending) {\n\t\t\t\tfor (const { collection, recordId } of await folder.listSnapshotRecords(tx)) {\n\t\t\t\t\tif (await folder.settleSnapshotInTx(tx, collection, recordId)) {\n\t\t\t\t\t\tsettled += 1\n\t\t\t\t\t\ttouched.add(collection)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [SNAPSHOT_RESYNC_META_KEY])\n\t\t\t}\n\t\t})\n\t\tfor (const collection of touched) this.subscriptionManager.invalidate(collection)\n\t\treturn settled\n\t}\n\n\t/**\n\t * Apply the cascades / set-nulls of a REMOTE delete as local-only provisional\n\t * effects (RT-69): folded into the children like operations, but never logged,\n\t * sequenced or queued for upload. The server derives and relays its own copy;\n\t * when it arrives (same parent, same record) the provisional effect is retired.\n\t *\n\t * @param parent - The remote delete\n\t * @param effects - Its side effects, as the referential check derived them\n\t */\n\tasync applyProvisionalSideEffects(\n\t\tparent: Operation,\n\t\teffects: ReadonlyArray<{\n\t\t\ttype: 'delete' | 'update'\n\t\t\tcollection: string\n\t\t\trecordId: string\n\t\t\tdata: Record<string, unknown> | null\n\t\t\tpreviousData: Record<string, unknown> | null\n\t\t\truleId: string\n\t\t}>,\n\t): Promise<number> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.activeFold()\n\t\tif (!folder || effects.length === 0) return 0\n\t\tconst touched = new Set<string>()\n\t\tlet applied = 0\n\t\t// Stamped right after the parent (its HLC, next logical ticks), exactly like the\n\t\t// server's copy, so a write to the child later than the delete still wins.\n\t\tconst clock = new HybridLogicalClock(PROVISIONAL_NODE_ID, {\n\t\t\tnow: () => parent.timestamp.wallTime,\n\t\t})\n\t\tclock.advanceTo(parent.timestamp)\n\t\tconst built: Operation[] = []\n\t\tfor (const effect of effects) {\n\t\t\tif (!this.schema.collections[effect.collection]) continue\n\t\t\tconst op: Operation = {\n\t\t\t\tid: await deriveSideEffectOpId(parent.id, `provisional/${effect.ruleId}`, effect.recordId),\n\t\t\t\tnodeId: PROVISIONAL_NODE_ID,\n\t\t\t\ttype: effect.type,\n\t\t\t\tcollection: effect.collection,\n\t\t\t\trecordId: effect.recordId,\n\t\t\t\tdata: effect.type === 'delete' ? null : effect.data,\n\t\t\t\tpreviousData: effect.type === 'delete' ? null : effect.previousData,\n\t\t\t\ttimestamp: clock.now(),\n\t\t\t\tsequenceNumber: 0,\n\t\t\t\tcausalDeps: [parent.id],\n\t\t\t\tschemaVersion: this.schema.version,\n\t\t\t}\n\t\t\tbuilt.push(op)\n\t\t}\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const op of built) {\n\t\t\t\tawait folder.applyProvisionalInTx(tx, op, parent.id)\n\t\t\t\ttouched.add(op.collection)\n\t\t\t\tapplied += 1\n\t\t\t}\n\t\t})\n\t\tfor (const collection of touched) this.subscriptionManager.invalidate(collection)\n\t\treturn applied\n\t}\n\n\t/**\n\t * Node ids whose writes win `merge('server-authoritative')` fields (the server's,\n\t * from the sync handshake). Every `kora:server:` id is authoritative by prefix, so\n\t * only explicit ids (legacy server node ids, configured extras) are kept: the device\n\t * persists the UNION of every explicit id it has learned and never drops one (RT-75).\n\t * Handshakes differ per server instance (each lists what it knows), so a list that\n\t * omits an id is not a revocation.\n\t *\n\t * Revocation is explicit (RT-81): ids a handshake lists in `revokedAuthoritativeNodeIds`\n\t * are removed from the union, persisted as revoked, and never learned again. Records\n\t * of collections with such fields are re-folded only when the explicit set changes\n\t * (grows, or loses a revoked id).\n\t *\n\t * @param nodeIds - The server's authoritative node ids (one handshake's list)\n\t * @param revokedNodeIds - Explicit ids the server revoked (one handshake's list)\n\t */\n\tasync setAuthoritativeNodeIds(\n\t\tnodeIds: readonly string[],\n\t\trevokedNodeIds: readonly string[] = [],\n\t): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tconst folder = this.folder\n\t\tconst persisted = await loadAuthoritativeNodeIds(this.adapter)\n\t\tconst persistedRevoked = await loadRevokedAuthoritativeNodeIds(this.adapter)\n\t\tconst revoked = new Set(\n\t\t\t[...persistedRevoked, ...revokedNodeIds].filter((id) => !isServerNodeId(id)),\n\t\t)\n\t\tif (revoked.size > persistedRevoked.length) {\n\t\t\tawait saveRevokedAuthoritativeNodeIds(this.adapter, [...revoked].sort())\n\t\t}\n\t\tconst previous = new Set(\n\t\t\t[...(persisted ?? []), ...(folder ? folder.getAuthoritativeNodeIds() : [])].filter(\n\t\t\t\t(id) => !isServerNodeId(id),\n\t\t\t),\n\t\t)\n\t\tconst known = new Set([...previous].filter((id) => !revoked.has(id)))\n\t\tconst dropped = previous.size - known.size\n\t\tconst learned = [...new Set(nodeIds)].filter(\n\t\t\t(id) => !isServerNodeId(id) && !known.has(id) && !revoked.has(id),\n\t\t)\n\t\tconst next = [...known, ...learned].sort()\n\t\tconst stored = persisted === null ? null : [...persisted].sort()\n\t\tif (stored === null || JSON.stringify(stored) !== JSON.stringify(next)) {\n\t\t\t// One persisted list (`sync_authoritative_node_ids`) serves the fold and the\n\t\t\t// sync engine's verification exemptions, so they can never disagree.\n\t\t\tawait saveAuthoritativeNodeIds(this.adapter, next)\n\t\t}\n\t\tif (!folder) return\n\t\tfolder.setAuthoritativeNodeIds(next)\n\t\tif (learned.length === 0 && dropped === 0) return\n\t\tconst fold = this.activeFold()\n\t\tif (!fold) return\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tif (!fold.hasAuthoritativeFields(collection)) continue\n\t\t\tconst ids = await this.adapter.query<{ record_id: string }>(\n\t\t\t\t`SELECT record_id FROM ${FOLD_STATE_TABLE} WHERE collection = ?`,\n\t\t\t\t[collection],\n\t\t\t)\n\t\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t\tfor (const { record_id } of ids) await fold.refoldInTx(tx, collection, record_id)\n\t\t\t})\n\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t}\n\t}\n\n\t/**\n\t * Re-fold the records of these operations from base + log (W7 exclusion: an\n\t * operation with a terminal-rejection marker is left out).\n\t */\n\tprivate async refoldRecordsOf(operationIds: readonly string[]): Promise<void> {\n\t\tconst fold = this.activeFold()\n\t\tif (!fold || operationIds.length === 0) return\n\t\tconst touched = new Map<string, Set<string>>()\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tconst table = quoteIdent(`_kora_ops_${collection}`)\n\t\t\tfor (let i = 0; i < operationIds.length; i += 500) {\n\t\t\t\tconst chunk = operationIds.slice(i, i + 500)\n\t\t\t\tconst rows = await this.adapter.query<{ record_id: string }>(\n\t\t\t\t\t`SELECT DISTINCT record_id FROM ${table} WHERE id IN (${chunk.map(() => '?').join(', ')})`,\n\t\t\t\t\tchunk,\n\t\t\t\t)\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tconst set = touched.get(collection) ?? new Set<string>()\n\t\t\t\t\tset.add(row.record_id)\n\t\t\t\t\ttouched.set(collection, set)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (touched.size === 0) return\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const [collection, records] of touched) {\n\t\t\t\tfor (const recordId of records) await fold.refoldInTx(tx, collection, recordId)\n\t\t\t}\n\t\t})\n\t\tfor (const [collection, records] of touched) {\n\t\t\tthis.subscriptionManager.invalidate(collection, [...records])\n\t\t}\n\t}\n\n\t/**\n\t * Append a remote operation to the log. If another operation of the same node\n\t * already holds its sequence number (a beta.12 device could produce such\n\t * pairs), the log keeps the existing row and this one is recorded in the\n\t * sequence-conflicts table, where dedup and record folds still see it.\n\t */\n\tprivate async appendRemoteOperationRow(tx: Transaction, op: Operation): Promise<void> {\n\t\tconst table = quoteIdent(`_kora_ops_${op.collection}`)\n\t\tconst holder = await tx.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${table} WHERE node_id = ? AND sequence_number = ?`,\n\t\t\t[op.nodeId, op.sequenceNumber],\n\t\t)\n\t\tconst opRow = serializeOperation(op)\n\t\tif (holder.length > 0) {\n\t\t\tawait insertConflictRow(\n\t\t\t\ttx,\n\t\t\t\top.collection,\n\t\t\t\topRow,\n\t\t\t\t'remote-sequence-conflict',\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tDate.now(),\n\t\t\t)\n\t\t\treturn\n\t\t}\n\t\tconst opInsert = buildInsertQuery(\n\t\t\t`_kora_ops_${op.collection}`,\n\t\t\topRow as unknown as Record<string, unknown>,\n\t\t)\n\t\tawait tx.execute(opInsert.sql, opInsert.params)\n\t}\n\n\t/**\n\t * Hide a record from this client's authorized materialized view. This writes no\n\t * replicated operation and therefore cannot be mistaken for a domain deletion.\n\t * The marker lets a later authoritative backfill reactivate the retained row.\n\t */\n\tasync applyScopeRetraction(collection: string, recordId: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tif (!this.schema.collections[collection]) return\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tawait tx.execute(`UPDATE ${quoteIdent(collection)} SET _deleted = 1 WHERE id = ?`, [recordId])\n\t\t\tawait tx.execute(\n\t\t\t\t'INSERT OR REPLACE INTO _kora_scope_retractions (collection, record_id) VALUES (?, ?)',\n\t\t\t\t[collection, recordId],\n\t\t\t)\n\t\t})\n\t\tthis.subscriptionManager.invalidate(collection, [recordId])\n\t}\n\n\t/** Hide all live rows that no longer match a newly accepted server scope. */\n\tasync applyScopeNarrowing(\n\t\tscopes: Record<string, Record<string, unknown>>,\n\t): Promise<Array<{ collection: string; recordId: string }>> {\n\t\tthis.ensureOpen()\n\t\tconst retractions: Array<{ collection: string; recordId: string }> = []\n\t\tfor (const [collection, definition] of Object.entries(this.schema.collections)) {\n\t\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE _deleted = 0`,\n\t\t\t)\n\t\t\tconst predicate = scopes[collection]\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst record = deserializeRecord(row, definition.fields)\n\t\t\t\tconst matches =\n\t\t\t\t\tpredicate !== undefined &&\n\t\t\t\t\tObject.entries(predicate).every(([field, expected]) => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\texpected &&\n\t\t\t\t\t\t\ttypeof expected === 'object' &&\n\t\t\t\t\t\t\t!Array.isArray(expected) &&\n\t\t\t\t\t\t\t'$in' in expected\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst values = (expected as { $in?: unknown }).$in\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\tArray.isArray(values) && values.some((value) => Object.is(record[field], value))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn Object.is(record[field], expected)\n\t\t\t\t\t})\n\t\t\t\tif (!matches) {\n\t\t\t\t\tawait this.applyScopeRetraction(collection, String(record.id))\n\t\t\t\t\tretractions.push({ collection, recordId: String(record.id) })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn retractions\n\t}\n\n\t/**\n\t * Materialize a server scope-entry insert (RT-19) whose fields each carry their\n\t * own version (RT-27). The entry restates the record's current server values; a\n\t * single whole-row stamp would let a field the server last wrote long ago\n\t * overwrite this device's newer unsynced edit of it, after which the device's own\n\t * operation uploads and wins on the server (divergence). So every field is resolved\n\t * on its own, by last-write-wins against this row's `_field_versions`:\n\t *\n\t * - no row: inserted with each field stamped at its own version, `_created_at`\n\t * at the record's creation (the entry's `timestamp`), then any orphaned\n\t * updates/deletes are folded in as for any insert;\n\t * - live row, or a row hidden by a scope retraction: per-field LWW (a retracted\n\t * row is shown again; `_created_at` is kept);\n\t * - domain tombstone: revived only when the entry's newest field version is\n\t * newer than the tombstone, then per-field LWW.\n\t *\n\t * Deterministic and idempotent: the outcome depends only on the stored and\n\t * incoming per-field versions, and a re-applied entry wins no field.\n\t */\n\tprivate async applyFieldVersionedInsert(\n\t\ttx: Transaction,\n\t\top: Operation,\n\t\tdefinition: NonNullable<SchemaDefinition['collections'][string]>,\n\t\tdata: Record<string, unknown>,\n\t\tcheckGuard: (row: RawCollectionRow | undefined) => void,\n\t): Promise<void> {\n\t\tconst collection = op.collection\n\t\tconst serialized = serializeRecord(data, definition.fields)\n\t\tconst versions = op.fieldVersions ?? {}\n\t\tconst latest = newestFieldVersion(op)\n\t\tconst latestVersion = serializeRowVersion(latest)\n\t\tconst incoming: FieldVersions = {}\n\t\tfor (const field of Object.keys(serialized)) {\n\t\t\t// A field without its own version (renamed by a schema transform) falls back\n\t\t\t// to the entry's newest version: the single-stamp rule of RT-19.\n\t\t\tconst version = versions[field]\n\t\t\tincoming[field] = version ? serializeRowVersion(version) : latestVersion\n\t\t}\n\n\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t`SELECT _updated_at, _version, _field_versions, _deleted FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t[op.recordId],\n\t\t)\n\t\tconst row = rows[0]\n\t\tcheckGuard(row)\n\n\t\tif (!row) {\n\t\t\tconst record: Record<string, unknown> = {\n\t\t\t\tid: op.recordId,\n\t\t\t\t...serialized,\n\t\t\t\t_created_at: op.timestamp.wallTime,\n\t\t\t\t_updated_at: latest.wallTime,\n\t\t\t\t_version: latestVersion,\n\t\t\t\t_field_versions: serializeFieldVersions(incoming),\n\t\t\t}\n\t\t\tconst insertQuery = buildInsertQuery(collection, record)\n\t\t\tawait tx.execute(insertQuery.sql, insertQuery.params)\n\t\t\tawait this.foldOrphanedOperations(tx, collection, definition, op.recordId, op)\n\t\t\treturn\n\t\t}\n\n\t\tlet retracted = false\n\t\tif (row._deleted === 1) {\n\t\t\tretracted =\n\t\t\t\t(\n\t\t\t\t\tawait tx.query<{ record_id: string }>(\n\t\t\t\t\t\t'SELECT record_id FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t\t\t[collection, op.recordId],\n\t\t\t\t\t)\n\t\t\t\t).length > 0\n\t\t\t// A domain delete newer than everything the entry carries still wins.\n\t\t\tif (!retracted && !isIncomingNewerThanRow(latest, row)) return\n\t\t}\n\n\t\tconst current = parseFieldVersions(row._field_versions)\n\t\tconst rowVersion = typeof row._version === 'string' ? row._version : undefined\n\t\tconst merged: FieldVersions = { ...current }\n\t\tconst changes: Record<string, unknown> = {}\n\t\tfor (const [field, version] of Object.entries(incoming)) {\n\t\t\tif (version > effectiveFieldVersion(current, field, rowVersion)) {\n\t\t\t\tchanges[field] = serialized[field]\n\t\t\t\tmerged[field] = version\n\t\t\t}\n\t\t}\n\t\tif (row._deleted === 1) {\n\t\t\tchanges._deleted = 0\n\t\t}\n\t\tchanges._field_versions = serializeFieldVersions(merged)\n\t\tconst update = buildFieldFastForwardUpdateQuery(\n\t\t\tcollection,\n\t\t\top.recordId,\n\t\t\tchanges,\n\t\t\tlatestVersion,\n\t\t\tlatest.wallTime,\n\t\t)\n\t\tawait tx.execute(update.sql, update.params)\n\t\tif (retracted) {\n\t\t\tawait tx.execute(\n\t\t\t\t'DELETE FROM _kora_scope_retractions WHERE collection = ? AND record_id = ?',\n\t\t\t\t[collection, op.recordId],\n\t\t\t)\n\t\t}\n\t}\n\n\t/**\n\t * Materialize update/delete operations that were logged for a record BEFORE\n\t * its insert arrived (reordered delivery). Runs inside the insert's write\n\t * transaction, folding each orphan in timestamp order through the exact\n\t * per-field LWW / LWW-delete rules the normal apply paths use, so the final\n\t * row state equals what a device that received the operations in causal\n\t * order computed. Called only when the insert created a previously-absent\n\t * row — in that case every logged update/delete for the record is\n\t * necessarily an orphan (rows are soft-deleted, never removed, so a row\n\t * that is absent now was never materialized).\n\t */\n\tprivate async foldOrphanedOperations(\n\t\ttx: Transaction,\n\t\tcollection: string,\n\t\tdefinition: NonNullable<SchemaDefinition['collections'][string]>,\n\t\trecordId: string,\n\t\tinsertOp: Operation,\n\t): Promise<void> {\n\t\tconst orphanRows = [\n\t\t\t...(await tx.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE record_id = ? AND type IN ('update', 'delete')`,\n\t\t\t\t[recordId],\n\t\t\t)),\n\t\t\t...(await loadRetainedConflictRows(\n\t\t\t\t(sql, params) => tx.query(sql, params),\n\t\t\t\tcollection,\n\t\t\t\trecordId,\n\t\t\t\t['update', 'delete'],\n\t\t\t)),\n\t\t]\n\t\tif (orphanRows.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tconst orphans = orphanRows\n\t\t\t.map((r) => deserializeOperationWithCollection(r, collection))\n\t\t\t.sort((a, b) => HybridLogicalClock.compare(a.timestamp, b.timestamp))\n\n\t\tfor (const orphan of orphans) {\n\t\t\tconst orphanVersion = serializeRowVersion(orphan.timestamp)\n\t\t\tconst orphanWall = orphan.timestamp.wallTime\n\n\t\t\tif (orphan.type === 'update' && orphan.data) {\n\t\t\t\tconst orphanChanges = serializeRecord(orphan.data, definition.fields)\n\t\t\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t\t\t`SELECT _version, _field_versions FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t\t\t[recordId],\n\t\t\t\t)\n\t\t\t\tconst current = rows[0]\n\t\t\t\tif (!current) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst { winners, merged } = resolvePerFieldLww(\n\t\t\t\t\tparseFieldVersions(current._field_versions),\n\t\t\t\t\tObject.keys(orphanChanges),\n\t\t\t\t\torphanVersion,\n\t\t\t\t\ttypeof current._version === 'string' ? current._version : undefined,\n\t\t\t\t)\n\t\t\t\tif (winners.length > 0) {\n\t\t\t\t\tconst winningChanges: Record<string, unknown> = {\n\t\t\t\t\t\t_field_versions: serializeFieldVersions(merged),\n\t\t\t\t\t}\n\t\t\t\t\tfor (const field of winners) {\n\t\t\t\t\t\twinningChanges[field] = orphanChanges[field]\n\t\t\t\t\t}\n\t\t\t\t\tconst query = buildFieldFastForwardUpdateQuery(\n\t\t\t\t\t\tcollection,\n\t\t\t\t\t\trecordId,\n\t\t\t\t\t\twinningChanges,\n\t\t\t\t\t\torphanVersion,\n\t\t\t\t\t\torphanWall,\n\t\t\t\t\t)\n\t\t\t\t\tawait tx.execute(query.sql, query.params)\n\t\t\t\t}\n\t\t\t} else if (orphan.type === 'delete') {\n\t\t\t\tconst query = buildLwwSoftDeleteQuery(collection, recordId, orphanWall, orphanVersion)\n\t\t\t\tawait tx.execute(query.sql, query.params)\n\t\t\t}\n\t\t}\n\n\t\t// Atomic-op fields need composition, not last-write-wins: the per-field LWW\n\t\t// loop above would keep only one concurrent increment's resolved value and drop\n\t\t// the rest. Re-materialize just the atomic fields by folding [insert, ...orphans]\n\t\t// in HLC order through the shared atomic-aware replay — the same fold the server\n\t\t// and the live apply path use — so an atomic op that arrived before its insert\n\t\t// (reordered delivery) composes correctly instead of losing deltas. Only the\n\t\t// field VALUES are overwritten; their per-field versions were already stamped to\n\t\t// the latest writer by the loop above, so future LWW stays correct.\n\t\tconst atomicFields = new Set<string>()\n\t\tfor (const orphan of orphans) {\n\t\t\tif (orphan.type === 'update' && orphan.atomicOps) {\n\t\t\t\tfor (const field of Object.keys(orphan.atomicOps)) {\n\t\t\t\t\tatomicFields.add(field)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (atomicFields.size > 0) {\n\t\t\t// A scope-entry insert expands into its per-field writes (RT-27).\n\t\t\tconst ordered = expandFieldVersionedOperations([insertOp, ...orphans])\n\t\t\tconst folded = replayOperationsForRecord(ordered)\n\t\t\tif (folded) {\n\t\t\t\tconst composed: Record<string, unknown> = {}\n\t\t\t\tfor (const field of atomicFields) {\n\t\t\t\t\tif (field in folded) {\n\t\t\t\t\t\tcomposed[field] = folded[field]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst serialized = serializeRecord(composed, definition.fields)\n\t\t\t\tconst cols = Object.keys(serialized)\n\t\t\t\tif (cols.length > 0) {\n\t\t\t\t\tconst setClause = cols.map((c) => `${quoteIdent(c)} = ?`).join(', ')\n\t\t\t\t\tawait tx.execute(`UPDATE ${quoteIdent(collection)} SET ${setClause} WHERE id = ?`, [\n\t\t\t\t\t\t...cols.map((c) => serialized[c]),\n\t\t\t\t\t\trecordId,\n\t\t\t\t\t])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get operations from a node within a sequence number range.\n\t * Implements the OperationLog interface for computeDelta.\n\t */\n\tasync getRange(nodeId: string, fromSeq: number, toSeq: number): Promise<Operation[]> {\n\t\treturn this.getOperationRange(nodeId, fromSeq, toSeq)\n\t}\n\n\t/**\n\t * Get operations from a node within a sequence number range.\n\t */\n\tasync getOperationRange(nodeId: string, fromSeq: number, toSeq: number): Promise<Operation[]> {\n\t\tthis.ensureOpen()\n\t\tconst allOps: Operation[] = []\n\n\t\tfor (const collectionName of Object.keys(this.schema.collections)) {\n\t\t\tconst rows = await this.adapter.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} WHERE node_id = ? AND sequence_number >= ? AND sequence_number <= ? ORDER BY sequence_number ASC`,\n\t\t\t\t[nodeId, fromSeq, toSeq],\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tallOps.push(deserializeOperationWithCollection(row, collectionName))\n\t\t\t}\n\t\t}\n\n\t\t// Sort by sequence number across collections\n\t\tallOps.sort((a, b) => a.sequenceNumber - b.sequenceNumber)\n\t\treturn allOps\n\t}\n\n\t/**\n\t * Load every operation from the local append-only log across all collections.\n\t * Used by sync delta computation, backup export, and time-travel replay.\n\t */\n\tasync getAllOperations(): Promise<Operation[]> {\n\t\tthis.ensureOpen()\n\t\tconst allOps: Operation[] = []\n\n\t\tfor (const collectionName of Object.keys(this.schema.collections)) {\n\t\t\tconst rows = await this.adapter.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} ORDER BY sequence_number ASC`,\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tallOps.push(deserializeOperationWithCollection(row, collectionName))\n\t\t\t}\n\t\t}\n\n\t\treturn allOps\n\t}\n\n\t/**\n\t * Rebuild an in-memory snapshot of materialized state at a causal cut in the op log.\n\t * Does not mutate the live store — intended for DevTools time-travel inspection.\n\t *\n\t * @param operationId - Content-addressed id of the operation to replay through (inclusive)\n\t * @throws {OperationError} When the operation id is not present in the local log\n\t */\n\tasync replayTo(operationId: string): Promise<ReplaySnapshot> {\n\t\tthis.ensureOpen()\n\t\tconst start = Date.now()\n\t\tconst allOps = await this.getAllOperations()\n\t\tconst aliasRows = await this.adapter.query<{ id: string; reemitted_as: string }>(\n\t\t\t`SELECT id, reemitted_as FROM ${SEQ_CONFLICTS_TABLE} WHERE reemitted_as IS NOT NULL AND reemitted_as <> id`,\n\t\t)\n\t\tconst aliases = new Map(aliasRows.map((row) => [row.id, row.reemitted_as]))\n\t\tconst snapshot = buildReplaySnapshot(\n\t\t\tthis.schema,\n\t\t\tallOps,\n\t\t\toperationId,\n\t\t\taliases,\n\t\t\tthis.operationTransforms,\n\t\t)\n\n\t\tif (this.emitter) {\n\t\t\tthis.emitter.emit({\n\t\t\t\ttype: 'replay:completed',\n\t\t\t\ttargetOperationId: operationId,\n\t\t\t\toperationsApplied: snapshot.operationsApplied.length,\n\t\t\t\tduration: Date.now() - start,\n\t\t\t})\n\t\t}\n\n\t\treturn snapshot\n\t}\n\n\t/**\n\t * Persist a merge trace to the durable audit log.\n\t */\n\tasync appendAuditTrace(trace: import('../audit/types').PersistedAuditTrace): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tconst { appendAuditTrace: append } = await import('../audit/audit-trace-store')\n\t\tawait append(this.adapter, trace)\n\t}\n\n\t/**\n\t * Read persisted audit traces with optional filters.\n\t */\n\tasync getAuditTraces(\n\t\tquery?: import('../audit/types').AuditTraceQuery,\n\t): Promise<import('../audit/types').PersistedAuditTrace[]> {\n\t\tthis.ensureOpen()\n\t\tconst { readAuditTraces } = await import('../audit/audit-trace-store')\n\t\treturn readAuditTraces(this.adapter, query)\n\t}\n\n\t/**\n\t * Export operations and merge traces as a portable audit bundle.\n\t */\n\tasync exportAudit(options?: import('../audit/types').AuditExportOptions): Promise<Uint8Array> {\n\t\tthis.ensureOpen()\n\t\tconst { exportAudit: doExport } = await import('../audit/export-audit')\n\t\treturn doExport(this.adapter, this.schema, this.nodeId, this.schema.version, options)\n\t}\n\n\t/**\n\t * Get the schema definition.\n\t */\n\tgetSchema(): SchemaDefinition {\n\t\treturn this.schema\n\t}\n\n\t/**\n\t * Route local CRUD through the unified apply pipeline (korajs ApplyPipeline).\n\t */\n\tsetLocalMutationHandler(handler: LocalMutationHandler | null): void {\n\t\tthis.localMutationHandler = handler\n\t\tfor (const col of this.collections.values()) {\n\t\t\tcol.setMutationHandler(handler)\n\t\t}\n\t}\n\n\t/**\n\t * Notify this store that another same-origin runtime committed an operation to\n\t * the shared local database. The operation has already been persisted and\n\t * materialized by the database owner; this method only advances in-memory causal\n\t * watermarks and invalidates local reactive queries so already-open tabs stay\n\t * live without reapplying or rewriting the operation.\n\t */\n\tnotifyExternalOperation(operation: Operation): void {\n\t\tthis.ensureOpen()\n\t\tconst definition = this.schema.collections[operation.collection]\n\t\tif (!definition) {\n\t\t\treturn\n\t\t}\n\t\tthis.recordOperationSequence(operation)\n\t\tthis.subscriptionManager.invalidateFromPeer(operation.collection)\n\t}\n\n\t/**\n\t * Notify this store that another same-origin runtime changed rows of a collection\n\t * in the shared local database without an operation this tab can see (a re-fold,\n\t * a scope retraction, a restore; RT-98). Only re-runs the affected live queries.\n\t *\n\t * @param collection - The collection whose rows changed\n\t */\n\tnotifyExternalChange(collection: string): void {\n\t\tthis.ensureOpen()\n\t\tif (!this.schema.collections[collection]) return\n\t\tthis.subscriptionManager.invalidateFromPeer(collection)\n\t}\n\n\t/**\n\t * Listen to every committed change this store makes to collection rows: local\n\t * writes, remote applies, and changes without a new operation (re-folds, scope\n\t * retraction, cascade settling, rematerialization, restore). The cross-tab bus\n\t * relays these to other tabs on the same database (RT-98).\n\t *\n\t * @returns An unsubscribe function\n\t */\n\tonRecordsChanged(listener: RecordsChangeListener): () => void {\n\t\treturn this.subscriptionManager.onRecordsChanged(listener)\n\t}\n\n\t/**\n\t * Build the local write context for a collection: everything the single local\n\t * write path needs (used by Collection writes and by ApplyPipeline).\n\t */\n\tcreateMutationContext(\n\t\tcollection: string,\n\t\toptions?: {\n\t\t\textraCausalDeps?: string[]\n\t\t\t/**\n\t\t\t * Stamp the writes with this clock instead of the store's (it must be this\n\t\t\t * node's). Used for the side effects of a remote delete, stamped right after\n\t\t\t * the delete like the server's copy (seam 5), never with the device's \"now\".\n\t\t\t */\n\t\t\tclock?: HybridLogicalClock\n\t\t},\n\t): LocalMutationContext {\n\t\tthis.ensureOpen()\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition || !this.clock) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t\tconst beforeLocalDelete = this.localMutationHandler?.beforeLocalDelete\n\t\tconst fold = this.activeFold()\n\t\treturn {\n\t\t\t...(fold ? { fold } : {}),\n\t\t\tcollection,\n\t\t\tdefinition,\n\t\t\tschema: this.schema,\n\t\t\tadapter: this.adapter,\n\t\t\tclock: options?.clock ?? this.clock,\n\t\t\tnodeId: this.nodeId,\n\t\t\tonMutation: (collectionName, operation) =>\n\t\t\t\tthis.publishLocalOperation(collectionName, operation),\n\t\t\trelationEnforcer: this.relationEnforcer,\n\t\t\tcausalTracker: this.causalTracker,\n\t\t\t...(options?.extraCausalDeps ? { extraCausalDeps: options.extraCausalDeps } : {}),\n\t\t\t...(this.secretKeyProvider ? { secretKeyProvider: this.secretKeyProvider } : {}),\n\t\t\t...(this.maxOperationBytes !== undefined\n\t\t\t\t? { maxOperationBytes: this.maxOperationBytes }\n\t\t\t\t: {}),\n\t\t\tassertLocalWriteAllowed: () => this.assertLocalWriteAllowed(),\n\t\t\t...(beforeLocalDelete\n\t\t\t\t? { beforeLocalDelete: beforeLocalDelete.bind(this.localMutationHandler) }\n\t\t\t\t: {}),\n\t\t\tonStorageError: (error) => this.reportStorageError(error),\n\t\t}\n\t}\n\n\t/**\n\t * Load a materialized row by ID, including soft-deleted tombstones.\n\t */\n\tasync findMaterializedRow(\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<MaterializedRowSnapshot | null> {\n\t\tthis.ensureOpen()\n\t\tconst definition = this.schema.collections[collection]\n\t\tif (!definition) {\n\t\t\treturn null\n\t\t}\n\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t[recordId],\n\t\t)\n\t\tconst row = rows[0]\n\t\tif (!row) {\n\t\t\treturn null\n\t\t}\n\n\t\treturn {\n\t\t\trecord: deserializeRecord(row, definition.fields),\n\t\t\tdeleted: row._deleted === 1,\n\t\t}\n\t}\n\n\t/**\n\t * Raw version state of a materialized row, for optimistic-concurrency guarded\n\t * applies: capture this snapshot before computing a merge, pass it as\n\t * `guardRowState`, and the apply refuses to write if the row changed since.\n\t * Returns null when no row exists (which is itself a valid guard state — the\n\t * apply then requires the row to still be absent).\n\t */\n\tasync getRowVersionState(collection: string, recordId: string): Promise<RowVersionState | null> {\n\t\tthis.ensureOpen()\n\t\tif (!this.schema.collections[collection]) {\n\t\t\treturn null\n\t\t}\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\t`SELECT _version, _field_versions FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t[recordId],\n\t\t)\n\t\tconst row = rows[0]\n\t\tif (!row) {\n\t\t\treturn null\n\t\t}\n\t\treturn {\n\t\t\tversion: typeof row._version === 'string' ? row._version : null,\n\t\t\tfieldVersions: typeof row._field_versions === 'string' ? row._field_versions : null,\n\t\t}\n\t}\n\n\t/**\n\t * Latest operation from this device for a record (used for delete-vs-update merge on sync).\n\t */\n\t/**\n\t * Load the last server version vector acknowledged by this client (persisted in `_kora_meta`).\n\t */\n\tasync loadLastAckedServerVector(): Promise<VersionVector> {\n\t\tthis.ensureOpen()\n\t\treturn loadLastAckedServerVector(this.adapter)\n\t}\n\n\t/**\n\t * Persist the last server version vector this client believes the server has applied.\n\t */\n\tasync saveLastAckedServerVector(vector: VersionVector): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveLastAckedServerVector(this.adapter, vector)\n\t}\n\n\t/**\n\t * Load the per-device node token the sync server issued for this node id (RT-12).\n\t */\n\tasync loadNodeToken(nodeId?: string): Promise<string | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadNodeToken(this.adapter, nodeId ?? this.nodeId)\n\t}\n\n\t/**\n\t * Persist the per-device node token under its node id (the current one by default).\n\t */\n\tasync saveNodeToken(token: string, nodeId?: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveNodeToken(this.adapter, token, nodeId ?? this.nodeId)\n\t}\n\n\t/**\n\t * Load the node ids the sync server named authoritative (protocol v2), or null when\n\t * no protocol-2 server ever answered.\n\t */\n\tasync loadAuthoritativeNodeIds(): Promise<string[] | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadAuthoritativeNodeIds(this.adapter)\n\t}\n\n\t/**\n\t * Persist the node ids the sync server named authoritative (protocol v2). Same as\n\t * {@link setAuthoritativeNodeIds}: merged into the union of learned explicit ids,\n\t * and the fold re-folds affected records only when that set grows.\n\t */\n\tasync saveAuthoritativeNodeIds(nodeIds: string[]): Promise<void> {\n\t\tawait this.setAuthoritativeNodeIds(nodeIds)\n\t}\n\n\t/**\n\t * Load persisted delta cursor for resuming paginated initial sync.\n\t */\n\tasync loadDeltaCursor(): Promise<string | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadDeltaCursor(this.adapter)\n\t}\n\n\t/**\n\t * Persist or clear the delta cursor for paginated initial sync resume.\n\t */\n\tasync saveDeltaCursor(cursor: string | null): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveDeltaCursor(this.adapter, cursor)\n\t}\n\n\t/**\n\t * Load the persisted delivery watermark for a view signature (0 when none recorded).\n\t * Defaults to the unfiltered view so existing single-watermark reads keep working.\n\t */\n\tasync loadDeliveryWatermark(signature = ''): Promise<number> {\n\t\tthis.ensureOpen()\n\t\treturn loadDeliveryWatermark(this.adapter, signature)\n\t}\n\n\t/**\n\t * Persist the delivery watermark for a view signature so it survives a client restart.\n\t */\n\tasync saveDeliveryWatermark(signature: string, watermark: number): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveDeliveryWatermark(this.adapter, signature, watermark)\n\t}\n\n\t/**\n\t * Load every persisted view watermark, keyed by signature.\n\t */\n\tasync loadAllDeliveryWatermarks(): Promise<Record<string, number>> {\n\t\tthis.ensureOpen()\n\t\treturn loadAllDeliveryWatermarks(this.adapter)\n\t}\n\n\t/**\n\t * Delete a persisted view watermark (safe: the view back-fills from 0 when next visited).\n\t */\n\tasync deleteDeliveryWatermark(signature: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait deleteDeliveryWatermark(this.adapter, signature)\n\t}\n\n\t/**\n\t * Record delivered operations the sync engine deliberately did not apply (inbound\n\t * quarantine, W4) and, when given, advance a view's delivery watermark in the same\n\t * transaction, so the watermark never passes an operation that is neither applied nor\n\t * recorded.\n\t */\n\tasync saveInboundQuarantine(\n\t\tentries: UnappliedOperation[],\n\t\twatermark?: { signature: string; watermark: number },\n\t): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveUnappliedOperations(this.adapter, entries, watermark)\n\t}\n\n\t/** Every quarantined inbound operation, oldest delivery first. */\n\tasync loadInboundQuarantine(): Promise<UnappliedOperation[]> {\n\t\tthis.ensureOpen()\n\t\treturn loadUnappliedOperations(this.adapter)\n\t}\n\n\t/** Remove quarantined inbound operations (applied on replay, or reconciled). */\n\tasync removeInboundQuarantine(operationIds: string[]): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait removeUnappliedOperations(this.adapter, operationIds)\n\t}\n\n\t/**\n\t * The contiguous acknowledged prefix of this device's own operations for a node id,\n\t * or null when none was recorded under that contract (W3).\n\t */\n\tasync loadOwnAckedThrough(nodeId: string): Promise<number | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadOwnAckedThrough(this.adapter, nodeId)\n\t}\n\n\t/** Persist the contiguous acknowledged own-operation prefix for a node id. */\n\tasync saveOwnAckedThrough(nodeId: string, sequence: number): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveOwnAckedThrough(this.adapter, nodeId, sequence)\n\t}\n\n\t/** The downlink scope the sync server last accepted (null when none). */\n\tasync loadAcceptedDownlinkScope(): Promise<Record<string, Record<string, unknown>> | null> {\n\t\tthis.ensureOpen()\n\t\treturn loadAcceptedDownlinkScope(this.adapter)\n\t}\n\n\t/** Persist (or clear) the downlink scope the sync server last accepted. */\n\tasync saveAcceptedDownlinkScope(\n\t\tscope: Record<string, Record<string, unknown>> | null,\n\t): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveAcceptedDownlinkScope(this.adapter, scope)\n\t}\n\n\t/**\n\t * Local operations not yet reflected on the server version vector.\n\t */\n\tasync getUnsyncedOperations(serverVector: VersionVector): Promise<Operation[]> {\n\t\tthis.ensureOpen()\n\t\treturn collectOperationsAheadOfServer(\n\t\t\tthis.getVersionVector(),\n\t\t\tserverVector,\n\t\t\t(nodeId, fromSeq, toSeq) => this.getOperationRange(nodeId, fromSeq, toSeq),\n\t\t)\n\t}\n\n\t/**\n\t * Re-stamp never-acknowledged local operations after a fast device clock was\n\t * corrected, so sync can resume immediately. Safe because unacknowledged\n\t * operations are private to this device (like unpushed git commits);\n\t * acknowledged/shared operations are immutable and never touched.\n\t *\n\t * After the rewrite the store's HLC is advanced past the highest new\n\t * timestamp so subsequent local writes keep sorting after the rebased ops.\n\t * No data-change notifications are emitted: materialized values are\n\t * unchanged, only version stamps move.\n\t */\n\t/**\n\t * Move this device to a fresh node id, re-authoring its never-acknowledged\n\t * operations under it (RT-21). Used when the sync server refuses the current node\n\t * id (`NODE_ID_CLAIMED`): the device keeps every local write and uploads it under\n\t * the new id. Acknowledged history stays under the old id. Persisted atomically;\n\t * later writes use the new id.\n\t *\n\t * @param unsyncedOpIds - Ids of this node's operations the server never acknowledged\n\t * @returns The new node id and the rewritten operations (for the outbound queue)\n\t * @throws {KoraError} When the node id is pinned (`StoreConfig.nodeId`, or per-tab isolation)\n\t */\n\tasync rotateNodeId(unsyncedOpIds: string[]): Promise<NodeRotationResult> {\n\t\tthis.ensureOpen()\n\t\tif (this.configNodeId || this.isolation === 'per-tab') {\n\t\t\tthrow new KoraError(\n\t\t\t\t'This store uses a pinned node id, so it cannot move to a fresh one after the sync server refused it.',\n\t\t\t\t'NODE_ID_PINNED',\n\t\t\t\t{\n\t\t\t\t\tnodeId: this.nodeId,\n\t\t\t\t\tfix: 'Remove StoreConfig.nodeId, or give the device a node id no other device uses.',\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst oldNodeId = this.nodeId\n\t\tconst oldClock = this.clock\n\t\tconst oldBinding = (await listLocalNodes(this.adapter)).find(\n\t\t\t(node) => node.nodeId === oldNodeId,\n\t\t)\n\t\tconst result = await rotateUnsyncedOperationsInLog(\n\t\t\tthis.adapter,\n\t\t\tthis.schema,\n\t\t\tunsyncedOpIds,\n\t\t\toldNodeId,\n\t\t\tgenerateUUIDv7(),\n\t\t)\n\t\tawait registerLocalNode(this.adapter, result.nodeId)\n\t\t// The re-authored writes keep their author (RT-50): the fresh node carries the old\n\t\t// node's binding, so they are never held as unassigned or given to another user.\n\t\tif (oldBinding?.principal) {\n\t\t\tawait setLocalNodePrincipal(\n\t\t\t\tthis.adapter,\n\t\t\t\tresult.nodeId,\n\t\t\t\toldBinding.principal,\n\t\t\t\toldBinding.binding ?? 'app',\n\t\t\t)\n\t\t}\n\t\tthis.nodeId = result.nodeId\n\t\tconst clock = new HybridLogicalClock(this.nodeId)\n\t\tif (oldClock) {\n\t\t\tconst last = oldClock.now()\n\t\t\tclock.advanceTo({ ...last, nodeId: this.nodeId })\n\t\t\tconst offset = oldClock.getReferenceOffset()\n\t\t\tif (offset !== null) clock.setReferenceOffset(offset)\n\t\t}\n\t\tthis.clock = clock\n\t\tthis.causalTracker = new CausalTracker()\n\t\tthis.sequenceManager = new SequenceManager(this.adapter, this.nodeId)\n\t\tthis.versionVector = await this.loadVersionVector()\n\t\t// The persisted counter (MAX with the stored value, W6), not a local count.\n\t\tthis.sequenceNumber = this.versionVector.get(this.nodeId) ?? result.operations.length\n\t\tfor (const collection of this.collections.values()) {\n\t\t\tcollection.rebindNode(clock, this.nodeId, this.relationEnforcer, this.causalTracker)\n\t\t}\n\t\t// The re-authored operations have new ids: their records' fold states still name\n\t\t// the old ones, so they are re-folded from the log.\n\t\tawait this.refoldRecordsOf(result.operations.map((op) => op.id))\n\t\treturn result\n\t}\n\n\t/**\n\t * Re-author another local node's never-acknowledged operations under a fresh node id\n\t * bound to `principal` (the user they belong to). Used when the sync server refuses an\n\t * adopted node whose writes belong to the signed-in user (the app assigned them, or\n\t * the node was created for them) but which no claims-aware server ever accepted: a\n\t * beta.12 database's node with history the server recorded no owner for. The store's\n\t * own node id, clock and counters are untouched; the fresh node is registered, so the\n\t * sync engine adopts it like any other local node.\n\t *\n\t * @param fromNodeId - The refused local node (never the store's own)\n\t * @param unsyncedOpIds - Ids of its operations the server never acknowledged\n\t * @param principal - The user the writes belong to (the fresh node's binding)\n\t * @returns The fresh node id and the rewritten operations (for the outbound queue)\n\t * @throws {KoraError} `NODE_ID_UNKNOWN` when `fromNodeId` is the store's own node or\n\t * not a local node\n\t */\n\tasync reauthorLocalNode(\n\t\tfromNodeId: string,\n\t\tunsyncedOpIds: string[],\n\t\tprincipal: string,\n\t): Promise<NodeRotationResult> {\n\t\tthis.ensureOpen()\n\t\tconst from = (await listLocalNodes(this.adapter)).find((node) => node.nodeId === fromNodeId)\n\t\tif (fromNodeId === this.nodeId || !from) {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Node id \"${fromNodeId}\" is not another local node of this database, so its writes cannot be re-authored.`,\n\t\t\t\t'NODE_ID_UNKNOWN',\n\t\t\t\t{ nodeId: fromNodeId, storeNodeId: this.nodeId },\n\t\t\t)\n\t\t}\n\t\tconst result = await rotateUnsyncedOperationsInLog(\n\t\t\tthis.adapter,\n\t\t\tthis.schema,\n\t\t\tunsyncedOpIds,\n\t\t\tfromNodeId,\n\t\t\tgenerateUUIDv7(),\n\t\t\t{ moveDatabaseNode: false },\n\t\t)\n\t\tawait registerLocalNode(this.adapter, result.nodeId)\n\t\tawait setLocalNodePrincipal(this.adapter, result.nodeId, principal, 'fresh')\n\t\tthis.versionVector = await this.loadVersionVector()\n\t\tawait this.refoldRecordsOf(result.operations.map((op) => op.id))\n\t\treturn result\n\t}\n\n\t/**\n\t * Move this database back to a node id it authored under before (RT-38): after the\n\t * sync server refused the current node, the device tries a node a returning user\n\t * owns. Nothing is rewritten; later writes use `nodeId`.\n\t *\n\t * @throws {KoraError} When the node id is pinned, or `nodeId` is not a local node\n\t */\n\tasync switchNodeId(nodeId: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tif (this.configNodeId || this.isolation === 'per-tab') {\n\t\t\tthrow new KoraError(\n\t\t\t\t'This store uses a pinned node id, so it cannot switch to another one.',\n\t\t\t\t'NODE_ID_PINNED',\n\t\t\t\t{ nodeId: this.nodeId },\n\t\t\t)\n\t\t}\n\t\tif (nodeId === this.nodeId) return\n\t\tif (isReservedNodeId(nodeId)) throw new ReservedNodeIdError(nodeId, 'switchNodeId')\n\t\tconst known = (await listLocalNodes(this.adapter)).some((node) => node.nodeId === nodeId)\n\t\tif (!known) {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Node id \"${nodeId}\" was never used by this database, so the store cannot switch to it.`,\n\t\t\t\t'NODE_ID_UNKNOWN',\n\t\t\t\t{ nodeId },\n\t\t\t)\n\t\t}\n\t\tawait this.adapter.transaction((tx) => moveDatabaseNodeId(tx, nodeId))\n\t\tawait this.rebindToNode(nodeId)\n\t}\n\n\t/** Point the clock, sequence counter and collections at `nodeId` (already persisted). */\n\tprivate async rebindToNode(nodeId: string): Promise<void> {\n\t\tconst oldClock = this.clock\n\t\tthis.nodeId = nodeId\n\t\tconst clock = new HybridLogicalClock(this.nodeId)\n\t\tif (oldClock) {\n\t\t\tconst last = oldClock.now()\n\t\t\tclock.advanceTo({ ...last, nodeId: this.nodeId })\n\t\t\tconst offset = oldClock.getReferenceOffset()\n\t\t\tif (offset !== null) clock.setReferenceOffset(offset)\n\t\t}\n\t\tthis.clock = clock\n\t\tthis.causalTracker = new CausalTracker()\n\t\tthis.sequenceManager = new SequenceManager(this.adapter, this.nodeId)\n\t\tthis.versionVector = await this.loadVersionVector()\n\t\tthis.sequenceNumber = this.versionVector.get(this.nodeId) ?? 0\n\t\tfor (const collection of this.collections.values()) {\n\t\t\tcollection.rebindNode(clock, this.nodeId, this.relationEnforcer, this.causalTracker)\n\t\t}\n\t}\n\n\t/**\n\t * Bind this database's writes to the signed-in user (RT-42). Call it whenever the\n\t * signed-in user is known or changes, BEFORE the next local write (`createApp` does\n\t * so at start and on every auth change of `sync.authClient`).\n\t *\n\t * - The current node belongs to `principal`: nothing changes.\n\t * - The current node is unbound and has no history (no write, never synced): it is\n\t * bound to `principal` (every write under it from now on is theirs).\n\t * - The current node is unbound but has history (a database from before RT-42, or\n\t * writes made while nobody was signed in): its owner is NOT guessed (RT-50). The\n\t * store moves to `principal`'s own node, and the old node's owner is learned from\n\t * the sync server (the first accepted handshake as it binds it; a refusal rules\n\t * that user out). A node that never synced cannot be attributed by anyone: its\n\t * unsynced writes are held for the app to assign or discard (`app.sync.assignHeld`,\n\t * `app.sync.discardHeld`).\n\t * - It belongs to another user: the store moves to `principal`'s own local node (the\n\t * most recent one, not held), or to a fresh node bound to `principal`. Nothing is\n\t * rewritten: the other user's unsynced writes stay under their node, and sync never\n\t * uploads them on this user's session (they count as `heldOperations`).\n\t *\n\t * A pinned node id (`StoreConfig.nodeId`, such as an auth device id) cannot move:\n\t * `conflict` is then true when it belongs to another user, and sync refuses to\n\t * upload it under `principal`; an unbound pinned node with history stays unbound\n\t * until the server accepts it for a user. Under `per-tab` isolation the tab moves to\n\t * a fresh per-tab node.\n\t *\n\t * @param principal - The signed-in user id\n\t * @returns The node now in use and whether it changed\n\t */\n\tasync bindPrincipal(principal: string): Promise<PrincipalBinding> {\n\t\tconst binding = await this.bindPrincipalToNode(principal)\n\t\t// The server's word was about the previous user; another user may own the node.\n\t\tif (principal !== this.signedInPrincipal) this.pinnedNodeRefusedByServer = false\n\t\t// While the pinned node belongs to another user, local writes are refused (F9):\n\t\t// they could only be written under that user's node and would upload as theirs.\n\t\tthis.pinnedNodeOwnedBy = binding.conflict\n\t\t\t? ((await listLocalNodes(this.adapter)).find((node) => node.nodeId === this.nodeId)\n\t\t\t\t\t?.principal ?? null)\n\t\t\t: null\n\t\tthis.signedInPrincipal = principal\n\t\treturn binding\n\t}\n\n\t/**\n\t * The sync server refused this store's pinned node id because another user owns it\n\t * (`owned: true`), or later accepted it (`false`). A pinned node cannot move to a fresh\n\t * id, so writes made under it could only ever upload as its owner: while the server\n\t * says so, local writes are refused (F9). A no-op for a store whose node is not pinned\n\t * (it moves to a fresh node instead).\n\t *\n\t * @param owned - Whether the server reported the node owned by another user\n\t */\n\tsetPinnedNodeOwnedElsewhere(owned: boolean): void {\n\t\tif (!this.configNodeId) return\n\t\tthis.pinnedNodeRefusedByServer = owned\n\t}\n\n\t/** Refuse a local write while the pinned node belongs to another user (F9). */\n\tprivate assertLocalWriteAllowed(): void {\n\t\tif (this.pinnedNodeOwnedBy === null && !this.pinnedNodeRefusedByServer) return\n\t\tthrow new NodeOwnedByAnotherUserError(this.nodeId, this.signedInPrincipal)\n\t}\n\n\tprivate async bindPrincipalToNode(principal: string): Promise<PrincipalBinding> {\n\t\tthis.ensureOpen()\n\t\tconst previousNodeId = this.nodeId\n\t\tconst nodes = await listLocalNodes(this.adapter)\n\t\tconst current = nodes.find((node) => node.nodeId === this.nodeId)\n\t\tconst owner = current?.principal ?? null\n\t\tif (owner === principal) {\n\t\t\treturn { nodeId: this.nodeId, previousNodeId, switched: false, conflict: false }\n\t\t}\n\t\tif (owner === null) {\n\t\t\tconst written = (await this.loadVersionVector()).get(this.nodeId) ?? 0\n\t\t\tif (written === 0 && !(current?.accepted ?? false)) {\n\t\t\t\tawait setLocalNodePrincipal(this.adapter, this.nodeId, principal, 'fresh')\n\t\t\t\treturn { nodeId: this.nodeId, previousNodeId, switched: false, conflict: false }\n\t\t\t}\n\t\t\tif (this.configNodeId) {\n\t\t\t\t// Cannot move: the server decides whose it is at the first handshake.\n\t\t\t\treturn { nodeId: this.nodeId, previousNodeId, switched: false, conflict: false }\n\t\t\t}\n\t\t} else if (this.configNodeId) {\n\t\t\treturn { nodeId: this.nodeId, previousNodeId, switched: false, conflict: true }\n\t\t}\n\t\tif (this.isolation === 'per-tab') {\n\t\t\t// A per-tab node belongs to its tab; another user in this tab gets a fresh one.\n\t\t\tconst fresh = generateUUIDv7()\n\t\t\tawait registerLocalNode(this.adapter, fresh)\n\t\t\tawait setLocalNodePrincipal(this.adapter, fresh, principal, 'fresh')\n\t\t\tsavePerTabNodeId(this.dbName, fresh)\n\t\t\tthis.releaseNodeLock?.()\n\t\t\tthis.releaseNodeLock = acquireNodeLock(nodeLockName(this.dbName, fresh))\n\t\t\tawait this.rebindToNode(fresh)\n\t\t\treturn { nodeId: fresh, previousNodeId, switched: true, conflict: false }\n\t\t}\n\t\tconst own = nodes\n\t\t\t.filter((node) => node.principal === principal && !node.held)\n\t\t\t.sort((a, b) => b.createdAt - a.createdAt)[0]\n\t\tif (own) {\n\t\t\tawait this.switchNodeId(own.nodeId)\n\t\t\treturn { nodeId: own.nodeId, previousNodeId, switched: true, conflict: false }\n\t\t}\n\t\tconst fresh = generateUUIDv7()\n\t\tawait this.adapter.transaction((tx) => moveDatabaseNodeId(tx, fresh))\n\t\tawait registerLocalNode(this.adapter, fresh)\n\t\tawait setLocalNodePrincipal(this.adapter, fresh, principal, 'fresh')\n\t\tawait this.rebindToNode(fresh)\n\t\treturn { nodeId: fresh, previousNodeId, switched: true, conflict: false }\n\t}\n\n\t/**\n\t * A sync handshake as `nodeId` was accepted for `principal` (RT-50): bind an unbound\n\t * node (or replace a guessed binding) from the server's answer.\n\t */\n\tasync confirmNodePrincipal(nodeId: string, principal: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait confirmLocalNodePrincipal(this.adapter, nodeId, principal)\n\t}\n\n\t/**\n\t * The sync server refused `nodeId` for `principal` (RT-50): clear a guessed binding,\n\t * and remember that an unbound node is not theirs.\n\t */\n\tasync recordNodeRefusedFor(nodeId: string, principal: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait recordLocalNodeRefusedFor(this.adapter, nodeId, principal)\n\t}\n\n\t/**\n\t * Assign a held, unbound local node's writes to `principal` (RT-50): an explicit app\n\t * decision for writes nobody can attribute (a database that never synced).\n\t *\n\t * @returns false when the node is unknown, the store's own, already bound, or was\n\t * refused for `principal` by the server\n\t */\n\tasync assignNodePrincipal(nodeId: string, principal: string): Promise<boolean> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return false\n\t\treturn assignLocalNodePrincipal(this.adapter, nodeId, principal)\n\t}\n\n\t/**\n\t * Forget a local node other than the store's own whatever it still holds (RT-50: the\n\t * app discarded its held writes, which were marked never to upload first).\n\t */\n\tasync dropLocalNode(nodeId: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return\n\t\tawait dropLocalNode(this.adapter, nodeId)\n\t}\n\n\t/** The adoption schedule of this database's local nodes (RT-46). */\n\tasync loadAdoptionSchedule(): Promise<AdoptionSchedule> {\n\t\tthis.ensureOpen()\n\t\treturn loadAdoptionSchedule(this.adapter)\n\t}\n\n\t/** Persist the adoption schedule (RT-46). */\n\tasync saveAdoptionSchedule(schedule: AdoptionSchedule): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait saveAdoptionSchedule(this.adapter, schedule)\n\t}\n\n\t/**\n\t * Raise a local node's sequence counter to at least `floor`, in a transaction (the\n\t * same MAX every reservation uses, W6), so the next write never reuses a number the\n\t * server already holds (RT-35: the device lost the tail of its log, for example on a\n\t * reload inside the IndexedDB snapshot window or after restoring an older copy).\n\t *\n\t * @returns Whether the counter moved\n\t */\n\tasync raiseSequenceFloor(nodeId: string, floor: number): Promise<boolean> {\n\t\tthis.ensureOpen()\n\t\tlet raised = false\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tconst rows = await tx.query<VersionVectorRow>(\n\t\t\t\t'SELECT sequence_number FROM _kora_version_vector WHERE node_id = ?',\n\t\t\t\t[nodeId],\n\t\t\t)\n\t\t\tconst current = rows[0]?.sequence_number ?? 0\n\t\t\tif (floor <= current) return\n\t\t\tawait tx.execute(\n\t\t\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\t\t[nodeId, floor],\n\t\t\t)\n\t\t\traised = true\n\t\t})\n\t\tif (raised) {\n\t\t\tconst previous = this.versionVector.get(nodeId) ?? 0\n\t\t\tthis.versionVector.set(nodeId, Math.max(previous, floor))\n\t\t\tif (nodeId === this.nodeId) this.sequenceNumber = Math.max(this.sequenceNumber, floor)\n\t\t}\n\t\treturn raised\n\t}\n\n\t/**\n\t * Give one of a local node's operations a fresh sequence number above `floor`\n\t * (RT-35): the server refused it with `SEQUENCE_CONFLICT` because it holds another\n\t * operation of this node under that number (one this device lost). A version-1\n\t * operation keeps its id (its hash does not cover the sequence number), exactly like\n\t * the W6 sequence repair; a version-2 operation (protocol v2) is re-hashed under the\n\t * new number, so it carries a new id. The old identity is recorded in\n\t * `_kora_seq_conflicts` (`reemitted_as`).\n\t *\n\t * A new id would leave later operations naming the old one in `causalDeps`: those in\n\t * `rewritableDependents` (operations the server never stored: never sent) are\n\t * rewritten to name the new id, and re-hashed, transitively, in the same\n\t * transaction. Dependents already sent keep their ids (the server may hold them);\n\t * their dep resolves through the `_kora_seq_conflicts` record. Every touched record\n\t * is re-folded (fold stamps carry operation ids).\n\t *\n\t * @param rewritableDependents - Ids of this node's operations that were never sent\n\t * @returns The renumbered operation and the rewritten dependents, or null when the\n\t * operation is not in the log\n\t */\n\tasync resequenceOperation(\n\t\toperationId: string,\n\t\tnodeId: string,\n\t\tfloor: number,\n\t\trewritableDependents: readonly string[] = [],\n\t): Promise<ResequenceResult | null> {\n\t\tthis.ensureOpen()\n\t\tconst found: { result: ResequenceResult | null } = { result: null }\n\t\tconst collections = Object.keys(this.schema.collections)\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const collection of collections) {\n\t\t\t\tconst table = quoteIdent(`_kora_ops_${collection}`)\n\t\t\t\tconst rows = await tx.query<OperationRow>(\n\t\t\t\t\t`SELECT * FROM ${table} WHERE id = ? AND node_id = ?`,\n\t\t\t\t\t[operationId, nodeId],\n\t\t\t\t)\n\t\t\t\tconst row = rows[0]\n\t\t\t\tif (!row) continue\n\t\t\t\tawait tx.execute(\n\t\t\t\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\t\t\t[nodeId, floor],\n\t\t\t\t)\n\t\t\t\tconst sequence = await allocateNextSequenceInTransaction(tx, nodeId)\n\t\t\t\t// A version-2 id covers the sequence number (CORE-1): such an operation is\n\t\t\t\t// re-hashed under the new number (the server never stored it).\n\t\t\t\tconst moved = await renumberOperationRow(tx, collection, row, sequence)\n\t\t\t\tawait insertConflictRow(\n\t\t\t\t\ttx,\n\t\t\t\t\tcollection,\n\t\t\t\t\trow,\n\t\t\t\t\t'server-sequence-conflict',\n\t\t\t\t\tmoved.id,\n\t\t\t\t\tsequence,\n\t\t\t\t\tDate.now(),\n\t\t\t\t)\n\t\t\t\tconst idMapping: Record<string, string> = moved.id !== row.id ? { [row.id]: moved.id } : {}\n\t\t\t\tconst rewritable = new Set(rewritableDependents)\n\t\t\t\trewritable.delete(row.id)\n\t\t\t\tconst dependents =\n\t\t\t\t\tmoved.id !== row.id\n\t\t\t\t\t\t? await rewriteDependentsInTx(tx, collections, nodeId, idMapping, rewritable)\n\t\t\t\t\t\t: []\n\t\t\t\tfound.result = { operation: moved, dependents, idMapping }\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t\tconst result = found.result\n\t\tif (!result) return null\n\t\tthis.recordOperationSequence(result.operation)\n\t\tif (Object.keys(result.idMapping).length > 0) {\n\t\t\tawait this.refoldRecordsOf([result.operation.id, ...result.dependents.map((op) => op.id)])\n\t\t}\n\t\treturn result\n\t}\n\n\t/**\n\t * Durability barrier (RT-35): resolves once every write committed so far is durable\n\t * on this device. Sync awaits it before an operation leaves the device.\n\t */\n\tasync ensureDurable(): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait this.adapter.ensureDurable?.()\n\t}\n\n\t/** Record operations the server refused for good (RT-36). Never cleared. */\n\tasync recordTerminalRejections(entries: TerminalRejection[]): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait recordTerminalRejections(this.adapter, entries)\n\t\t// The server never stored these operations: re-fold their records without them,\n\t\t// so this device converges to the server's state (W7 step 2).\n\t\tawait this.refoldRecordsOf(entries.map((entry) => entry.operationId))\n\t}\n\n\t/** Which of these operation ids the server refused for good (RT-36). */\n\tasync findTerminalRejections(operationIds: string[]): Promise<Set<string>> {\n\t\tthis.ensureOpen()\n\t\treturn findTerminalRejections(this.adapter, operationIds)\n\t}\n\n\t/** Every node id this database authored operations under (RT-38, RT-40). */\n\tasync listLocalNodes(): Promise<LocalNodeRecord[]> {\n\t\tthis.ensureOpen()\n\t\treturn listLocalNodes(this.adapter)\n\t}\n\n\t/** Forget a drained local node other than this store's own (RT-40). */\n\tasync forgetLocalNode(nodeId: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return\n\t\tawait forgetLocalNode(this.adapter, nodeId)\n\t}\n\n\t/** The current refusal cycle: the count of accepted sync handshakes (RT-38). */\n\tasync loadAcceptedCycle(): Promise<number> {\n\t\tthis.ensureOpen()\n\t\treturn loadAcceptedCycle(this.adapter)\n\t}\n\n\t/** Record an accepted sync handshake as `nodeId` (RT-38). */\n\tasync markLocalNodeAccepted(nodeId: string): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait markLocalNodeAccepted(this.adapter, nodeId)\n\t}\n\n\t/** Record that the sync server refused `nodeId`; `held` holds its writes (RT-38). */\n\tasync markLocalNodeRefused(nodeId: string, held: boolean): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tawait markLocalNodeRefused(this.adapter, nodeId, held)\n\t}\n\n\t/**\n\t * Take over another local node's unsynced writes (RT-40): resolves to a release\n\t * function when no live tab uses `nodeId` (its lock is free), or null when one does.\n\t * Without Web Locks (Node, old browsers) the node is assumed free.\n\t */\n\tasync claimLocalNode(nodeId: string): Promise<(() => void) | null> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return null\n\t\treturn tryAcquireNodeLock(nodeLockName(this.dbName, nodeId))\n\t}\n\n\t/** Whether a live tab holds `nodeId` (per-tab isolation, RT-40). */\n\tasync isLocalNodeLive(nodeId: string): Promise<boolean> {\n\t\tthis.ensureOpen()\n\t\tif (nodeId === this.nodeId) return true\n\t\treturn isNodeLockHeld(nodeLockName(this.dbName, nodeId))\n\t}\n\n\tasync rebaseUnsyncedOperations(\n\t\tunsyncedOpIds: string[],\n\t\tcorrectedNowMs: number,\n\t): Promise<ClockRebaseResult> {\n\t\tthis.ensureOpen()\n\t\tconst result = await rebaseUnsyncedOperationsInLog(\n\t\t\tthis.adapter,\n\t\t\tthis.schema,\n\t\t\tunsyncedOpIds,\n\t\t\tcorrectedNowMs,\n\t\t)\n\t\tif (result.newMaxTimestamp && this.clock) {\n\t\t\tthis.clock.advanceTo(result.newMaxTimestamp)\n\t\t}\n\t\t// Re-stamped operations order differently: re-fold their records.\n\t\tawait this.refoldRecordsOf(result.operations.map((op) => op.id))\n\t\treturn result\n\t}\n\n\t/**\n\t * Count of local operations ahead of the server version vector.\n\t */\n\tasync countUnsyncedOperations(serverVector: VersionVector): Promise<number> {\n\t\tconst ops = await this.getUnsyncedOperations(serverVector)\n\t\treturn ops.length\n\t}\n\n\t/**\n\t * Compact the local operation log. Only removes ops the server has acknowledged\n\t * (per {@link CompactionStrategy}). With the W7 fold (STORE-14), the effect of the\n\t * removed operations is first joined into each record's base fold state, so a\n\t * re-fold (rejection exclusion, a later re-materialization) and the merge of a\n\t * late operation stay exact; delete, atomic and custom-resolver operations are\n\t * kept, and a re-delivered compacted id is a duplicate by its node's compacted\n\t * prefix.\n\t */\n\tasync compact(strategy: CompactionStrategy): Promise<CompactionResult> {\n\t\tthis.ensureOpen()\n\t\tconst fold = this.activeFold()\n\t\tif (strategy.mode === 'never') {\n\t\t\treturn compactOperationLog(this.adapter, this.schema, strategy, createVersionVector())\n\t\t}\n\n\t\tconst serverVector = strategy.serverVector ?? (await loadLastAckedServerVector(this.adapter))\n\t\tif (fold) {\n\t\t\treturn compactFoldedLog(this.adapter, this.schema, fold, strategy, serverVector)\n\t\t}\n\t\treturn compactOperationLog(this.adapter, this.schema, strategy, serverVector)\n\t}\n\n\t/**\n\t * Merge session remote vector with persisted last-acked vector (max per node).\n\t */\n\tmergeServerVectors(sessionVector: VersionVector, persistedVector: VersionVector): VersionVector {\n\t\treturn mergeVersionVectors(persistedVector, sessionVector)\n\t}\n\n\tasync getLatestLocalOperationForRecord(\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<Operation | null> {\n\t\tthis.ensureOpen()\n\t\tconst rows = await this.adapter.query<OperationRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE node_id = ? AND record_id = ? ORDER BY sequence_number DESC LIMIT 1`,\n\t\t\t[this.nodeId, recordId],\n\t\t)\n\t\tconst row = rows[0]\n\t\tif (!row) {\n\t\t\treturn null\n\t\t}\n\t\treturn deserializeOperationWithCollection(row, collection)\n\t}\n\n\t/**\n\t * Latest operation for a record from any node (for 3-way merge when local op log is empty).\n\t */\n\tasync getLatestOperationForRecord(\n\t\tcollection: string,\n\t\trecordId: string,\n\t): Promise<Operation | null> {\n\t\tthis.ensureOpen()\n\t\tconst rows = await this.adapter.query<OperationRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE record_id = ?`,\n\t\t\t[recordId],\n\t\t)\n\n\t\tlet latest: Operation | null = null\n\t\tfor (const row of rows) {\n\t\t\tconst op = deserializeOperationWithCollection(row, collection)\n\t\t\tif (!latest || HybridLogicalClock.compare(op.timestamp, latest.timestamp) > 0) {\n\t\t\t\tlatest = op\n\t\t\t}\n\t\t}\n\t\treturn latest\n\t}\n\n\t/**\n\t * All operations for a record, sorted in HLC total order (wallTime, logical,\n\t * nodeId). Used by the apply pipeline to materialize atomic-op fields by folding\n\t * the record's log, matching the server's materialization exactly.\n\t */\n\tasync getOperationsForRecord(collection: string, recordId: string): Promise<Operation[]> {\n\t\tthis.ensureOpen()\n\t\tconst rows = [\n\t\t\t...(await this.adapter.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE record_id = ?`,\n\t\t\t\t[recordId],\n\t\t\t)),\n\t\t\t// Other nodes' operations kept only in the sequence-conflicts table still\n\t\t\t// belong to the record's history.\n\t\t\t...(await loadRetainedConflictRows(\n\t\t\t\t(sql, params) => this.adapter.query(sql, params),\n\t\t\t\tcollection,\n\t\t\t\trecordId,\n\t\t\t)),\n\t\t]\n\t\tconst ops = rows.map((row) => deserializeOperationWithCollection(row, collection))\n\t\tops.sort((a, b) => HybridLogicalClock.compare(a.timestamp, b.timestamp))\n\t\treturn ops\n\t}\n\n\t/** Expose the subscription manager for direct access (e.g., by QueryBuilder) */\n\tgetSubscriptionManager(): SubscriptionManager {\n\t\treturn this.subscriptionManager\n\t}\n\n\t/**\n\t * Get the sequence manager for offline-safe sequence generation.\n\t * @throws {StoreNotOpenError} If the store is not open\n\t */\n\tgetSequenceManager(): SequenceManager {\n\t\tthis.ensureOpen()\n\t\tif (!this.sequenceManager) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t\treturn this.sequenceManager\n\t}\n\n\t/**\n\t * Create a TransactionContext for atomic multi-collection operations.\n\t * The returned context buffers all mutations and commits them atomically.\n\t *\n\t * After commit, the caller is responsible for notifying subscriptions\n\t * and emitting events for each operation.\n\t */\n\tcreateTransaction(): TransactionContext {\n\t\tthis.ensureOpen()\n\t\tif (!this.clock) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t\tconst beforeLocalDelete = this.localMutationHandler?.beforeLocalDelete\n\t\tconst fold = this.activeFold()\n\t\treturn new TransactionContext({\n\t\t\t...(this.maxOperationBytes !== undefined\n\t\t\t\t? { maxOperationBytes: this.maxOperationBytes }\n\t\t\t\t: {}),\n\t\t\tassertLocalWriteAllowed: () => this.assertLocalWriteAllowed(),\n\t\t\t...(fold ? { fold } : {}),\n\t\t\tschema: this.schema,\n\t\t\tadapter: this.adapter,\n\t\t\tclock: this.clock,\n\t\t\tnodeId: this.nodeId,\n\t\t\trelationEnforcer: this.relationEnforcer,\n\t\t\tcausalTracker: this.causalTracker,\n\t\t\t...(this.secretKeyProvider ? { secretKeyProvider: this.secretKeyProvider } : {}),\n\t\t\t...(beforeLocalDelete\n\t\t\t\t? { beforeLocalDelete: beforeLocalDelete.bind(this.localMutationHandler) }\n\t\t\t\t: {}),\n\t\t\tonStorageError: (error) => this.reportStorageError(error),\n\t\t})\n\t}\n\n\t/**\n\t * Execute a function within a transaction. All mutations performed on the\n\t * TransactionContext are committed atomically. Subscription notifications\n\t * are batched and fired after the commit.\n\t *\n\t * If the function throws, the transaction is rolled back and the error is re-thrown.\n\t *\n\t * @param fn - Function receiving a TransactionContext for buffered operations\n\t * @returns The operations that were committed\n\t */\n\tasync transaction(fn: (tx: TransactionContext) => Promise<void>): Promise<Operation[]> {\n\t\tconst tx = this.createTransaction()\n\t\ttry {\n\t\t\tawait fn(tx)\n\t\t} catch (error) {\n\t\t\ttx.rollback()\n\t\t\tthrow error\n\t\t}\n\t\tconst { operations } = await tx.commit()\n\n\t\t// Notify subscriptions and emit events after commit\n\t\tfor (const op of operations) {\n\t\t\tthis.publishLocalOperation(op.collection, op)\n\t\t}\n\n\t\treturn operations\n\t}\n\n\t/**\n\t * Export all data as a portable backup binary.\n\t * Includes operations, version vector, metadata, and optionally materialized records.\n\t *\n\t * @param options - Backup options (includeRecords, collections, onProgress)\n\t * @returns Backup as a Uint8Array\n\t */\n\tasync exportBackup(options?: BackupOptions): Promise<Uint8Array> {\n\t\tthis.ensureOpen()\n\t\tconst { exportBackup: doExport } = await import('../backup/backup')\n\t\treturn doExport(this.adapter, this.schema, this.nodeId, this.schema.version, options)\n\t}\n\n\t/**\n\t * Restore data from a backup binary (format version 2, STORE-5).\n\t *\n\t * - `merge: true`: every backup operation is applied through the remote-apply path\n\t * (deduplicated by id, merged per field), the version vector advances by MAX, and\n\t * nothing of the exporting device's identity or sync state is imported.\n\t * - Replace (default): the data is replaced by the backup's while this device keeps\n\t * its node id, local nodes and principal bindings, its own sequence counters never\n\t * move backwards, and unsynced own writes are kept (see\n\t * `RestoreOptions.keepUnsyncedWrites`). Then {@link reloadFromDisk} runs.\n\t *\n\t * A version-1 file (Kora 1.0.0-beta.12 and earlier) is converted first, exactly as\n\t * `convertBackupV1` does (`result.convertedFromVersion: 1`); one holding an operation\n\t * whose timestamp cannot be recovered is refused (`BACKUP_OPERATION_INVALID`).\n\t *\n\t * @param data - The backup data\n\t * @param options - Restore options (merge, collections, keepUnsyncedWrites, onProgress)\n\t * @param internal - `applyOperation`: the app's remote-apply path (defaults to\n\t * {@link applyRemoteOperation}); `createApp` passes the merge-aware pipeline sync uses\n\t * @returns Result of the restore operation\n\t */\n\tasync importBackup(\n\t\tdata: Uint8Array,\n\t\toptions?: RestoreOptions,\n\t\tinternal?: { applyOperation?: (operation: Operation) => Promise<ApplyResult> },\n\t): Promise<RestoreResult> {\n\t\tthis.ensureOpen()\n\t\tconst started = Date.now()\n\t\tconst onProgress = options?.onProgress ?? (() => {})\n\t\tconst { BackupFormatError, convertBackupV1, parseBackup, readBackupManifest } = await import(\n\t\t\t'../backup/backup'\n\t\t)\n\t\tconst { restoreMerge, restoreReplace } = await import('../backup/restore')\n\t\tonProgress({ phase: 'verifying', progress: 0, message: 'Verifying backup' })\n\t\tlet parsed: Awaited<ReturnType<typeof parseBackup>>\n\t\tlet convertedFromVersion: 1 | undefined\n\t\ttry {\n\t\t\t// A version-1 file (beta.12 and earlier) is converted here, with the same\n\t\t\t// deterministic rules as convertBackupV1 (F3): the exporting device's identity is\n\t\t\t// dropped and damaged timestamps are recovered. An operation that cannot be\n\t\t\t// recovered still refuses the file; dropping it stays an explicit choice.\n\t\t\tlet bytes = data\n\t\t\tif (readBackupManifest(data).version === 1) {\n\t\t\t\tbytes = await convertBackupV1(data)\n\t\t\t\tconvertedFromVersion = 1\n\t\t\t}\n\t\t\tparsed = await parseBackup(\n\t\t\t\tbytes,\n\t\t\t\toptions?.collections ? { collections: options.collections } : undefined,\n\t\t\t)\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof BackupFormatError)) throw error\n\t\t\treturn {\n\t\t\t\toperationsRestored: 0,\n\t\t\t\trecordsRestored: 0,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: error.message,\n\t\t\t\terrorCode: error.code,\n\t\t\t\tduration: Date.now() - started,\n\t\t\t}\n\t\t}\n\t\tif (parsed.manifest.schemaVersion > this.schema.version) {\n\t\t\treturn {\n\t\t\t\toperationsRestored: 0,\n\t\t\t\trecordsRestored: 0,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: `The backup was written by schema version ${parsed.manifest.schemaVersion}; this app runs version ${this.schema.version}. Update the app before restoring it.`,\n\t\t\t\terrorCode: 'BACKUP_SCHEMA_NEWER',\n\t\t\t\tduration: Date.now() - started,\n\t\t\t}\n\t\t}\n\t\tonProgress({ phase: 'restoring', progress: 0.3, message: 'Restoring' })\n\t\tconst explicitAuthorities = new Set((await loadAuthoritativeNodeIds(this.adapter)) ?? [])\n\t\tconst host = {\n\t\t\tadapter: this.adapter,\n\t\t\tschema: this.schema,\n\t\t\tapplyOperation:\n\t\t\t\tinternal?.applyOperation ?? ((op: Operation) => this.applyRemoteOperation(op)),\n\t\t\tlistLocalNodes: () => listLocalNodes(this.adapter),\n\t\t\tisServerAuthority: (nodeId: string) =>\n\t\t\t\tisReservedNodeId(nodeId) || explicitAuthorities.has(nodeId),\n\t\t}\n\t\tif (options?.merge) await this.mergeBackupFoldState(parsed, options.collections !== undefined)\n\t\tconst counts = options?.merge\n\t\t\t? await restoreMerge(host, parsed, options.collections !== undefined)\n\t\t\t: await restoreReplace(host, parsed, {\n\t\t\t\t\tcollections: options?.collections ?? null,\n\t\t\t\t\tkeepUnsyncedWrites: options?.keepUnsyncedWrites ?? true,\n\t\t\t\t})\n\t\tif (!options?.merge && this.folder) {\n\t\t\t// Restored rows and log replace what the fold states described: rebuild them,\n\t\t\t// from the backup's base states and log (RT-66). A file from an earlier\n\t\t\t// release carries no base states, and its log may have been compacted: its\n\t\t\t// records are rebuilt on top of its rows instead (row snapshots).\n\t\t\tawait this.adapter.execute('DELETE FROM _kora_meta WHERE key = ?', [\n\t\t\t\tFOLD_MATERIALIZATION_META_KEY,\n\t\t\t])\n\t\t\tthis.foldActive = false\n\t\t\tawait this.ensureMaterialization(parsed.manifest.includesFoldState !== true)\n\t\t}\n\t\tawait this.reloadFromDisk()\n\t\tonProgress({ phase: 'restoring', progress: 1, message: 'Done' })\n\t\treturn {\n\t\t\toperationsRestored: counts.operationsRestored,\n\t\t\trecordsRestored: counts.recordsRestored,\n\t\t\t...(options?.merge ? {} : { unsyncedWritesKept: counts.unsyncedWritesKept }),\n\t\t\t...(counts.serverOperationsSkipped\n\t\t\t\t? { serverOperationsSkipped: counts.serverOperationsSkipped }\n\t\t\t\t: {}),\n\t\t\t...(convertedFromVersion ? { convertedFromVersion } : {}),\n\t\t\tsuccess: true,\n\t\t\tduration: Date.now() - started,\n\t\t}\n\t}\n\n\t/**\n\t * Merge mode (RT-66): join the backup's compacted base states and row snapshots\n\t * into this database's, and re-fold those records, before the backup's operations\n\t * are applied. The join is the fold's state-based merge, so the result equals\n\t * folding both devices' histories together. Compacted prefixes advance by MAX\n\t * (unfiltered restores only: the prefix is per node, across collections).\n\t */\n\tprivate async mergeBackupFoldState(\n\t\tparsed: import('../backup/backup').ParsedBackup,\n\t\tfiltered: boolean,\n\t): Promise<void> {\n\t\tconst folder = this.activeFold()\n\t\tif (!folder) return\n\t\tconst touched = new Map<string, Set<string>>()\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\tfor (const [rows, kind] of [\n\t\t\t\t[parsed.foldBases, 'base'],\n\t\t\t\t[parsed.foldSnapshots, 'snapshot'],\n\t\t\t] as const) {\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tif (!this.schema.collections[row.collection]) continue\n\t\t\t\t\tlet state: FoldState\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstate = deserializeFoldState(row.state)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif (state.c !== row.collection || state.r !== row.recordId) continue\n\t\t\t\t\tif (kind === 'base') await folder.joinIntoBase(tx, state)\n\t\t\t\t\telse await folder.saveSnapshot(tx, state)\n\t\t\t\t\tconst ids = touched.get(row.collection) ?? new Set<string>()\n\t\t\t\t\tids.add(row.recordId)\n\t\t\t\t\ttouched.set(row.collection, ids)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!filtered) {\n\t\t\t\tfor (const [nodeId, sequence] of parsed.compactedThrough) {\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t`INSERT INTO ${COMPACTED_THROUGH_TABLE} (node_id, sequence_number) VALUES (?, ?)\n ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t\t\t[nodeId, sequence],\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const [collection, ids] of touched) {\n\t\t\t\tfor (const recordId of ids) await folder.refoldInTx(tx, collection, recordId)\n\t\t\t}\n\t\t})\n\t\tfor (const [collection, ids] of touched)\n\t\t\tthis.subscriptionManager.invalidate(collection, [...ids])\n\t}\n\n\t/**\n\t * Re-read this store's state from the database after it changed underneath it (a\n\t * backup restore): the node id, version vector and own sequence counter, the clock\n\t * (advanced past every timestamp in the log), and a fresh causal tracker. Every live\n\t * query re-runs. The local node registry and terminal rejections are always read\n\t * from the database, so they need no reload.\n\t */\n\tasync reloadFromDisk(): Promise<void> {\n\t\tthis.ensureOpen()\n\t\tlet nodeId = this.nodeId\n\t\tif (!this.configNodeId && this.isolation !== 'per-tab') {\n\t\t\tconst rows = await this.adapter.query<MetaRow>(\n\t\t\t\t\"SELECT value FROM _kora_meta WHERE key = 'node_id'\",\n\t\t\t)\n\t\t\tnodeId = rows[0]?.value ?? this.nodeId\n\t\t}\n\t\tawait this.rebindToNode(nodeId)\n\t\tconst newest = await this.loadNewestLogTimestamp()\n\t\tif (newest && this.clock) {\n\t\t\tthis.clock.advanceTo({ ...newest, nodeId: this.nodeId })\n\t\t}\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tthis.subscriptionManager.invalidate(collection)\n\t\t}\n\t}\n\n\t/** The greatest HLC timestamp in the operation log (canonical strings sort by HLC). */\n\tprivate async loadNewestLogTimestamp(): Promise<HLCTimestamp | null> {\n\t\tlet newest: string | null = null\n\t\tfor (const collection of Object.keys(this.schema.collections)) {\n\t\t\tconst rows = await this.adapter.query<{ t: string | null }>(\n\t\t\t\t`SELECT MAX(timestamp) AS t FROM ${quoteIdent(`_kora_ops_${collection}`)}`,\n\t\t\t)\n\t\t\tconst value = rows[0]?.t ?? null\n\t\t\tif (value !== null && (newest === null || value > newest)) newest = value\n\t\t}\n\t\treturn newest === null ? null : HybridLogicalClock.deserialize(newest)\n\t}\n\n\t/**\n\t * Read backup manifest without loading the entire backup.\n\t *\n\t * @param data - The raw backup data\n\t * @returns The backup manifest\n\t */\n\tstatic readBackupManifest(data: Uint8Array): BackupManifest {\n\t\treturn readManifest(data)\n\t}\n\n\tprivate recordOperationSequence(operation: Operation): void {\n\t\tconst prev = this.versionVector.get(operation.nodeId) ?? 0\n\t\tif (operation.sequenceNumber > prev) {\n\t\t\tthis.versionVector.set(operation.nodeId, operation.sequenceNumber)\n\t\t}\n\t\tif (operation.nodeId === this.nodeId) {\n\t\t\tthis.sequenceNumber = Math.max(this.sequenceNumber, operation.sequenceNumber)\n\t\t}\n\t}\n\n\t/** Post-commit publication of a committed local operation. */\n\tprivate publishLocalOperation(collection: string, operation: Operation): void {\n\t\tthis.recordOperationSequence(operation)\n\t\tthis.subscriptionManager.notify(collection, operation)\n\t\tthis.emitter?.emit({ type: 'operation:created', operation })\n\t}\n\n\t/**\n\t * Map an out-of-space storage failure to `store:quota-exceeded` (STORE-15).\n\t * The error itself still propagates to the caller; this only makes the\n\t * condition observable on every adapter, not just IndexedDB.\n\t */\n\tprivate reportStorageError(error: unknown): void {\n\t\tif (!isStorageFullError(error)) return\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:quota-exceeded',\n\t\t\tdbName: this.dbName,\n\t\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\t})\n\t}\n\n\t/** Report a database a newer build migrated (`store:schema-ahead`) and build the error. */\n\tprivate schemaAhead(storedVersion: number): SchemaVersionAheadError {\n\t\tconst error = new SchemaVersionAheadError(this.dbName, storedVersion, this.schema.version)\n\t\tthis.emitter?.emit({\n\t\t\ttype: 'store:schema-ahead',\n\t\t\tdbName: this.dbName,\n\t\t\tstoredVersion,\n\t\t\tcodeVersion: this.schema.version,\n\t\t\tmessage: error.message,\n\t\t})\n\t\treturn error\n\t}\n\n\t/**\n\t * Run pending schema migrations (STORE-13, NEW-STORE-1): one transaction per version\n\t * (DDL, backfills, `schema_version`); backfills write operations through the local\n\t * write path so they sync, unless declared `localOnly`.\n\t */\n\tprivate async runMigrationsIfNeeded(): Promise<void> {\n\t\tconst clock = this.clock\n\t\tif (!clock) throw new StoreNotOpenError()\n\t\tconst fold = this.activeFold()\n\t\tawait runSchemaMigrations({\n\t\t\tadapter: this.adapter,\n\t\t\tschema: this.schema,\n\t\t\tenv: {\n\t\t\t\t...(fold ? { fold } : {}),\n\t\t\t\tschema: this.schema,\n\t\t\t\tclock,\n\t\t\t\tnodeId: this.nodeId,\n\t\t\t\trelationEnforcer: null,\n\t\t\t\t...(this.secretKeyProvider ? { secretKeyProvider: this.secretKeyProvider } : {}),\n\t\t\t},\n\t\t\tcausalTracker: this.causalTracker,\n\t\t\tonOperation: (operation) => this.publishLocalOperation(operation.collection, operation),\n\t\t})\n\t}\n\n\t/** The node id the database persisted before this open, if any. */\n\tprivate async readPersistedNodeId(): Promise<string | null> {\n\t\tconst rows = await this.adapter.query<MetaRow>(\n\t\t\t\"SELECT value FROM _kora_meta WHERE key = 'node_id'\",\n\t\t)\n\t\treturn rows[0]?.value ?? null\n\t}\n\n\t/**\n\t * Register node ids this database authored under that the registry does not know\n\t * yet: the node id a pinned `nodeId` (the auth device id) just replaced, and the\n\t * authors of queued operations. A beta.12 database had no registry, and a template\n\t * app created before its user signed in authored under a random node; once the\n\t * store is pinned to the device id, that node's queued writes would otherwise sit in\n\t * the queue forever, neither uploaded nor reported. Registered, they are adopted or\n\t * held (`status.heldNodes`) like any other local node's writes. Only the outbound\n\t * queue is read: received operations never enter it.\n\t */\n\tprivate async registerUnregisteredAuthors(persistedNodeId: string | null): Promise<void> {\n\t\tconst authors = new Set<string>()\n\t\tif (persistedNodeId !== null && persistedNodeId !== this.nodeId) authors.add(persistedNodeId)\n\t\tconst queued = await this.adapter.query<{ payload: string }>(\n\t\t\t'SELECT payload FROM _kora_sync_queue',\n\t\t)\n\t\tfor (const row of queued) {\n\t\t\ttry {\n\t\t\t\tconst nodeId = (JSON.parse(row.payload) as { node_id?: unknown }).node_id\n\t\t\t\tif (typeof nodeId === 'string' && nodeId.length > 0) authors.add(nodeId)\n\t\t\t} catch {\n\t\t\t\t// An unreadable queue row is surfaced by the queue's own load.\n\t\t\t}\n\t\t}\n\t\tauthors.delete(this.nodeId)\n\t\tfor (const nodeId of authors) {\n\t\t\tif (isReservedNodeId(nodeId)) continue\n\t\t\tawait registerLocalNode(this.adapter, nodeId)\n\t\t}\n\t}\n\n\tprivate async loadOrGenerateNodeId(): Promise<string> {\n\t\t// The `kora:` namespace is Kora's own (server nodes `kora:server:<id>` are\n\t\t// authoritative by prefix, RT-61): a device never authors under such an id.\n\t\tif (this.configNodeId && isReservedNodeId(this.configNodeId)) {\n\t\t\tthrow new ReservedNodeIdError(this.configNodeId, 'StoreConfig.nodeId')\n\t\t}\n\t\tif (this.configNodeId) {\n\t\t\tif (this.isolation !== 'per-tab') {\n\t\t\t\tawait this.adapter.execute(\n\t\t\t\t\t\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('node_id', ?)\",\n\t\t\t\t\t[this.configNodeId],\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn this.configNodeId\n\t\t}\n\n\t\tif (this.isolation === 'per-tab') {\n\t\t\treturn resolvePerTabNodeId(this.dbName)\n\t\t}\n\n\t\t// Try to load existing node ID\n\t\tconst rows = await this.adapter.query<MetaRow>(\n\t\t\t\"SELECT value FROM _kora_meta WHERE key = 'node_id'\",\n\t\t)\n\t\tif (rows[0] && !isReservedNodeId(rows[0].value)) {\n\t\t\treturn rows[0].value\n\t\t}\n\n\t\t// Generate a new node id (a UUIDv7, never in the reserved `kora:` namespace). A\n\t\t// persisted reserved id (written by something other than this client) is never\n\t\t// adopted: the database gets a fresh identity instead.\n\t\tconst newNodeId = generateUUIDv7()\n\t\tawait this.adapter.execute(\n\t\t\t\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('node_id', ?)\",\n\t\t\t[newNodeId],\n\t\t)\n\t\treturn newNodeId\n\t}\n\n\tprivate async loadSequenceNumber(): Promise<number> {\n\t\tconst rows = await this.adapter.query<VersionVectorRow>(\n\t\t\t'SELECT sequence_number FROM _kora_version_vector WHERE node_id = ?',\n\t\t\t[this.nodeId],\n\t\t)\n\t\treturn rows[0]?.sequence_number ?? 0\n\t}\n\n\tprivate async loadVersionVector(): Promise<VersionVector> {\n\t\tconst rows = await this.adapter.query<VersionVectorRow>(\n\t\t\t'SELECT node_id, sequence_number FROM _kora_version_vector',\n\t\t)\n\t\tconst vector = createVersionVector()\n\t\tfor (const row of rows) {\n\t\t\tvector.set(row.node_id, row.sequence_number)\n\t\t}\n\t\treturn vector\n\t}\n\n\tprivate ensureOpen(): void {\n\t\tif (!this.opened) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t}\n}\n\n/**\n * Public-facing collection accessor. Provides CRUD + where.\n */\nexport interface CollectionAccessor {\n\tinsert(data: Record<string, unknown>): Promise<import('../types').CollectionRecord>\n\tfindById(id: string): Promise<import('../types').CollectionRecord | null>\n\tupdate(id: string, data: Record<string, unknown>): Promise<import('../types').CollectionRecord>\n\tdelete(id: string): Promise<void>\n\twhere(conditions: Record<string, unknown>): QueryBuilder\n}\n\n/**\n * The newest HLC an operation carries: its timestamp, or for a scope-entry insert\n * (RT-27) the greatest of its timestamp and every per-field version.\n */\nfunction newestFieldVersion(op: Operation): HLCTimestamp {\n\tlet newest = op.timestamp\n\tfor (const version of Object.values(op.fieldVersions ?? {})) {\n\t\tif (HybridLogicalClock.compare(version, newest) > 0) newest = version\n\t}\n\treturn newest\n}\n","import type {\n\tCausalTracker,\n\tCollectionDefinition,\n\tHybridLogicalClock,\n\tOperation,\n\tSchemaDefinition,\n\tSecretKeyProvider,\n} from '@korajs/core'\nimport { quoteIdent } from '@korajs/core'\nimport type { RecordFolder } from '../fold/record-folder'\nimport { executeDelete } from '../mutations/execute-delete'\nimport { executeInsert } from '../mutations/execute-insert'\nimport { executeUpdate } from '../mutations/execute-update'\nimport type { LocalMutationContext } from '../mutations/types'\nimport type { RelationEnforcer } from '../relations/relation-enforcer'\nimport { deserializeRecord } from '../serialization/serializer'\nimport type {\n\tCollectionRecord,\n\tLocalMutationHandler,\n\tRawCollectionRow,\n\tStorageAdapter,\n} from '../types'\n\n/**\n * Callback invoked after a mutation so the Store can notify subscriptions.\n */\nexport type MutationCallback = (collection: string, operation: Operation) => void\n\n/**\n * Collection provides CRUD operations on a single schema collection.\n * Delegates to {@link LocalMutationHandler} when configured (unified apply pipeline),\n * otherwise uses shared mutation executors directly.\n */\nexport class Collection {\n\tconstructor(\n\t\tprivate readonly name: string,\n\t\tprivate readonly definition: CollectionDefinition,\n\t\tprivate readonly schema: SchemaDefinition,\n\t\tprivate readonly adapter: StorageAdapter,\n\t\tprivate clock: HybridLogicalClock,\n\t\tprivate nodeId: string,\n\t\tprivate readonly onMutation: MutationCallback,\n\t\tprivate relationEnforcer: RelationEnforcer | null,\n\t\tprivate mutationHandler: LocalMutationHandler | null,\n\t\tprivate causalTracker: CausalTracker | null,\n\t\tprivate readonly secretKeyProvider?: SecretKeyProvider,\n\t\tprivate readonly onStorageError?: (error: unknown) => void,\n\t\tprivate readonly fold?: () => RecordFolder | undefined,\n\t\tprivate readonly maxOperationBytes?: number,\n\t\tprivate readonly assertLocalWriteAllowed?: () => void,\n\t) {}\n\n\t/**\n\t * Point this collection at the store's new device identity after a node-id\n\t * rotation (RT-21). Internal: called by the owning Store only.\n\t *\n\t * @internal\n\t */\n\trebindNode(\n\t\tclock: HybridLogicalClock,\n\t\tnodeId: string,\n\t\trelationEnforcer: RelationEnforcer | null,\n\t\tcausalTracker: CausalTracker | null,\n\t): void {\n\t\tthis.clock = clock\n\t\tthis.nodeId = nodeId\n\t\tthis.relationEnforcer = relationEnforcer\n\t\tthis.causalTracker = causalTracker\n\t}\n\n\tprivate mutationContext(): LocalMutationContext {\n\t\tconst fold = this.fold?.()\n\t\treturn {\n\t\t\t...(fold ? { fold } : {}),\n\t\t\tcollection: this.name,\n\t\t\tdefinition: this.definition,\n\t\t\tschema: this.schema,\n\t\t\tadapter: this.adapter,\n\t\t\tclock: this.clock,\n\t\t\tnodeId: this.nodeId,\n\t\t\tonMutation: this.onMutation,\n\t\t\trelationEnforcer: this.relationEnforcer,\n\t\t\tcausalTracker: this.causalTracker,\n\t\t\t...(this.secretKeyProvider ? { secretKeyProvider: this.secretKeyProvider } : {}),\n\t\t\t...(this.onStorageError ? { onStorageError: this.onStorageError } : {}),\n\t\t\t...(this.maxOperationBytes !== undefined\n\t\t\t\t? { maxOperationBytes: this.maxOperationBytes }\n\t\t\t\t: {}),\n\t\t\t...(this.assertLocalWriteAllowed\n\t\t\t\t? { assertLocalWriteAllowed: this.assertLocalWriteAllowed }\n\t\t\t\t: {}),\n\t\t}\n\t}\n\n\tasync insert(data: Record<string, unknown>): Promise<CollectionRecord> {\n\t\tif (this.mutationHandler) {\n\t\t\treturn this.mutationHandler.insert(this.name, data)\n\t\t}\n\t\treturn executeInsert(this.mutationContext(), data)\n\t}\n\n\tasync findById(id: string): Promise<CollectionRecord | null> {\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(this.name)} WHERE id = ? AND _deleted = 0`,\n\t\t\t[id],\n\t\t)\n\t\tconst row = rows[0]\n\t\tif (!row) return null\n\t\treturn deserializeRecord(row, this.definition.fields)\n\t}\n\n\tasync update(id: string, data: Record<string, unknown>): Promise<CollectionRecord> {\n\t\tif (this.mutationHandler) {\n\t\t\treturn this.mutationHandler.update(this.name, id, data)\n\t\t}\n\t\treturn executeUpdate(this.mutationContext(), id, data)\n\t}\n\n\tasync delete(id: string): Promise<void> {\n\t\tif (this.mutationHandler) {\n\t\t\tawait this.mutationHandler.delete(this.name, id)\n\t\t\treturn\n\t\t}\n\t\tawait executeDelete(this.mutationContext(), id)\n\t}\n\n\tgetName(): string {\n\t\treturn this.name\n\t}\n\n\tgetDefinition(): CollectionDefinition {\n\t\treturn this.definition\n\t}\n\n\t/** Replace the mutation handler (e.g. after ApplyPipeline is wired in createApp). */\n\tsetMutationHandler(handler: LocalMutationHandler | null): void {\n\t\tthis.mutationHandler = handler\n\t}\n}\n","import type { SchemaDefinition, VersionVector } from '@korajs/core'\nimport { HybridLogicalClock, createVersionVector, quoteIdent } from '@korajs/core'\nimport type { StorageAdapter, Transaction } from '../types'\nimport type { CompactionResult, CompactionStrategy } from './types'\nimport { COMPACTION_BASELINE_META_KEY } from './types'\n\n/**\n * Compute per-node sequence watermarks safe to compact (server has acknowledged these ops).\n */\nexport function computeAckCompactionWatermark(serverVector: VersionVector): VersionVector {\n\tconst watermark = createVersionVector()\n\tfor (const [nodeId, seq] of serverVector) {\n\t\tif (seq > 0) {\n\t\t\twatermark.set(nodeId, seq)\n\t\t}\n\t}\n\treturn watermark\n}\n\n/**\n * Remove acknowledged, materialized operation log entries from `_kora_ops_*` tables.\n * Does not modify collection rows — they are the compaction baseline snapshot.\n */\nexport async function compactOperationLog(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tstrategy: CompactionStrategy,\n\tserverVector: VersionVector,\n): Promise<CompactionResult> {\n\tif (strategy.mode === 'never') {\n\t\treturn { deletedCount: 0, watermark: createVersionVector() }\n\t}\n\n\tconst watermark = computeAckCompactionWatermark(serverVector)\n\tif (watermark.size === 0) {\n\t\treturn { deletedCount: 0, watermark }\n\t}\n\n\tconst ageCutoffWall =\n\t\tstrategy.mode === 'after-days' ? Date.now() - strategy.days * 24 * 60 * 60 * 1000 : null\n\tconst ageCutoffSerialized =\n\t\tageCutoffWall !== null\n\t\t\t? HybridLogicalClock.serialize({\n\t\t\t\t\twallTime: ageCutoffWall,\n\t\t\t\t\tlogical: 0,\n\t\t\t\t\tnodeId: '',\n\t\t\t\t}).slice(0, 15)\n\t\t\t: null\n\n\tlet deletedCount = 0\n\tconst collectionNames = Object.keys(schema.collections)\n\n\tawait adapter.transaction(async (tx: Transaction) => {\n\t\tfor (const collectionName of collectionNames) {\n\t\t\t// Already quoted here so the buildCountSql / buildDeleteSql helpers can\n\t\t\t// interpolate it verbatim (they do not route through sql-builder).\n\t\t\tconst table = quoteIdent(`_kora_ops_${collectionName}`)\n\t\t\tfor (const [nodeId, maxSeq] of watermark) {\n\t\t\t\tif (maxSeq <= 0) continue\n\n\t\t\t\tconst countSql = buildCountSql(table, ageCutoffSerialized !== null)\n\t\t\t\tconst countParams =\n\t\t\t\t\tageCutoffSerialized !== null ? [nodeId, maxSeq, ageCutoffSerialized] : [nodeId, maxSeq]\n\t\t\t\tconst countRows = await tx.query<{ count: number }>(countSql, countParams)\n\t\t\t\tdeletedCount += countRows[0]?.count ?? 0\n\n\t\t\t\tconst deleteSql = buildDeleteSql(table, ageCutoffSerialized !== null)\n\t\t\t\tawait tx.execute(deleteSql, countParams)\n\t\t\t}\n\t\t}\n\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tCOMPACTION_BASELINE_META_KEY,\n\t\t\tString(Date.now()),\n\t\t])\n\t})\n\n\treturn { deletedCount, watermark }\n}\n\nfunction buildCountSql(table: string, withAge: boolean): string {\n\tif (withAge) {\n\t\treturn `SELECT COUNT(*) as count FROM ${table} WHERE node_id = ? AND sequence_number <= ? AND SUBSTR(timestamp, 1, 15) < ?`\n\t}\n\treturn `SELECT COUNT(*) as count FROM ${table} WHERE node_id = ? AND sequence_number <= ?`\n}\n\nfunction buildDeleteSql(table: string, withAge: boolean): string {\n\tif (withAge) {\n\t\treturn `DELETE FROM ${table} WHERE node_id = ? AND sequence_number <= ? AND SUBSTR(timestamp, 1, 15) < ?`\n\t}\n\treturn `DELETE FROM ${table} WHERE node_id = ? AND sequence_number <= ?`\n}\n","import {\n\ttype FoldState,\n\tHybridLogicalClock,\n\ttype Operation,\n\ttype SchemaDefinition,\n\ttype VersionVector,\n\tcreateFoldState,\n\tcreateVersionVector,\n\tmergeOp,\n\tquoteIdent,\n} from '@korajs/core'\nimport { computeAckCompactionWatermark } from '../compaction/compact-operation-log'\nimport type { CompactionResult, CompactionStrategy } from '../compaction/types'\nimport { COMPACTION_BASELINE_META_KEY } from '../compaction/types'\nimport { deserializeOperationWithCollection } from '../serialization/serializer'\nimport { SEQ_CONFLICTS_TABLE } from '../store/sequence-repair'\nimport type { OperationRow, StorageAdapter, Transaction } from '../types'\nimport { COMPACTED_THROUGH_TABLE, type RecordFolder } from './record-folder'\n\n/**\n * Whether compaction must keep this operation in the log. The fold state alone is\n * enough to merge later operations, but the plan keeps the operations whose effect\n * cannot be rebuilt from a row snapshot should a future fold-state version need to\n * re-fold from the log: deletes (the tombstone register), atomic intents and writes\n * to custom-resolver fields.\n */\nfunction mustKeep(op: Operation, schema: SchemaDefinition): boolean {\n\tif (op.type === 'delete') return true\n\tif (op.atomicOps !== undefined && Object.keys(op.atomicOps).length > 0) return true\n\tconst resolvers = schema.collections[op.collection]?.resolvers ?? {}\n\treturn Object.keys(op.data ?? {}).some((field) => resolvers[field] !== undefined)\n}\n\n/**\n * Per node, the largest sequence k <= the server's acknowledged sequence such that\n * this database holds every operation 1..k (in some collection's log or the\n * retained sequence conflicts). Only such a prefix can be declared compacted:\n * an operation of that node at or below it is then known to be a duplicate.\n */\nasync function contiguousPrefixes(\n\ttx: Transaction,\n\tschema: SchemaDefinition,\n\tacked: VersionVector,\n): Promise<VersionVector> {\n\tconst out = createVersionVector()\n\tfor (const [nodeId, ackedSeq] of acked) {\n\t\tif (ackedSeq <= 0) continue\n\t\tconst seqs = new Set<number>()\n\t\tfor (const collection of Object.keys(schema.collections)) {\n\t\t\tconst rows = await tx.query<{ sequence_number: number }>(\n\t\t\t\t`SELECT sequence_number FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE node_id = ? AND sequence_number <= ?`,\n\t\t\t\t[nodeId, ackedSeq],\n\t\t\t)\n\t\t\tfor (const row of rows) seqs.add(row.sequence_number)\n\t\t}\n\t\tconst conflicts = await tx.query<{ sequence_number: number }>(\n\t\t\t`SELECT sequence_number FROM ${SEQ_CONFLICTS_TABLE} WHERE node_id = ? AND sequence_number <= ?`,\n\t\t\t[nodeId, ackedSeq],\n\t\t)\n\t\tfor (const row of conflicts) seqs.add(row.sequence_number)\n\t\tconst through = await tx.query<{ sequence_number: number }>(\n\t\t\t`SELECT sequence_number FROM ${COMPACTED_THROUGH_TABLE} WHERE node_id = ?`,\n\t\t\t[nodeId],\n\t\t)\n\t\tlet k = through[0]?.sequence_number ?? 0\n\t\twhile (k < ackedSeq && seqs.has(k + 1)) k += 1\n\t\tif (k > 0) out.set(nodeId, k)\n\t}\n\treturn out\n}\n\n/**\n * Compaction under the W7 fold (STORE-14). For every node, operations within the\n * contiguous prefix the server acknowledged (and older than the age cutoff, for\n * `after-days`) are folded per record into the record's base state, then removed\n * from the log. The record's live fold state is unchanged (it already holds them):\n * `state = join(base, fold(log))` holds before and after.\n *\n * Operations the server terminally rejected are never folded into a base.\n */\nexport async function compactFoldedLog(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tfolder: RecordFolder,\n\tstrategy: CompactionStrategy,\n\tserverVector: VersionVector,\n): Promise<CompactionResult> {\n\tconst acked = computeAckCompactionWatermark(serverVector)\n\tif (acked.size === 0) return { deletedCount: 0, watermark: acked }\n\tconst cutoff =\n\t\tstrategy.mode === 'after-days'\n\t\t\t? HybridLogicalClock.serialize({\n\t\t\t\t\twallTime: Date.now() - strategy.days * 24 * 60 * 60 * 1000,\n\t\t\t\t\tlogical: 0,\n\t\t\t\t\tnodeId: '',\n\t\t\t\t}).slice(0, 15)\n\t\t\t: null\n\n\tlet deletedCount = 0\n\tlet watermark = createVersionVector()\n\tawait adapter.transaction(async (tx) => {\n\t\twatermark = await contiguousPrefixes(tx, schema, acked)\n\t\tfor (const collection of Object.keys(schema.collections)) {\n\t\t\tconst table = quoteIdent(`_kora_ops_${collection}`)\n\t\t\tconst byRecord = new Map<string, Operation[]>()\n\t\t\tfor (const [nodeId, maxSeq] of watermark) {\n\t\t\t\tconst rows = await tx.query<OperationRow>(\n\t\t\t\t\t`SELECT * FROM ${table} WHERE node_id = ? AND sequence_number <= ?${cutoff !== null ? ' AND SUBSTR(timestamp, 1, 15) < ?' : ''}`,\n\t\t\t\t\tcutoff !== null ? [nodeId, maxSeq, cutoff] : [nodeId, maxSeq],\n\t\t\t\t)\n\t\t\t\tfor (const row of rows) {\n\t\t\t\t\tconst op = deserializeOperationWithCollection(row, collection)\n\t\t\t\t\tif (mustKeep(op, schema)) continue\n\t\t\t\t\tconst list = byRecord.get(op.recordId) ?? []\n\t\t\t\t\tlist.push(op)\n\t\t\t\t\tbyRecord.set(op.recordId, list)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const [recordId, ops] of byRecord) {\n\t\t\t\tconst rejected = await folder.loadTerminalRejections(\n\t\t\t\t\ttx,\n\t\t\t\t\tops.map((op) => op.id),\n\t\t\t\t)\n\t\t\t\tlet addition: FoldState = createFoldState(collection, recordId)\n\t\t\t\tlet any = false\n\t\t\t\tfor (const op of ops) {\n\t\t\t\t\tif (rejected.has(op.id)) continue\n\t\t\t\t\taddition = mergeOp(addition, op, schema, folder.options()).state\n\t\t\t\t\tany = true\n\t\t\t\t}\n\t\t\t\tif (any) await folder.joinIntoBase(tx, addition)\n\t\t\t\tfor (let i = 0; i < ops.length; i += 500) {\n\t\t\t\t\tconst chunk = ops.slice(i, i + 500)\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t`DELETE FROM ${table} WHERE id IN (${chunk.map(() => '?').join(', ')})`,\n\t\t\t\t\t\tchunk.map((op) => op.id),\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tdeletedCount += ops.length\n\t\t\t}\n\t\t}\n\t\tfor (const [nodeId, seq] of watermark) {\n\t\t\tawait tx.execute(\n\t\t\t\t`INSERT INTO ${COMPACTED_THROUGH_TABLE} (node_id, sequence_number) VALUES (?, ?)\n ON CONFLICT(node_id) DO UPDATE SET sequence_number = MAX(sequence_number, excluded.sequence_number)`,\n\t\t\t\t[nodeId, seq],\n\t\t\t)\n\t\t}\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tCOMPACTION_BASELINE_META_KEY,\n\t\t\tString(Date.now()),\n\t\t])\n\t})\n\treturn { deletedCount, watermark }\n}\n","import {\n\tcanonicalizeLegacyOperation,\n\tcanonicalizeProvenLegacyClear,\n\tquoteIdent,\n} from '@korajs/core'\nimport type { Operation, SchemaDefinition } from '@korajs/core'\nimport { deserializeOperationWithCollection, serializeOperation } from '../serialization/serializer'\nimport type { OperationRow, StorageAdapter } from '../types'\n\n/** `_kora_meta` key: the op log's legacy bodies were made canonical (RT-83, RT-85). */\nexport const LEGACY_BODIES_META_KEY = 'legacy_bodies_canonical'\n\n/** A log row rewritten into its canonical legacy body. */\nexport interface CanonicalizedLegacyBody {\n\tcollection: string\n\trecordId: string\n}\n\n/**\n * Make every genuine beta.12 clear in the operation log explicit, once per database\n * (RT-83, RT-85).\n *\n * beta.12 applied `update(id, { field: undefined })` as a clear, hashed the member as\n * `null`, and logged JSON without it. Every later replica folds a stored body as\n * written (the fold has no legacy rule: a body a schema transform rewrote must never be\n * read as a clear), so the clear is written into the logged body here, where its\n * provenance is known:\n * - this device's own operations that declare no hash version were written by its\n * beta.12 self (beta.13 always declares version 2): a `previousData` key absent from\n * `data` is always such a clear;\n * - any other node's undeclared update is rewritten only when its id PROVES the clear\n * (`canonicalizeProvenLegacyClear`), as on inbound delivery.\n * The restored body has the same id: version 1 hashes `undefined` and `null` alike.\n *\n * @param adapter - The storage adapter\n * @param schema - The schema (collections with a log)\n * @param ownNodeId - This device's node id\n * @returns The rewritten rows' records (to re-fold)\n */\nexport async function canonicalizeLegacyLogBodies(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\townNodeId: string,\n): Promise<CanonicalizedLegacyBody[]> {\n\tconst rewritten: CanonicalizedLegacyBody[] = []\n\tfor (const collection of Object.keys(schema.collections)) {\n\t\tconst table = quoteIdent(`_kora_ops_${collection}`)\n\t\tconst rows = await adapter.query<OperationRow>(\n\t\t\t`SELECT * FROM ${table} WHERE type = 'update' AND previous_data IS NOT NULL`,\n\t\t)\n\t\tconst updates: Array<{ id: string; data: string | null }> = []\n\t\tfor (const row of rows) {\n\t\t\tlet op: Operation\n\t\t\ttry {\n\t\t\t\top = deserializeOperationWithCollection(row, collection)\n\t\t\t} catch {\n\t\t\t\t// An unreadable row is the log-integrity scan's business, not this one's.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (op.hashVersion === 2 || canonicalizeLegacyOperation(op) === op) continue\n\t\t\tconst canonical =\n\t\t\t\top.nodeId === ownNodeId\n\t\t\t\t\t? canonicalizeLegacyOperation(op)\n\t\t\t\t\t: await canonicalizeProvenLegacyClear(op)\n\t\t\tif (canonical === op) continue\n\t\t\tupdates.push({ id: op.id, data: serializeOperation(canonical).data })\n\t\t\trewritten.push({ collection, recordId: op.recordId })\n\t\t}\n\t\tif (updates.length === 0) continue\n\t\tawait adapter.transaction(async (tx) => {\n\t\t\tfor (const update of updates) {\n\t\t\t\tawait tx.execute(`UPDATE ${table} SET data = ? WHERE id = ?`, [update.data, update.id])\n\t\t\t}\n\t\t})\n\t}\n\treturn rewritten\n}\n","import {\n\ttype FoldState,\n\ttype HLCTimestamp,\n\tHybridLogicalClock,\n\ttype SchemaDefinition,\n\tcreateSnapshotState,\n\tjoinStates,\n\tquoteIdent,\n} from '@korajs/core'\nimport { deserializeRecord } from '../serialization/serializer'\nimport type { RawCollectionRow, StorageAdapter, Transaction } from '../types'\nimport {\n\tFOLD_BASE_TABLE,\n\tFOLD_SNAPSHOT_TABLE,\n\tFOLD_STATE_TABLE,\n\tPROVISIONAL_OPS_TABLE,\n\ttype RecordFolder,\n} from './record-folder'\n\n/**\n * How a database is re-materialized on its first open with the W7 fold:\n *\n * - `'log'`: the log is clean (W8 integrity scan): every record is rebuilt with the\n * fold from its operations. This also repairs replicas that diverged under the\n * pairwise merge of beta.12/13.\n * - `'snapshot+log'`: the log is not complete (it was compacted, or has sequence\n * gaps): each existing row becomes the record's row snapshot (its values at\n * their `_field_versions`, exact where a stored fold state still has them), and\n * the remaining operations are folded on top.\n * - `'kept'`: the log has quarantined rows (W8). Only the records that own a\n * quarantined row are kept exactly as they are (their row becomes their snapshot,\n * nothing is rebuilt from their log); every other record is rebuilt as in `'log'`\n * or `'snapshot+log'` (RT-68).\n *\n * Row snapshots are approximate (see `createSnapshotState`); records that fold\n * against one are listed in `_kora_fold_snapshot` until their history is complete\n * again (a scope entry with the server's fold state, or a full resync).\n */\nexport type RematerializationMode = 'log' | 'snapshot+log' | 'kept'\n\n/** Result of {@link rematerializeDatabase}. */\nexport interface RematerializationResult {\n\tmode: RematerializationMode\n\t/** Records whose state was rebuilt. */\n\trecords: number\n\t/** Rows whose visible values changed. */\n\tchangedRows: number\n\t/** Records that now fold against a row snapshot (approximate until settled). */\n\tsnapshots: number\n}\n\n/** Which records to keep as row snapshots (they own quarantined log rows). */\nexport interface KeptRecords {\n\t/** `collection` -> record ids. */\n\trecords: ReadonlyMap<string, ReadonlySet<string>>\n\t/** Collections with a quarantined row whose record id is unknown: kept whole. */\n\tcollections: ReadonlySet<string>\n}\n\nconst BATCH = 200\n\n/**\n * Rebuild every record's fold state and row. Runs once per database (the store\n * records completion in `_kora_meta`), after the W8 log-integrity scan and the\n * schema migrations. One write transaction per batch of records, so a crash\n * resumes from scratch safely (the rebuild is a pure function of the log and rows).\n *\n * @param mode - `'log'` or `'snapshot+log'` for the records that are not kept;\n * `'kept'` is reported when `kept` names any record\n * @param kept - Records owning quarantined log rows (kept as they are)\n * @param collections - Only these collections (default: all)\n */\nexport async function rematerializeDatabase(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tfolder: RecordFolder,\n\tmode: Exclude<RematerializationMode, 'kept'>,\n\tkept: KeptRecords = { records: new Map(), collections: new Set() },\n\tcollections?: readonly string[],\n): Promise<RematerializationResult> {\n\tlet records = 0\n\tlet changedRows = 0\n\tlet snapshots = 0\n\tconst authoritative = folder.getAuthoritativeNodeIds()\n\tfor (const [collection, definition] of Object.entries(schema.collections)) {\n\t\tif (collections && !collections.includes(collection)) continue\n\t\tconst ids = new Set<string>()\n\t\tfor (const row of await adapter.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${quoteIdent(collection)}`,\n\t\t)) {\n\t\t\tids.add(row.id)\n\t\t}\n\t\tfor (const row of await adapter.query<{ record_id: string }>(\n\t\t\t`SELECT DISTINCT record_id FROM ${quoteIdent(`_kora_ops_${collection}`)}`,\n\t\t)) {\n\t\t\tids.add(row.record_id)\n\t\t}\n\t\tconst keptIds = kept.records.get(collection)\n\t\tconst keepAll = kept.collections.has(collection)\n\t\tconst all = [...ids].sort()\n\t\tfor (let i = 0; i < all.length; i += BATCH) {\n\t\t\tconst batch = all.slice(i, i + BATCH)\n\t\t\tawait adapter.transaction(async (tx) => {\n\t\t\t\tfor (const recordId of batch) {\n\t\t\t\t\trecords += 1\n\t\t\t\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t\t\t\t[recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst row = rows[0]\n\t\t\t\t\tconst before = row ? JSON.stringify(deserializeRecord(row, definition.fields)) : null\n\t\t\t\t\tconst seed = await folder.loadStoredState(tx, collection, recordId)\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t`DELETE FROM ${FOLD_STATE_TABLE} WHERE collection = ? AND record_id = ?`,\n\t\t\t\t\t\t[collection, recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst snapshotOf = (from: RawCollectionRow): FoldState =>\n\t\t\t\t\t\tsnapshotFromRow(from, collection, schema, { seed, authoritative })\n\t\t\t\t\tif (keepAll || keptIds?.has(recordId)) {\n\t\t\t\t\t\tif (row) {\n\t\t\t\t\t\t\t// Owns a quarantined row: never rebuilt from its log; the row stays as\n\t\t\t\t\t\t\t// it is and later operations merge onto it.\n\t\t\t\t\t\t\tconst snapshot = snapshotOf(row)\n\t\t\t\t\t\t\tawait folder.saveSnapshot(tx, snapshot)\n\t\t\t\t\t\t\tsnapshots += 1\n\t\t\t\t\t\t\tconst base = await folder.loadBase(tx, collection, recordId)\n\t\t\t\t\t\t\tawait folder.saveState(tx, base ? joinStates(base, snapshot, schema) : snapshot)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif (mode === 'snapshot+log' && row) {\n\t\t\t\t\t\tawait folder.saveSnapshot(tx, snapshotOf(row))\n\t\t\t\t\t\tsnapshots += 1\n\t\t\t\t\t}\n\t\t\t\t\tconst state = await folder.foldFromLog(tx, collection, recordId)\n\t\t\t\t\tif (state === null) {\n\t\t\t\t\t\t// No operation and no base: a row the log never had (cannot happen on a\n\t\t\t\t\t\t// clean log; kept as a snapshot rather than dropped).\n\t\t\t\t\t\tif (row) {\n\t\t\t\t\t\t\tconst snapshot = snapshotOf(row)\n\t\t\t\t\t\t\tawait folder.saveSnapshot(tx, snapshot)\n\t\t\t\t\t\t\tawait folder.saveState(tx, snapshot)\n\t\t\t\t\t\t\tsnapshots += 1\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tawait folder.saveState(tx, state)\n\t\t\t\t\tawait folder.materializeRow(tx, state, 'all', { clearRetraction: false })\n\t\t\t\t\tconst afterRows = await tx.query<RawCollectionRow>(\n\t\t\t\t\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ?`,\n\t\t\t\t\t\t[recordId],\n\t\t\t\t\t)\n\t\t\t\t\tconst after = afterRows[0]\n\t\t\t\t\t\t? JSON.stringify(deserializeRecord(afterRows[0], definition.fields))\n\t\t\t\t\t\t: null\n\t\t\t\t\tif (before !== after) changedRows += 1\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\tconst keptAny = kept.collections.size > 0 || [...kept.records.values()].some((s) => s.size > 0)\n\treturn { mode: keptAny ? 'kept' : mode, records, changedRows, snapshots }\n}\n\n/**\n * The base snapshot of a materialized row: its values at their `_field_versions`\n * (rows from before per-field versions fall back to `_version`, then `_updated_at`).\n * With a `seed` (the record's stored fold state), every field it still holds in\n * the current plan's kind is taken from it exactly (RT-68).\n */\nexport function snapshotFromRow(\n\trow: RawCollectionRow,\n\tcollection: string,\n\tschema: SchemaDefinition,\n\toptions: { seed?: FoldState | null; authoritative?: ReadonlySet<string> } = {},\n): FoldState {\n\tconst definition = schema.collections[collection]\n\tconst record = definition ? deserializeRecord(row, definition.fields) : { id: row.id }\n\tconst { id: _id, createdAt: _c, updatedAt: _u, ...values } = record as Record<string, unknown>\n\tconst latest = rowVersion(row)\n\tconst fieldVersions: Record<string, HLCTimestamp> = {}\n\tconst raw = typeof row._field_versions === 'string' ? row._field_versions : '{}'\n\ttry {\n\t\tfor (const [field, version] of Object.entries(JSON.parse(raw) as Record<string, unknown>)) {\n\t\t\tif (typeof version === 'string' && version.length > 0) {\n\t\t\t\tfieldVersions[field] = HybridLogicalClock.deserialize(version)\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// Malformed versions: every field falls back to the row version.\n\t}\n\tconst createdAt = typeof row._created_at === 'number' ? row._created_at : latest.wallTime\n\treturn createSnapshotState(\n\t\t{\n\t\t\tcollection,\n\t\t\trecordId: row.id,\n\t\t\tvalues,\n\t\t\tfieldVersions,\n\t\t\tcreated: { wallTime: createdAt, logical: 0, nodeId: '' },\n\t\t\tlatest,\n\t\t\tdeleted: row._deleted === 1,\n\t\t},\n\t\tschema,\n\t\t{\n\t\t\t...(options.seed ? { seed: options.seed } : {}),\n\t\t\t...(options.authoritative ? { authoritativeNodeIds: options.authoritative } : {}),\n\t\t},\n\t)\n}\n\nfunction rowVersion(row: RawCollectionRow): HLCTimestamp {\n\tif (typeof row._version === 'string' && row._version.length > 0) {\n\t\ttry {\n\t\t\treturn HybridLogicalClock.deserialize(row._version)\n\t\t} catch {\n\t\t\t// fall through\n\t\t}\n\t}\n\tconst wall = typeof row._updated_at === 'number' ? row._updated_at : 0\n\treturn { wallTime: wall, logical: 0, nodeId: '' }\n}\n\n/** Remove every fold state, base, row snapshot and provisional effect (mode switch). */\nexport async function clearFoldTables(tx: Transaction): Promise<void> {\n\tawait tx.execute(`DELETE FROM ${FOLD_STATE_TABLE}`)\n\tawait tx.execute(`DELETE FROM ${FOLD_BASE_TABLE}`)\n\tawait tx.execute(`DELETE FROM ${FOLD_SNAPSHOT_TABLE}`)\n\tawait tx.execute(`DELETE FROM ${PROVISIONAL_OPS_TABLE}`)\n}\n","import { KoraError, migrationStepsToSQL, quoteIdent, validateRecord } from '@korajs/core'\nimport type { CausalTracker, MigrationStep, Operation, SchemaDefinition } from '@korajs/core'\nimport {\n\tCausalScope,\n\ttype WriteEnv,\n\ttype WriteScope,\n\twithWriteScope,\n} from '../mutations/write-context'\nimport { writeUpdateInTx } from '../mutations/write-ops'\nimport { deserializeRecord, serializeRecord } from '../serialization/serializer'\nimport type { MetaRow, RawCollectionRow, StorageAdapter, Transaction } from '../types'\n\ntype BackfillStep = Extract<MigrationStep, { type: 'backfill' }>\n\n/** Keys every record carries besides its schema fields. */\nconst RECORD_KEYS: ReadonlySet<string> = new Set(['id', 'createdAt', 'updatedAt'])\n\n/** Everything the migration runner needs from the store. */\nexport interface MigrationRunContext {\n\treadonly adapter: StorageAdapter\n\treadonly schema: SchemaDefinition\n\t/** Write environment of the store's current node (clock, node id, secrets). */\n\treadonly env: Omit<WriteEnv, 'mutationName' | 'transactionId'>\n\treadonly causalTracker: CausalTracker | null\n\t/** Called after each version commits, once per operation its backfills wrote. */\n\treadonly onOperation: (operation: Operation) => void\n}\n\n/**\n * Bring the local database from its stored schema version to `schema.version`\n * (STORE-13, NEW-STORE-1).\n *\n * Each version runs in ONE transaction: its structural DDL, its backfills and the\n * `schema_version` write. A failure (a throwing transform, a crash) leaves no partial\n * effect, so a retry never applies a non-idempotent backfill twice.\n *\n * Backfill transforms receive the deserialized record (booleans, arrays, objects as the\n * app reads them). Every changed record is written through the single local write path\n * as an update operation with mutation name `migration:v<N>`, so the backfilled values\n * sync to the server and other devices; a step declared `localOnly` rewrites the rows\n * only. Fields the transform returns unchanged are not written.\n *\n * @returns The operations the backfills wrote, in commit order\n */\nexport async function runSchemaMigrations(ctx: MigrationRunContext): Promise<Operation[]> {\n\tconst stored = await readStoredSchemaVersion(ctx.adapter)\n\tconst target = ctx.schema.version\n\tif (stored >= target) {\n\t\tif (stored === 0) await writeSchemaVersion(ctx.adapter, target)\n\t\treturn []\n\t}\n\n\tconst written: Operation[] = []\n\tconst migrations = ctx.schema.migrations ?? {}\n\tfor (let version = stored + 1; version <= target; version++) {\n\t\tconst migration = migrations[version]\n\t\tconst steps = migration?.steps ?? []\n\t\tconst committed: Operation[] = []\n\t\tconst causal = new CausalScope(ctx.causalTracker, false)\n\t\tawait ctx.adapter.transaction(async (tx) => {\n\t\t\tfor (const step of steps) {\n\t\t\t\tif (step.type === 'renameField') {\n\t\t\t\t\tawait renameColumn(tx, step.collection, step.from, step.to)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor (const sql of migrationStepsToSQL([step])) {\n\t\t\t\t\tawait executeStructural(tx, sql)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst backfills = steps.filter((step): step is BackfillStep => step.type === 'backfill')\n\t\t\tif (backfills.length > 0) {\n\t\t\t\tconst env: WriteEnv = { ...ctx.env, mutationName: `migration:v${version}` }\n\t\t\t\tawait withWriteScope(tx, ctx.env.nodeId, causal, async (scope) => {\n\t\t\t\t\tfor (const step of backfills) {\n\t\t\t\t\t\tcommitted.push(...(await runBackfill(ctx.schema, env, scope, version, step)))\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait tx.execute(\n\t\t\t\t\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('schema_version', ?)\",\n\t\t\t\t[String(version)],\n\t\t\t)\n\t\t})\n\t\tcausal.publish()\n\t\tfor (const operation of committed) ctx.onOperation(operation)\n\t\twritten.push(...committed)\n\t}\n\treturn written\n}\n\n/**\n * Structural DDL, tolerating \"duplicate column name\": the adapter's open already ran the\n * current schema's DDL, which adds the target schema's columns (`--kora:safe-alter`).\n * Inside a transaction a failed statement rolls back only itself.\n */\nasync function executeStructural(tx: Transaction, sql: string): Promise<void> {\n\ttry {\n\t\tawait tx.execute(sql)\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error)\n\t\tif (!message.includes('duplicate column name')) throw error\n\t}\n}\n\n/**\n * A `renameField` step. The adapter's open has already run the target schema's DDL, whose\n * `--kora:safe-alter` adds the renamed field's column (empty, or holding its default) and\n * creates the target schema's indexes on it; a plain `RENAME COLUMN` would then fail\n * \"duplicate column name\" and leave the values in the old column. The pre-added column is\n * dropped first (with the indexes on it, recreated afterwards), so the rename keeps the\n * values and the source column's constraints. Runs inside the version's transaction.\n */\nasync function renameColumn(\n\ttx: Transaction,\n\tcollection: string,\n\tfrom: string,\n\tto: string,\n): Promise<void> {\n\tconst table = quoteIdent(collection)\n\tconst columns = await tx.query<{ name: string }>(\n\t\t`SELECT name FROM pragma_table_info(${sqlText(collection)})`,\n\t)\n\tconst names = new Set(columns.map((column) => column.name))\n\t// A database created at (or past) this version: the open's DDL already made `to` and\n\t// there is no `from` to carry over (a fresh install of a schema whose history has\n\t// renames). Nothing to rename.\n\tif (!names.has(from) && names.has(to)) return\n\tif (names.has(from) && names.has(to)) {\n\t\tconst indexes = await tx.query<{ name: string; sql: string }>(\n\t\t\t`SELECT m.name AS name, m.sql AS sql FROM sqlite_master m WHERE m.type = 'index' AND m.tbl_name = ${sqlText(collection)} AND m.sql IS NOT NULL AND EXISTS (SELECT 1 FROM pragma_index_info(m.name) i WHERE i.name = ${sqlText(to)})`,\n\t\t)\n\t\tfor (const index of indexes) await tx.execute(`DROP INDEX ${quoteIdent(index.name)}`)\n\t\tawait tx.execute(`ALTER TABLE ${table} DROP COLUMN ${quoteIdent(to)}`)\n\t\tawait tx.execute(`ALTER TABLE ${table} RENAME COLUMN ${quoteIdent(from)} TO ${quoteIdent(to)}`)\n\t\tfor (const index of indexes) {\n\t\t\tawait tx.execute(index.sql.replace(/^CREATE INDEX /i, 'CREATE INDEX IF NOT EXISTS '))\n\t\t}\n\t\treturn\n\t}\n\tawait executeStructural(\n\t\ttx,\n\t\t`ALTER TABLE ${table} RENAME COLUMN ${quoteIdent(from)} TO ${quoteIdent(to)}`,\n\t)\n}\n\nfunction sqlText(value: string): string {\n\treturn `'${value.replaceAll(\"'\", \"''\")}'`\n}\n\nasync function runBackfill(\n\tschema: SchemaDefinition,\n\tenv: WriteEnv,\n\tscope: WriteScope,\n\tversion: number,\n\tstep: BackfillStep,\n): Promise<Operation[]> {\n\tconst definition = schema.collections[step.collection]\n\tif (!definition) {\n\t\tthrow new KoraError(\n\t\t\t`Migration v${version} backfills unknown collection \"${step.collection}\".`,\n\t\t\t'MIGRATION_UNKNOWN_COLLECTION',\n\t\t\t{ version, collection: step.collection },\n\t\t)\n\t}\n\tconst rows = await scope.tx.query<RawCollectionRow>(\n\t\t`SELECT * FROM ${quoteIdent(step.collection)} WHERE _deleted = 0 ORDER BY id`,\n\t)\n\tconst operations: Operation[] = []\n\tfor (const row of rows) {\n\t\tconst record = deserializeRecord(row, definition.fields)\n\t\tconst updates = step.transform({ ...record })\n\t\tif (updates === null || typeof updates !== 'object') continue\n\t\tconst changes: Record<string, unknown> = {}\n\t\tfor (const [field, value] of Object.entries(updates)) {\n\t\t\t// `{ ...record, x }` restates the record's own keys: unchanged ones are ignored.\n\t\t\tif (RECORD_KEYS.has(field) && sameValue(record[field], value)) continue\n\t\t\tif (!(field in definition.fields)) {\n\t\t\t\tthrow new KoraError(\n\t\t\t\t\t`Migration v${version} backfill of \"${step.collection}\" returned unknown field \"${field}\".`,\n\t\t\t\t\t'MIGRATION_UNKNOWN_FIELD',\n\t\t\t\t\t{ version, collection: step.collection, field, fix: 'Return only schema fields.' },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!sameValue(record[field], value)) changes[field] = value\n\t\t}\n\t\tif (Object.keys(changes).length === 0) continue\n\n\t\tif (step.localOnly) {\n\t\t\tconst serialized = serializeRecord(changes, definition.fields)\n\t\t\tconst columns = Object.keys(serialized)\n\t\t\tawait scope.tx.execute(\n\t\t\t\t`UPDATE ${quoteIdent(step.collection)} SET ${columns.map((c) => `${quoteIdent(c)} = ?`).join(', ')} WHERE id = ?`,\n\t\t\t\t[...columns.map((c) => serialized[c]), row.id],\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst validated = validateRecord(step.collection, definition, changes, 'update')\n\t\tconst result = await writeUpdateInTx(env, scope, step.collection, row.id, validated)\n\t\tif (result.operation) operations.push(result.operation)\n\t}\n\treturn operations\n}\n\n/** Structural equality for record values (JSON-shaped; bytes compared bytewise). */\nfunction sameValue(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) return true\n\tif (a instanceof Uint8Array || b instanceof Uint8Array) {\n\t\tif (!(a instanceof Uint8Array) || !(b instanceof Uint8Array) || a.length !== b.length) {\n\t\t\treturn false\n\t\t}\n\t\treturn a.every((byte, index) => byte === b[index])\n\t}\n\tif (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {\n\t\t// A missing value and null are the same stored value.\n\t\treturn (a ?? null) === (b ?? null)\n\t}\n\tif (Array.isArray(a) !== Array.isArray(b)) return false\n\tconst keysA = Object.keys(a)\n\tconst keysB = Object.keys(b)\n\tif (keysA.length !== keysB.length) return false\n\treturn keysA.every((key) =>\n\t\tsameValue((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n\t)\n}\n\nasync function readStoredSchemaVersion(adapter: StorageAdapter): Promise<number> {\n\tconst rows = await adapter.query<MetaRow>(\n\t\t\"SELECT value FROM _kora_meta WHERE key = 'schema_version'\",\n\t)\n\treturn rows[0] ? Number(rows[0].value) : 0\n}\n\nasync function writeSchemaVersion(adapter: StorageAdapter, version: number): Promise<void> {\n\tawait adapter.execute(\n\t\t\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('schema_version', ?)\",\n\t\t[String(version)],\n\t)\n}\n","import type { CollectionDefinition, SchemaDefinition } from '@korajs/core'\nimport { encodeStoredText, quoteIdent } from '@korajs/core'\nimport { QueryError } from '../errors'\nimport { deserializeRecord } from '../serialization/serializer'\nimport { type ResultsEqual, createResultsEqual } from '../subscription/result-equality'\nimport type { SubscriptionManager } from '../subscription/subscription-manager'\nimport type {\n\tCollectionRecord,\n\tOrderByDirection,\n\tQueryDescriptor,\n\tRawCollectionRow,\n\tStorageAdapter,\n\tSubscribeOptions,\n\tSubscriptionCallback,\n\tWhereClause,\n} from '../types'\nimport { pluralize, singularize } from './pluralize'\nimport { normalizeWhere } from './query-key'\nimport { buildCountQuery, buildSelectQuery } from './sql-builder'\n\nconst RESULTS_EQUAL_CACHE = new WeakMap<CollectionDefinition, ResultsEqual>()\n\n/**\n * Fluent query builder for constructing and executing collection queries.\n * Supports where, orderBy, limit, offset, include, exec, count, and subscribe.\n *\n * The generic parameter `T` defaults to `CollectionRecord` for backward compatibility\n * but can be narrowed to a specific record type for full type inference.\n *\n * @example\n * ```typescript\n * const todos = await app.todos\n * .where({ completed: false })\n * .orderBy('createdAt', 'desc')\n * .limit(10)\n * .exec()\n * ```\n */\nexport class QueryBuilder<T = CollectionRecord> {\n\tprivate descriptor: QueryDescriptor\n\n\tconstructor(\n\t\tprivate readonly collectionName: string,\n\t\tprivate readonly definition: CollectionDefinition,\n\t\tprivate readonly adapter: StorageAdapter,\n\t\tprivate readonly subscriptionManager: SubscriptionManager,\n\t\tinitialWhere: WhereClause = {},\n\t\tprivate readonly schema?: SchemaDefinition,\n\t) {\n\t\tthis.descriptor = {\n\t\t\tcollection: collectionName,\n\t\t\twhere: normalizeWhere(initialWhere),\n\t\t\torderBy: [],\n\t\t}\n\t}\n\n\t/**\n\t * Add WHERE conditions (AND semantics, merged with existing conditions).\n\t *\n\t * A field whose value is `undefined` adds no condition (it does not remove an\n\t * earlier one); `null` matches missing values (`IS NULL`). Non-finite numbers are\n\t * refused. See {@link normalizeWhere} (RT-102).\n\t */\n\twhere(conditions: WhereClause): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tclone.descriptor = {\n\t\t\t...clone.descriptor,\n\t\t\twhere: { ...clone.descriptor.where, ...normalizeWhere(conditions) },\n\t\t}\n\t\treturn clone\n\t}\n\n\t/**\n\t * Add ORDER BY clause.\n\t */\n\torderBy(field: string, direction: OrderByDirection = 'asc'): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tclone.descriptor = {\n\t\t\t...clone.descriptor,\n\t\t\torderBy: [...clone.descriptor.orderBy, { field, direction }],\n\t\t}\n\t\treturn clone\n\t}\n\n\t/**\n\t * Set result limit.\n\t */\n\tlimit(n: number): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tclone.descriptor = { ...clone.descriptor, limit: n }\n\t\treturn clone\n\t}\n\n\t/**\n\t * Set result offset.\n\t */\n\toffset(n: number): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tclone.descriptor = { ...clone.descriptor, offset: n }\n\t\treturn clone\n\t}\n\n\t/**\n\t * Include related records in the query results.\n\t * Follows relations defined in the schema to batch-fetch related data.\n\t *\n\t * @param targets - Relation target names (collection names or relation names)\n\t * @returns A new QueryBuilder with include targets added\n\t *\n\t * @example\n\t * ```typescript\n\t * const todosWithProject = await app.todos\n\t * .where({ completed: false })\n\t * .include('project')\n\t * .exec()\n\t * ```\n\t */\n\tinclude(...targets: string[]): QueryBuilder<T> {\n\t\tconst clone = this.clone()\n\t\tconst existing = clone.descriptor.include ?? []\n\t\tclone.descriptor = {\n\t\t\t...clone.descriptor,\n\t\t\tinclude: [...existing, ...targets],\n\t\t}\n\t\treturn clone\n\t}\n\n\t/**\n\t * Execute the query and return results.\n\t */\n\tasync exec(): Promise<T[]> {\n\t\tconst { sql, params } = buildSelectQuery(this.descriptor, this.definition.fields)\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(sql, params)\n\t\tconst records = rows.map((row) => deserializeRecord(row, this.definition.fields))\n\n\t\t// Resolve includes if any\n\t\tif (this.descriptor.include && this.descriptor.include.length > 0 && this.schema) {\n\t\t\tawait this.resolveIncludes(records)\n\t\t}\n\n\t\treturn records as T[]\n\t}\n\n\t/**\n\t * Execute a COUNT query and return the count.\n\t */\n\tasync count(): Promise<number> {\n\t\tconst { sql, params } = buildCountQuery(this.descriptor, this.definition.fields)\n\t\tconst rows = await this.adapter.query<{ count: number }>(sql, params)\n\t\treturn rows[0]?.count ?? 0\n\t}\n\n\t/**\n\t * Subscribe to query results. Callback is called immediately with current results,\n\t * then again whenever the results change due to mutations.\n\t *\n\t * @returns An unsubscribe function\n\t */\n\tsubscribe(callback: SubscriptionCallback<T>, options?: SubscribeOptions): () => void {\n\t\tconst executeFn = () => this.exec()\n\n\t\t// Resolve includeCollections for subscription tracking\n\t\tconst descriptorCopy = { ...this.descriptor }\n\t\tif (descriptorCopy.include && descriptorCopy.include.length > 0 && this.schema) {\n\t\t\tdescriptorCopy.includeCollections = this.resolveIncludeCollections(descriptorCopy.include)\n\t\t}\n\n\t\t// Use registerAndFetch to execute immediately, set lastResults,\n\t\t// and call callback — ensuring subsequent flushes diff correctly.\n\t\treturn this.subscriptionManager.registerAndFetch(\n\t\t\tdescriptorCopy,\n\t\t\tcallback as SubscriptionCallback<CollectionRecord>,\n\t\t\texecuteFn as () => Promise<CollectionRecord[]>,\n\t\t\t{ onError: options?.onError, resultsEqual: this.getResultsEqual() },\n\t\t)\n\t}\n\n\t/** Comparator built once per collection definition and shared by its queries. */\n\tprivate getResultsEqual(): ResultsEqual {\n\t\tlet cached = RESULTS_EQUAL_CACHE.get(this.definition)\n\t\tif (!cached) {\n\t\t\tcached = createResultsEqual(this.definition.fields)\n\t\t\tRESULTS_EQUAL_CACHE.set(this.definition, cached)\n\t\t}\n\t\treturn cached\n\t}\n\n\t/** Get the internal descriptor (for testing/debugging) */\n\tgetDescriptor(): QueryDescriptor {\n\t\treturn { ...this.descriptor }\n\t}\n\n\tprivate clone(): QueryBuilder<T> {\n\t\tconst qb = new QueryBuilder<T>(\n\t\t\tthis.collectionName,\n\t\t\tthis.definition,\n\t\t\tthis.adapter,\n\t\t\tthis.subscriptionManager,\n\t\t\t{},\n\t\t\tthis.schema,\n\t\t)\n\t\tqb.descriptor = {\n\t\t\t...this.descriptor,\n\t\t\twhere: { ...this.descriptor.where },\n\t\t\torderBy: [...this.descriptor.orderBy],\n\t\t\tinclude: this.descriptor.include ? [...this.descriptor.include] : undefined,\n\t\t\tincludeCollections: this.descriptor.includeCollections\n\t\t\t\t? [...this.descriptor.includeCollections]\n\t\t\t\t: undefined,\n\t\t}\n\t\treturn qb\n\t}\n\n\t/**\n\t * Resolve include targets to their actual collection names for subscription tracking.\n\t */\n\tprivate resolveIncludeCollections(targets: string[]): string[] {\n\t\tif (!this.schema) return []\n\t\tconst collections: string[] = []\n\n\t\tfor (const target of targets) {\n\t\t\tconst relation = this.findRelation(target)\n\t\t\tif (relation) {\n\t\t\t\t// For many-to-one: the related collection is `relation.to`\n\t\t\t\t// For one-to-many: the related collection is `relation.from`\n\t\t\t\tif (relation.from === this.collectionName) {\n\t\t\t\t\tcollections.push(relation.to)\n\t\t\t\t} else {\n\t\t\t\t\tcollections.push(relation.from)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn collections\n\t}\n\n\t/**\n\t * Resolve includes after primary query, batch-fetching related records.\n\t */\n\tprivate async resolveIncludes(records: CollectionRecord[]): Promise<void> {\n\t\tif (!this.schema || !this.descriptor.include || records.length === 0) return\n\n\t\tfor (const target of this.descriptor.include) {\n\t\t\tconst relation = this.findRelation(target)\n\t\t\tif (!relation) {\n\t\t\t\tthrow new QueryError(\n\t\t\t\t\t`No relation found for include target \"${target}\" on collection \"${this.collectionName}\". ` +\n\t\t\t\t\t\t`Check that a relation is defined in your schema that connects \"${this.collectionName}\" to \"${target}\".`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (relation.from === this.collectionName) {\n\t\t\t\t// Many-to-one or one-to-one: primary has FK → fetch parent records\n\t\t\t\tawait this.resolveManyToOneInclude(records, relation, target)\n\t\t\t} else {\n\t\t\t\t// One-to-many: related collection has FK → fetch children\n\t\t\t\tawait this.resolveOneToManyInclude(records, relation, target)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Many-to-one: collect FK values from primary results, batch-fetch related, attach as singular.\n\t */\n\tprivate async resolveManyToOneInclude(\n\t\trecords: CollectionRecord[],\n\t\trelation: { from: string; to: string; field: string },\n\t\ttarget: string,\n\t): Promise<void> {\n\t\tconst fkField = relation.field\n\t\tconst fkValues = records\n\t\t\t.map((r) => r[fkField])\n\t\t\t.filter((v): v is string => v !== null && v !== undefined && typeof v === 'string')\n\n\t\tif (fkValues.length === 0) {\n\t\t\t// All null FKs — set property to null on all records\n\t\t\tconst propName = singularize(target)\n\t\t\tfor (const record of records) {\n\t\t\t\t;(record as Record<string, unknown>)[propName] = null\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tconst uniqueFks = [...new Set(fkValues)]\n\t\tconst relatedCollection = relation.to\n\t\tconst relatedDef = this.schema?.collections[relatedCollection]\n\t\tif (!relatedDef) return\n\n\t\t// Batch fetch: SELECT * FROM <to> WHERE id IN (...) AND _deleted = 0\n\t\tconst placeholders = uniqueFks.map(() => '?').join(', ')\n\t\tconst sql = `SELECT * FROM ${quoteIdent(relatedCollection)} WHERE id IN (${placeholders}) AND _deleted = 0`\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(sql, uniqueFks)\n\t\tconst relatedRecords = rows.map((row) => deserializeRecord(row, relatedDef.fields))\n\n\t\t// Build lookup\n\t\tconst lookup = new Map<string, CollectionRecord>()\n\t\tfor (const r of relatedRecords) {\n\t\t\tlookup.set(r.id, r)\n\t\t}\n\n\t\t// Attach as singular property\n\t\tconst propName = singularize(target)\n\t\tfor (const record of records) {\n\t\t\tconst fk = record[fkField] as string | null\n\t\t\t;(record as Record<string, unknown>)[propName] = fk ? (lookup.get(fk) ?? null) : null\n\t\t}\n\t}\n\n\t/**\n\t * One-to-many: collect primary IDs, batch-fetch children, attach as array.\n\t */\n\tprivate async resolveOneToManyInclude(\n\t\trecords: CollectionRecord[],\n\t\trelation: { from: string; to: string; field: string },\n\t\ttarget: string,\n\t): Promise<void> {\n\t\tconst primaryIds = records.map((r) => r.id)\n\t\tconst relatedCollection = relation.from\n\t\tconst relatedDef = this.schema?.collections[relatedCollection]\n\t\tif (!relatedDef) return\n\n\t\tconst fkField = relation.field\n\t\tconst placeholders = primaryIds.map(() => '?').join(', ')\n\t\tconst sql = `SELECT * FROM ${quoteIdent(relatedCollection)} WHERE ${quoteIdent(fkField)} IN (${placeholders}) AND _deleted = 0`\n\t\tconst rows = await this.adapter.query<RawCollectionRow>(\n\t\t\tsql,\n\t\t\tprimaryIds.map((id) => encodeStoredText(id)),\n\t\t)\n\t\tconst relatedRecords = rows.map((row) => deserializeRecord(row, relatedDef.fields))\n\n\t\t// Group by FK\n\t\tconst grouped = new Map<string, CollectionRecord[]>()\n\t\tfor (const r of relatedRecords) {\n\t\t\tconst fk = r[fkField] as string\n\t\t\tif (!grouped.has(fk)) {\n\t\t\t\tgrouped.set(fk, [])\n\t\t\t}\n\t\t\tgrouped.get(fk)?.push(r)\n\t\t}\n\n\t\t// Attach as array property\n\t\tconst propName = pluralize(target)\n\t\tfor (const record of records) {\n\t\t\t;(record as Record<string, unknown>)[propName] = grouped.get(record.id) ?? []\n\t\t}\n\t}\n\n\t/**\n\t * Find a relation definition matching the include target.\n\t * Searches by relation name, target collection name, and singularized/pluralized variants.\n\t */\n\tprivate findRelation(\n\t\ttarget: string,\n\t): { from: string; to: string; field: string; type: string } | null {\n\t\tif (!this.schema) return null\n\n\t\tfor (const [_name, rel] of Object.entries(this.schema.relations)) {\n\t\t\t// Direct match: target is the related collection name\n\t\t\tif (rel.from === this.collectionName && rel.to === target) return rel\n\t\t\tif (rel.to === this.collectionName && rel.from === target) return rel\n\n\t\t\t// Singularized match: \"project\" matches relation to \"projects\"\n\t\t\tif (rel.from === this.collectionName && rel.to === pluralize(target)) return rel\n\t\t\tif (rel.to === this.collectionName && rel.from === pluralize(target)) return rel\n\n\t\t\t// Pluralized match: \"todos\" matches relation from \"todos\"\n\t\t\tif (rel.from === this.collectionName && rel.to === singularize(target)) return rel\n\t\t\tif (rel.to === this.collectionName && rel.from === singularize(target)) return rel\n\t\t}\n\n\t\treturn null\n\t}\n}\n","import type { FieldDescriptor, FieldKind } from '@korajs/core'\nimport type { CollectionRecord } from '../types'\n\n/** Compares two query result sets; true means subscribers need not be notified. */\nexport type ResultsEqual = (\n\tprev: readonly CollectionRecord[],\n\tnext: readonly CollectionRecord[],\n) => boolean\n\ntype ValueEqual = (a: unknown, b: unknown) => boolean\n\n/**\n * Structural equality for any value a deserialized record can hold: primitives\n * (with `Object.is`, so NaN equals NaN), arrays, byte views (richtext and blob\n * state), Dates and plain objects (own enumerable keys, order-insensitive).\n *\n * Deserialization builds fresh arrays and objects on every query run, so a\n * reference comparison reports every structured field as changed (STORE-12) and\n * every subscriber re-renders on every unrelated write to the collection.\n */\nexport function structurallyEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) return true\n\tif (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false\n\n\tif (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {\n\t\tif (!ArrayBuffer.isView(a) || !ArrayBuffer.isView(b)) return false\n\t\treturn bytesEqual(a, b)\n\t}\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\tif (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false\n\t\tfor (let i = 0; i < a.length; i++) {\n\t\t\tif (!structurallyEqual(a[i], b[i])) return false\n\t\t}\n\t\treturn true\n\t}\n\tif (a instanceof Date || b instanceof Date) {\n\t\treturn a instanceof Date && b instanceof Date && Object.is(a.getTime(), b.getTime())\n\t}\n\n\tconst objA = a as Record<string, unknown>\n\tconst objB = b as Record<string, unknown>\n\tconst keysA = Object.keys(objA)\n\tif (keysA.length !== Object.keys(objB).length) return false\n\tfor (const key of keysA) {\n\t\tif (!Object.hasOwn(objB, key)) return false\n\t\tif (!structurallyEqual(objA[key], objB[key])) return false\n\t}\n\treturn true\n}\n\nfunction bytesEqual(a: ArrayBufferView, b: ArrayBufferView): boolean {\n\tif (a.byteLength !== b.byteLength) return false\n\tconst x = new Uint8Array(a.buffer, a.byteOffset, a.byteLength)\n\tconst y = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)\n\tfor (let i = 0; i < x.length; i++) {\n\t\tif (x[i] !== y[i]) return false\n\t}\n\treturn true\n}\n\nfunction scalarEqual(a: unknown, b: unknown): boolean {\n\treturn Object.is(a, b)\n}\n\n/**\n * The comparator for one field kind. Scalars deserialize to primitives, so\n * identity is exact for them; structured kinds deserialize to fresh containers\n * and need a structural comparison.\n */\nfunction equalityForKind(kind: FieldKind): ValueEqual {\n\tswitch (kind) {\n\t\tcase 'string':\n\t\tcase 'number':\n\t\tcase 'boolean':\n\t\tcase 'timestamp':\n\t\tcase 'enum':\n\t\t\treturn scalarEqual\n\t\tcase 'array':\n\t\tcase 'object':\n\t\tcase 'json':\n\t\tcase 'blob':\n\t\tcase 'richtext':\n\t\tcase 'secret':\n\t\t\treturn structurallyEqual\n\t\tdefault:\n\t\t\treturn structurallyEqual\n\t}\n}\n\n/**\n * Build the result-set comparator for a collection's records: per schema field,\n * the comparator for its kind; for every other key (id, createdAt, updatedAt and\n * included relations) a structural comparison.\n *\n * @param fields - The collection's field descriptors\n * @returns A comparator that is true when both result sets hold the same records,\n * in the same order, with structurally equal values\n */\nexport function createResultsEqual(fields: Record<string, FieldDescriptor>): ResultsEqual {\n\tconst perField = new Map<string, ValueEqual>()\n\tfor (const [name, descriptor] of Object.entries(fields)) {\n\t\tperField.set(name, equalityForKind(descriptor.kind))\n\t}\n\n\tconst recordEqual = (a: CollectionRecord, b: CollectionRecord): boolean => {\n\t\tconst recA = a as Record<string, unknown>\n\t\tconst recB = b as Record<string, unknown>\n\t\tconst keysA = Object.keys(recA)\n\t\tif (keysA.length !== Object.keys(recB).length) return false\n\t\tfor (const key of keysA) {\n\t\t\tif (!Object.hasOwn(recB, key)) return false\n\t\t\tconst eq = perField.get(key) ?? structurallyEqual\n\t\t\tif (!eq(recA[key], recB[key])) return false\n\t\t}\n\t\treturn true\n\t}\n\n\treturn (prev, next) => {\n\t\tif (prev === next) return true\n\t\tif (prev.length !== next.length) return false\n\t\t// Cheap pass first: a different id at any position means the set changed.\n\t\tfor (let i = 0; i < prev.length; i++) {\n\t\t\tif (prev[i]?.id !== next[i]?.id) return false\n\t\t}\n\t\tfor (let i = 0; i < prev.length; i++) {\n\t\t\tconst a = prev[i]\n\t\t\tconst b = next[i]\n\t\t\tif (a === undefined || b === undefined) return a === b\n\t\t\tif (!recordEqual(a, b)) return false\n\t\t}\n\t\treturn true\n\t}\n}\n\n/**\n * Comparator used when the collection's schema is unknown (a subscription\n * registered directly on the manager): structural comparison of every value.\n */\nexport const defaultResultsEqual: ResultsEqual = createResultsEqual({})\n","/**\n * Minimal pluralization/singularization utilities for relation name resolution.\n * Handles common English patterns — not meant to be exhaustive.\n */\n\nfunction isVowel(char: string | undefined): boolean {\n\tif (!char) return false\n\treturn 'aeiouAEIOU'.includes(char)\n}\n\n/**\n * Pluralize a word using common English rules.\n *\n * @example\n * ```\n * pluralize('project') // 'projects'\n * pluralize('category') // 'categories'\n * pluralize('match') // 'matches'\n * ```\n */\nexport function pluralize(word: string): string {\n\tif (word.endsWith('s')) return word\n\tif (word.endsWith('y') && !isVowel(word[word.length - 2])) {\n\t\treturn `${word.slice(0, -1)}ies`\n\t}\n\tif (word.endsWith('sh') || word.endsWith('ch') || word.endsWith('x') || word.endsWith('z')) {\n\t\treturn `${word}es`\n\t}\n\treturn `${word}s`\n}\n\n/**\n * Singularize a word using common English rules.\n *\n * @example\n * ```\n * singularize('projects') // 'project'\n * singularize('categories') // 'category'\n * singularize('matches') // 'match'\n * ```\n */\nexport function singularize(word: string): string {\n\tif (word.endsWith('ies') && !isVowel(word[word.length - 4])) {\n\t\treturn `${word.slice(0, -3)}y`\n\t}\n\tif (\n\t\tword.endsWith('shes') ||\n\t\tword.endsWith('ches') ||\n\t\tword.endsWith('xes') ||\n\t\tword.endsWith('zes')\n\t) {\n\t\treturn word.slice(0, -2)\n\t}\n\tif (word.endsWith('ses')) {\n\t\treturn word.slice(0, -2)\n\t}\n\tif (word.endsWith('s') && !word.endsWith('ss')) {\n\t\treturn word.slice(0, -1)\n\t}\n\treturn word\n}\n","import { QueryError } from '../errors'\nimport type { QueryDescriptor, WhereClause } from '../types'\n\n/**\n * Normalise a `where` clause to its canonical form (RT-102). This is the ONE place that\n * decides what a where value means, so the SQL the store runs, the descriptor and the\n * query key (store cache, React/Vue/Svelte bindings) always agree:\n *\n * - `undefined` means \"no condition\": `where({ projectId: undefined })` is `where({})`\n * (the usual \"nothing selected yet\" pattern), and an operator whose operand is\n * `undefined` (`{ $gt: undefined }`) is dropped; a field left with no operator is\n * dropped. A later `.where({ x: undefined })` therefore does not remove an earlier\n * condition on `x`.\n * - `null` means SQL `IS NULL` (`$ne: null` means `IS NOT NULL`).\n * - Non-finite numbers (`NaN`, `Infinity`) have no stored representation: refused.\n * - `undefined` inside a `$in` list is refused (ambiguous: no condition cannot be one\n * element of a list).\n *\n * @param where - The clause as the developer wrote it\n * @returns A new clause with the rules above applied\n * @throws {QueryError} For a non-finite number or an `undefined` `$in` element\n */\nexport function normalizeWhere(where: WhereClause): WhereClause {\n\tconst out: WhereClause = {}\n\tfor (const [field, value] of Object.entries(where)) {\n\t\tif (value === undefined) continue\n\t\tif (isOperatorObject(value)) {\n\t\t\tconst operators: Record<string, unknown> = {}\n\t\t\tfor (const [operator, operand] of Object.entries(value)) {\n\t\t\t\tif (operand === undefined) continue\n\t\t\t\toperators[operator] = normalizeOperand(field, operator, operand)\n\t\t\t}\n\t\t\tif (Object.keys(operators).length === 0) continue\n\t\t\tout[field] = operators\n\t\t\tcontinue\n\t\t}\n\t\tout[field] = normalizeOperand(field, '$eq', value)\n\t}\n\treturn out\n}\n\nfunction normalizeOperand(field: string, operator: string, operand: unknown): unknown {\n\tif (Array.isArray(operand)) {\n\t\treturn operand.map((item) => {\n\t\t\tif (item === undefined) {\n\t\t\t\tthrow new QueryError(\n\t\t\t\t\t`Invalid ${operator} list for field \"${field}\": it contains undefined. Remove the undefined element, or use null to match missing values.`,\n\t\t\t\t\t{ field, operator },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn assertFinite(field, operator, item)\n\t\t})\n\t}\n\treturn assertFinite(field, operator, operand)\n}\n\nfunction assertFinite(field: string, operator: string, value: unknown): unknown {\n\tif (typeof value === 'number' && !Number.isFinite(value)) {\n\t\tthrow new QueryError(\n\t\t\t`Invalid value for field \"${field}\" (${operator}): ${String(value)} is not a finite number and cannot match a stored value.`,\n\t\t\t{ field, operator, value: String(value) },\n\t\t)\n\t}\n\treturn value\n}\n\nfunction isOperatorObject(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n\tif (value instanceof Date || ArrayBuffer.isView(value)) return false\n\treturn true\n}\n\n/**\n * The canonical identity of a query: equal keys if and only if the descriptors run the\n * same query (RT-102). Used by the store's query-store cache and by every framework\n * binding to decide when to share a store or re-subscribe.\n *\n * Unlike `JSON.stringify`, nothing is dropped or conflated: `where` keys are sorted\n * (their order does not change the query), `undefined` is dropped exactly as\n * {@link normalizeWhere} drops it, and `NaN`, `Date` and byte values keep distinct,\n * typed encodings.\n *\n * @param descriptor - The query descriptor (`queryBuilder.getDescriptor()`)\n * @returns A string key\n */\nexport function queryKey(descriptor: QueryDescriptor): string {\n\treturn canonical({\n\t\tcollection: descriptor.collection,\n\t\twhere: normalizeWhere(descriptor.where),\n\t\torderBy: descriptor.orderBy.map((clause) => [clause.field, clause.direction]),\n\t\tlimit: descriptor.limit,\n\t\toffset: descriptor.offset,\n\t\tinclude: descriptor.include,\n\t})\n}\n\nfunction canonical(value: unknown): string {\n\tif (value === undefined) return 'u'\n\tif (value === null) return 'n'\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn JSON.stringify(value)\n\t\tcase 'number':\n\t\t\t// Distinguishes NaN, Infinity and -0 (never equal to another stored number).\n\t\t\treturn Object.is(value, -0) ? 'num:-0' : `num:${String(value)}`\n\t\tcase 'boolean':\n\t\t\treturn value ? 'true' : 'false'\n\t\tcase 'bigint':\n\t\t\treturn `big:${value.toString()}`\n\t\tdefault:\n\t\t\tbreak\n\t}\n\tif (value instanceof Date) return `date:${value.getTime()}`\n\tif (ArrayBuffer.isView(value)) {\n\t\tconst bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n\t\treturn `bytes:${Array.from(bytes).join(',')}`\n\t}\n\tif (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`\n\tif (typeof value === 'object') {\n\t\tconst entries = Object.entries(value as Record<string, unknown>)\n\t\t\t.filter(([, item]) => item !== undefined)\n\t\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\t\treturn `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(',')}}`\n\t}\n\treturn `?:${typeof value}`\n}\n","import type { Operation, SchemaDefinition } from '@korajs/core'\nimport { KoraError, encodeStoredText, quoteIdent } from '@korajs/core'\nimport type { WriteEnv, WriteScope } from '../mutations/write-context'\nimport { writeDeleteInTx, writeUpdateInTx } from '../mutations/write-ops'\nimport type { Transaction } from '../types'\nimport type { IncomingRelation } from './relation-lookup'\nimport { buildRelationLookup, getIncomingRelations } from './relation-lookup'\n\n/**\n * Error thrown when a delete is refused due to a 'restrict' referential integrity policy.\n * The error includes context about which relation caused the restriction and\n * how many referencing records exist.\n */\nexport class ReferentialIntegrityError extends KoraError {\n\tconstructor(\n\t\tcollection: string,\n\t\trecordId: string,\n\t\treferencingCollection: string,\n\t\trelationName: string,\n\t\treferencingCount: number,\n\t) {\n\t\tsuper(\n\t\t\t`Cannot delete record \"${recordId}\" from \"${collection}\": ${referencingCount} record(s) in \"${referencingCollection}\" reference it via relation \"${relationName}\" with onDelete: 'restrict'. Delete or reassign the referencing records first.`,\n\t\t\t'REFERENTIAL_INTEGRITY',\n\t\t\t{\n\t\t\t\tcollection,\n\t\t\t\trecordId,\n\t\t\t\treferencingCollection,\n\t\t\t\trelationName,\n\t\t\t\treferencingCount,\n\t\t\t},\n\t\t)\n\t\tthis.name = 'ReferentialIntegrityError'\n\t}\n}\n\n/**\n * Configuration for the RelationEnforcer.\n */\nexport interface RelationEnforcerConfig {\n\tschema: SchemaDefinition\n}\n\n/**\n * Result of enforcing referential integrity on a delete operation.\n * Contains all additional operations that were created as side effects\n * (cascaded deletes and set-null updates).\n */\nexport interface EnforcementResult {\n\t/** Additional operations created by cascading deletes and set-null updates */\n\toperations: Operation[]\n}\n\n/**\n * Enforces referential integrity constraints during local delete operations.\n *\n * When a record is deleted, this enforcer checks all relations that reference\n * the deleted record's collection and applies the appropriate onDelete policy:\n *\n * - **cascade**: Recursively deletes all referencing records\n * - **set-null**: Sets the foreign key to null on all referencing records\n * - **restrict**: Throws a ReferentialIntegrityError if any references exist\n * - **no-action**: Does nothing (the foreign key is left dangling)\n *\n * The enforcer runs inside the delete's write transaction and writes every side\n * effect through the single local write path (`writeDeleteInTx` /\n * `writeUpdateInTx`), so cascaded operations reserve their sequence numbers in\n * the same contiguous block as the parent and carry per-field version stamps\n * (STORE-2, STORE-3). Every generated operation depends causally on the delete\n * that caused it.\n *\n * @example\n * ```typescript\n * const enforcer = new RelationEnforcer({ schema })\n * // inside a write transaction, after building the parent delete operation:\n * const result = await enforcer.enforceDelete('projects', 'proj-1', scope, env, deleteOp.id)\n * // result.operations contains any cascaded delete/update ops\n * ```\n */\nexport class RelationEnforcer {\n\tprivate readonly lookup: Map<string, IncomingRelation[]>\n\n\tconstructor(config: RelationEnforcerConfig) {\n\t\tthis.lookup = buildRelationLookup(config.schema)\n\t}\n\n\t/**\n\t * Enforce referential integrity for a record being deleted.\n\t *\n\t * @param collection - The collection the deleted record belongs to\n\t * @param recordId - The ID of the deleted record\n\t * @param scope - The active write scope (transaction + causal scope)\n\t * @param env - The write environment of the delete\n\t * @param parentOpId - Id of the delete operation; every side effect depends on it\n\t * @returns All additional operations created as side effects\n\t * @throws {ReferentialIntegrityError} If a 'restrict' policy is violated\n\t */\n\tasync enforceDelete(\n\t\tcollection: string,\n\t\trecordId: string,\n\t\tscope: WriteScope,\n\t\tenv: WriteEnv,\n\t\tparentOpId: string,\n\t): Promise<EnforcementResult> {\n\t\tconst incomingRelations = getIncomingRelations(this.lookup, collection)\n\t\tif (incomingRelations.length === 0) {\n\t\t\treturn { operations: [] }\n\t\t}\n\n\t\tconst allOperations: Operation[] = []\n\n\t\t// Process relations in a deterministic order (sorted by relation name)\n\t\t// to ensure identical results regardless of Map iteration order.\n\t\tconst sortedRelations = [...incomingRelations].sort((a, b) =>\n\t\t\ta.relationName.localeCompare(b.relationName),\n\t\t)\n\n\t\tfor (const incoming of sortedRelations) {\n\t\t\tconst ops = await this.enforceRelation(incoming, recordId, scope, env, parentOpId)\n\t\t\tallOperations.push(...ops)\n\t\t}\n\n\t\treturn { operations: allOperations }\n\t}\n\n\t/**\n\t * Enforce a single relation's onDelete policy.\n\t */\n\tprivate async enforceRelation(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\tscope: WriteScope,\n\t\tenv: WriteEnv,\n\t\tparentOpId: string,\n\t): Promise<Operation[]> {\n\t\tswitch (incoming.onDelete) {\n\t\t\tcase 'cascade':\n\t\t\t\treturn this.enforceCascade(incoming, deletedRecordId, scope, env, parentOpId)\n\t\t\tcase 'set-null':\n\t\t\t\treturn this.enforceSetNull(incoming, deletedRecordId, scope, env, parentOpId)\n\t\t\tcase 'restrict':\n\t\t\t\treturn this.enforceRestrict(incoming, deletedRecordId, scope.tx)\n\t\t\tcase 'no-action':\n\t\t\t\treturn []\n\t\t}\n\t}\n\n\t/**\n\t * Cascade: delete every live record that references the deleted record. Each\n\t * cascaded delete runs the full delete path, so it recurses into its own\n\t * referencing records.\n\t */\n\tprivate async enforceCascade(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\tscope: WriteScope,\n\t\tenv: WriteEnv,\n\t\tparentOpId: string,\n\t): Promise<Operation[]> {\n\t\tconst referencingIds = await this.findReferencing(incoming, deletedRecordId, scope.tx)\n\t\tconst operations: Operation[] = []\n\t\tfor (const id of referencingIds) {\n\t\t\tconst result = await writeDeleteInTx(env, scope, incoming.sourceCollection, id, {\n\t\t\t\textraCausalDeps: [parentOpId],\n\t\t\t})\n\t\t\tif (result.operation) operations.push(result.operation)\n\t\t\toperations.push(...result.sideEffects)\n\t\t}\n\t\treturn operations\n\t}\n\n\t/**\n\t * Set-null: set the foreign key to null on every live referencing record.\n\t */\n\tprivate async enforceSetNull(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\tscope: WriteScope,\n\t\tenv: WriteEnv,\n\t\tparentOpId: string,\n\t): Promise<Operation[]> {\n\t\tconst referencingIds = await this.findReferencing(incoming, deletedRecordId, scope.tx)\n\t\tconst operations: Operation[] = []\n\t\tfor (const id of referencingIds) {\n\t\t\tconst result = await writeUpdateInTx(\n\t\t\t\tenv,\n\t\t\t\tscope,\n\t\t\t\tincoming.sourceCollection,\n\t\t\t\tid,\n\t\t\t\t{ [incoming.foreignKeyField]: null },\n\t\t\t\t[parentOpId],\n\t\t\t)\n\t\t\tif (result.operation) operations.push(result.operation)\n\t\t}\n\t\treturn operations\n\t}\n\n\t/**\n\t * Restrict: refuse the delete if any referencing records exist.\n\t */\n\tprivate async enforceRestrict(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\ttx: Transaction,\n\t): Promise<Operation[]> {\n\t\tconst { sourceCollection, foreignKeyField, relationName } = incoming\n\n\t\tconst countRows = await tx.query<{ cnt: number }>(\n\t\t\t`SELECT COUNT(*) as cnt FROM ${quoteIdent(sourceCollection)} WHERE ${quoteIdent(foreignKeyField)} = ? AND _deleted = 0`,\n\t\t\t// The foreign key column holds the stored-text form (RT-65).\n\t\t\t[encodeStoredText(deletedRecordId)],\n\t\t)\n\t\tconst count = countRows[0]?.cnt ?? 0\n\n\t\tif (count > 0) {\n\t\t\tthrow new ReferentialIntegrityError(\n\t\t\t\tincoming.relation.to,\n\t\t\t\tdeletedRecordId,\n\t\t\t\tsourceCollection,\n\t\t\t\trelationName,\n\t\t\t\tcount,\n\t\t\t)\n\t\t}\n\n\t\treturn []\n\t}\n\n\t/** Ids of live records referencing `deletedRecordId`, in id order (deterministic). */\n\tprivate async findReferencing(\n\t\tincoming: IncomingRelation,\n\t\tdeletedRecordId: string,\n\t\ttx: Transaction,\n\t): Promise<string[]> {\n\t\tconst rows = await tx.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${quoteIdent(incoming.sourceCollection)} WHERE ${quoteIdent(incoming.foreignKeyField)} = ? AND _deleted = 0 ORDER BY id`,\n\t\t\t// The foreign key column holds the stored-text form (RT-65).\n\t\t\t[encodeStoredText(deletedRecordId)],\n\t\t)\n\t\treturn rows.map((row) => row.id)\n\t}\n\n\t/**\n\t * Get the relation lookup map for external use (e.g., by the merge engine).\n\t */\n\tgetRelationLookup(): Map<string, IncomingRelation[]> {\n\t\treturn this.lookup\n\t}\n}\n","import type { OnDeleteAction, RelationDefinition, SchemaDefinition } from '@korajs/core'\n\n/**\n * A resolved relation reference: describes a relation that points TO a given collection.\n * When a record in `targetCollection` is deleted, we must handle records in\n * `sourceCollection` that reference it via `foreignKeyField`.\n */\nexport interface IncomingRelation {\n\t/** Name of the relation in the schema */\n\trelationName: string\n\t/** Collection that holds the foreign key (the \"from\" side) */\n\tsourceCollection: string\n\t/** Field in the source collection that references the target */\n\tforeignKeyField: string\n\t/** What to do when the referenced record is deleted */\n\tonDelete: OnDeleteAction\n\t/** The full relation definition */\n\trelation: RelationDefinition\n}\n\n/**\n * Builds an efficient lookup from target collection to all relations that reference it.\n *\n * Given a schema with relations like:\n * ```\n * todoBelongsToProject: { from: 'todos', to: 'projects', field: 'projectId', onDelete: 'cascade' }\n * ```\n *\n * The lookup for 'projects' would return:\n * ```\n * [{ sourceCollection: 'todos', foreignKeyField: 'projectId', onDelete: 'cascade', ... }]\n * ```\n *\n * This enables O(1) lookup when deleting a record to find all dependent relations.\n *\n * @param schema - The full schema definition containing relations\n * @returns A map from target collection name to its incoming relations\n */\nexport function buildRelationLookup(schema: SchemaDefinition): Map<string, IncomingRelation[]> {\n\tconst lookup = new Map<string, IncomingRelation[]>()\n\n\tfor (const [relationName, relation] of Object.entries(schema.relations)) {\n\t\tconst targetCollection = relation.to\n\t\tconst existing = lookup.get(targetCollection) ?? []\n\t\texisting.push({\n\t\t\trelationName,\n\t\t\tsourceCollection: relation.from,\n\t\t\tforeignKeyField: relation.field,\n\t\t\tonDelete: relation.onDelete,\n\t\t\trelation,\n\t\t})\n\t\tlookup.set(targetCollection, existing)\n\t}\n\n\treturn lookup\n}\n\n/**\n * Get all incoming relations for a given collection.\n * Returns an empty array if no relations reference the collection.\n *\n * @param lookup - The pre-built relation lookup map\n * @param collection - The target collection name\n * @returns Array of incoming relations\n */\nexport function getIncomingRelations(\n\tlookup: Map<string, IncomingRelation[]>,\n\tcollection: string,\n): IncomingRelation[] {\n\treturn lookup.get(collection) ?? []\n}\n","import {\n\tHybridLogicalClock,\n\tOperationError,\n\tfoldRecord,\n\tisFoldStateLive,\n\tmaterialize,\n} from '@korajs/core'\nimport type {\n\tCollectionDefinition,\n\tOperation,\n\tOperationTransform,\n\tSchemaDefinition,\n} from '@korajs/core'\nimport { topologicalSort } from '@korajs/core/internal'\nimport { mergeYjsUpdates } from '../fold/record-folder'\nimport { decodeRichtextFieldsFromOpData } from '../serialization/op-data-encoding'\nimport type { CollectionRecord } from '../types'\n\n/**\n * In-memory materialized state at a causal cut in the operation log.\n * Read-only — does not mutate the live store.\n */\nexport interface ReplaySnapshot {\n\t/** The operation whose causal past was replayed (inclusive). */\n\ttargetOperation: Operation\n\t/** Operations applied in causal order (ancestors + target). */\n\toperationsApplied: Operation[]\n\t/** Non-deleted records per collection after replay. */\n\tcollections: Record<string, CollectionRecord[]>\n\t/** Look up a single record at the replay cut. Returns null if deleted or missing. */\n\tfindRecord(collection: string, recordId: string): CollectionRecord | null\n}\n\ninterface MutableReplayRecord {\n\tid: string\n\tfields: Record<string, unknown>\n\tdeleted: boolean\n\tcreatedAt: number\n\tupdatedAt: number\n}\n\ntype ReplayMemoryState = Map<string, Map<string, MutableReplayRecord>>\n\n/**\n * Collect the target operation and all causal ancestors present in `allOps`.\n *\n * @param aliases - Old operation id -> the id it was re-emitted under (a renumbered\n * version-2 operation, `_kora_seq_conflicts.reemitted_as`). A dependent the server\n * already stored keeps naming the old id; the alias resolves it.\n */\nexport function collectCausalClosure(\n\tallOps: Operation[],\n\ttargetOperationId: string,\n\taliases: ReadonlyMap<string, string> = new Map(),\n): Operation[] {\n\tconst opMap = new Map<string, Operation>()\n\tfor (const op of allOps) {\n\t\topMap.set(op.id, op)\n\t}\n\n\tconst target = opMap.get(targetOperationId)\n\tif (!target) {\n\t\tthrow new OperationError(\n\t\t\t`Operation \"${targetOperationId}\" not found in the local operation log`,\n\t\t\t{\n\t\t\t\toperationId: targetOperationId,\n\t\t\t},\n\t\t)\n\t}\n\n\tconst included = new Set<string>()\n\tconst stack: string[] = [targetOperationId]\n\n\twhile (stack.length > 0) {\n\t\tconst id = stack.pop()\n\t\tif (id === undefined || included.has(id)) {\n\t\t\tcontinue\n\t\t}\n\t\tincluded.add(id)\n\t\tconst op = opMap.get(id)\n\t\tif (!op) {\n\t\t\tcontinue\n\t\t}\n\t\tfor (const dep of op.causalDeps) {\n\t\t\tlet depId = dep\n\t\t\t// Follow re-emissions (a renumbered op may itself have been renumbered again).\n\t\t\tfor (let hops = 0; !opMap.has(depId) && aliases.has(depId) && hops < 8; hops++) {\n\t\t\t\tdepId = aliases.get(depId) ?? depId\n\t\t\t}\n\t\t\tif (opMap.has(depId)) {\n\t\t\t\tstack.push(depId)\n\t\t\t}\n\t\t}\n\t}\n\n\tconst subset = allOps.filter((op) => included.has(op.id))\n\treturn topologicalSort(subset)\n}\n\n/**\n * Replay a causal subset of operations into an in-memory materialized snapshot.\n * Does not use the merge engine — concurrent ops outside the causal cut are excluded.\n */\nexport function buildReplaySnapshot(\n\tschema: SchemaDefinition,\n\tallOps: Operation[],\n\ttargetOperationId: string,\n\taliases: ReadonlyMap<string, string> = new Map(),\n\ttransforms: readonly OperationTransform[] = [],\n): ReplaySnapshot {\n\tconst operationsApplied = collectCausalClosure(allOps, targetOperationId, aliases)\n\tconst targetOperation = operationsApplied.find((op) => op.id === targetOperationId)\n\tif (!targetOperation) {\n\t\tthrow new OperationError(`Operation \"${targetOperationId}\" not found after causal sort`, {\n\t\t\toperationId: targetOperationId,\n\t\t})\n\t}\n\n\tconst memory = foldIntoMemory(operationsApplied, schema, transforms)\n\n\tconst collections = materializeCollections(schema, memory)\n\n\treturn {\n\t\ttargetOperation,\n\t\toperationsApplied,\n\t\tcollections,\n\t\tfindRecord(collection: string, recordId: string): CollectionRecord | null {\n\t\t\tconst colMap = memory.get(collection)\n\t\t\tconst record = colMap?.get(recordId)\n\t\t\tif (!record || record.deleted) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tconst definition = schema.collections[collection]\n\t\t\tif (!definition) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\treturn toCollectionRecord(record, definition)\n\t\t},\n\t}\n}\n\n/**\n * Fold every record of the causal cut with the W7 fold, exactly as the live store\n * materializes it (the cut may hold concurrent branches: the fold, not the\n * application order, decides).\n */\nfunction foldIntoMemory(\n\tops: readonly Operation[],\n\tschema: SchemaDefinition,\n\ttransforms: readonly OperationTransform[],\n): ReplayMemoryState {\n\tconst byRecord = new Map<string, Operation[]>()\n\tfor (const op of ops) {\n\t\tif (!schema.collections[op.collection]) continue\n\t\tconst key = `${op.collection}\\u0000${op.recordId}`\n\t\tconst list = byRecord.get(key) ?? []\n\t\tlist.push(op)\n\t\tbyRecord.set(key, list)\n\t}\n\tconst state: ReplayMemoryState = new Map()\n\tfor (const recordOps of byRecord.values()) {\n\t\tconst first = recordOps[0] as Operation\n\t\tconst definition = schema.collections[first.collection] as CollectionDefinition\n\t\t// The live store folds with the schema transforms (RT-84): so does time travel.\n\t\tconst folded = foldRecord(recordOps, schema, {\n\t\t\trichtext: mergeYjsUpdates,\n\t\t\t...(transforms.length > 0 ? { transforms } : {}),\n\t\t}).state\n\t\tif (folded === null || folded.cr === null || folded.u === null) continue\n\t\tconst values = materialize({ ...folded, d: null }, { richtext: mergeYjsUpdates }) ?? {}\n\t\tlet colMap = state.get(first.collection)\n\t\tif (!colMap) {\n\t\t\tcolMap = new Map()\n\t\t\tstate.set(first.collection, colMap)\n\t\t}\n\t\tcolMap.set(first.recordId, {\n\t\t\tid: first.recordId,\n\t\t\t// The fold materializes op-data form (tagged binary); snapshots expose\n\t\t\t// record-shaped values (Uint8Array / string).\n\t\t\tfields: decodeRichtextFieldsFromOpData(values, definition.fields),\n\t\t\tdeleted: !isFoldStateLive(folded),\n\t\t\tcreatedAt: HybridLogicalClock.deserialize(folded.cr.t).wallTime,\n\t\t\tupdatedAt: HybridLogicalClock.deserialize(folded.u.t).wallTime,\n\t\t})\n\t}\n\treturn state\n}\n\nfunction materializeCollections(\n\tschema: SchemaDefinition,\n\tmemory: ReplayMemoryState,\n): Record<string, CollectionRecord[]> {\n\tconst collections: Record<string, CollectionRecord[]> = {}\n\n\tfor (const [collectionName, definition] of Object.entries(schema.collections)) {\n\t\tconst colMap = memory.get(collectionName)\n\t\tconst records: CollectionRecord[] = []\n\t\tif (colMap) {\n\t\t\tfor (const record of colMap.values()) {\n\t\t\t\tif (!record.deleted) {\n\t\t\t\t\trecords.push(toCollectionRecord(record, definition))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcollections[collectionName] = records\n\t}\n\n\treturn collections\n}\n\nfunction toCollectionRecord(\n\trecord: MutableReplayRecord,\n\tdefinition: CollectionDefinition,\n): CollectionRecord {\n\tconst result: CollectionRecord = {\n\t\tid: record.id,\n\t\tcreatedAt: record.createdAt,\n\t\tupdatedAt: record.updatedAt,\n\t}\n\tfor (const [fieldName] of Object.entries(definition.fields)) {\n\t\tif (fieldName in record.fields) {\n\t\t\tresult[fieldName] = record.fields[fieldName]\n\t\t}\n\t}\n\treturn result\n}\n","import type { SequenceConfig } from '@korajs/core'\nimport { defaultSequenceFormat, formatSequenceValue } from '@korajs/core'\nimport type { StorageAdapter } from '../types'\n\ninterface SequenceRow {\n\tcounter: number\n}\n\n/**\n * Manages offline-safe sequences backed by a `_kora_sequences` table.\n *\n * Each sequence counter is scoped by (name, scope, nodeId), ensuring\n * that different devices never collide. The counter is atomically\n * incremented within a database transaction.\n *\n * @example\n * ```typescript\n * const mgr = new SequenceManager(adapter, 'node-abc')\n *\n * const receipt = await mgr.next('receipt', {\n * scope: 'store-1',\n * format: 'S-{date}-{node4}-{seq}',\n * })\n * // → \"S-20260508-node-0001\"\n * ```\n */\nexport class SequenceManager {\n\tprivate readonly adapter: StorageAdapter\n\tprivate readonly nodeId: string\n\n\tconstructor(adapter: StorageAdapter, nodeId: string) {\n\t\tthis.adapter = adapter\n\t\tthis.nodeId = nodeId\n\t}\n\n\t/**\n\t * Get the next value in a sequence, atomically incrementing the counter.\n\t *\n\t * @param name - The sequence name (e.g., 'receipt', 'invoice')\n\t * @param config - Optional configuration for scope, format, and starting value\n\t * @returns The formatted sequence value\n\t */\n\tasync next(name: string, config?: SequenceConfig): Promise<string> {\n\t\tconst scope = config?.scope ?? ''\n\t\tconst startAt = config?.startAt ?? 1\n\t\tconst format = config?.format ?? defaultSequenceFormat(name)\n\n\t\tlet counter = 0\n\n\t\tawait this.adapter.transaction(async (tx) => {\n\t\t\t// Try to read the current counter\n\t\t\tconst rows = await tx.query<SequenceRow>(\n\t\t\t\t'SELECT counter FROM _kora_sequences WHERE name = ? AND scope = ? AND node_id = ?',\n\t\t\t\t[name, scope, this.nodeId],\n\t\t\t)\n\n\t\t\tif (rows.length > 0) {\n\t\t\t\tconst row = rows[0] as SequenceRow\n\t\t\t\tcounter = row.counter + 1\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t'UPDATE _kora_sequences SET counter = ? WHERE name = ? AND scope = ? AND node_id = ?',\n\t\t\t\t\t[counter, name, scope, this.nodeId],\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\t// First use — initialize with startAt\n\t\t\t\tcounter = startAt\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t'INSERT INTO _kora_sequences (name, scope, node_id, counter) VALUES (?, ?, ?, ?)',\n\t\t\t\t\t[name, scope, this.nodeId, counter],\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\n\t\treturn formatSequenceValue(format, counter, this.nodeId)\n\t}\n\n\t/**\n\t * Get the current counter value without incrementing.\n\t *\n\t * @param name - The sequence name\n\t * @param config - Optional scope\n\t * @returns The current counter value, or 0 if the sequence has never been used\n\t */\n\tasync current(name: string, config?: { scope?: string }): Promise<number> {\n\t\tconst scope = config?.scope ?? ''\n\n\t\tconst rows = await this.adapter.query<SequenceRow>(\n\t\t\t'SELECT counter FROM _kora_sequences WHERE name = ? AND scope = ? AND node_id = ?',\n\t\t\t[name, scope, this.nodeId],\n\t\t)\n\n\t\tif (rows.length > 0) {\n\t\t\treturn (rows[0] as SequenceRow).counter\n\t\t}\n\t\treturn 0\n\t}\n\n\t/**\n\t * Reset a sequence counter.\n\t *\n\t * @param name - The sequence name\n\t * @param config - Optional scope and target value\n\t */\n\tasync reset(name: string, config?: { scope?: string; to?: number }): Promise<void> {\n\t\tconst scope = config?.scope ?? ''\n\t\tconst to = config?.to ?? 0\n\n\t\tawait this.adapter.execute(\n\t\t\t'DELETE FROM _kora_sequences WHERE name = ? AND scope = ? AND node_id = ?',\n\t\t\t[name, scope, this.nodeId],\n\t\t)\n\n\t\tif (to > 0) {\n\t\t\tawait this.adapter.execute(\n\t\t\t\t'INSERT INTO _kora_sequences (name, scope, node_id, counter) VALUES (?, ?, ?, ?)',\n\t\t\t\t[name, scope, this.nodeId, to],\n\t\t\t)\n\t\t}\n\t}\n}\n","import { quoteIdent } from '@korajs/core'\nimport type { SchemaDefinition } from '@korajs/core'\nimport type { StorageAdapter } from '../types'\nimport { isRawTextKind } from './serializer'\n\n/** `_kora_meta` key: raw-string columns hold the stored-text codec's form (RT-65). */\nexport const STORED_TEXT_CODEC_META_KEY = 'stored_text_codec'\n\n/** Version of the codec the rows are written with. */\nconst STORED_TEXT_CODEC_VERSION = '1'\n\n/**\n * Once per database: re-encode the U+FFFF of rows written before the stored-text codec\n * (RT-65) so the decoder returns them unchanged. A row written before the codec holds\n * the raw string; the only code unit whose meaning changes under the decoder is the\n * escape introducer U+FFFF (`U+FFFF` -> `U+FFFF F`). NUL needs no rewrite (better-sqlite3\n * stored it as is), and a lone surrogate a pre-codec row held was already replaced by\n * U+FFFD when it was bound, so nothing is left to recover.\n *\n * Every collection table of the schema that exists is rewritten, for the columns of its\n * raw-string fields that exist. One transaction; the meta key makes it idempotent.\n *\n * @param adapter - An open storage adapter\n * @param schema - The schema whose collection tables to migrate\n */\nexport async function ensureStoredTextCodec(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n): Promise<void> {\n\tconst rows = await adapter.query<{ value: string }>(\n\t\t'SELECT value FROM _kora_meta WHERE key = ?',\n\t\t[STORED_TEXT_CODEC_META_KEY],\n\t)\n\tif (rows[0]?.value === STORED_TEXT_CODEC_VERSION) return\n\tawait adapter.transaction(async (tx) => {\n\t\tfor (const [name, collection] of Object.entries(schema.collections)) {\n\t\t\tconst columns = new Set(\n\t\t\t\t(await tx.query<{ name: string }>(`PRAGMA table_info(${quoteIdent(name)})`)).map(\n\t\t\t\t\t(column) => column.name,\n\t\t\t\t),\n\t\t\t)\n\t\t\tif (columns.size === 0) continue\n\t\t\tfor (const [field, descriptor] of Object.entries(collection.fields)) {\n\t\t\t\tif (!isRawTextKind(descriptor.kind) || !columns.has(field)) continue\n\t\t\t\tconst column = quoteIdent(field)\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`UPDATE ${quoteIdent(name)} SET ${column} = replace(${column}, char(65535), char(65535) || 'F') WHERE instr(${column}, char(65535)) > 0`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tawait tx.execute('INSERT OR REPLACE INTO _kora_meta (key, value) VALUES (?, ?)', [\n\t\t\tSTORED_TEXT_CODEC_META_KEY,\n\t\t\tSTORED_TEXT_CODEC_VERSION,\n\t\t])\n\t})\n}\n","/**\n * Bloom filter for fast subscription dependency pre-checking.\n *\n * When the SubscriptionManager has many active subscriptions, checking whether a\n * mutation might affect any subscription requires scanning all subscriptions.\n * This bloom filter provides a fast O(k) pre-check: if the filter says \"definitely\n * not present\", we can skip the subscription entirely. If it says \"maybe present\",\n * we fall through to the precise collection/field matching.\n *\n * Uses FNV-1a for hashing and Kirsch-Mitzenmacker double hashing to derive k\n * hash functions from two base hashes.\n */\n\n// FNV-1a constants for 32-bit hashes\nconst FNV_OFFSET_BASIS = 0x811c9dc5\nconst FNV_PRIME = 0x01000193\n\n/**\n * Compute FNV-1a 32-bit hash of a string.\n *\n * FNV-1a is a non-cryptographic hash function optimized for speed and distribution.\n * It processes one byte at a time: XOR then multiply, which gives better avalanche\n * behavior than the original FNV-1 (multiply then XOR).\n *\n * @param input - The string to hash\n * @returns A 32-bit unsigned integer hash\n */\nexport function fnv1a32(input: string): number {\n\tlet hash = FNV_OFFSET_BASIS\n\tfor (let i = 0; i < input.length; i++) {\n\t\thash ^= input.charCodeAt(i)\n\t\t// Math.imul gives true 32-bit integer multiplication without overflow issues\n\t\thash = Math.imul(hash, FNV_PRIME)\n\t}\n\t// Ensure unsigned 32-bit result\n\treturn hash >>> 0\n}\n\n/**\n * Calculate the optimal number of bits for a bloom filter.\n *\n * Formula: m = -(n * ln(p)) / (ln(2)^2)\n * Rounded up to the nearest multiple of 32 for Uint32Array alignment.\n *\n * @param expectedItems - Expected number of items to insert\n * @param falsePositiveRate - Desired false positive rate (0-1)\n * @returns Number of bits, rounded to nearest 32-bit multiple (minimum 32)\n */\nexport function optimalBitCount(expectedItems: number, falsePositiveRate: number): number {\n\tif (expectedItems <= 0) return 32\n\tif (falsePositiveRate <= 0 || falsePositiveRate >= 1) return 32\n\n\tconst ln2Squared = Math.LN2 * Math.LN2\n\tconst rawBits = -(expectedItems * Math.log(falsePositiveRate)) / ln2Squared\n\n\t// Round up to nearest 32-bit multiple for Uint32Array alignment\n\tconst aligned = Math.ceil(rawBits / 32) * 32\n\treturn Math.max(32, aligned)\n}\n\n/**\n * Calculate the optimal number of hash functions for a bloom filter.\n *\n * Formula: k = (m/n) * ln(2)\n * Clamped to [1, 30] to avoid degenerate cases.\n *\n * @param bitCount - Total number of bits in the filter\n * @param expectedItems - Expected number of items to insert\n * @returns Number of hash functions, clamped to [1, 30]\n */\nexport function optimalHashCount(bitCount: number, expectedItems: number): number {\n\tif (expectedItems <= 0) return 1\n\tconst raw = (bitCount / expectedItems) * Math.LN2\n\treturn Math.max(1, Math.min(30, Math.round(raw)))\n}\n\n/**\n * Bloom filter for subscription dependency tracking.\n *\n * Each subscription adds its watched collection (and optionally fields) to the\n * filter. When a mutation arrives, we check \"collection\" and \"collection:field\"\n * keys against the filter. A negative result means no subscription cares about\n * this mutation, so we can skip the expensive per-subscription scan.\n *\n * @example\n * ```typescript\n * const filter = new SubscriptionBloomFilter(100, 0.01)\n * filter.add('todos')\n * filter.add('todos', 'completed')\n *\n * filter.mightContain('todos') // true (definitely added)\n * filter.mightContain('projects') // false (definitely not added)\n * filter.mightContain('todos', 'completed') // true (definitely added)\n * ```\n */\nexport class SubscriptionBloomFilter {\n\tprivate bits: Uint32Array\n\tprivate readonly bitCount: number\n\tprivate readonly hashCount: number\n\tprivate itemCount = 0\n\n\tconstructor(expectedItems: number, falsePositiveRate = 0.01) {\n\t\tthis.bitCount = optimalBitCount(expectedItems, falsePositiveRate)\n\t\tthis.hashCount = optimalHashCount(this.bitCount, expectedItems)\n\t\tthis.bits = new Uint32Array(this.bitCount / 32)\n\t}\n\n\t/**\n\t * Add a collection (and optional field) to the bloom filter.\n\t *\n\t * @param collection - Collection name (e.g., \"todos\")\n\t * @param field - Optional field name (e.g., \"completed\")\n\t */\n\tadd(collection: string, field?: string): void {\n\t\tconst key = field !== undefined ? `${collection}:${field}` : collection\n\t\tconst positions = this.getPositions(key)\n\t\tfor (const pos of positions) {\n\t\t\tconst wordIndex = pos >>> 5 // equivalent to Math.floor(pos / 32)\n\t\t\tconst bitIndex = pos & 31 // equivalent to pos % 32\n\t\t\tconst current = this.bits[wordIndex] ?? 0\n\t\t\tthis.bits[wordIndex] = current | (1 << bitIndex)\n\t\t}\n\t\tthis.itemCount++\n\t}\n\n\t/**\n\t * Check if a collection (and optional field) might be in the filter.\n\t *\n\t * A return value of `false` means the item is DEFINITELY NOT in the filter.\n\t * A return value of `true` means the item MIGHT be in the filter (possible false positive).\n\t *\n\t * @param collection - Collection name to check\n\t * @param field - Optional field name to check\n\t * @returns false = definitely absent, true = possibly present\n\t */\n\tmightContain(collection: string, field?: string): boolean {\n\t\tconst key = field !== undefined ? `${collection}:${field}` : collection\n\t\tconst positions = this.getPositions(key)\n\t\tfor (const pos of positions) {\n\t\t\tconst wordIndex = pos >>> 5\n\t\t\tconst bitIndex = pos & 31\n\t\t\tif (((this.bits[wordIndex] ?? 0) & (1 << bitIndex)) === 0) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t/**\n\t * Reset the bloom filter, clearing all bits and the item count.\n\t */\n\tclear(): void {\n\t\tthis.bits.fill(0)\n\t\tthis.itemCount = 0\n\t}\n\n\t/**\n\t * Estimate the current false positive rate based on the number of items inserted.\n\t *\n\t * Formula: (1 - e^(-kn/m))^k\n\t * where k = hash count, n = item count, m = bit count.\n\t *\n\t * @returns Estimated false positive rate as a number between 0 and 1\n\t */\n\testimatedFalsePositiveRate(): number {\n\t\tif (this.itemCount === 0) return 0\n\t\tconst exponent = -(this.hashCount * this.itemCount) / this.bitCount\n\t\treturn (1 - Math.exp(exponent)) ** this.hashCount\n\t}\n\n\t/**\n\t * @returns The number of items that have been added to the filter\n\t */\n\tgetItemCount(): number {\n\t\treturn this.itemCount\n\t}\n\n\t/**\n\t * @returns The total number of bits in the filter\n\t */\n\tgetBitCount(): number {\n\t\treturn this.bitCount\n\t}\n\n\t/**\n\t * @returns The number of hash functions used\n\t */\n\tgetHashCount(): number {\n\t\treturn this.hashCount\n\t}\n\n\t/**\n\t * Count the number of bits currently set to 1.\n\t * Uses Brian Kernighan's algorithm: each iteration clears the lowest set bit,\n\t * so the loop runs exactly as many times as there are set bits.\n\t *\n\t * @returns Number of bits set to 1\n\t */\n\tgetSetBitCount(): number {\n\t\tlet count = 0\n\t\tfor (let i = 0; i < this.bits.length; i++) {\n\t\t\tlet word = this.bits[i] ?? 0\n\t\t\twhile (word !== 0) {\n\t\t\t\t// Clear the lowest set bit: n & (n - 1) removes the rightmost 1-bit\n\t\t\t\tword &= word - 1\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t\treturn count\n\t}\n\n\t/**\n\t * Compute k bit positions for a given key using Kirsch-Mitzenmacker double hashing.\n\t *\n\t * Instead of computing k independent hash functions, we compute two base hashes\n\t * (h1 and h2) and derive the rest as: h_i = (h1 + i * h2) mod m.\n\t * This technique is proven to have the same asymptotic false positive rate as\n\t * k independent hash functions.\n\t *\n\t * We derive h1 and h2 from a single FNV-1a hash by splitting and mixing:\n\t * h1 = fnv1a(key), h2 = fnv1a(key + \"\\0salt\") to ensure independence.\n\t */\n\tprivate getPositions(key: string): number[] {\n\t\tconst h1 = fnv1a32(key)\n\t\t// Use a null-byte separator + salt suffix to derive a second independent hash\n\t\tconst h2 = fnv1a32(`${key}\\0bloom`)\n\n\t\tconst positions = new Array<number>(this.hashCount)\n\t\tfor (let i = 0; i < this.hashCount; i++) {\n\t\t\t// Combine h1 and h2 with Kirsch-Mitzenmacker technique\n\t\t\tpositions[i] = ((h1 + Math.imul(i, h2)) >>> 0) % this.bitCount\n\t\t}\n\t\treturn positions\n\t}\n}\n","import type { Operation } from '@korajs/core'\nimport { QueryError } from '../errors'\nimport type {\n\tCollectionRecord,\n\tQueryDescriptor,\n\tQueryErrorPhase,\n\tQuerySubscriptionError,\n\tSubscribeOptions,\n\tSubscription,\n\tSubscriptionCallback,\n} from '../types'\nimport { SubscriptionBloomFilter } from './bloom-filter'\nimport { type ResultsEqual, defaultResultsEqual } from './result-equality'\n\n/**\n * Per-subscription options accepted by `register` / `registerAndFetch`.\n */\nexport interface RegisterOptions extends SubscribeOptions {\n\t/** Result-set comparator; defaults to structural comparison of every value. */\n\tresultsEqual?: ResultsEqual\n}\n\nlet nextSubId = 0\n\n/**\n * Default threshold for activating bloom filter-based dependency tracking.\n * Below this count, linear scanning is faster due to bloom filter rebuild overhead.\n */\nconst DEFAULT_BLOOM_THRESHOLD = 100\n\n/**\n * Default expected items for bloom filter sizing.\n * Sized to handle typical subscription dependency counts with headroom.\n */\nconst DEFAULT_BLOOM_EXPECTED_ITEMS = 500\n\n/**\n * Default false positive rate for bloom filter.\n * 1% provides a good balance between filter size and accuracy.\n */\nconst DEFAULT_BLOOM_FALSE_POSITIVE_RATE = 0.01\n\n/**\n * Configuration options for the SubscriptionManager.\n */\nexport interface SubscriptionManagerOptions {\n\t/**\n\t * Minimum number of subscriptions before activating bloom filter.\n\t * Below this threshold, linear scanning is used (bloom filter overhead not worth it).\n\t * @default 100\n\t */\n\tbloomThreshold?: number\n\n\t/**\n\t * Expected number of unique collection+field dependencies for bloom filter sizing.\n\t * @default 500\n\t */\n\tbloomExpectedItems?: number\n\n\t/**\n\t * Target false positive rate for the bloom filter.\n\t * Lower values require more memory but reduce unnecessary precise checks.\n\t * @default 0.01\n\t */\n\tbloomFalsePositiveRate?: number\n\n\t/** Called when a query subscription is registered (e.g. to register sync query subsets). */\n\tonQuerySubscribed?: (descriptor: QueryDescriptor) => () => void\n\n\t/**\n\t * Called for every subscription failure (the store emits `query:error`), in\n\t * addition to the subscriber's own `onError`.\n\t */\n\tonQueryError?: (failure: QuerySubscriptionError) => void\n}\n\n/**\n * A committed change to the rows of one collection that can affect query results\n * (RT-98). Every invalidation the store makes produces one: local writes and remote\n * applies (with the operation), and changes made without a new operation (rejection\n * re-folds, scope retraction, cascade settling, rematerialization, backup restore,\n * held/discarded writes).\n */\nexport interface RecordsChange {\n\t/** Collection whose rows changed */\n\treadonly collection: string\n\t/** Changed record ids, or null when unknown (treat the whole collection as changed) */\n\treadonly ids: readonly string[] | null\n\t/** The operation that caused the change, when there is one */\n\treadonly operation?: Operation\n}\n\n/** Listener for {@link RecordsChange}s made by this runtime (not those relayed from peers). */\nexport type RecordsChangeListener = (change: RecordsChange) => void\n\n/**\n * Performance statistics for monitoring subscription checking efficiency.\n */\nexport interface SubscriptionStats {\n\t/** Total number of mutation notifications processed */\n\ttotalChecks: number\n\t/** Number of times bloom filter said \"maybe\" (proceeded to precise check) */\n\tbloomFilterHits: number\n\t/** Number of times bloom filter said \"definitely not\" (skipped all subscriptions) */\n\tbloomFilterMisses: number\n\t/** Number of times bloom filter said \"maybe\" but precise check found no match */\n\tfalsePositives: number\n\t/** Average time per check in milliseconds */\n\taverageCheckTimeMs: number\n\t/** Whether bloom filter is currently active */\n\tbloomFilterActive: boolean\n\t/** Current subscription count */\n\tsubscriptionCount: number\n}\n\n/**\n * Manages reactive subscriptions with two-level dependency checking.\n *\n * When a mutation occurs on a collection, affected subscriptions are re-evaluated\n * in a microtask batch and callbacks are invoked only if results actually changed.\n *\n * For large subscription counts (>= bloomThreshold), a bloom filter provides O(k)\n * pre-filtering to avoid scanning all subscriptions on every mutation:\n *\n * Level 1 (Bloom filter): Fast O(k) check -- does this mutation potentially affect\n * any subscription? If NO: skip all subscriptions (guaranteed correct).\n * If MAYBE: proceed to Level 2.\n *\n * Level 2 (Precise check): Only evaluate subscriptions that match the mutated\n * collection, including included (related) collection tracking.\n */\nexport class SubscriptionManager {\n\tprivate subscriptions = new Map<string, Subscription>()\n\tprivate pendingCollections = new Set<string>()\n\tprivate flushScheduled = false\n\tprivate readonly onQuerySubscribed?: (descriptor: QueryDescriptor) => () => void\n\tprivate readonly onQueryError?: (failure: QuerySubscriptionError) => void\n\tprivate readonly changeListeners = new Set<RecordsChangeListener>()\n\t/**\n\t * Collections changed before the first change listener attached (a store's open:\n\t * rematerialization, migration backfills). Replayed to that listener, so other tabs\n\t * hear about changes made while this tab was still opening. Bounded by the schema.\n\t */\n\tprivate unheardCollections: Set<string> | null = new Set()\n\n\t// Bloom filter state\n\tprivate bloomFilter: SubscriptionBloomFilter | null = null\n\tprivate bloomDirty = false\n\tprivate readonly bloomThreshold: number\n\tprivate readonly bloomExpectedItems: number\n\tprivate readonly bloomFalsePositiveRate: number\n\n\t// Performance stats\n\tprivate totalChecks = 0\n\tprivate bloomFilterHits = 0\n\tprivate bloomFilterMisses = 0\n\tprivate falsePositives = 0\n\tprivate totalCheckTimeMs = 0\n\n\tconstructor(options?: SubscriptionManagerOptions) {\n\t\tthis.bloomThreshold = options?.bloomThreshold ?? DEFAULT_BLOOM_THRESHOLD\n\t\tthis.bloomExpectedItems = options?.bloomExpectedItems ?? DEFAULT_BLOOM_EXPECTED_ITEMS\n\t\tthis.bloomFalsePositiveRate =\n\t\t\toptions?.bloomFalsePositiveRate ?? DEFAULT_BLOOM_FALSE_POSITIVE_RATE\n\t\tthis.onQuerySubscribed = options?.onQuerySubscribed\n\t\tthis.onQueryError = options?.onQueryError\n\t}\n\n\t/**\n\t * Register a new subscription.\n\t *\n\t * @param descriptor - The query descriptor defining what this subscription watches\n\t * @param callback - Called with results whenever they change\n\t * @param executeFn - Function to re-execute the query and get current results\n\t * @returns An unsubscribe function\n\t */\n\tregister(\n\t\tdescriptor: QueryDescriptor,\n\t\tcallback: SubscriptionCallback<CollectionRecord>,\n\t\texecuteFn: () => Promise<CollectionRecord[]>,\n\t\toptions?: RegisterOptions,\n\t): () => void {\n\t\t// No initial run: the empty baseline counts as delivered, so a flush only\n\t\t// notifies when the results differ from it.\n\t\tconst subscription = this.createSubscription(descriptor, callback, executeFn, options)\n\t\tsubscription.delivered = true\n\t\treturn this.track(subscription)\n\t}\n\n\t/**\n\t * Register a subscription and immediately execute the query.\n\t * The initial results are stored as lastResults so subsequent flushes\n\t * correctly diff against the initial state. A failing initial run is reported\n\t * through `options.onError` and the `query:error` hook, never as an unhandled\n\t * rejection (STORE-12).\n\t *\n\t * @returns An unsubscribe function\n\t */\n\tregisterAndFetch(\n\t\tdescriptor: QueryDescriptor,\n\t\tcallback: SubscriptionCallback<CollectionRecord>,\n\t\texecuteFn: () => Promise<CollectionRecord[]>,\n\t\toptions?: RegisterOptions,\n\t): () => void {\n\t\tconst subscription = this.createSubscription(descriptor, callback, executeFn, options)\n\t\tconst unsubscribe = this.track(subscription)\n\t\tvoid this.run(subscription)\n\t\treturn unsubscribe\n\t}\n\n\tprivate createSubscription(\n\t\tdescriptor: QueryDescriptor,\n\t\tcallback: SubscriptionCallback<CollectionRecord>,\n\t\texecuteFn: () => Promise<CollectionRecord[]>,\n\t\toptions: RegisterOptions | undefined,\n\t): Subscription {\n\t\treturn {\n\t\t\tid: `sub_${++nextSubId}`,\n\t\t\tdescriptor,\n\t\t\tcallback,\n\t\t\texecuteFn,\n\t\t\tlastResults: [],\n\t\t\tresultsEqual: options?.resultsEqual ?? defaultResultsEqual,\n\t\t\tonError: options?.onError,\n\t\t\trunsStarted: 0,\n\t\t\tlastAppliedRun: 0,\n\t\t\terrored: false,\n\t\t\tdelivered: false,\n\t\t}\n\t}\n\n\tprivate track(subscription: Subscription): () => void {\n\t\tconst id = subscription.id\n\t\tthis.subscriptions.set(id, subscription)\n\n\t\t// Mark bloom filter as needing rebuild since dependencies changed\n\t\tthis.bloomDirty = true\n\n\t\tconst externalCleanup = this.onQuerySubscribed?.(subscription.descriptor)\n\n\t\treturn () => {\n\t\t\tif (!this.subscriptions.delete(id)) return\n\t\t\tthis.bloomDirty = true\n\t\t\texternalCleanup?.()\n\t\t}\n\t}\n\n\t/**\n\t * Run a subscription's query and deliver the result when it changed. Never\n\t * throws: failures go to the error channel. Runs are numbered so a slow,\n\t * older run never overwrites the result of a newer one.\n\t */\n\tprivate async run(sub: Subscription): Promise<void> {\n\t\tconst runNumber = (sub.runsStarted ?? 0) + 1\n\t\tsub.runsStarted = runNumber\n\t\tlet results: CollectionRecord[]\n\t\ttry {\n\t\t\tresults = await sub.executeFn()\n\t\t} catch (error) {\n\t\t\tif (!this.isCurrent(sub, runNumber)) return\n\t\t\tsub.lastAppliedRun = runNumber\n\t\t\tsub.errored = true\n\t\t\tthis.reportError(sub, error, sub.delivered ? 'refresh' : 'initial')\n\t\t\treturn\n\t\t}\n\t\tif (!this.isCurrent(sub, runNumber)) return\n\t\tsub.lastAppliedRun = runNumber\n\n\t\t// After a failure, the next success is always delivered (even when equal to\n\t\t// the last results) so bindings can leave their error state.\n\t\tconst equal = sub.resultsEqual ?? defaultResultsEqual\n\t\tif (sub.delivered && !sub.errored && equal(sub.lastResults, results)) return\n\n\t\tsub.lastResults = results\n\t\tsub.delivered = true\n\t\tsub.errored = false\n\t\ttry {\n\t\t\tsub.callback(results)\n\t\t} catch (error) {\n\t\t\tthis.reportError(sub, error, 'callback')\n\t\t}\n\t}\n\n\tprivate isCurrent(sub: Subscription, runNumber: number): boolean {\n\t\treturn this.subscriptions.get(sub.id) === sub && runNumber > (sub.lastAppliedRun ?? 0)\n\t}\n\n\tprivate reportError(sub: Subscription, thrown: unknown, phase: QueryErrorPhase): void {\n\t\tconst error =\n\t\t\tthrown instanceof Error\n\t\t\t\t? thrown\n\t\t\t\t: new QueryError(`Query subscription failed: ${String(thrown)}`, {\n\t\t\t\t\t\tcollection: sub.descriptor.collection,\n\t\t\t\t\t})\n\t\tconst failure: QuerySubscriptionError = {\n\t\t\terror,\n\t\t\tphase,\n\t\t\tcollection: sub.descriptor.collection,\n\t\t\tqueryId: sub.id,\n\t\t}\n\t\ttry {\n\t\t\tthis.onQueryError?.(failure)\n\t\t} catch (hookError) {\n\t\t\tconsole.error('[kora] query:error listener threw', hookError)\n\t\t}\n\t\tif (sub.onError) {\n\t\t\ttry {\n\t\t\t\tsub.onError(failure)\n\t\t\t} catch (handlerError) {\n\t\t\t\tconsole.error('[kora] subscription onError handler threw', handlerError)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t// No subscriber handler: log so the failure is never silent.\n\t\tconsole.error(\n\t\t\t`[kora] Query subscription ${sub.id} on \"${sub.descriptor.collection}\" failed (${phase}). Pass subscribe(cb, { onError }) to handle it.`,\n\t\t\terror,\n\t\t)\n\t}\n\n\t/**\n\t * Notify the manager that a mutation occurred on a collection.\n\t * Schedules a microtask flush to batch multiple mutations in the same tick.\n\t */\n\tnotify(collection: string, operation: Operation): void {\n\t\tthis.recordsChanged({ collection, ids: [operation.recordId], operation })\n\t}\n\n\t/**\n\t * Invalidate a collection after a local-view change that has no domain operation\n\t * (a re-fold, a retraction, a restore). Pass the record ids when known.\n\t */\n\tinvalidate(collection: string, ids: readonly string[] | null = null): void {\n\t\tthis.recordsChanged({ collection, ids })\n\t}\n\n\t/**\n\t * The single entry point for a committed change made by this runtime (RT-98): it\n\t * schedules the affected queries and tells every change listener (the cross-tab\n\t * bus), so no invalidation path can reach this tab's queries without reaching the\n\t * other tabs' too.\n\t */\n\trecordsChanged(change: RecordsChange): void {\n\t\tthis.pendingCollections.add(change.collection)\n\t\tthis.scheduleFlush()\n\t\tif (this.unheardCollections) this.unheardCollections.add(change.collection)\n\t\tfor (const listener of this.changeListeners) {\n\t\t\ttry {\n\t\t\t\tlistener(change)\n\t\t\t} catch (error) {\n\t\t\t\t// A failing listener must not stop this tab's queries or other listeners.\n\t\t\t\tconsole.error('[kora] records-change listener failed', error)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Invalidate a collection for a change another runtime made to the shared\n\t * database. Not relayed to change listeners (the peer already broadcast it).\n\t */\n\tinvalidateFromPeer(collection: string): void {\n\t\tthis.pendingCollections.add(collection)\n\t\tthis.scheduleFlush()\n\t}\n\n\t/**\n\t * Listen to every committed change this runtime makes.\n\t *\n\t * @returns An unsubscribe function\n\t */\n\tonRecordsChanged(listener: RecordsChangeListener): () => void {\n\t\tthis.changeListeners.add(listener)\n\t\tconst unheard = this.unheardCollections\n\t\tthis.unheardCollections = null\n\t\tfor (const collection of unheard ?? []) {\n\t\t\ttry {\n\t\t\t\tlistener({ collection, ids: null })\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[kora] records-change listener failed', error)\n\t\t\t}\n\t\t}\n\t\treturn () => {\n\t\t\tthis.changeListeners.delete(listener)\n\t\t}\n\t}\n\n\t/**\n\t * Immediately flush all pending notifications.\n\t * Useful for testing. In production, flushing happens via microtask.\n\t */\n\tasync flush(): Promise<void> {\n\t\tif (this.pendingCollections.size === 0) return\n\n\t\tconst collections = new Set(this.pendingCollections)\n\t\tthis.pendingCollections.clear()\n\t\tthis.flushScheduled = false\n\n\t\tconst affected = this.findAffectedSubscriptions(collections)\n\n\t\t// Re-execute and diff. run() never throws: failures reach the error channel.\n\t\tfor (const sub of affected) {\n\t\t\tawait this.run(sub)\n\t\t}\n\t}\n\n\t/**\n\t * Remove all subscriptions. Called on store close.\n\t */\n\tclear(): void {\n\t\tthis.subscriptions.clear()\n\t\tthis.pendingCollections.clear()\n\t\tthis.flushScheduled = false\n\t\tthis.bloomFilter = null\n\t\tthis.bloomDirty = false\n\t\tthis.totalChecks = 0\n\t\tthis.bloomFilterHits = 0\n\t\tthis.bloomFilterMisses = 0\n\t\tthis.falsePositives = 0\n\t\tthis.totalCheckTimeMs = 0\n\t}\n\n\t/** Number of active subscriptions (for testing/debugging) */\n\tget size(): number {\n\t\treturn this.subscriptions.size\n\t}\n\n\t/**\n\t * Get performance statistics for monitoring subscription checking efficiency.\n\t * Useful for DevTools integration and performance tuning.\n\t */\n\tgetStats(): SubscriptionStats {\n\t\treturn {\n\t\t\ttotalChecks: this.totalChecks,\n\t\t\tbloomFilterHits: this.bloomFilterHits,\n\t\t\tbloomFilterMisses: this.bloomFilterMisses,\n\t\t\tfalsePositives: this.falsePositives,\n\t\t\taverageCheckTimeMs: this.totalChecks > 0 ? this.totalCheckTimeMs / this.totalChecks : 0,\n\t\t\tbloomFilterActive: this.isBloomActive(),\n\t\t\tsubscriptionCount: this.subscriptions.size,\n\t\t}\n\t}\n\n\t/**\n\t * Check if bloom filter is currently active.\n\t * Active when subscription count meets or exceeds the threshold.\n\t */\n\tisBloomActive(): boolean {\n\t\treturn this.subscriptions.size >= this.bloomThreshold\n\t}\n\n\t/**\n\t * Find subscriptions affected by mutations to the given collections.\n\t * Uses two-level checking when bloom filter is active:\n\t *\n\t * Level 1: Bloom filter pre-check -- if no subscription depends on any\n\t * of the mutated collections, skip everything (O(k) per collection).\n\t *\n\t * Level 2: Precise check -- linear scan of subscriptions, matching\n\t * against the mutated collections.\n\t */\n\tprivate findAffectedSubscriptions(collections: Set<string>): Subscription[] {\n\t\tconst startTime = performance.now()\n\t\tthis.totalChecks++\n\n\t\tconst useBloom = this.isBloomActive()\n\n\t\tif (useBloom) {\n\t\t\t// Rebuild bloom filter if dependencies have changed\n\t\t\tif (this.bloomDirty || this.bloomFilter === null) {\n\t\t\t\tthis.rebuildBloomFilter()\n\t\t\t}\n\n\t\t\tconst filter = this.bloomFilter\n\t\t\tif (filter !== null) {\n\t\t\t\t// Level 1: Bloom filter pre-check\n\t\t\t\tlet anyPossibleMatch = false\n\t\t\t\tfor (const col of collections) {\n\t\t\t\t\tif (filter.mightContain(col)) {\n\t\t\t\t\t\tanyPossibleMatch = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!anyPossibleMatch) {\n\t\t\t\t\t// Bloom filter guarantees no subscription depends on these collections\n\t\t\t\t\tthis.bloomFilterMisses++\n\t\t\t\t\tthis.totalCheckTimeMs += performance.now() - startTime\n\t\t\t\t\treturn []\n\t\t\t\t}\n\n\t\t\t\tthis.bloomFilterHits++\n\t\t\t}\n\t\t}\n\n\t\t// Level 2: Precise check (or only check when bloom is not active)\n\t\tconst affected: Subscription[] = []\n\t\tlet anyPreciseMatch = false\n\n\t\tfor (const sub of this.subscriptions.values()) {\n\t\t\tif (collections.has(sub.descriptor.collection)) {\n\t\t\t\taffected.push(sub)\n\t\t\t\tanyPreciseMatch = true\n\t\t\t} else if (sub.descriptor.includeCollections) {\n\t\t\t\t// Re-evaluate if a mutation affects an included (related) collection\n\t\t\t\tfor (const incCol of sub.descriptor.includeCollections) {\n\t\t\t\t\tif (collections.has(incCol)) {\n\t\t\t\t\t\taffected.push(sub)\n\t\t\t\t\t\tanyPreciseMatch = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Track false positives: bloom said \"maybe\" but precise check found nothing\n\t\tif (useBloom && !anyPreciseMatch) {\n\t\t\tthis.falsePositives++\n\t\t}\n\n\t\tthis.totalCheckTimeMs += performance.now() - startTime\n\t\treturn affected\n\t}\n\n\t/**\n\t * Rebuild the bloom filter from all current subscriptions.\n\t * Adds collection-level dependencies for every subscription, plus\n\t * any included collection dependencies.\n\t */\n\tprivate rebuildBloomFilter(): void {\n\t\tconst filter = new SubscriptionBloomFilter(this.bloomExpectedItems, this.bloomFalsePositiveRate)\n\n\t\tfor (const sub of this.subscriptions.values()) {\n\t\t\t// Add the primary collection dependency\n\t\t\tfilter.add(sub.descriptor.collection)\n\n\t\t\t// Add included (related) collection dependencies\n\t\t\tif (sub.descriptor.includeCollections) {\n\t\t\t\tfor (const incCol of sub.descriptor.includeCollections) {\n\t\t\t\t\tfilter.add(incCol)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.bloomFilter = filter\n\t\tthis.bloomDirty = false\n\t}\n\n\tprivate scheduleFlush(): void {\n\t\tif (this.flushScheduled) return\n\t\tthis.flushScheduled = true\n\t\tqueueMicrotask(() => {\n\t\t\t// flush() cannot reject: run() routes every failure to the error channel.\n\t\t\tvoid this.flush()\n\t\t})\n\t}\n}\n","import { HybridLogicalClock, MAX_LOGICAL, quoteIdent } from '@korajs/core'\nimport type { HLCTimestamp, Operation, SchemaDefinition } from '@korajs/core'\nimport { parseFieldVersions, serializeFieldVersions } from '../lww/field-versions'\nimport { serializeRowVersion } from '../lww/row-version'\nimport { buildInsertQuery } from '../query/sql-builder'\nimport { deserializeOperationWithCollection, serializeOperation } from '../serialization/serializer'\nimport type { OperationRow, RawCollectionRow, StorageAdapter } from '../types'\nimport { rehashOperation } from './rehash-operation'\n\n/**\n * Result of re-stamping unsynced operations after a clock correction.\n */\nexport interface ClockRebaseResult {\n\t/** The rewritten operations, in causal order (original HLC total order preserved). */\n\toperations: Operation[]\n\t/** Maps each old (pre-rebase) operation id to its new content-addressed id. */\n\tidMapping: Record<string, string>\n\t/** Number of operations that were re-stamped. */\n\trebasedCount: number\n\t/** Highest timestamp assigned during the rebase, or null when nothing was rebased. */\n\tnewMaxTimestamp: HLCTimestamp | null\n}\n\n/**\n * The serialized logical counter is zero-padded to 5 digits; a logical value\n * needing more digits would break the lexicographic ordering of the stored\n * timestamp / `_version` columns. Overflow spills into wallTime instead.\n * Derived from the clock's own cap so the two can never drift apart.\n */\nconst LOGICAL_COUNTER_LIMIT = MAX_LOGICAL + 1\n\nfunction emptyResult(): ClockRebaseResult {\n\treturn { operations: [], idMapping: {}, rebasedCount: 0, newMaxTimestamp: null }\n}\n\n/**\n * Re-stamp unsynced (never server-acknowledged) operations after a fast device\n * clock was corrected, so sync can resume immediately instead of waiting for\n * real time to catch up with the future timestamps.\n *\n * This is safe for exactly the same reason rewriting unpushed git commits is\n * safe: unacknowledged operations have never been shared, so no other replica\n * can hold a reference to their old ids or timestamps. Acknowledged operations\n * are immutable forever and are never touched here.\n *\n * The relative order of the rebased operations is preserved: they are sorted by\n * their original HLC total order and assigned consecutive logical counters on a\n * single new wall time, chosen to sort after every non-rebased operation in the\n * log (and after corrected \"now\").\n */\nexport async function rebaseUnsyncedOperationsInLog(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tunsyncedOpIds: string[],\n\tcorrectedNowMs: number,\n): Promise<ClockRebaseResult> {\n\tif (unsyncedOpIds.length === 0) {\n\t\treturn emptyResult()\n\t}\n\tconst rebaseIds = new Set(unsyncedOpIds)\n\n\t// Read phase. A single full scan per collection serves two purposes at once:\n\t// locating the rebased rows and finding the max timestamp of everything else.\n\t// This avoids SQL IN-list size limits and keeps the logic trivially correct\n\t// (correctness over performance; the op log is compacted periodically anyway).\n\tconst rebased: Operation[] = []\n\t// Serialized HLC strings sort lexicographically in the same order as\n\t// HybridLogicalClock.compare, so a plain string max is a timestamp max.\n\tlet maxOtherSerializedTs: string | null = null\n\n\tfor (const collectionName of Object.keys(schema.collections)) {\n\t\tconst rows = await adapter.query<OperationRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)}`,\n\t\t)\n\t\tfor (const row of rows) {\n\t\t\tif (rebaseIds.has(row.id)) {\n\t\t\t\trebased.push(deserializeOperationWithCollection(row, collectionName))\n\t\t\t} else if (maxOtherSerializedTs === null || row.timestamp > maxOtherSerializedTs) {\n\t\t\t\tmaxOtherSerializedTs = row.timestamp\n\t\t\t}\n\t\t}\n\t}\n\n\tif (rebased.length === 0) {\n\t\treturn emptyResult()\n\t}\n\n\t// The new wall time must sort after both corrected real time and every\n\t// operation that stays in the log, or the rebased ops could lose LWW\n\t// conflicts they previously won locally (silent data reordering).\n\tconst maxOtherWallTime =\n\t\tmaxOtherSerializedTs === null\n\t\t\t? Number.NEGATIVE_INFINITY\n\t\t\t: HybridLogicalClock.deserialize(maxOtherSerializedTs).wallTime\n\tconst baseWallTime = Math.max(correctedNowMs, maxOtherWallTime + 1)\n\n\t// Preserve the ORIGINAL total order so causal relationships (dep before\n\t// dependent) survive the re-stamp.\n\trebased.sort((a, b) => HybridLogicalClock.compare(a.timestamp, b.timestamp))\n\n\tconst newTimestamps: HLCTimestamp[] = rebased.map((op, i) => ({\n\t\t// Spill into wallTime past the 5-digit logical serialization limit so the\n\t\t// serialized order stays correct even for enormous offline queues.\n\t\twallTime: baseWallTime + Math.floor(i / LOGICAL_COUNTER_LIMIT),\n\t\tlogical: i % LOGICAL_COUNTER_LIMIT,\n\t\tnodeId: op.nodeId,\n\t}))\n\n\t// Recompute content-addressed ids in the original (causal) order. A version-2 id\n\t// (protocol v2, CORE-1) covers causalDeps, so each dependency's new id must be known\n\t// before its dependents are hashed: deps among the rebased set are remapped first.\n\t// Deps on non-rebased (already acknowledged or foreign) operations keep their ids.\n\t// Each operation keeps its own hash version: a version-1 operation (written before\n\t// beta.13) is re-hashed with version 1. The deserialized `data` has the embedded\n\t// metadata keys already stripped, matching exactly what the creation path hashed.\n\tconst idMapping: Record<string, string> = {}\n\tconst newOperations: Operation[] = []\n\tfor (let i = 0; i < rebased.length; i++) {\n\t\tconst op = rebased[i]\n\t\tconst ts = newTimestamps[i]\n\t\tif (!op || !ts) {\n\t\t\tcontinue\n\t\t}\n\t\tconst causalDeps = op.causalDeps.map((dep) => idMapping[dep] ?? dep)\n\t\tconst newId = await rehashOperation({ ...op, timestamp: ts, causalDeps })\n\t\tidMapping[op.id] = newId\n\t\tnewOperations.push({ ...op, id: newId, timestamp: ts, causalDeps })\n\t}\n\n\t// Write phase: one transaction so a crash can never leave the log with a\n\t// mix of old and new stamps (which would corrupt causal deps).\n\tawait adapter.transaction(async (tx) => {\n\t\tfor (let i = 0; i < rebased.length; i++) {\n\t\t\tconst oldOp = rebased[i]\n\t\t\tconst newOp = newOperations[i]\n\t\t\tif (!oldOp || !newOp) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst opsTable = `_kora_ops_${oldOp.collection}`\n\t\t\tawait tx.execute(`DELETE FROM ${quoteIdent(opsTable)} WHERE id = ?`, [oldOp.id])\n\t\t\tconst opInsert = buildInsertQuery(\n\t\t\t\topsTable,\n\t\t\t\tserializeOperation(newOp) as unknown as Record<string, unknown>,\n\t\t\t)\n\t\t\tawait tx.execute(opInsert.sql, opInsert.params)\n\n\t\t\t// Only touch materialized rows whose current version stamp came from\n\t\t\t// this exact operation — a row last written by a different (newer,\n\t\t\t// non-rebased) op must keep its version, or LWW guards would lie.\n\t\t\tconst oldVersion = serializeRowVersion(oldOp.timestamp)\n\t\t\tconst newVersion = serializeRowVersion(newOp.timestamp)\n\t\t\tawait tx.execute(\n\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _version = ?, _updated_at = ? WHERE id = ? AND _version = ?`,\n\t\t\t\t[newVersion, newOp.timestamp.wallTime, oldOp.recordId, oldVersion],\n\t\t\t)\n\n\t\t\t// Per-field versions stamped by this operation carry the same old (pre-\n\t\t\t// rebase) version string, so re-stamp them too — otherwise field-level\n\t\t\t// LWW would keep comparing against the uncorrected timestamp forever.\n\t\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t\t`SELECT _field_versions FROM ${quoteIdent(oldOp.collection)} WHERE id = ?`,\n\t\t\t\t[oldOp.recordId],\n\t\t\t)\n\t\t\tconst fieldVersions = parseFieldVersions(rows[0]?._field_versions)\n\t\t\tlet changed = false\n\t\t\tfor (const [field, version] of Object.entries(fieldVersions)) {\n\t\t\t\tif (version === oldVersion) {\n\t\t\t\t\tfieldVersions[field] = newVersion\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (changed) {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _field_versions = ? WHERE id = ?`,\n\t\t\t\t\t[serializeFieldVersions(fieldVersions), oldOp.recordId],\n\t\t\t\t)\n\t\t\t}\n\n\t\t\t// The insert op also stamped `_created_at` (the developer-visible\n\t\t\t// `createdAt`). Replicas materialize it from the rebased op's corrected\n\t\t\t// wallTime, so the originating device must re-stamp its own row too or\n\t\t\t// `createdAt` diverges forever after a clock rebase. Match on the old\n\t\t\t// (pre-rebase) created time so only rows this op created are touched.\n\t\t\tif (oldOp.type === 'insert') {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _created_at = ? WHERE id = ? AND _created_at = ?`,\n\t\t\t\t\t[newOp.timestamp.wallTime, oldOp.recordId, oldOp.timestamp.wallTime],\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\t// sequenceNumbers are intentionally unchanged, so `_kora_version_vector`\n\t\t// needs no update: the version vector tracks sequences, not timestamps.\n\t})\n\n\tconst newMaxTimestamp = newTimestamps[newTimestamps.length - 1] ?? null\n\n\treturn {\n\t\toperations: newOperations,\n\t\tidMapping,\n\t\trebasedCount: newOperations.length,\n\t\tnewMaxTimestamp,\n\t}\n}\n","import { quoteIdent } from '@korajs/core'\nimport type { Operation, SchemaDefinition } from '@korajs/core'\nimport { parseFieldVersions, serializeFieldVersions } from '../lww/field-versions'\nimport { serializeRowVersion } from '../lww/row-version'\nimport { buildInsertQuery } from '../query/sql-builder'\nimport { deserializeOperationWithCollection, serializeOperation } from '../serialization/serializer'\nimport type { OperationRow, RawCollectionRow, StorageAdapter } from '../types'\nimport { rehashOperation } from './rehash-operation'\nimport { NODE_TOKEN_META_KEY } from './sync-state'\n\n/** Result of {@link rotateUnsyncedOperationsInLog}. */\nexport interface NodeRotationResult {\n\t/** The node id the device uses from now on. */\n\tnodeId: string\n\t/** The rewritten operations under the new node id, in their original causal order. */\n\toperations: Operation[]\n\t/** Maps each old operation id to its new content-addressed id. */\n\tidMapping: Record<string, string>\n}\n\n/**\n * Move a device's never-acknowledged operations to a fresh node id (RT-21).\n *\n * The server refused this device's node id (`NODE_ID_CLAIMED`: another device holds\n * it, typically because the node token issued at the first claim was lost). The\n * device keeps its data by re-authoring its unsynced operations under a new node id:\n * same type, record, data and HLC wall time / counter, but the new node id in both\n * `nodeId` and `timestamp.nodeId`, sequence numbers 1..n in the original order, and\n * recomputed content-addressed ids (causal deps among them remapped). This is safe\n * for the same reason a clock rebase is: unacknowledged operations were never\n * shared, so no replica holds their old ids.\n *\n * Materialized rows are re-stamped so per-field LWW keeps comparing against the\n * rewritten timestamps; the version vector gets the new node's sequence (MAX with the\n * stored value) and the old node's entry is never lowered (W6). Everything, the scan\n * of the rotated operations included, runs in one transaction.\n *\n * @param adapter - The store's adapter\n * @param schema - The store schema (collections to scan)\n * @param unsyncedOpIds - Ids of the old node's operations the server never acknowledged\n * @param oldNodeId - The refused node id\n * @param newNodeId - The fresh node id\n * @param options - `moveDatabaseNode: false` re-authors another local node's operations\n * without moving the database's own node id or node token (default true)\n */\nexport async function rotateUnsyncedOperationsInLog(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n\tunsyncedOpIds: string[],\n\toldNodeId: string,\n\tnewNodeId: string,\n\toptions: { moveDatabaseNode?: boolean } = {},\n): Promise<NodeRotationResult> {\n\tconst moveDatabaseNode = options.moveDatabaseNode !== false\n\tconst rotateIds = new Set(unsyncedOpIds)\n\tconst idMapping: Record<string, string> = {}\n\tconst rewritten: Operation[] = []\n\n\t// One transaction from the scan to the last write (W6): the rotated set is read in\n\t// the transaction that rewrites it, so nothing committed in between is missed.\n\tawait adapter.transaction(async (tx) => {\n\t\tconst rotated: Operation[] = []\n\t\tfor (const collectionName of Object.keys(schema.collections)) {\n\t\t\tconst rows = await tx.query<OperationRow>(\n\t\t\t\t`SELECT * FROM ${quoteIdent(`_kora_ops_${collectionName}`)} WHERE node_id = ?`,\n\t\t\t\t[oldNodeId],\n\t\t\t)\n\t\t\tfor (const row of rows) {\n\t\t\t\tif (rotateIds.has(row.id)) {\n\t\t\t\t\trotated.push(deserializeOperationWithCollection(row, collectionName))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Original authoring order: sequence numbers are allocated in causal order.\n\t\trotated.sort((a, b) => a.sequenceNumber - b.sequenceNumber)\n\n\t\tfor (let i = 0; i < rotated.length; i++) {\n\t\t\tconst op = rotated[i]\n\t\t\tif (!op) continue\n\t\t\tconst timestamp = { ...op.timestamp, nodeId: newNodeId }\n\t\t\t// Deps among the rotated set are remapped BEFORE hashing: a version-2 id covers\n\t\t\t// causalDeps, and sequence order is causal order, so every dep is already\n\t\t\t// mapped. Deps on acknowledged operations keep their ids.\n\t\t\tconst causalDeps = op.causalDeps.map((dep) => idMapping[dep] ?? dep)\n\t\t\tconst moved: Operation = {\n\t\t\t\t...op,\n\t\t\t\tnodeId: newNodeId,\n\t\t\t\ttimestamp,\n\t\t\t\tsequenceNumber: i + 1,\n\t\t\t\tcausalDeps,\n\t\t\t}\n\t\t\tconst id = await rehashOperation(moved)\n\t\t\tidMapping[op.id] = id\n\t\t\trewritten.push({ ...moved, id })\n\t\t}\n\n\t\tfor (let i = 0; i < rotated.length; i++) {\n\t\t\tconst oldOp = rotated[i]\n\t\t\tconst newOp = rewritten[i]\n\t\t\tif (!oldOp || !newOp) continue\n\t\t\tconst opsTable = `_kora_ops_${oldOp.collection}`\n\t\t\tawait tx.execute(`DELETE FROM ${quoteIdent(opsTable)} WHERE id = ?`, [oldOp.id])\n\t\t\tconst insert = buildInsertQuery(\n\t\t\t\topsTable,\n\t\t\t\tserializeOperation(newOp) as unknown as Record<string, unknown>,\n\t\t\t)\n\t\t\tawait tx.execute(insert.sql, insert.params)\n\n\t\t\t// Re-stamp the row and field versions this operation wrote (the version\n\t\t\t// string carries the node id), exactly like a clock rebase.\n\t\t\tconst oldVersion = serializeRowVersion(oldOp.timestamp)\n\t\t\tconst newVersion = serializeRowVersion(newOp.timestamp)\n\t\t\tawait tx.execute(\n\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _version = ? WHERE id = ? AND _version = ?`,\n\t\t\t\t[newVersion, oldOp.recordId, oldVersion],\n\t\t\t)\n\t\t\tconst rows = await tx.query<RawCollectionRow>(\n\t\t\t\t`SELECT _field_versions FROM ${quoteIdent(oldOp.collection)} WHERE id = ?`,\n\t\t\t\t[oldOp.recordId],\n\t\t\t)\n\t\t\tconst fieldVersions = parseFieldVersions(rows[0]?._field_versions)\n\t\t\tlet changed = false\n\t\t\tfor (const [field, version] of Object.entries(fieldVersions)) {\n\t\t\t\tif (version === oldVersion) {\n\t\t\t\t\tfieldVersions[field] = newVersion\n\t\t\t\t\tchanged = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (changed) {\n\t\t\t\tawait tx.execute(\n\t\t\t\t\t`UPDATE ${quoteIdent(oldOp.collection)} SET _field_versions = ? WHERE id = ?`,\n\t\t\t\t\t[serializeFieldVersions(fieldVersions), oldOp.recordId],\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tif (moveDatabaseNode) {\n\t\t\tawait tx.execute(\"INSERT OR REPLACE INTO _kora_meta (key, value) VALUES ('node_id', ?)\", [\n\t\t\t\tnewNodeId,\n\t\t\t])\n\t\t\t// The node token belonged to the refused node id.\n\t\t\tawait tx.execute('DELETE FROM _kora_meta WHERE key = ?', [NODE_TOKEN_META_KEY])\n\t\t}\n\t\t// The new node's counter covers the rewritten operations: MAX with the stored\n\t\t// value, in this transaction, like every sequence reservation (W6).\n\t\tif (rewritten.length > 0) {\n\t\t\tawait tx.execute(\n\t\t\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\t\t[newNodeId, rewritten.length],\n\t\t\t)\n\t\t}\n\t\t// The old node's counter is left as it is, never lowered: a rotated operation\n\t\t// may have reached the server unacknowledged, and a writer still on the old id\n\t\t// (another tab) must not reuse its number for different content. The numbers the\n\t\t// rotated operations held become holes in the old node's log, which upload\n\t\t// tracking treats as resolved.\n\t})\n\n\treturn { nodeId: newNodeId, operations: rewritten, idMapping }\n}\n","import type {\n\tCausalTracker,\n\tCollectionDefinition,\n\tHybridLogicalClock,\n\tOperation,\n\tSchemaDefinition,\n\tSecretKeyProvider,\n} from '@korajs/core'\nimport {\n\tKoraError,\n\tgenerateUUIDv7,\n\tisAtomicOp,\n\tquoteIdent,\n\tresolveAtomicOp,\n\tvalidateRecord,\n} from '@korajs/core'\nimport { RecordNotFoundError } from '../errors'\nimport type { RecordFolder } from '../fold/record-folder'\nimport { toAtRestWriteData } from '../mutations/secret-write'\nimport {\n\tCausalScope,\n\ttype LocalDeleteHook,\n\ttype WriteEnv,\n\twithWriteScope,\n} from '../mutations/write-context'\nimport {\n\ttype PreparedInsert,\n\ttype WriteResult,\n\tprepareInsert,\n\twriteDeleteInTx,\n\twriteInsertInTx,\n\twriteUpdateInTx,\n} from '../mutations/write-ops'\nimport type { RelationEnforcer } from '../relations/relation-enforcer'\nimport { deserializeRecord, toRichtextReadShape } from '../serialization/serializer'\nimport { validateUpdateStateMachine } from '../state-machine/state-validator'\nimport type { CollectionRecord, RawCollectionRow, StorageAdapter } from '../types'\n\n/**\n * A buffered mutation. Buffered entries hold the developer's INTENT, not built\n * operations: they are written at commit, inside the commit's storage\n * transaction, through the same single local write path as single-record writes\n * (W6). That is what gives transaction writes in-transaction sequence\n * reservation, per-field version stamps, state-machine validation and atomic ops\n * resolved against the committed row.\n */\ntype BufferedEntry =\n\t| { readonly kind: 'insert'; readonly collection: string; readonly insert: PreparedInsert }\n\t| {\n\t\t\treadonly kind: 'update'\n\t\t\treadonly collection: string\n\t\t\treadonly id: string\n\t\t\t/** Schema-validated update data; may contain atomic op descriptors. */\n\t\t\treadonly data: Record<string, unknown>\n\t }\n\t| { readonly kind: 'delete'; readonly collection: string; readonly id: string }\n\n/**\n * Internal configuration for creating a TransactionContext.\n * Passed from Store to avoid exposing Store internals publicly.\n */\nexport interface TransactionContextConfig {\n\tschema: SchemaDefinition\n\tadapter: StorageAdapter\n\tclock: HybridLogicalClock\n\tnodeId: string\n\trelationEnforcer: RelationEnforcer | null\n\tcausalTracker: CausalTracker | null\n\t/**\n\t * Key provider for `t.secret()` encrypted fields. Transaction writes transform\n\t * secret fields through the same helper as single-record writes (STORE-4).\n\t */\n\tsecretKeyProvider?: SecretKeyProvider\n\t/** Referential hook run for every local delete inside the commit (see {@link LocalDeleteHook}). */\n\tbeforeLocalDelete?: LocalDeleteHook\n\t/** Called when the commit's storage transaction fails, before the error propagates. */\n\tonStorageError?: (error: unknown) => void\n\t/** The W7 record fold (see `WriteEnv.fold`). */\n\tfold?: RecordFolder\n\t/** See `WriteEnv.maxOperationBytes`. */\n\tmaxOperationBytes?: number\n\t/** See `WriteEnv.assertLocalWriteAllowed`. */\n\tassertLocalWriteAllowed?: () => void\n}\n\n/**\n * A collection accessor within a transaction.\n * Operations are buffered and committed atomically when the transaction completes.\n */\nexport interface TransactionCollectionAccessor {\n\tinsert(data: Record<string, unknown>): Promise<CollectionRecord>\n\tupdate(id: string, data: Record<string, unknown>): Promise<CollectionRecord>\n\tdelete(id: string): Promise<void>\n\tfindById(id: string): Promise<CollectionRecord | null>\n}\n\n/**\n * TransactionContext provides atomic multi-collection operations.\n *\n * Mutations are validated and buffered when called (so errors surface at the\n * call site and `insert` returns the new id immediately), then written in a\n * single `StorageAdapter.transaction()` at commit. All operations share the\n * same transactionId (UUID v7) and one contiguous block of sequence numbers.\n *\n * Subscription notifications are deferred until after commit.\n *\n * @example\n * ```typescript\n * const { operations, affectedCollections } = await txContext.commit()\n * // Notify subscriptions after commit\n * for (const op of operations) {\n * subscriptionManager.notify(op.collection, op)\n * }\n * ```\n */\nexport class TransactionContext {\n\tprivate readonly transactionId: string\n\tprivate mutationName: string | undefined\n\tprivate readonly buffer: BufferedEntry[] = []\n\tprivate committed = false\n\tprivate rolledBack = false\n\tprivate readonly config: TransactionContextConfig\n\n\tconstructor(config: TransactionContextConfig) {\n\t\tthis.config = config\n\t\tthis.transactionId = generateUUIDv7()\n\t}\n\n\t/**\n\t * Set a human-readable mutation name for this transaction.\n\t * Propagated to all operations for DevTools display.\n\t */\n\tsetMutationName(name: string): void {\n\t\tthis.mutationName = name\n\t}\n\n\t/**\n\t * Get the mutation name, if set.\n\t */\n\tgetMutationName(): string | undefined {\n\t\treturn this.mutationName\n\t}\n\n\t/**\n\t * Get a collection accessor for buffered operations within this transaction.\n\t */\n\tcollection(name: string): TransactionCollectionAccessor {\n\t\tconst definition = this.config.schema.collections[name]\n\t\tif (!definition) {\n\t\t\tthrow new KoraError(\n\t\t\t\t`Unknown collection \"${name}\". Available: ${Object.keys(this.config.schema.collections).join(', ')}`,\n\t\t\t\t'UNKNOWN_COLLECTION',\n\t\t\t\t{ collection: name },\n\t\t\t)\n\t\t}\n\n\t\treturn {\n\t\t\tinsert: (data: Record<string, unknown>) => this.insert(name, data),\n\t\t\tupdate: (id: string, data: Record<string, unknown>) =>\n\t\t\t\tthis.update(name, definition, id, data),\n\t\t\tdelete: (id: string) => this.deleteRecord(name, definition, id),\n\t\t\tfindById: (id: string) => this.getEffectiveRecord(name, definition, id),\n\t\t}\n\t}\n\n\t/**\n\t * Commit all buffered mutations atomically.\n\t *\n\t * Every entry is written, in call order, inside ONE storage transaction through\n\t * the single local write path: sequence numbers are reserved inside the\n\t * transaction (one contiguous block covering referential side effects too) and\n\t * each operation is built only after its number is reserved.\n\t *\n\t * Returns the list of operations and affected collections for subscription notification.\n\t */\n\tasync commit(): Promise<{ operations: Operation[]; affectedCollections: Set<string> }> {\n\t\tif (this.committed) {\n\t\t\tthrow new KoraError('Transaction already committed.', 'TRANSACTION_COMMITTED', {\n\t\t\t\ttransactionId: this.transactionId,\n\t\t\t})\n\t\t}\n\t\tif (this.rolledBack) {\n\t\t\tthrow new KoraError(\n\t\t\t\t'Transaction was rolled back and cannot be committed.',\n\t\t\t\t'TRANSACTION_ROLLED_BACK',\n\t\t\t\t{ transactionId: this.transactionId },\n\t\t\t)\n\t\t}\n\n\t\tthis.committed = true\n\n\t\tif (this.buffer.length === 0) {\n\t\t\treturn { operations: [], affectedCollections: new Set() }\n\t\t}\n\n\t\tconst env = this.writeEnv()\n\t\tconst causal = new CausalScope(this.config.causalTracker, true)\n\t\tconst operations: Operation[] = []\n\n\t\ttry {\n\t\t\tawait this.config.adapter.transaction(async (tx) => {\n\t\t\t\tawait withWriteScope(tx, env.nodeId, causal, async (scope) => {\n\t\t\t\t\tfor (const entry of this.buffer) {\n\t\t\t\t\t\tlet result: WriteResult\n\t\t\t\t\t\tswitch (entry.kind) {\n\t\t\t\t\t\t\tcase 'insert':\n\t\t\t\t\t\t\t\tresult = await writeInsertInTx(env, scope, entry.insert)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tcase 'update':\n\t\t\t\t\t\t\t\tresult = await writeUpdateInTx(env, scope, entry.collection, entry.id, entry.data)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tcase 'delete':\n\t\t\t\t\t\t\t\tresult = await writeDeleteInTx(env, scope, entry.collection, entry.id)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.operation) operations.push(result.operation)\n\t\t\t\t\t\toperations.push(...result.sideEffects)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t} catch (error) {\n\t\t\tthis.config.onStorageError?.(error)\n\t\t\tthrow error\n\t\t}\n\n\t\tcausal.publish()\n\t\tconst affectedCollections = new Set(operations.map((op) => op.collection))\n\t\treturn { operations, affectedCollections }\n\t}\n\n\t/**\n\t * Mark the transaction as rolled back. No operations will be committed.\n\t */\n\trollback(): void {\n\t\tthis.rolledBack = true\n\t\tthis.buffer.length = 0\n\t}\n\n\t/**\n\t * Get the transaction ID shared by all operations in this transaction.\n\t */\n\tgetTransactionId(): string {\n\t\treturn this.transactionId\n\t}\n\n\tprivate writeEnv(): WriteEnv {\n\t\treturn {\n\t\t\tschema: this.config.schema,\n\t\t\tclock: this.config.clock,\n\t\t\tnodeId: this.config.nodeId,\n\t\t\trelationEnforcer: this.config.relationEnforcer,\n\t\t\ttransactionId: this.transactionId,\n\t\t\t...(this.config.secretKeyProvider\n\t\t\t\t? { secretKeyProvider: this.config.secretKeyProvider }\n\t\t\t\t: {}),\n\t\t\t...(this.mutationName !== undefined ? { mutationName: this.mutationName } : {}),\n\t\t\t...(this.config.beforeLocalDelete\n\t\t\t\t? { beforeLocalDelete: this.config.beforeLocalDelete }\n\t\t\t\t: {}),\n\t\t\t...(this.config.fold ? { fold: this.config.fold } : {}),\n\t\t\t...(this.config.maxOperationBytes !== undefined\n\t\t\t\t? { maxOperationBytes: this.config.maxOperationBytes }\n\t\t\t\t: {}),\n\t\t\t...(this.config.assertLocalWriteAllowed\n\t\t\t\t? { assertLocalWriteAllowed: this.config.assertLocalWriteAllowed }\n\t\t\t\t: {}),\n\t\t}\n\t}\n\n\tprivate ensureActive(): void {\n\t\tif (this.committed) {\n\t\t\tthrow new KoraError(\n\t\t\t\t'Cannot perform operations on a committed transaction.',\n\t\t\t\t'TRANSACTION_COMMITTED',\n\t\t\t\t{ transactionId: this.transactionId },\n\t\t\t)\n\t\t}\n\t\tif (this.rolledBack) {\n\t\t\tthrow new KoraError(\n\t\t\t\t'Cannot perform operations on a rolled-back transaction.',\n\t\t\t\t'TRANSACTION_ROLLED_BACK',\n\t\t\t\t{ transactionId: this.transactionId },\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate async insert(\n\t\tcollectionName: string,\n\t\tdata: Record<string, unknown>,\n\t): Promise<CollectionRecord> {\n\t\tthis.ensureActive()\n\t\tconst insert = await prepareInsert(this.writeEnv(), collectionName, data)\n\t\tthis.buffer.push({ kind: 'insert', collection: collectionName, insert })\n\t\tconst now = Date.now()\n\t\t// The returned record carries the at-rest form (secrets hashed/encrypted) and the\n\t\t// read form of richtext (bytes), exactly like a single-record insert.\n\t\tconst fields = this.config.schema.collections[collectionName]?.fields ?? {}\n\t\treturn {\n\t\t\tid: insert.recordId,\n\t\t\t...toRichtextReadShape(insert.data, fields),\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t}\n\t}\n\n\tprivate async update(\n\t\tcollectionName: string,\n\t\tdefinition: CollectionDefinition,\n\t\tid: string,\n\t\tdata: Record<string, unknown>,\n\t): Promise<CollectionRecord> {\n\t\tthis.ensureActive()\n\n\t\tconst currentRecord = await this.getEffectiveRecord(collectionName, definition, id)\n\t\tif (!currentRecord) {\n\t\t\tthrow new RecordNotFoundError(collectionName, id)\n\t\t}\n\n\t\tconst validated = validateRecord(collectionName, definition, data, 'update')\n\t\t// Early check so an invalid transition fails at the call site. The commit\n\t\t// re-validates against the row read inside the write transaction, which is\n\t\t// authoritative.\n\t\tconst allowed = validateUpdateStateMachine(\n\t\t\tcollectionName,\n\t\t\tid,\n\t\t\tdefinition,\n\t\t\tcurrentRecord,\n\t\t\tvalidated,\n\t\t)\n\t\tthis.buffer.push({ kind: 'update', collection: collectionName, id, data: validated })\n\n\t\tconst preview = await this.previewUpdate(definition, currentRecord, allowed)\n\t\treturn { ...currentRecord, ...preview, updatedAt: Date.now() } as CollectionRecord\n\t}\n\n\tprivate async deleteRecord(\n\t\tcollectionName: string,\n\t\tdefinition: CollectionDefinition,\n\t\tid: string,\n\t): Promise<void> {\n\t\tthis.ensureActive()\n\n\t\tconst currentRecord = await this.getEffectiveRecord(collectionName, definition, id)\n\t\tif (!currentRecord) {\n\t\t\tthrow new RecordNotFoundError(collectionName, id)\n\t\t}\n\t\tthis.buffer.push({ kind: 'delete', collection: collectionName, id })\n\t}\n\n\t/**\n\t * The values an update will write, resolved against `current` (the effective\n\t * record) for read-your-writes inside the transaction. Secret fields are shown\n\t * in their at-rest form, like the record a committed update returns.\n\t */\n\tprivate async previewUpdate(\n\t\tdefinition: CollectionDefinition,\n\t\tcurrent: CollectionRecord,\n\t\tdata: Record<string, unknown>,\n\t): Promise<Record<string, unknown>> {\n\t\tconst resolved: Record<string, unknown> = {}\n\t\tfor (const [key, value] of Object.entries(data)) {\n\t\t\tresolved[key] = isAtomicOp(value) ? resolveAtomicOp(current[key], value) : value\n\t\t}\n\t\tconst atRest = await toAtRestWriteData(resolved, definition, this.config.secretKeyProvider)\n\t\treturn toRichtextReadShape(atRest, definition.fields)\n\t}\n\n\t/**\n\t * The effective state of a record: the committed row overlaid with this\n\t * transaction's buffered mutations, in call order.\n\t */\n\tprivate async getEffectiveRecord(\n\t\tcollectionName: string,\n\t\tdefinition: CollectionDefinition,\n\t\tid: string,\n\t): Promise<CollectionRecord | null> {\n\t\tconst rows = await this.config.adapter.query<RawCollectionRow>(\n\t\t\t`SELECT * FROM ${quoteIdent(collectionName)} WHERE id = ? AND _deleted = 0`,\n\t\t\t[id],\n\t\t)\n\t\tlet record: CollectionRecord | null = rows[0]\n\t\t\t? deserializeRecord(rows[0], definition.fields)\n\t\t\t: null\n\n\t\tfor (const entry of this.buffer) {\n\t\t\tif (entry.collection !== collectionName) continue\n\t\t\tif (entry.kind === 'insert') {\n\t\t\t\tif (entry.insert.recordId !== id) continue\n\t\t\t\tconst now = Date.now()\n\t\t\t\trecord = {\n\t\t\t\t\tid,\n\t\t\t\t\t...toRichtextReadShape(entry.insert.data, definition.fields),\n\t\t\t\t\tcreatedAt: now,\n\t\t\t\t\tupdatedAt: now,\n\t\t\t\t}\n\t\t\t} else if (entry.id === id && entry.kind === 'update') {\n\t\t\t\tif (record) {\n\t\t\t\t\tlet allowed: Record<string, unknown>\n\t\t\t\t\ttry {\n\t\t\t\t\t\tallowed = validateUpdateStateMachine(collectionName, id, definition, record, entry.data)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Already reported to the caller when the update was buffered.\n\t\t\t\t\t\tallowed = {}\n\t\t\t\t\t}\n\t\t\t\t\tconst preview = await this.previewUpdate(definition, record, allowed)\n\t\t\t\t\trecord = { ...record, ...preview, updatedAt: Date.now() }\n\t\t\t\t}\n\t\t\t} else if (entry.id === id) {\n\t\t\t\trecord = null\n\t\t\t}\n\t\t}\n\n\t\treturn record\n\t}\n}\n","import { quoteIdent } from '@korajs/core'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { collectionIndexName, legacyCollectionIndexName } from '@korajs/core/internal'\nimport type { StorageAdapter } from '../types'\n\n/**\n * Retire indexes created under the pre-beta.13 naming scheme (STORE-15).\n *\n * `idx_<collection>_<field>` collided across collections (`a_b`.`c` and\n * `a`.`b_c`), so one of the two indexes was silently never created. The schema\n * DDL now creates collision-free names ({@link collectionIndexName}); this pass\n * drops each legacy index that sits on the table and column it was named for,\n * once its replacement exists. A legacy name that belongs to another table is\n * left to that table's own pass, so nothing a collection still needs is dropped.\n *\n * SQLite cannot rename an index; drop-and-recreate is the rename.\n *\n * @param adapter - The opened adapter (schema DDL already applied)\n * @param schema - The schema whose collections are checked\n */\nexport async function dropLegacyIndexes(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n): Promise<void> {\n\tconst indexed = new Map<string, Set<string>>()\n\tfor (const [name, definition] of Object.entries(schema.collections)) {\n\t\tindexed.set(name, new Set(definition.indexes))\n\t}\n\tfor (const relation of Object.values(schema.relations)) {\n\t\tindexed.get(relation.from)?.add(relation.field)\n\t}\n\n\tconst existing = await adapter.query<{ name: string; tbl_name: string }>(\n\t\t\"SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name LIKE 'idx_%'\",\n\t)\n\tconst byName = new Map(existing.map((row) => [row.name, row.tbl_name]))\n\n\tfor (const [collection, fields] of indexed) {\n\t\tfor (const field of fields) {\n\t\t\tconst legacy = legacyCollectionIndexName(collection, field)\n\t\t\tconst current = collectionIndexName(collection, field)\n\t\t\tif (legacy === current) continue\n\t\t\tif (byName.get(legacy) !== collection) continue\n\t\t\tif (byName.get(current) !== collection) continue\n\t\t\tconst columns = await adapter.query<{ name: string }>(\n\t\t\t\t`SELECT name FROM pragma_index_info(${sqlString(legacy)})`,\n\t\t\t)\n\t\t\tif (columns.length !== 1 || columns[0]?.name !== field) continue\n\t\t\tawait adapter.execute(`DROP INDEX IF EXISTS ${quoteIdent(legacy)}`)\n\t\t}\n\t}\n}\n\nfunction sqlString(value: string): string {\n\treturn `'${value.replace(/'/g, \"''\")}'`\n}\n","/**\n * Web Locks per local node id (RT-40). Under per-tab isolation every tab writes under\n * its own node id into one shared database; a live tab holds its node's lock for its\n * lifetime, so another tab can tell a closed tab's node (lock free: adopt its unsynced\n * writes) from a live one (lock held: leave it alone). An adopter holds the lock while\n * it uploads, so two tabs never adopt the same node at once.\n *\n * Without the Web Locks API (Node, workers without it) every node is reported free and\n * acquisition is a no-op: there is no other tab to coordinate with.\n */\n\ninterface LockLike {\n\tname?: string\n}\n\ninterface LockManagerLike {\n\trequest(\n\t\tname: string,\n\t\toptions: { mode?: 'exclusive' | 'shared'; ifAvailable?: boolean },\n\t\tcallback: (lock: LockLike | null) => Promise<void> | void,\n\t): Promise<unknown>\n\tquery?(): Promise<{ held?: LockLike[] }>\n}\n\nfunction lockManager(): LockManagerLike | null {\n\tconst nav = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator\n\treturn nav?.locks && typeof nav.locks.request === 'function' ? nav.locks : null\n}\n\n/** Lock name of a node id in a database. */\nexport function nodeLockName(dbName: string, nodeId: string): string {\n\treturn `kora-node:${dbName}:${nodeId}`\n}\n\n/**\n * Hold a node's lock until the returned function is called. Acquisition is\n * asynchronous (it waits while an adopter holds the lock); the caller never waits.\n */\nexport function acquireNodeLock(name: string): () => void {\n\tconst locks = lockManager()\n\tif (!locks) return () => {}\n\tlet release: () => void = () => {}\n\tlet released = false\n\tconst held = new Promise<void>((resolve) => {\n\t\trelease = () => {\n\t\t\treleased = true\n\t\t\tresolve()\n\t\t}\n\t})\n\tlocks\n\t\t.request(name, { mode: 'exclusive' }, async () => {\n\t\t\tif (released) return\n\t\t\tawait held\n\t\t})\n\t\t.catch(() => {\n\t\t\t// A lock that cannot be taken only weakens the liveness hint; never fatal.\n\t\t})\n\treturn () => release()\n}\n\n/**\n * Take a node's lock only when it is free. Resolves to a release function, or null\n * when another context (a live tab, another adopter) holds it.\n */\nexport function tryAcquireNodeLock(name: string): Promise<(() => void) | null> {\n\tconst locks = lockManager()\n\tif (!locks) return Promise.resolve(() => {})\n\treturn new Promise((resolveResult) => {\n\t\tlet release: () => void = () => {}\n\t\tconst held = new Promise<void>((resolve) => {\n\t\t\trelease = resolve\n\t\t})\n\t\tlocks\n\t\t\t.request(name, { mode: 'exclusive', ifAvailable: true }, async (lock) => {\n\t\t\t\tif (!lock) {\n\t\t\t\t\tresolveResult(null)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tresolveResult(() => release())\n\t\t\t\tawait held\n\t\t\t})\n\t\t\t.catch(() => resolveResult(null))\n\t})\n}\n\n/** Whether some context holds a node's lock. */\nexport async function isNodeLockHeld(name: string): Promise<boolean> {\n\tconst locks = lockManager()\n\tif (!locks?.query) return false\n\ttry {\n\t\tconst snapshot = await locks.query()\n\t\treturn (snapshot.held ?? []).some((lock) => lock.name === name)\n\t} catch {\n\t\treturn false\n\t}\n}\n","import type { SchemaDefinition } from '@korajs/core'\nimport {\n\ttype SqliteQueryFn,\n\treadSqliteTableCatalog,\n\tsqliteConstraintRelaxationStatements,\n} from '@korajs/core/internal'\nimport type { StorageAdapter } from '../types'\n\n/**\n * One-time migration (RT-101): rebuild collection tables that still carry value-domain\n * constraints (an enum `CHECK`, `NOT NULL` on a schema field) created by beta.12 and\n * earlier DDL. Validation is the single authority for the value domain; a table\n * constraint cannot evolve with the schema, so it refused enum values added later and\n * nulls of fields made optional.\n *\n * Every table is rebuilt in ONE transaction (all or nothing), preserving rows, columns,\n * defaults, keys, indexes and triggers. Foreign key enforcement is switched off around\n * it when the database enforces foreign keys, as SQLite's table-rebuild procedure\n * requires. Idempotent: a relaxed table is left alone, so later opens do nothing;\n * resumable: an interrupted rebuild rolls back and runs again at the next open.\n *\n * Works for every client adapter (better-sqlite3, SQLite WASM/OPFS, and the IndexedDB\n * adapter, which runs SQLite in memory): they all store in SQLite.\n *\n * @param adapter - The opened adapter (schema DDL already applied)\n * @param schema - The schema whose collection tables are checked\n * @returns The collections whose tables were rebuilt\n */\nexport async function relaxValueDomainConstraints(\n\tadapter: StorageAdapter,\n\tschema: SchemaDefinition,\n): Promise<string[]> {\n\tconst collections = Object.keys(schema.collections)\n\t// Only enum checks on the schema's enum fields are Kora's; any other CHECK was added\n\t// by hand and is kept through the rebuild, and never triggers one (RT-111).\n\tconst enumColumns = (collection: string): string[] =>\n\t\tObject.entries(schema.collections[collection]?.fields ?? {})\n\t\t\t.filter(([, descriptor]) => descriptor.kind === 'enum')\n\t\t\t.map(([field]) => field)\n\tconst viaAdapter: SqliteQueryFn = (sql) => adapter.query<Record<string, unknown>>(sql)\n\tconst pending: string[] = []\n\tfor (const collection of collections) {\n\t\tconst catalog = await readSqliteTableCatalog(viaAdapter, collection)\n\t\tif (\n\t\t\tcatalog &&\n\t\t\tsqliteConstraintRelaxationStatements(catalog, enumColumns(collection)).length > 0\n\t\t) {\n\t\t\tpending.push(collection)\n\t\t}\n\t}\n\tif (pending.length === 0) return []\n\n\tconst enforced = await adapter.query<{ foreign_keys: number }>('PRAGMA foreign_keys')\n\tconst foreignKeysOn = Number(enforced[0]?.foreign_keys) === 1\n\tif (foreignKeysOn) await adapter.execute('PRAGMA foreign_keys = OFF')\n\tconst rebuilt: string[] = []\n\ttry {\n\t\tawait adapter.transaction(async (tx) => {\n\t\t\tconst viaTx: SqliteQueryFn = (sql) => tx.query<Record<string, unknown>>(sql)\n\t\t\t// Re-read inside the transaction: another tab may have relaxed a table already.\n\t\t\tfor (const collection of pending) {\n\t\t\t\tconst catalog = await readSqliteTableCatalog(viaTx, collection)\n\t\t\t\tif (!catalog) continue\n\t\t\t\tconst statements = sqliteConstraintRelaxationStatements(catalog, enumColumns(collection))\n\t\t\t\tif (statements.length === 0) continue\n\t\t\t\tfor (const sql of statements) await tx.execute(sql)\n\t\t\t\trebuilt.push(collection)\n\t\t\t}\n\t\t})\n\t} finally {\n\t\tif (foreignKeysOn) await adapter.execute('PRAGMA foreign_keys = ON')\n\t}\n\treturn rebuilt\n}\n","import { generateUUIDv7 } from '@korajs/core'\n\nexport type StoreIsolation = 'shared' | 'per-tab'\n\nfunction perTabStorageKey(dbName: string): string {\n\treturn `kora-tab-node-${dbName}`\n}\n\n/**\n * Load a per-tab node id from sessionStorage (browser only).\n */\nexport function loadPerTabNodeId(dbName: string): string | null {\n\tif (typeof sessionStorage === 'undefined') {\n\t\treturn null\n\t}\n\treturn sessionStorage.getItem(perTabStorageKey(dbName))\n}\n\n/**\n * Persist a per-tab node id for this browser tab.\n */\nexport function savePerTabNodeId(dbName: string, nodeId: string): void {\n\tif (typeof sessionStorage === 'undefined') {\n\t\treturn\n\t}\n\tsessionStorage.setItem(perTabStorageKey(dbName), nodeId)\n}\n\n/**\n * Resolve or create a node id for `per-tab` isolation.\n */\nexport function resolvePerTabNodeId(dbName: string): string {\n\tconst existing = loadPerTabNodeId(dbName)\n\t// Never adopt an id in Kora's reserved `kora:` namespace (RT-61).\n\tif (existing && !existing.startsWith('kora:')) {\n\t\treturn existing\n\t}\n\tconst nodeId = generateUUIDv7()\n\tsavePerTabNodeId(dbName, nodeId)\n\treturn nodeId\n}\n"],"mappings":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nD,UAAM,OAAO,MAAM,KAAK,QAAQ;AAAA,MAC/B;AAAA,MACA,CAAC,KAAK,MAAM;AAAA,IACb;AACA,WAAO,KAAK,CAAC,GAAG,mBAAmB;AAAA,EACpC;AAAA,EAEA,MAAc,oBAA4C;AACzD,UAAM,OAAO,MAAM,KAAK,QAAQ;AAAA,MAC/B;AAAA,IACD;AACA,UAAM,SAASJ,qBAAoB;AACnC,eAAW,OAAO,MAAM;AACvB,aAAO,IAAI,IAAI,SAAS,IAAI,eAAe;AAAA,IAC5C;AACA,WAAO;AAAA,EACR;AAAA,EAEQ,aAAmB;AAC1B,QAAI,CAAC,KAAK,QAAQ;AACjB,YAAM,IAAI,kBAAkB;AAAA,IAC7B;AAAA,EACD;AACD;AAiBA,SAAS,mBAAmB,IAA6B;AACxD,MAAI,SAAS,GAAG;AAChB,aAAW,WAAW,OAAO,OAAO,GAAG,iBAAiB,CAAC,CAAC,GAAG;AAC5D,QAAIC,oBAAmB,QAAQ,SAAS,MAAM,IAAI,EAAG,UAAS;AAAA,EAC/D;AACA,SAAO;AACR;","names":["HybridLogicalClock","KoraError","createVersionVector","generateUUIDv7","quoteIdent","quoteIdent","quoteIdent","HybridLogicalClock","createVersionVector","quoteIdent","createVersionVector","quoteIdent","HybridLogicalClock","quoteIdent","quoteIdent","canonical","HybridLogicalClock","quoteIdent","quoteIdent","HybridLogicalClock","quoteIdent","quoteIdent","quoteIdent","propName","quoteIdent","KoraError","encodeStoredText","quoteIdent","KoraError","quoteIdent","encodeStoredText","HybridLogicalClock","HybridLogicalClock","quoteIdent","quoteIdent","HybridLogicalClock","quoteIdent","quoteIdent","HybridLogicalClock","quoteIdent","quoteIdent","KoraError","quoteIdent","validateRecord","KoraError","validateRecord","quoteIdent","quoteIdent","generateUUIDv7","KoraError","createVersionVector","HybridLogicalClock","quoteIdent","rowVersion","generateUUIDv7","fresh","readBackupManifest"]}
|