{"version":3,"sources":["/home/runner/work/kora/kora/packages/store/dist/chunk-EFZJB6YB.cjs","../src/instrumentation/phase-timers.ts","../src/state-machine/state-validator.ts","../src/overlay/write-overlay.ts","../src/overlay/predict.ts","../src/mutations/same-value.ts","../src/mutations/unchanged-fields.ts","../src/mutations/write-shapes.ts","../src/transaction/write-behind.ts","../src/mutations/write-context.ts","../src/lww/field-versions.ts","../src/mutations/execute-delete.ts","../src/types.ts","../src/mutations/run-local-write.ts","../src/mutations/commit-outcome.ts","../src/mutations/write-ops.ts","../src/mutations/secret-write.ts","../src/mutations/execute-insert.ts","../src/mutations/execute-update.ts"],"names":["KoraError","quoteIdent"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACyBO,IAAM,YAAA,EAAoC;AAAA,EAChD,SAAA;AAAA,EACA,QAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,SAAA;AAAA,EACA,YAAA;AAAA,EACA,cAAA;AAAA,EACA,QAAA;AAAA,EACA;AACD,CAAA;AAmBA,SAAS,WAAA,CAAA,EAAyC;AACjD,EAAA,OAAO;AAAA,IACN,OAAA,EAAS,CAAA;AAAA,IACT,MAAA,EAAQ,CAAA;AAAA,IACR,QAAA,EAAU,CAAA;AAAA,IACV,IAAA,EAAM,CAAA;AAAA,IACN,MAAA,EAAQ,CAAA;AAAA,IACR,OAAA,EAAS,CAAA;AAAA,IACT,UAAA,EAAY,CAAA;AAAA,IACZ,YAAA,EAAc,CAAA;AAAA,IACd,MAAA,EAAQ,CAAA;AAAA,IACR,UAAA,EAAY;AAAA,EACb,CAAA;AACD;AAMO,IAAM,YAAA,YAAN,MAAkB;AAAA,iBAChB,QAAA,EAA8B,KAAA;AAAA,kBACrB,SAAA,EAA0B,CAAC,EAAA;AAAA;AAAA,EAG5C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AAA;AACU,IAAA;AACe,MAAA;AAOvB,MAAA;AACA,QAAA;AACA,QAAA;AACI,QAAA;AACJ,QAAA;AACmD,QAAA;AACpD,MAAA;AACqC,MAAA;AAC9B,MAAA;AACT,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACuC,QAAA;AACvC,QAAA;AACD,MAAA;AACD,IAAA;AACgB,IAAA;AACf,MAAA;AAEqF,MAAA;AACrF,MAAA;AACC,QAAA;AACgC,QAAA;AAE7B,QAAA;AACoD,UAAA;AACN,UAAA;AACiB,YAAA;AACY,YAAA;AAC3E,UAAA;AAEC,QAAA;AACL,MAAA;AACD,IAAA;AAEc,oBAAA;AACO,IAAA;AACP,IAAA;AACC,EAAA;AACM,oBAAA;AACf,IAAA;AACL,EAAA;AACa,oBAAA;AACf,EAAA;AACD;AlB42DmQ;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/kora/kora/packages/store/dist/chunk-EFZJB6YB.cjs","sourcesContent":[null,"/**\n * Internal write-to-UI phase timers (instant-UI stage S0).\n *\n * Measures where the latency between `await collection.insert(...)` and a reactive\n * subscriber callback goes. This is a measurement aid for benchmarks and the\n * design doc `docs/design/instant-ui-updates.md`; it is NOT public API and is only\n * reachable through `@korajs/store/internal`.\n *\n * Cost when nothing is installed: one module-level null check per hook. Timers only\n * observe: no hook changes ordering, awaits or results of the write or read path.\n */\n\n/** The kind of local write a record belongs to. */\nexport type PhaseWriteKind = 'insert' | 'update' | 'delete'\n\n/**\n * Phases, in the order a write-to-callback travels through them.\n *\n * Write side (main thread view of `runLocalWrite`):\n * - `prepare`: validation, defaults, id generation before the transaction opens.\n * - `txOpen`: from calling `adapter.transaction` until the body starts (adapter mutex wait plus BEGIN round trip).\n * - `sequence`: sequence reservation inside the body (a subset of `body`).\n * - `body`: the transaction body (sequence reservation, operation build, buffered statements).\n * - `commit`: from the body returning until `adapter.transaction` resolves (flush of buffered statements plus COMMIT).\n * - `publish`: synchronous post-commit work (causal heads, observer, `subscriptionManager.notify`, `operation:created`).\n *\n * Read side (subscription manager, summed over every affected subscription):\n * - `flushDelay`: from `notify` to the start of the flush microtask.\n * - `findAffected`: choosing the affected subscriptions.\n * - `reread`: `executeFn` (adapter mutex wait plus the SELECT plus row decoding).\n * - `diffNotify`: result equality check plus the subscriber callback itself.\n */\nexport type PhaseName =\n\t| 'prepare'\n\t| 'txOpen'\n\t| 'sequence'\n\t| 'body'\n\t| 'commit'\n\t| 'publish'\n\t| 'flushDelay'\n\t| 'findAffected'\n\t| 'reread'\n\t| 'diffNotify'\n\n/** All phase names, in travel order. */\nexport const PHASE_NAMES: readonly PhaseName[] = [\n\t'prepare',\n\t'txOpen',\n\t'sequence',\n\t'body',\n\t'commit',\n\t'publish',\n\t'flushDelay',\n\t'findAffected',\n\t'reread',\n\t'diffNotify',\n]\n\n/** Timings of one write and the subscription re-runs it caused. */\nexport interface PhaseRecord {\n\treadonly kind: PhaseWriteKind\n\t/** Milliseconds per phase (summed when a phase ran more than once). */\n\treadonly phases: Record<PhaseName, number>\n\t/** Number of subscription re-runs. */\n\trereads: number\n\t/** Number of subscriber callbacks actually invoked. */\n\tcallbacks: number\n\t/** `performance.now()` when the write was started. */\n\treadonly startedAt: number\n\t/** `performance.now()` of the first subscriber callback after the commit, or null. */\n\tfirstCallbackAt: number | null\n\t/** `performance.now()` when `publish` ended (the notify moment). */\n\tpublishedAt: number | null\n}\n\nfunction emptyPhases(): Record<PhaseName, number> {\n\treturn {\n\t\tprepare: 0,\n\t\ttxOpen: 0,\n\t\tsequence: 0,\n\t\tbody: 0,\n\t\tcommit: 0,\n\t\tpublish: 0,\n\t\tflushDelay: 0,\n\t\tfindAffected: 0,\n\t\treread: 0,\n\t\tdiffNotify: 0,\n\t}\n}\n\n/**\n * Collects {@link PhaseRecord}s. One record is open at a time (writes in a\n * measurement are sequential); read-side phases are attributed to it.\n */\nexport class PhaseTimers {\n\tprivate current: PhaseRecord | null = null\n\tprivate readonly finished: PhaseRecord[] = []\n\n\t/** Start a record for a write; closes the previous open record. */\n\tbegin(kind: PhaseWriteKind): void {\n\t\tthis.close()\n\t\tthis.current = {\n\t\t\tkind,\n\t\t\tphases: emptyPhases(),\n\t\t\trereads: 0,\n\t\t\tcallbacks: 0,\n\t\t\tstartedAt: performance.now(),\n\t\t\tfirstCallbackAt: null,\n\t\t\tpublishedAt: null,\n\t\t}\n\t}\n\n\t/** Add elapsed milliseconds to a phase of the open record. */\n\tadd(phase: PhaseName, ms: number): void {\n\t\tif (this.current) this.current.phases[phase] += ms\n\t}\n\n\t/** Note that one subscription re-run finished. */\n\tnoteReread(): void {\n\t\tif (this.current) this.current.rereads++\n\t}\n\n\t/** Note the moment the post-commit publish ended. */\n\tnotePublished(at: number): void {\n\t\tif (this.current && this.current.publishedAt === null) this.current.publishedAt = at\n\t}\n\n\t/** Note a subscriber callback invocation. */\n\tnoteCallback(at: number): void {\n\t\tconst record = this.current\n\t\tif (!record) return\n\t\trecord.callbacks++\n\t\t// With instant updates the first callback is the prediction, which runs BEFORE the\n\t\t// commit publish; requiring `publishedAt` here timed the post-commit re-run instead\n\t\t// and hid exactly the latency the feature removes (S4 finding).\n\t\tif (record.firstCallbackAt === null) record.firstCallbackAt = at\n\t}\n\n\t/** The open record, if any. */\n\tpeek(): PhaseRecord | null {\n\t\treturn this.current\n\t}\n\n\t/** Close the open record and return every finished record, clearing the buffer. */\n\ttake(): PhaseRecord[] {\n\t\tthis.close()\n\t\treturn this.finished.splice(0, this.finished.length)\n\t}\n\n\tprivate close(): void {\n\t\tif (this.current) this.finished.push(this.current)\n\t\tthis.current = null\n\t}\n}\n\nlet active: PhaseTimers | null = null\n\n/** Install (or with null, remove) the process-wide timers. Internal. */\nexport function installPhaseTimers(timers: PhaseTimers | null): void {\n\tactive = timers\n}\n\n/** The installed timers, or null (the normal case). */\nexport function activePhaseTimers(): PhaseTimers | null {\n\treturn active\n}\n\n/** Median and 95th percentile of a sample (nearest rank). */\nexport function summarizeSamples(samples: readonly number[]): { p50: number; p95: number } {\n\tif (samples.length === 0) return { p50: 0, p95: 0 }\n\tconst sorted = [...samples].sort((a, b) => a - b)\n\tconst at = (p: number): number =>\n\t\tsorted[Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * p))] ?? 0\n\treturn { p50: at(0.5), p95: at(0.95) }\n}\n\n/** Per-phase p50 and p95 over a list of records. */\nexport function summarizePhases(\n\trecords: readonly PhaseRecord[],\n): Record<PhaseName, { p50: number; p95: number }> {\n\tconst out = {} as Record<PhaseName, { p50: number; p95: number }>\n\tfor (const name of PHASE_NAMES) {\n\t\tout[name] = summarizeSamples(records.map((record) => record.phases[name]))\n\t}\n\treturn out\n}\n","import { KoraError, validateTransition } from '@korajs/core'\nimport type {\n\tCollectionDefinition,\n\tStateMachineConstraint,\n\tStateMachineDefinition,\n} from '@korajs/core'\n\n/**\n * Error thrown when a local mutation attempts an invalid state transition.\n *\n * Contains enough context to debug without reproduction:\n * the collection, record, field, current state, attempted state, and allowed transitions.\n */\nexport class InvalidStateTransitionError extends KoraError {\n\tconstructor(\n\t\tpublic readonly collection: string,\n\t\tpublic readonly recordId: string,\n\t\tpublic readonly field: string,\n\t\tpublic readonly fromState: string,\n\t\tpublic readonly toState: string,\n\t\tpublic readonly allowedStates: string[],\n\t) {\n\t\tsuper(\n\t\t\t`Invalid state transition in collection \"${collection}\": ` +\n\t\t\t\t`cannot transition field \"${field}\" from \"${fromState}\" to \"${toState}\". ` +\n\t\t\t\t`Allowed transitions from \"${fromState}\": ${allowedStates.length > 0 ? allowedStates.join(', ') : '(none -- terminal state)'}`,\n\t\t\t'INVALID_STATE_TRANSITION',\n\t\t\t{ collection, recordId, field, fromState, toState, allowedStates },\n\t\t)\n\t\tthis.name = 'InvalidStateTransitionError'\n\t}\n}\n\n/**\n * Validates a state machine transition for a local mutation (insert or update).\n *\n * For inserts: validates that the initial state (from the data or the default value)\n * is a known state in the state machine.\n *\n * For updates: looks up the current state field value and checks whether\n * the transition to the new value is allowed.\n *\n * @param collectionName - Name of the collection\n * @param recordId - The record being mutated\n * @param stateMachine - The state machine definition\n * @param currentState - The current value of the state field (null for inserts)\n * @param newState - The new value being set for the state field\n * @returns An object indicating whether the transition is valid, and if not, the allowed states.\n *          When `onInvalidTransition` is 'last-valid-state', callers should suppress the field update\n *          rather than throwing.\n */\nexport function validateStateTransition(\n\tcollectionName: string,\n\trecordId: string,\n\tstateMachine: StateMachineDefinition,\n\tcurrentState: string | null,\n\tnewState: string,\n): { valid: boolean; allowedStates: string[] } {\n\t// For inserts, any valid enum value is acceptable as the initial state\n\t// (schema validation already ensures the value is a valid enum value)\n\tif (currentState === null) {\n\t\treturn { valid: true, allowedStates: [] }\n\t}\n\n\t// Same-state transitions are always valid (idempotent updates)\n\tif (currentState === newState) {\n\t\treturn { valid: true, allowedStates: stateMachine.transitions[currentState] ?? [] }\n\t}\n\n\tconst constraint: StateMachineConstraint = {\n\t\tfield: stateMachine.field,\n\t\tcollection: collectionName,\n\t\ttransitions: stateMachine.transitions,\n\t}\n\tconst transitionResult = validateTransition(constraint, currentState, newState)\n\tif (transitionResult.valid) {\n\t\treturn { valid: true, allowedStates: transitionResult.allowedTargets }\n\t}\n\n\tconst allowedStates = transitionResult.allowedTargets\n\n\tif (stateMachine.onInvalidTransition === 'reject') {\n\t\tthrow new InvalidStateTransitionError(\n\t\t\tcollectionName,\n\t\t\trecordId,\n\t\t\tstateMachine.field,\n\t\t\tcurrentState,\n\t\t\tnewState,\n\t\t\tallowedStates,\n\t\t)\n\t}\n\n\t// 'last-valid-state': return invalid so the caller can suppress the field update\n\treturn { valid: false, allowedStates }\n}\n\n/**\n * Checks whether a collection update data object contains a change to the state machine field,\n * and if so, validates the transition.\n *\n * If the state field is not in the update data, returns the data unchanged.\n * If the transition is invalid and mode is 'last-valid-state', removes the field from the data.\n * If the transition is invalid and mode is 'reject', throws InvalidStateTransitionError.\n *\n * @param collectionName - Name of the collection\n * @param recordId - The record being updated\n * @param collectionDef - The collection definition from the schema\n * @param currentRecord - The current record data (must include the state field)\n * @param updateData - The partial update data\n * @returns The update data, potentially with the state field removed if invalid and mode is 'last-valid-state'\n */\nexport function validateUpdateStateMachine(\n\tcollectionName: string,\n\trecordId: string,\n\tcollectionDef: CollectionDefinition,\n\tcurrentRecord: Record<string, unknown>,\n\tupdateData: Record<string, unknown>,\n): Record<string, unknown> {\n\tlet result = updateData\n\tconst stateMachine = collectionDef.stateMachine\n\tif (stateMachine !== undefined) {\n\t\tresult = applyStateMachine(collectionName, recordId, stateMachine, currentRecord, result)\n\t}\n\t// Field-level `t.enum(...).transitions()` maps are state machines too, in the\n\t// default 'reject' mode (NEW-STORE-3). A collection-level machine on the same\n\t// field takes precedence.\n\tfor (const [field, descriptor] of Object.entries(collectionDef.fields)) {\n\t\tif (descriptor.kind !== 'enum' || !descriptor.transitions) continue\n\t\tif (stateMachine?.field === field) continue\n\t\tresult = applyStateMachine(\n\t\t\tcollectionName,\n\t\t\trecordId,\n\t\t\t{ field, transitions: descriptor.transitions, onInvalidTransition: 'reject' },\n\t\t\tcurrentRecord,\n\t\t\tresult,\n\t\t)\n\t}\n\treturn result\n}\n\nfunction applyStateMachine(\n\tcollectionName: string,\n\trecordId: string,\n\tstateMachine: StateMachineDefinition,\n\tcurrentRecord: Record<string, unknown>,\n\tupdateData: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst stateField = stateMachine.field\n\tif (!(stateField in updateData)) {\n\t\t// State field not being changed -- no validation needed\n\t\treturn updateData\n\t}\n\n\tconst currentState = currentRecord[stateField]\n\tconst newState = updateData[stateField]\n\n\t// Both values must be strings for state machine validation\n\tif (typeof currentState !== 'string' || typeof newState !== 'string') {\n\t\treturn updateData\n\t}\n\n\tconst result = validateStateTransition(\n\t\tcollectionName,\n\t\trecordId,\n\t\tstateMachine,\n\t\tcurrentState,\n\t\tnewState,\n\t)\n\n\tif (result.valid) {\n\t\treturn updateData\n\t}\n\n\t// Mode is 'last-valid-state': silently remove the state field from the update\n\tconst filtered = { ...updateData }\n\tdelete filtered[stateField]\n\n\t// If no fields remain after removing the state field, the update becomes a no-op.\n\t// Return the empty object -- the caller can decide whether to proceed.\n\treturn filtered\n}\n","import type { CollectionDefinition, FoldState, SchemaDefinition } from '@korajs/core'\nimport { deserializeFoldState, mismatchedFoldFields, quoteIdent } from '@korajs/core'\nimport type { LocalMutationContext } from '../mutations/types'\nimport type { WriteEnv } from '../mutations/write-context'\nimport type { WriteResult } from '../mutations/write-ops'\nimport type { PreparedInsert } from '../mutations/write-shapes'\nimport { deserializeRecord } from '../serialization/serializer'\nimport type { ObservedRead, TransactionWrite } from '../transaction/transaction-context'\nimport type { CollectionRecord, RawCollectionRow, StorageAdapter } from '../types'\nimport type { CommitInfo, GroupChange, PendingEntry, PendingWrites } from './pending-writes'\nimport {\n\ttype MissReason,\n\ttype PredictEnv,\n\ttype PredictedChange,\n\ttype PredictedWriteKind,\n\ttype Prediction,\n\tdivergentFields,\n\tisDeletePredictable,\n\tpredictDelete,\n\tpredictInsert,\n\tpredictUpdate,\n\tsameValue,\n\ttoReadShape,\n\tupdateNeedsFoldState,\n} from './predict'\n\n/*\n * Prepare-once plumbing between the local write entry points (`execute-*.ts`) and the\n * overlay (instant-UI stage S2, docs/design/instant-ui-updates.md 4.1, 5.3a, 5.6).\n *\n * OFF BY DEFAULT and PER STORE (stage S4): a store built with `instantUpdates` owns an\n * {@link OverlayController}, whose {@link WriteOverlay} rides on the store's mutation\n * contexts (`LocalMutationContext.overlay`). A context without one (the default) is never\n * touched by anything here. The write path never reads the overlay (I1): the entry points\n * only report a write's outcome to it.\n */\n\n/** Longest the base-record read for an update may take before the write is not predicted (5.6). */\nexport const BASE_READ_TIMEOUT_MS = 4\n\n/** What a base-record read needs: the adapter to read through and the schema to shape the row. */\nexport interface OverlayReadEnv {\n\treadonly adapter: StorageAdapter\n\treadonly schema: SchemaDefinition\n}\n\n/** What predicting a transaction (an entry group) needs from the write environment. */\nexport type GroupEnv = PredictEnv & OverlayReadEnv & Pick<WriteEnv, 'assertLocalWriteAllowed'>\n\n/** What the entry points need from an installed overlay. */\nexport interface WriteOverlay {\n\treadonly registry: PendingWrites\n\t/**\n\t * True while the adapter refuses writes (the durability-lost state). Checked before a\n\t * write is registered, never after (F2). Default: writes are accepted.\n\t */\n\treadonly writesRefused?: () => boolean\n\t/**\n\t * Read a record by id (the read the store itself would make). Default: a `SELECT` on\n\t * the write's adapter. Tests pass a controllable one.\n\t */\n\treadonly readRecord?: (\n\t\tctx: OverlayReadEnv,\n\t\tcollection: string,\n\t\tid: string,\n\t) => Promise<CollectionRecord | null>\n\t/**\n\t * Read a record's stored fold state (an array write builds on it, S6b). Default: a\n\t * `SELECT` on the write's adapter. Resolves null when there is none or it cannot be\n\t * used. Tests pass a controllable one.\n\t */\n\treadonly readFoldState?: (\n\t\tctx: OverlayReadEnv,\n\t\tcollection: string,\n\t\tid: string,\n\t) => Promise<FoldState | null>\n\t/** Wall clock for predicted timestamps; default `Date.now`. Injected by tests. */\n\treadonly wallClock?: () => number\n\t/** Longest base read, in ms; default {@link BASE_READ_TIMEOUT_MS}. */\n\treadonly baseReadTimeoutMs?: number\n\t/**\n\t * True while prediction is switched off for a collection (the circuit breaker, I10).\n\t * Checked before a write is registered; such a write runs as it does without the overlay.\n\t */\n\treadonly isCollectionDisabled?: (collection: string) => boolean\n\t/**\n\t * Called after a write was rolled back, with every entry the rollback removed (the\n\t * write's own and the ones derived from it) and the error that failed the write.\n\t */\n\treadonly onRolledBack?: (entries: readonly PendingEntry[], error: unknown) => void\n}\n\n/** Per-write options the entry points pass on (`{ durable: true }` skips prediction). */\nexport interface TrackOptions {\n\treadonly durable?: boolean\n}\n\n/**\n * Follows one predicted write from registration to its outcome. The entry points call\n * {@link WriteTracker.committed} from `runLocalWrite`'s post-commit hook and\n * {@link WriteTracker.failed} when the write rejects. Neither can throw.\n */\nexport interface WriteTracker {\n\t/** The transaction committed. */\n\tcommitted(results: readonly WriteResult[]): void\n\t/**\n\t * The write failed. A no-op once the write has committed (a later barrier failure is\n\t * not a rollback) or its outcome was left unknown (a commit that cannot be confirmed\n\t * is never silently rolled back, F11).\n\t */\n\tfailed(error?: unknown): void\n\t/**\n\t * The commit's answer was lost and the lookup could not decide: the entries stay shown\n\t * as `unknown` until a later read decides (7).\n\t *\n\t * @param lookupOperationId - The content-addressed id that decides whether it landed\n\t */\n\tunknown(lookupOperationId: string | null): void\n}\n\n/** Wall time to predict: at least now, and at least every timestamp this registry saw committed. */\nfunction predictedWallTime(overlay: WriteOverlay): number {\n\treturn Math.max((overlay.wallClock ?? Date.now)(), overlay.registry.wallTimeFloor())\n}\n\n/** Whether the write may be predicted at all, before looking at its values (5.2, F1, F2). */\nfunction gateMiss(\n\tctx: Pick<WriteEnv, 'assertLocalWriteAllowed'>,\n\toverlay: WriteOverlay,\n\tcollection: string,\n\toptions: TrackOptions | undefined,\n): MissReason | null {\n\tif (options?.durable === true) return 'durable-option'\n\ttry {\n\t\tctx.assertLocalWriteAllowed?.()\n\t} catch {\n\t\treturn 'write-gate'\n\t}\n\tif (overlay.writesRefused?.()) return 'writes-refused'\n\tif (overlay.isCollectionDisabled?.(collection)) return 'collection-disabled'\n\treturn null\n}\n\n/** Whether a write this one was derived from (transitively) has not reported its outcome yet. */\nfunction baseUnsettled(overlay: WriteOverlay, entry: PendingEntry): boolean {\n\tfor (const id of entry.ancestors) {\n\t\t// A write derived from one that has since been rolled back was stored on the old record.\n\t\tif (overlay.registry.wasRolledBack(id)) return true\n\t\tif (overlay.registry.get(id)?.state === 'pending') return true\n\t}\n\treturn false\n}\n\n/**\n * The fields on which a committed write differs from its prediction (5.3e).\n *\n * The prediction was made on a base (the pending chain, the row cache, a read). When the\n * base the transaction really read differs from it on a field the write sets\n * (`operation.previousData` against the predicted base), a remote write or another tab\n * changed that field in between and a value that depends on its base (an atomic op, a\n * counter, a max or min) legitimately differs. Those fields are then judged against a\n * prediction made again from the base the transaction read: that tests the predictor\n * (`prediction(real base) == committed fold`), not the race. A field that cannot be\n * predicted again (an array needs the fold state) is not judged. When the collection also\n * changed under the write (a remote apply, another tab), only the fields the write sets are\n * compared; otherwise the whole record is, as before.\n */\nfunction divergenceOf(\n\toverlay: WriteOverlay,\n\tentry: PendingEntry,\n\tchange: PredictedChange | undefined,\n\tresult: WriteResult,\n\tcommitted: CollectionRecord,\n\tdefinition: CollectionDefinition | undefined,\n): string[] {\n\tif (entry.kind !== 'update') {\n\t\t// A delete removes the record whatever a remote write changed in it meanwhile.\n\t\tconst unsettled = baseUnsettled(overlay, entry)\n\t\tconst concurrent =\n\t\t\toverlay.registry.foreignCount(entry.collection) !== entry.foreignAtAdd ||\n\t\t\toverlay.registry.foreignSince(entry)\n\t\tif (entry.kind === 'delete' && (unsettled || concurrent)) {\n\t\t\toverlay.registry.noteUnverified(unsettled ? 'unsettled-base' : 'concurrent-remote')\n\t\t\treturn []\n\t\t}\n\t\treturn divergentFields(entry.record, committed)\n\t}\n\tconst written = Object.keys(entry.patch ?? {}).filter((field) => field !== 'updatedAt')\n\tconst operated = result.operation?.previousData ?? null\n\t// A field the commit left out of the operation was already the record's value (a write\n\t// that moved under the prediction): its base is the stored value, which is also what was\n\t// written, so the base and the written value agree for it.\n\tconst actual =\n\t\toperated === null\n\t\t\t? null\n\t\t\t: {\n\t\t\t\t\t...operated,\n\t\t\t\t\t...Object.fromEntries(\n\t\t\t\t\t\twritten\n\t\t\t\t\t\t\t.filter((field) => !(field in operated))\n\t\t\t\t\t\t\t.map((field) => [field, committed[field]]),\n\t\t\t\t\t),\n\t\t\t\t}\n\tconst moved =\n\t\tactual === null\n\t\t\t? []\n\t\t\t: written.filter((field) => !sameValue(entry.previous?.[field], actual[field]))\n\t// The write this one was derived from has not reported yet: it committed (its bookkeeping\n\t// is queued behind this one's) or it failed and its rollback is on the way. Either way the\n\t// stored record may not hold what the prediction built on, so only the fields this write\n\t// sets are judged.\n\tconst unsettled = baseUnsettled(overlay, entry)\n\tconst concurrent =\n\t\toverlay.registry.foreignCount(entry.collection) !== entry.foreignAtAdd ||\n\t\toverlay.registry.foreignSince(entry)\n\tconst noisy = unsettled || concurrent\n\tif (noisy) overlay.registry.noteUnverified(unsettled ? 'unsettled-base' : 'concurrent-remote')\n\tconst expected: Record<string, unknown> = { ...entry.record }\n\tconst skipped = new Set<string>()\n\t// An array write is re-predicted whenever the commit reported the fold state it merged\n\t// into, not only when a value moved: which copy of an element is present is not in the\n\t// values, so two equal-looking bases can fold differently.\n\tconst replayAlways = entry.foldState !== null && result.priorFoldState !== undefined\n\tif ((moved.length > 0 || replayAlways) && actual !== null) {\n\t\tconst again = change?.replay?.(actual, result.priorFoldState ?? null)\n\t\tif (again?.predicted) Object.assign(expected, again.patch)\n\t\telse {\n\t\t\tfor (const field of moved) skipped.add(field)\n\t\t\tif (skipped.size > 0) overlay.registry.noteUnverified('replay-declined')\n\t\t}\n\t}\n\tif (!noisy) {\n\t\tfor (const field of skipped) expected[field] = committed[field]\n\t\treturn divergentFields(expected as CollectionRecord, committed)\n\t}\n\t// A field whose stored value depends on its base (a merge strategy, an array, an atomic\n\t// intent) cannot be judged on a base that is not settled: the write before it may have\n\t// failed (its rollback on the way) or be queued behind this one, so the prediction folded\n\t// the write into a different base than the one it was stored on.\n\tconst atomic = result.operation?.atomicOps ?? null\n\tconst baseDependent = (field: string): boolean => {\n\t\tconst descriptor = definition?.fields[field]\n\t\treturn (\n\t\t\t(descriptor?.mergeStrategy ?? null) !== null ||\n\t\t\tdescriptor?.kind === 'array' ||\n\t\t\t(atomic !== null && field in atomic)\n\t\t)\n\t}\n\treturn written\n\t\t.filter((field) => !(unsettled && baseDependent(field)))\n\t\t.filter((field) => !skipped.has(field) && !sameValue(expected[field], committed[field]))\n\t\t.sort()\n}\n\nfunction track(\n\tctx: LocalMutationContext,\n\toverlay: WriteOverlay,\n\tchanges: readonly PredictedChange[],\n\tdependsOn: string | null,\n): WriteTracker | null {\n\tconst [only] = changes\n\tconst added =\n\t\tchanges.length === 1 && only\n\t\t\t? overlay.registry.add(only, { dependsOn })\n\t\t\t: overlay.registry.addMany(changes)\n\tif (!added.ok) {\n\t\t// Refused (caps): the write runs unpredicted, so it is a miss as far as the records go.\n\t\treturn guardMiss(\n\t\t\toverlay,\n\t\t\tonly?.kind ?? 'insert',\n\t\t\tchanges[0]?.collection ?? ctx.collection,\n\t\t\tchanges.map((change) => change.recordId),\n\t\t)\n\t}\n\tconst entries = 'entries' in added ? added.entries : [added.entry]\n\tconst first = entries[0]\n\tif (!first) return null\n\t// Settled once, one way: committed, rolled back, or left unknown.\n\tlet done = false\n\treturn {\n\t\tcommitted(results) {\n\t\t\tif (done) return\n\t\t\tdone = true\n\t\t\ttry {\n\t\t\t\tconst definition = ctx.schema.collections[first.collection]\n\t\t\t\tentries.forEach((entry, index) => {\n\t\t\t\t\tconst result = results[index]\n\t\t\t\t\t// In the shape reads have, so it is comparable with the prediction and is a\n\t\t\t\t\t// valid base for the next update (an insert returns absent optionals, a\n\t\t\t\t\t// SELECT returns null).\n\t\t\t\t\tconst record = result && definition ? toReadShape(definition, result.record) : undefined\n\t\t\t\t\tconst operationIds = result\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t...(result.operation ? [result.operation.id] : []),\n\t\t\t\t\t\t\t\t...result.sideEffects.map((operation) => operation.id),\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: []\n\t\t\t\t\t// A delete reports the record as it stood, not a committed row.\n\t\t\t\t\tconst committedRecord = entry.kind === 'delete' ? undefined : record\n\t\t\t\t\tconst retired = overlay.registry.commit(entry.writeId, {\n\t\t\t\t\t\t...(committedRecord ? { record: committedRecord } : {}),\n\t\t\t\t\t\toperationIds,\n\t\t\t\t\t\t// The commit found nothing to write (the base moved under the prediction).\n\t\t\t\t\t\t...(entry.kind === 'update' && result && result.operation === null\n\t\t\t\t\t\t\t? { unchanged: true }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t})\n\t\t\t\t\t// Verification at commit (5.3e): the prediction against what the write stored.\n\t\t\t\t\tif (retired && record && result) {\n\t\t\t\t\t\toverlay.registry.reportDivergence(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t\tdivergenceOf(overlay, entry, changes[index], result, record, definition),\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[kora] overlay commit bookkeeping failed', error)\n\t\t\t}\n\t\t},\n\t\tfailed(error) {\n\t\t\tif (done) return\n\t\t\tdone = true\n\t\t\ttry {\n\t\t\t\tconst removed: PendingEntry[] = []\n\t\t\t\tfor (const entry of entries) removed.push(...overlay.registry.rollback(entry.writeId))\n\t\t\t\tif (removed.length > 0) overlay.onRolledBack?.(removed, error)\n\t\t\t} catch (failure) {\n\t\t\t\tconsole.error('[kora] overlay rollback bookkeeping failed', failure)\n\t\t\t}\n\t\t},\n\t\tunknown(lookupOperationId) {\n\t\t\tif (done) return\n\t\t\t// Without a witness nothing can decide it later, and a write that produced no\n\t\t\t// operation changed nothing: taking its prediction back is exact (as for a\n\t\t\t// transaction).\n\t\t\tif (lookupOperationId === null) {\n\t\t\t\tthis.failed(new Error('The write produced no operation and its commit was not confirmed.'))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdone = true\n\t\t\ttry {\n\t\t\t\tfor (const entry of entries) overlay.registry.markUnknown(entry.writeId, lookupOperationId)\n\t\t\t} catch (failure) {\n\t\t\t\tconsole.error('[kora] overlay unknown-outcome bookkeeping failed', failure)\n\t\t\t}\n\t\t},\n\t}\n}\n\nfunction noteMiss(\n\toverlay: WriteOverlay,\n\tkind: PredictedWriteKind,\n\tcollection: string,\n\trecordIds: readonly string[],\n\treason: MissReason,\n): WriteTracker | null {\n\toverlay.registry.noteMiss(kind, collection, recordIds, reason)\n\treturn guardMiss(overlay, kind, collection, recordIds)\n}\n\n/**\n * A write that is not predicted still changes records the registry may know: while it\n * runs, the registry must not derive a later write from what it knew before. Inserts\n * create new ids and need no guard (null: the write runs as it does with the overlay off).\n */\nfunction guardMiss(\n\toverlay: WriteOverlay,\n\tkind: PredictedWriteKind,\n\tcollection: string,\n\trecordIds: readonly string[],\n): WriteTracker | null {\n\tif (kind === 'insert') return null\n\tconst release = overlay.registry.holdUnpredicted(collection, recordIds)\n\treturn { committed: release, failed: release, unknown: release }\n}\n\n/**\n * Predict an insert from the prepared insert the transaction will write (the SAME\n * object, I4) and register it. Synchronous: an insert needs no read.\n *\n * @returns A tracker, or null when the write is not predicted (it then runs as today)\n */\nexport function trackInsert(\n\tctx: LocalMutationContext,\n\toverlay: WriteOverlay,\n\tprepared: PreparedInsert,\n\toptions?: TrackOptions,\n): WriteTracker | null {\n\tconst gate = gateMiss(ctx, overlay, prepared.collection, options)\n\tif (gate) return noteMiss(overlay, 'insert', prepared.collection, [prepared.recordId], gate)\n\tconst prediction = safely(() => predictInsert(ctx, prepared, predictedWallTime(overlay)))\n\treturn register(ctx, overlay, prediction, 'insert', prepared.collection, prepared.recordId, null)\n}\n\n/**\n * Predict a bulk insert (one transaction, all or none) and register one entry per record,\n * together or not at all: a write over the record or byte caps, or with a record the\n * predictor declines, is not predicted (8). The entries share the write's fate.\n *\n * @param prepared - The objects `executeInsertMany` will write, in input order\n */\nexport function trackInsertMany(\n\tctx: LocalMutationContext,\n\toverlay: WriteOverlay,\n\tprepared: readonly PreparedInsert[],\n\toptions?: TrackOptions,\n): WriteTracker | null {\n\tconst first = prepared[0]\n\tif (!first) return null\n\tconst ids = prepared.map((insert) => insert.recordId)\n\tconst gate = gateMiss(ctx, overlay, first.collection, options)\n\tif (gate) return noteMiss(overlay, 'insert', first.collection, ids, gate)\n\tif (prepared.length > overlay.registry.limits.maxRecordsPerWrite) {\n\t\treturn noteMiss(overlay, 'insert', first.collection, ids, 'records-cap')\n\t}\n\tconst wallTime = predictedWallTime(overlay)\n\tconst changes: PredictedChange[] = []\n\tfor (const insert of prepared) {\n\t\tconst prediction = safely(() => predictInsert(ctx, insert, wallTime))\n\t\tif (!prediction.predicted) {\n\t\t\treturn noteMiss(overlay, 'insert', first.collection, ids, prediction.reason)\n\t\t}\n\t\tchanges.push(prediction)\n\t}\n\treturn track(ctx, overlay, changes, null)\n}\n\n/**\n * The outcome of the one read an update or delete may need for its base record (5.6).\n * Only produced when neither a pending write nor the committed-row cache knows the record.\n */\nexport type BaseRead =\n\t| { readonly status: 'skipped' }\n\t| {\n\t\t\treadonly status: 'read'\n\t\t\treadonly record: CollectionRecord | null\n\t\t\t/**\n\t\t\t * The stored fold state, when one was asked for (S6b): null when there is none.\n\t\t\t * `stateToken` is the registry's seed stamp taken before the read was issued.\n\t\t\t */\n\t\t\treadonly foldState?: FoldState | null\n\t\t\treadonly stateToken?: number\n\t  }\n\t| { readonly status: 'timeout' }\n\t| { readonly status: 'error' }\n\n/**\n * Read the record an update or delete needs as its base, but only when the registry does\n * not already know it. Returns synchronously (`skipped`) in the common case, so the\n * caller's registration and its `runLocalWrite` call stay in one synchronous step: the\n * registration order of overlapping writes is then the order of their transactions,\n * which is the order patches must be applied in. A read that takes longer than\n * {@link BASE_READ_TIMEOUT_MS} gives up (`timeout`) and the write is not predicted.\n */\nexport function readBaseIfNeeded(\n\tctx: OverlayReadEnv,\n\toverlay: WriteOverlay,\n\tcollection: string,\n\tid: string,\n\tneedsState = false,\n): BaseRead | Promise<BaseRead> {\n\tconst needRecord = overlay.registry.baseFor(collection, id).found === 'none'\n\t// An unsettled write that carries no state (\"unknown\") cannot be helped by a read.\n\tconst needState = needsState && overlay.registry.foldStateFor(collection, id).found === 'none'\n\tif (!needRecord && !needState) return { status: 'skipped' }\n\treturn readBase(ctx, overlay, collection, id, needRecord, needState)\n}\n\nasync function readBase(\n\tctx: OverlayReadEnv,\n\toverlay: WriteOverlay,\n\tcollection: string,\n\tid: string,\n\twantRecord: boolean,\n\twantState: boolean,\n): Promise<BaseRead> {\n\tconst read = overlay.readRecord ?? defaultReadRecord\n\tconst readState = overlay.readFoldState ?? defaultReadFoldState\n\tconst timeoutMs = overlay.baseReadTimeoutMs ?? BASE_READ_TIMEOUT_MS\n\tlet stateToken = 0\n\tlet timer: ReturnType<typeof setTimeout> | undefined\n\tconst timedOut = new Promise<'timeout'>((resolve) => {\n\t\ttimer = setTimeout(() => resolve('timeout'), timeoutMs)\n\t})\n\ttry {\n\t\tconst outcome = await Promise.race([\n\t\t\t(async () => {\n\t\t\t\t// An earlier write of this record that is still running (pending, or not predicted)\n\t\t\t\t// is not in the database yet: read after it, or the base lacks it. Within the same\n\t\t\t\t// budget, so a slow commit makes this write a miss, never a wrong prediction.\n\t\t\t\tconst running = overlay.registry.whenRecordSettled(collection, id)\n\t\t\t\tif (running) await running\n\t\t\t\t// Taken when the read is issued: any change the registry hears of before the\n\t\t\t\t// result arrives makes the state older than what it knows.\n\t\t\t\tstateToken = overlay.registry.seedStamp(collection)\n\t\t\t\treturn Promise.all([\n\t\t\t\t\twantRecord ? read(ctx, collection, id) : Promise.resolve(null),\n\t\t\t\t\twantState ? readState(ctx, collection, id) : Promise.resolve(null),\n\t\t\t\t])\n\t\t\t})(),\n\t\t\ttimedOut,\n\t\t])\n\t\tif (outcome === 'timeout') return { status: 'timeout' }\n\t\tconst [record, foldState] = outcome\n\t\treturn {\n\t\t\tstatus: 'read',\n\t\t\trecord,\n\t\t\t...(wantState ? { foldState, stateToken } : {}),\n\t\t}\n\t} catch {\n\t\treturn { status: 'error' }\n\t} finally {\n\t\tif (timer !== undefined) clearTimeout(timer)\n\t}\n}\n\ntype BaseResolution =\n\t| { miss: null; record: CollectionRecord; dependsOn: string | null }\n\t| { miss: MissReason }\n\n/**\n * The record's current values for an update or delete (5.6): the newest pending write\n * (the chain), else the committed-row cache, else the read. Looked up again here, after\n * any read, so a write registered while the read was in flight wins over the read.\n */\nfunction resolveBase(\n\toverlay: WriteOverlay,\n\tcollection: string,\n\tid: string,\n\tread: BaseRead,\n): BaseResolution {\n\tconst known = overlay.registry.baseFor(collection, id)\n\tif (known.found === 'deleted') return { miss: 'no-base' }\n\tif (known.found === 'record') {\n\t\tconst pending = overlay.registry.pendingFor(collection, id)\n\t\treturn { miss: null, record: known.record, dependsOn: pending?.writeId ?? null }\n\t}\n\tif (read.status === 'timeout') return { miss: 'base-timeout' }\n\tif (read.status !== 'read' || read.record === null) return { miss: 'no-base' }\n\toverlay.registry.cacheRecord(collection, read.record)\n\treturn { miss: null, record: read.record, dependsOn: null }\n}\n\ntype StateResolution = { miss: null; state: FoldState } | { miss: MissReason }\n\n/**\n * The record's fold state for an array write (S6b): the newest unsettled write of the\n * record carries it, else the committed state the read returned, if nothing the registry\n * heard of (a commit, a remote apply, a clear) happened since the read was issued.\n */\nfunction resolveFoldState(\n\toverlay: WriteOverlay,\n\tcollection: string,\n\tid: string,\n\tread: BaseRead,\n): StateResolution {\n\tconst known = overlay.registry.foldStateFor(collection, id)\n\tif (known.found === 'state') return { miss: null, state: known.state }\n\tif (known.found === 'unknown') return { miss: 'array-chain' }\n\tif (read.status === 'timeout') return { miss: 'base-timeout' }\n\tif (read.status !== 'read' || !read.foldState) return { miss: 'no-fold-state' }\n\tif (read.stateToken !== overlay.registry.seedStamp(collection))\n\t\treturn { miss: 'fold-state-stale' }\n\treturn { miss: null, state: read.foldState }\n}\n\n/**\n * Predict an update and register it, synchronously (the caller then starts the write in\n * the same step).\n *\n * @param read - Result of {@link readBaseIfNeeded}\n */\nexport function trackUpdate(\n\tctx: LocalMutationContext,\n\toverlay: WriteOverlay,\n\tid: string,\n\tvalidated: Record<string, unknown>,\n\tread: BaseRead,\n\toptions?: TrackOptions,\n): WriteTracker | null {\n\tconst collection = ctx.collection\n\tconst gate = gateMiss(ctx, overlay, collection, options)\n\tif (gate) return noteMiss(overlay, 'update', collection, [id], gate)\n\tconst base = resolveBase(overlay, collection, id, read)\n\tif (base.miss) return noteMiss(overlay, 'update', collection, [id], base.miss)\n\tlet baseState: FoldState | null = null\n\tif (updateNeedsFoldState(ctx, collection, validated)) {\n\t\tconst state = resolveFoldState(overlay, collection, id, read)\n\t\tif (state.miss) return noteMiss(overlay, 'update', collection, [id], state.miss)\n\t\tbaseState = state.state\n\t}\n\tconst prediction = safely(() =>\n\t\tpredictUpdate(\n\t\t\tctx,\n\t\t\tcollection,\n\t\t\tid,\n\t\t\tvalidated,\n\t\t\tbase.record,\n\t\t\tpredictedWallTime(overlay),\n\t\t\tbaseState,\n\t\t),\n\t)\n\treturn register(ctx, overlay, prediction, 'update', collection, id, base.dependsOn)\n}\n\n/** Predict a delete (a tombstone) and register it, synchronously. */\nexport function trackDelete(\n\tctx: LocalMutationContext,\n\toverlay: WriteOverlay,\n\tid: string,\n\tread: BaseRead,\n\toptions?: TrackOptions,\n): WriteTracker | null {\n\tconst collection = ctx.collection\n\tconst gate = gateMiss(ctx, overlay, collection, options)\n\tif (gate) return noteMiss(overlay, 'delete', collection, [id], gate)\n\t// Declined by the schema whatever the record holds: no base is needed (nor was one read).\n\tif (!isDeletePredictable(ctx.schema, collection)) {\n\t\treturn noteMiss(overlay, 'delete', collection, [id], 'cascade-target')\n\t}\n\tconst base = resolveBase(overlay, collection, id, read)\n\tif (base.miss) return noteMiss(overlay, 'delete', collection, [id], base.miss)\n\tconst prediction = safely(() => predictDelete(ctx, collection, id, base.record))\n\treturn register(ctx, overlay, prediction, 'delete', collection, id, base.dependsOn)\n}\n\nfunction register(\n\tctx: LocalMutationContext,\n\toverlay: WriteOverlay,\n\tprediction: Prediction,\n\tkind: PredictedWriteKind,\n\tcollection: string,\n\trecordId: string,\n\tdependsOn: string | null,\n): WriteTracker | null {\n\tif (!prediction.predicted) {\n\t\treturn noteMiss(overlay, kind, collection, [recordId], prediction.reason)\n\t}\n\treturn track(ctx, overlay, [prediction], dependsOn)\n}\n\nfunction safely(predict: () => Prediction): Prediction {\n\ttry {\n\t\treturn predict()\n\t} catch {\n\t\treturn { predicted: false, reason: 'predictor-error' }\n\t}\n}\n\nasync function defaultReadRecord(\n\tctx: OverlayReadEnv,\n\tcollection: string,\n\tid: string,\n): Promise<CollectionRecord | null> {\n\tconst rows = await ctx.adapter.query<RawCollectionRow>(\n\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ? AND _deleted = 0`,\n\t\t[id],\n\t)\n\tconst row = rows[0]\n\tconst definition = ctx.schema.collections[collection]\n\treturn row && definition ? deserializeRecord(row, definition.fields) : null\n}\n\nasync function defaultReadFoldState(\n\tctx: OverlayReadEnv,\n\tcollection: string,\n\tid: string,\n): Promise<FoldState | null> {\n\tconst rows = await ctx.adapter.query<{ state: string }>(\n\t\t'SELECT state FROM _kora_fold_state WHERE collection = ? AND record_id = ?',\n\t\t[collection, id],\n\t)\n\tconst raw = rows[0]?.state\n\tif (raw === undefined) return null\n\ttry {\n\t\tconst state = deserializeFoldState(raw)\n\t\t// A state folded under another plan is re-folded by the write path; it is not a base.\n\t\treturn mismatchedFoldFields(state, ctx.schema).length > 0 ? null : state\n\t} catch {\n\t\treturn null\n\t}\n}\n\n// --- transactions: one entry group (design 5.9) ---\n\n/** Key of a record in the maps keyed by collection and id (also the write-order key). */\nexport const recordKey = (collection: string, id: string): string => `${collection}\\u0000${id}`\n\n/** The record a buffered write targets. */\nfunction targetOf(write: TransactionWrite): { collection: string; id: string } {\n\treturn write.kind === 'insert'\n\t\t? { collection: write.collection, id: write.insert.recordId }\n\t\t: { collection: write.collection, id: write.id }\n}\n\n/** The records a transaction touches, for the write order; `all` when it deletes (cascades). */\nexport function groupOrderKeys(writes: readonly TransactionWrite[]): {\n\tkeys: string[]\n\tall: boolean\n} {\n\treturn {\n\t\tkeys: writes.map((write) => {\n\t\t\tconst { collection, id } = targetOf(write)\n\t\t\treturn recordKey(collection, id)\n\t\t}),\n\t\tall: writes.some((write) => write.kind === 'delete'),\n\t}\n}\n\n/** Base reads a group needs, by record key. A record absent from the map needs none. */\nexport type GroupBaseReads = ReadonlyMap<string, BaseRead>\n\n/** Committed rows the transaction's callback read, by record key (see {@link ObservedRead}). */\nexport type ObservedReads = ReadonlyMap<string, ObservedRead>\n\n/**\n * The committed row the callback read for a record, if it is still as fresh as everything\n * the registry knows: the registry's seed stamp for the collection (foreign changes, its own\n * commits, clears) is the one taken before the read was issued, the rule\n * `PendingWrites.seedFromRead` uses for subscription rows. Null when it is not usable.\n */\nfunction observedBase(\n\toverlay: WriteOverlay,\n\tobserved: ObservedReads,\n\tcollection: string,\n\tid: string,\n): CollectionRecord | null {\n\tconst read = observed.get(recordKey(collection, id))\n\tif (!read || read.record === null || overlay.registry.isHeld(collection, id)) return null\n\treturn read.token === overlay.registry.seedStamp(collection) ? read.record : null\n}\n\n/**\n * The records of a group some write of which needs the fold state (an array write). The\n * record's earlier writes then carry the state forward too, so a later array write builds on\n * it instead of declining.\n */\nfunction recordsNeedingState(\n\tenv: PredictEnv,\n\twrites: readonly TransactionWrite[],\n): ReadonlySet<string> {\n\tconst keys = new Set<string>()\n\tfor (const write of writes) {\n\t\tif (write.kind !== 'update') continue\n\t\tconst { collection, id } = targetOf(write)\n\t\tif (updateNeedsFoldState(env, collection, write.data)) keys.add(recordKey(collection, id))\n\t}\n\treturn keys\n}\n\n/**\n * Step 2b of the group lifecycle: read the base record of every update or delete whose\n * record the group has not written earlier and the registry does not know, all in\n * parallel, each with the base-read budget. Synchronous (an empty map) when nothing needs\n * a read, which is the case for a transaction of inserts and for records a list showed.\n *\n * @param writes - The sealed transaction's writes, in buffer order\n */\nexport function readGroupBasesIfNeeded(\n\tenv: OverlayReadEnv & PredictEnv,\n\toverlay: WriteOverlay,\n\twrites: readonly TransactionWrite[],\n\tobserved: ObservedReads = new Map(),\n): GroupBaseReads | Promise<GroupBaseReads> {\n\tconst written = new Set<string>()\n\tconst needed = new Map<string, { collection: string; id: string }>()\n\tconst needsState = new Set<string>()\n\tconst stateKeys = recordsNeedingState(env, writes)\n\tfor (const write of writes) {\n\t\tconst { collection, id } = targetOf(write)\n\t\tconst key = recordKey(collection, id)\n\t\t// A delete the schema never predicts declines the group whatever the record holds.\n\t\tconst neverPredicted = write.kind === 'delete' && !isDeletePredictable(env.schema, collection)\n\t\tif (write.kind !== 'insert' && !neverPredicted && !written.has(key) && !needed.has(key)) {\n\t\t\t// Only the record's first write reads: a later write of it derives from the\n\t\t\t// group's own prediction (and an array write after a plain one is a miss).\n\t\t\tconst wantsState = write.kind === 'update' && stateKeys.has(key)\n\t\t\tconst knowsRecord =\n\t\t\t\toverlay.registry.baseFor(collection, id).found !== 'none' ||\n\t\t\t\tobservedBase(overlay, observed, collection, id) !== null\n\t\t\tconst knowsState =\n\t\t\t\t!wantsState || overlay.registry.foldStateFor(collection, id).found !== 'none'\n\t\t\tif (!knowsRecord || !knowsState) {\n\t\t\t\tneeded.set(key, { collection, id })\n\t\t\t\tif (wantsState) needsState.add(key)\n\t\t\t}\n\t\t}\n\t\twritten.add(key)\n\t}\n\tif (needed.size === 0) return new Map()\n\treturn Promise.all(\n\t\t[...needed].map(async ([key, { collection, id }]) => {\n\t\t\tconst read = readBaseIfNeeded(env, overlay, collection, id, needsState.has(key))\n\t\t\treturn [key, read instanceof Promise ? await read : read] as const\n\t\t}),\n\t).then((pairs) => new Map(pairs))\n}\n\n/**\n * Steps 2a, 2c and 2d of the group lifecycle: predict every write of a sealed transaction,\n * in buffer order, and register them as ONE entry group, all or nothing (T1). Synchronous,\n * so the caller starts the storage transaction in the same step.\n *\n * A write of a record the group already wrote derives from the group's own earlier\n * prediction; any other update or delete derives from the registry (and depends on its\n * pending entry, if any) or from the read of {@link readGroupBasesIfNeeded}. One declined\n * write, a gated collection, or a cap makes the whole group a miss: nothing is registered,\n * one miss is reported, and the records it updates or deletes are held until it settles.\n *\n * @param reads - Result of {@link readGroupBasesIfNeeded}\n * @param observed - Committed rows the callback read; one still fresh (its token matches)\n *   is the base of a record the registry does not know, so the group needs no read of it\n * @returns The group's tracker; null when nothing needs one (an unpredicted group of inserts)\n */\nexport function trackGroup(\n\tenv: GroupEnv,\n\toverlay: WriteOverlay,\n\twrites: readonly TransactionWrite[],\n\treads: GroupBaseReads,\n\tobserved: ObservedReads = new Map(),\n): WriteTracker | null {\n\tif (writes.length === 0) return null\n\tconst collections = [...new Set(writes.map((write) => write.collection))]\n\tconst recordIds = writes.map((write) => targetOf(write).id)\n\tconst miss = (reason: MissReason): WriteTracker | null => {\n\t\toverlay.registry.noteGroupMiss(collections, recordIds, reason)\n\t\treturn guardGroup(overlay, writes)\n\t}\n\tfor (const collection of collections) {\n\t\tconst gate = gateMiss(env, overlay, collection, undefined)\n\t\tif (gate) return miss(gate)\n\t}\n\tif (writes.length > overlay.registry.limits.maxRecordsPerWrite) return miss('records-cap')\n\tconst wallTime = predictedWallTime(overlay)\n\tconst stateKeys = recordsNeedingState(env, writes)\n\t// What the group itself has written so far: the base of its later writes of the record.\n\tconst local = new Map<string, CollectionRecord | 'deleted'>()\n\t// The fold state after the group's own write of a record, when its prediction produced one.\n\tconst localStates = new Map<string, FoldState>()\n\tconst changes: GroupChange[] = []\n\tfor (const write of writes) {\n\t\tconst { collection, id } = targetOf(write)\n\t\tconst key = recordKey(collection, id)\n\t\tlet prediction: Prediction\n\t\tlet dependsOn: string | null = null\n\t\tif (write.kind === 'delete' && !isDeletePredictable(env.schema, collection)) {\n\t\t\treturn miss('cascade-target')\n\t\t}\n\t\tif (write.kind === 'insert') {\n\t\t\tconst insert = write.insert\n\t\t\tprediction = safely(() => predictInsert(env, insert, wallTime))\n\t\t} else {\n\t\t\tconst own = local.get(key)\n\t\t\tlet base: CollectionRecord\n\t\t\tif (own === 'deleted') return miss('no-base')\n\t\t\tconst seen =\n\t\t\t\town === undefined && overlay.registry.baseFor(collection, id).found === 'none'\n\t\t\t\t\t? observedBase(overlay, observed, collection, id)\n\t\t\t\t\t: null\n\t\t\tif (own !== undefined) {\n\t\t\t\tbase = own\n\t\t\t} else if (seen !== null) {\n\t\t\t\t// The callback's own read of the committed row, still fresh: no second read.\n\t\t\t\toverlay.registry.cacheRecord(collection, seen)\n\t\t\t\tbase = seen\n\t\t\t} else {\n\t\t\t\tconst resolved = resolveBase(\n\t\t\t\t\toverlay,\n\t\t\t\t\tcollection,\n\t\t\t\t\tid,\n\t\t\t\t\treads.get(key) ?? { status: 'skipped' },\n\t\t\t\t)\n\t\t\t\tif (resolved.miss) return miss(resolved.miss)\n\t\t\t\tbase = resolved.record\n\t\t\t\tdependsOn = resolved.dependsOn\n\t\t\t}\n\t\t\tif (write.kind === 'update') {\n\t\t\t\tconst data = write.data\n\t\t\t\tlet baseState: FoldState | null = null\n\t\t\t\tif (stateKeys.has(key)) {\n\t\t\t\t\tif (own !== undefined) {\n\t\t\t\t\t\t// The group already wrote the record: build on its own prediction's state.\n\t\t\t\t\t\tbaseState = localStates.get(key) ?? null\n\t\t\t\t\t\tif (baseState === null) return miss('array-chain')\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst state = resolveFoldState(\n\t\t\t\t\t\t\toverlay,\n\t\t\t\t\t\t\tcollection,\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\treads.get(key) ?? { status: 'skipped' },\n\t\t\t\t\t\t)\n\t\t\t\t\t\tif (state.miss) return miss(state.miss)\n\t\t\t\t\t\tbaseState = state.state\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprediction = safely(() =>\n\t\t\t\t\tpredictUpdate(env, collection, id, data, base, wallTime, baseState),\n\t\t\t\t)\n\t\t\t} else {\n\t\t\t\tprediction = safely(() => predictDelete(env, collection, id, base))\n\t\t\t}\n\t\t}\n\t\tif (!prediction.predicted) return miss(prediction.reason)\n\t\tlocal.set(key, prediction.kind === 'delete' ? 'deleted' : prediction.record)\n\t\tif (prediction.foldState) localStates.set(key, prediction.foldState)\n\t\telse localStates.delete(key)\n\t\tchanges.push({ change: prediction, dependsOn })\n\t}\n\tconst added = overlay.registry.addGroup(changes)\n\t// Refused by a cap: the registry reported the miss; the group runs unpredicted.\n\tif (!added.ok) return guardGroup(overlay, writes)\n\treturn groupTracker(\n\t\tenv,\n\t\toverlay,\n\t\tadded.groupId,\n\t\tadded.entries,\n\t\tchanges.map((one) => one.change),\n\t)\n}\n\n/** The tracker of a registered group: every outcome acts on the whole group (T2). */\nfunction groupTracker(\n\tenv: GroupEnv,\n\toverlay: WriteOverlay,\n\tgroupId: string,\n\tentries: readonly PendingEntry[],\n\tchanges: readonly PredictedChange[],\n): WriteTracker {\n\tconst first = entries[0]\n\tlet done = false\n\tconst rollBack = (error: unknown): void => {\n\t\tif (!first) return\n\t\tconst removed = overlay.registry.rollback(first.writeId)\n\t\tif (removed.length > 0) overlay.onRolledBack?.(removed, error)\n\t}\n\treturn {\n\t\tcommitted(results) {\n\t\t\tif (done) return\n\t\t\tdone = true\n\t\t\ttry {\n\t\t\t\t// One result per buffered write, in order: entry i is write i.\n\t\t\t\tconst infos = new Map<string, CommitInfo>()\n\t\t\t\tconst committedRecords = new Map<string, CollectionRecord>()\n\t\t\t\tentries.forEach((entry, index) => {\n\t\t\t\t\tconst result = results[index]\n\t\t\t\t\tconst definition = env.schema.collections[entry.collection]\n\t\t\t\t\tconst record = result && definition ? toReadShape(definition, result.record) : undefined\n\t\t\t\t\tconst operationIds = result\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t...(result.operation ? [result.operation.id] : []),\n\t\t\t\t\t\t\t\t...result.sideEffects.map((operation) => operation.id),\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: []\n\t\t\t\t\t// A delete reports the record as it stood, not a committed row.\n\t\t\t\t\tconst committedRecord = entry.kind === 'delete' ? undefined : record\n\t\t\t\t\tinfos.set(entry.writeId, {\n\t\t\t\t\t\t...(committedRecord ? { record: committedRecord } : {}),\n\t\t\t\t\t\toperationIds,\n\t\t\t\t\t\t// The commit found nothing to write (the base moved under the prediction).\n\t\t\t\t\t\t...(entry.kind === 'update' && result && result.operation === null\n\t\t\t\t\t\t\t? { unchanged: true }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t})\n\t\t\t\t\tif (record) committedRecords.set(entry.writeId, record)\n\t\t\t\t})\n\t\t\t\tconst retired = overlay.registry.commitGroup(groupId, infos)\n\t\t\t\t// Verification at commit (5.3e), per member, against what its own write stored.\n\t\t\t\tentries.forEach((entry, index) => {\n\t\t\t\t\tconst record = committedRecords.get(entry.writeId)\n\t\t\t\t\tconst result = results[index]\n\t\t\t\t\tif (record && result && retired.some((one) => one.writeId === entry.writeId)) {\n\t\t\t\t\t\toverlay.registry.reportDivergence(\n\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t\tdivergenceOf(\n\t\t\t\t\t\t\t\toverlay,\n\t\t\t\t\t\t\t\tentry,\n\t\t\t\t\t\t\t\tchanges[index],\n\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\trecord,\n\t\t\t\t\t\t\t\tenv.schema.collections[entry.collection],\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})\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error('[kora] overlay transaction commit bookkeeping failed', error)\n\t\t\t}\n\t\t},\n\t\tfailed(error) {\n\t\t\tif (done) return\n\t\t\tdone = true\n\t\t\ttry {\n\t\t\t\trollBack(error)\n\t\t\t} catch (failure) {\n\t\t\t\tconsole.error('[kora] overlay transaction rollback bookkeeping failed', failure)\n\t\t\t}\n\t\t},\n\t\tunknown(lookupOperationId) {\n\t\t\tif (done) return\n\t\t\tdone = true\n\t\t\ttry {\n\t\t\t\t// Without a witness nothing can decide it later, and a transaction that wrote no\n\t\t\t\t// operation changed nothing: taking its prediction back is exact.\n\t\t\t\tif (lookupOperationId === null) {\n\t\t\t\t\trollBack(\n\t\t\t\t\t\tnew Error('The transaction wrote no operation and its commit was not confirmed.'),\n\t\t\t\t\t)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (first) overlay.registry.markUnknown(first.writeId, lookupOperationId)\n\t\t\t} catch (failure) {\n\t\t\t\tconsole.error('[kora] overlay transaction unknown-outcome bookkeeping failed', failure)\n\t\t\t}\n\t\t},\n\t}\n}\n\n/**\n * An unpredicted transaction still changes the records it updates and deletes: hold them\n * (one hold per collection) until it settles, as {@link guardMiss} does for a single\n * write. A transaction of inserts only needs no hold (null).\n */\nfunction guardGroup(\n\toverlay: WriteOverlay,\n\twrites: readonly TransactionWrite[],\n): WriteTracker | null {\n\tconst byCollection = new Map<string, string[]>()\n\tfor (const write of writes) {\n\t\tif (write.kind === 'insert') continue\n\t\tconst ids = byCollection.get(write.collection) ?? []\n\t\tif (!ids.includes(write.id)) ids.push(write.id)\n\t\tbyCollection.set(write.collection, ids)\n\t}\n\tif (byCollection.size === 0) return null\n\tconst releases = [...byCollection].map(([collection, ids]) =>\n\t\toverlay.registry.holdUnpredicted(collection, ids),\n\t)\n\tconst release = (): void => {\n\t\tfor (const one of releases) one()\n\t}\n\treturn { committed: release, failed: release, unknown: release }\n}\n","import type {\n\tCollectionDefinition,\n\tFieldDescriptor,\n\tFoldState,\n\tOperation,\n\tSchemaDefinition,\n} from '@korajs/core'\nimport { createFoldState, isAtomicOp, materialize, mergeOp } from '@korajs/core'\nimport { predictLocalUpdate } from '@korajs/core/internal'\nimport { mergeYjsUpdates } from '../fold/record-folder'\nimport type { RecordFolder } from '../fold/record-folder'\nimport { sameValue } from '../mutations/same-value'\nimport { withoutUnchangedFields } from '../mutations/unchanged-fields'\nimport type { WriteEnv } from '../mutations/write-context'\nimport {\n\ttype PreparedInsert,\n\tinsertOperationData,\n\tpatchForUpdate,\n\ttombstone,\n} from '../mutations/write-shapes'\nimport { deserializeRecord, serializeRecord } from '../serialization/serializer'\nimport { validateUpdateStateMachine } from '../state-machine/state-validator'\nimport type { CollectionRecord, RawCollectionRow } from '../types'\n\n/*\n * The overlay predictor (instant-UI stage S2, docs/design/instant-ui-updates.md 5.2 and 5.3).\n *\n * Given the SAME validated input the write path is about to write, compute the record\n * the committed row will read back as. Pure: no storage, no clock (the caller passes the\n * wall time to predict), no registration. Anything the predictor cannot prove it gets\n * exactly right is a miss with a reason (an allowlist, invariant I7), and a miss means\n * the write runs exactly as it does today.\n *\n * The predicted record is produced by the read-side functions, `serializeRecord` then\n * `deserializeRecord` (5.3b), so its shape (absent optionals are `null`, booleans are\n * booleans, ...) is the shape a `SELECT` row has, not the shape `insert()` returns.\n */\n\n/** Why a write was not predicted. Stable strings: they are reported to DevTools. */\nexport type MissReason =\n\t| 'secret-field'\n\t| 'richtext-field'\n\t| 'unsupported-field-kind'\n\t| 'atomic-op'\n\t| 'merge-strategy'\n\t| 'custom-resolver'\n\t| 'state-machine'\n\t| 'cascade-target'\n\t| 'no-base'\n\t| 'base-timeout'\n\t/** An array is written and the record's fold state could not be had (read refused or empty). */\n\t| 'no-fold-state'\n\t/** An earlier unsettled write of the record carries no fold state to build the array write on. */\n\t| 'array-chain'\n\t/** The fold state read does not describe the base record (a change landed between the two). */\n\t| 'fold-state-stale'\n\t| 'no-change'\n\t| 'write-gate'\n\t| 'writes-refused'\n\t| 'pending-cap'\n\t| 'bytes-cap'\n\t| 'records-cap'\n\t| 'unsupported-write'\n\t| 'predictor-error'\n\t/** The write passed `{ durable: true }`: shown at commit, as with instant updates off. */\n\t| 'durable-option'\n\t/** The circuit breaker opened for the collection after repeated divergences (I10). */\n\t| 'collection-disabled'\n\n/** The kind of a local write. */\nexport type PredictedWriteKind = 'insert' | 'update' | 'delete'\n\n/** What a write is predicted to do to one record. */\nexport interface PredictedChange {\n\treadonly predicted: true\n\treadonly kind: PredictedWriteKind\n\treadonly collection: string\n\treadonly recordId: string\n\t/**\n\t * Read-shaped field values the write sets: every field of the record for an insert,\n\t * the written fields plus `updatedAt` for an update, null for a delete (a tombstone).\n\t */\n\treadonly patch: Readonly<Record<string, unknown>> | null\n\t/**\n\t * For an update: the values the patched fields (and `updatedAt`) had before the write,\n\t * from the same base the prediction used. Lets the patcher tell a row that enters a\n\t * query (it did not match before) from one that vanished (it did) without reading it.\n\t * Null for an insert and a delete.\n\t */\n\treadonly previous?: Readonly<Record<string, unknown>> | null\n\t/**\n\t * The record as it stands after the write (the full record for an insert and update).\n\t * For a delete: the record as it stood when it was tombstoned.\n\t */\n\treadonly record: CollectionRecord\n\t/**\n\t * The record's fold state after the write, when the prediction was made on a real fold\n\t * state (a fresh insert, or an update of an array). The next write of the record builds\n\t * on it while this one is unsettled.\n\t */\n\treadonly foldState?: FoldState\n\t/**\n\t * Predict the same write again from the values the transaction actually read as its\n\t * base (`operation.previousData`), for the commit-time check when the base moved. Not\n\t * stored in the registry.\n\t */\n\treadonly replay?: (\n\t\tprevious: Readonly<Record<string, unknown>>,\n\t\tpriorState?: FoldState | null,\n\t) => Prediction\n}\n\n/** A write the predictor declined. */\nexport interface PredictionMiss {\n\treadonly predicted: false\n\treadonly reason: MissReason\n}\n\n/** The predictor's answer. */\nexport type Prediction = PredictedChange | PredictionMiss\n\n/** The part of the write environment the predictor reads. */\nexport type PredictEnv = Pick<WriteEnv, 'schema' | 'nodeId' | 'fold'>\n\n/** Field kinds an update may write under prediction (5.2). */\nconst SCALAR_UPDATE_KINDS: ReadonlySet<string> = new Set([\n\t'string',\n\t'number',\n\t'boolean',\n\t'enum',\n\t'timestamp',\n])\n\n/** `onDelete` actions whose enforcement writes or refuses in the transaction (5.2, F4). */\nconst ENFORCED_DELETE_ACTIONS: ReadonlySet<string> = new Set(['cascade', 'set-null', 'restrict'])\n\nconst miss = (reason: MissReason): PredictionMiss => ({ predicted: false, reason })\n\n/** True when any field of the collection is a secret (stored hashed or encrypted). */\nfunction hasSecretField(definition: CollectionDefinition): boolean {\n\treturn Object.values(definition.fields).some(\n\t\t(field) => field.kind === 'secret' || field.secretMode != null,\n\t)\n}\n\n/**\n * Whether a delete of a record of `collection` is free of in-transaction side effects:\n * no relation with an enforced `onDelete` points at the collection. Static per schema.\n */\nexport function isDeletePredictable(schema: SchemaDefinition, collection: string): boolean {\n\tfor (const relation of Object.values(schema.relations ?? {})) {\n\t\tif (relation.to === collection && ENFORCED_DELETE_ACTIONS.has(relation.onDelete)) return false\n\t}\n\treturn true\n}\n\n/** Build the read-shaped record of a row, through the same functions every read uses. */\nfunction readShape(\n\tdefinition: CollectionDefinition,\n\tid: string,\n\tvalues: Record<string, unknown>,\n\tcreatedAt: number,\n\tupdatedAt: number,\n): CollectionRecord {\n\tconst row: RawCollectionRow = {\n\t\t...serializeRecord(values, definition.fields),\n\t\tid,\n\t\t_created_at: createdAt,\n\t\t_updated_at: updatedAt,\n\t\t_deleted: 0,\n\t}\n\treturn deserializeRecord(row, definition.fields)\n}\n\n/**\n * A record the write path returned, in the shape a `SELECT` row reads back as (an\n * optional field that was not given is `null`, not absent). Used to compare a committed\n * `WriteResult.record` with a prediction (5.3e) and to seed the committed-row cache.\n */\nexport function toReadShape(\n\tdefinition: CollectionDefinition,\n\trecord: CollectionRecord,\n): CollectionRecord {\n\treturn readShape(\n\t\tdefinition,\n\t\trecord.id,\n\t\tfieldValues(definition, record),\n\t\trecord.createdAt,\n\t\trecord.updatedAt,\n\t)\n}\n\n/**\n * The provisional operation the fold merges for a fresh local insert. Its id, sequence\n * number and causal parents are placeholders: the materialized values of a\n * single-operation state do not depend on them. It is never hashed, stored or published.\n */\nfunction provisionalInsertOperation(\n\tenv: PredictEnv,\n\tinsert: PreparedInsert,\n\tdefinition: CollectionDefinition,\n\twallTime: number,\n): Operation {\n\treturn {\n\t\tid: 'overlay-prediction',\n\t\tnodeId: env.nodeId,\n\t\ttype: 'insert',\n\t\tcollection: insert.collection,\n\t\trecordId: insert.recordId,\n\t\tdata: insertOperationData(insert, definition),\n\t\tpreviousData: null,\n\t\ttimestamp: { wallTime, logical: 0, nodeId: env.nodeId },\n\t\tsequenceNumber: 0,\n\t\tcausalDeps: [],\n\t\tschemaVersion: env.schema.version,\n\t}\n}\n\n/**\n * The row values a fresh insert materializes to under the W7 fold: the same pure\n * functions `RecordFolder.applyInTx` runs for a fresh local insert (`mergeOp` on a\n * `createFoldState`, then `materialize`), keeping only the fields the fold state holds\n * as `materializeRow` does.\n */\nfunction foldedInsertValues(\n\tenv: PredictEnv,\n\tfold: RecordFolder,\n\tinsert: PreparedInsert,\n\tdefinition: CollectionDefinition,\n\twallTime: number,\n): { values: Record<string, unknown>; state: FoldState } {\n\tconst op = provisionalInsertOperation(env, insert, definition, wallTime)\n\tconst { state } = mergeOp(\n\t\tcreateFoldState(insert.collection, insert.recordId),\n\t\top,\n\t\tenv.schema,\n\t\tfold.options(),\n\t)\n\tconst values = materialize({ ...state, d: null }, { richtext: mergeYjsUpdates }) ?? {}\n\tconst out: Record<string, unknown> = {}\n\tfor (const field of Object.keys(definition.fields)) {\n\t\tif (field in state.f) out[field] = values[field] ?? null\n\t}\n\treturn { values: out, state }\n}\n\n/**\n * Predict an insert from the prepared insert the transaction will write (prepare once,\n * share: invariant I4).\n *\n * @param env - Schema, node id and the record fold (absent before re-materialization)\n * @param insert - The object `writeInsertInTx` will write\n * @param wallTime - The wall time to give `createdAt` and `updatedAt`\n */\nexport function predictInsert(\n\tenv: PredictEnv,\n\tinsert: PreparedInsert,\n\twallTime: number,\n): Prediction {\n\tconst definition = env.schema.collections[insert.collection]\n\tif (!definition) return miss('unsupported-write')\n\tif (hasSecretField(definition)) return miss('secret-field')\n\tfor (const name of Object.keys(insert.data)) {\n\t\tif (definition.fields[name]?.kind === 'richtext') return miss('richtext-field')\n\t}\n\ttry {\n\t\tconst folded = env.fold ? foldedInsertValues(env, env.fold, insert, definition, wallTime) : null\n\t\tconst record = readShape(\n\t\t\tdefinition,\n\t\t\tinsert.recordId,\n\t\t\tfolded ? folded.values : insert.data,\n\t\t\twallTime,\n\t\t\twallTime,\n\t\t)\n\t\treturn {\n\t\t\tpredicted: true,\n\t\t\tkind: 'insert',\n\t\t\tcollection: insert.collection,\n\t\t\trecordId: insert.recordId,\n\t\t\tpatch: fieldsOf(record),\n\t\t\trecord,\n\t\t\t// Only an array write builds on a fold state, so only collections with an array\n\t\t\t// field keep it (the entry's bytes and the registry's memory otherwise).\n\t\t\t...(folded && hasArrayField(definition) ? { foldState: folded.state } : {}),\n\t\t}\n\t} catch {\n\t\treturn miss('predictor-error')\n\t}\n}\n\n/** The schema fields of a record plus `updatedAt` (what an insert's patch carries). */\nfunction fieldsOf(record: CollectionRecord): Record<string, unknown> {\n\tconst { id: _id, createdAt: _createdAt, ...rest } = record\n\treturn rest\n}\n\n/** How a written field takes part in an update prediction. */\ninterface FieldClass {\n\t/** Why the field forbids predicting the update, or null. */\n\treadonly block: MissReason | null\n\t/**\n\t * Null for a plain last-write-wins scalar (the written value is the materialized value).\n\t * Otherwise the reason to give when the record fold is unavailable (before re-materialization): the\n\t * field's value comes from the fold itself (an atomic op, a merge strategy, an array).\n\t */\n\treadonly folded: MissReason | null\n}\n\nconst PLAIN_FIELD: FieldClass = { block: null, folded: null }\n\nconst blocked = (reason: MissReason): FieldClass => ({ block: reason, folded: null })\n\nconst NUMERIC_ATOMIC_TYPES: ReadonlySet<string> = new Set(['increment', 'max', 'min'])\nconst ARRAY_ATOMIC_TYPES: ReadonlySet<string> = new Set(['append', 'remove'])\n\n/** True for a kind whose values are numbers (counter, max and min fold numbers). */\nconst isNumericKind = (kind: string): boolean => kind === 'number' || kind === 'timestamp'\n\n/** Classify one written field of an update (5.2, S6b). */\nfunction classifyUpdateField(\n\tdefinition: CollectionDefinition,\n\tfield: string,\n\tdescriptor: FieldDescriptor | undefined,\n\tvalue: unknown,\n): FieldClass {\n\tif (descriptor === undefined) return blocked('unsupported-field-kind')\n\tif (descriptor.kind === 'richtext') return blocked('richtext-field')\n\tif (definition.resolvers[field] !== undefined) return blocked('custom-resolver')\n\tconst isArray = descriptor.kind === 'array'\n\tif (!isArray && !SCALAR_UPDATE_KINDS.has(descriptor.kind)) {\n\t\treturn blocked('unsupported-field-kind')\n\t}\n\tlet folded: MissReason | null = isArray ? 'unsupported-field-kind' : null\n\tconst strategy = descriptor.mergeStrategy\n\tif (strategy === 'server-authoritative') return blocked('merge-strategy')\n\tif (strategy === 'counter' || strategy === 'max' || strategy === 'min') {\n\t\t// The three fold numbers; on any other kind the schema is not one this predictor knows.\n\t\tif (!isNumericKind(descriptor.kind)) return blocked('merge-strategy')\n\t\tfolded = 'merge-strategy'\n\t} else if (strategy === 'append-only' && !isArray) {\n\t\treturn blocked('merge-strategy')\n\t}\n\tif (isAtomicOp(value)) {\n\t\tconst fits =\n\t\t\t(NUMERIC_ATOMIC_TYPES.has(value.type) && isNumericKind(descriptor.kind)) ||\n\t\t\t(ARRAY_ATOMIC_TYPES.has(value.type) && isArray)\n\t\tif (!fits) return blocked('atomic-op')\n\t\tfolded = 'atomic-op'\n\t}\n\treturn folded === null ? PLAIN_FIELD : { block: null, folded }\n}\n\n/** Whether the collection has an array field (the only kind whose writes need a fold state). */\nfunction hasArrayField(definition: CollectionDefinition): boolean {\n\treturn Object.values(definition.fields).some((field) => field.kind === 'array')\n}\n\n/**\n * Whether predicting an update of `data` needs the record's fold state: an array is\n * written (which copy of a value is present is the element's identity, kept only in the\n * fold state). False when the fold is unavailable. Looked at before the base is read.\n */\nexport function updateNeedsFoldState(\n\tenv: Pick<PredictEnv, 'schema' | 'fold'>,\n\tcollection: string,\n\tdata: Record<string, unknown>,\n): boolean {\n\tif (!env.fold) return false\n\tconst definition = env.schema.collections[collection]\n\tif (!definition) return false\n\treturn Object.keys(data).some((field) => definition.fields[field]?.kind === 'array')\n}\n\n/**\n * Predict an update of a record whose current values are `base`.\n *\n * A plain last-write-wins scalar is predicted as the written value: the local operation is\n * the newest writer of every field it touches (the HLC is past everything this device has\n * received), so that is what the fold materializes (5.3c). A field whose value comes from\n * the fold itself (an atomic op such as `op.increment`, a `counter`, `max`, `min` or\n * `append-only` merge strategy, an array) is predicted by running the fold on the update:\n * from the record's values (`@korajs/core`'s `predictLocalUpdate`), or from `baseState`, the\n * record's real fold state, which an array needs (S6b).\n *\n * @param env - Schema, node id and the record fold\n * @param collection - The collection\n * @param id - The record id\n * @param data - The schema-validated values being written (may hold atomic op descriptors)\n * @param base - The record's current values (pending chain or committed row)\n * @param wallTime - The wall time to give `updatedAt`\n * @param baseState - The record's fold state as of `base`, when known\n */\nexport function predictUpdate(\n\tenv: PredictEnv,\n\tcollection: string,\n\tid: string,\n\tdata: Record<string, unknown>,\n\tbase: CollectionRecord,\n\twallTime: number,\n\tbaseState: FoldState | null = null,\n): Prediction {\n\tconst definition = env.schema.collections[collection]\n\tif (!definition) return miss('unsupported-write')\n\tif (hasSecretField(definition)) return miss('secret-field')\n\tlet folded: MissReason | null = null\n\tfor (const [field, value] of Object.entries(data)) {\n\t\tconst one = classifyUpdateField(definition, field, definition.fields[field], value)\n\t\tif (one.block !== null) return miss(one.block)\n\t\t// The first folded field decides the reason a store without the fold gives.\n\t\tif (one.folded !== null && folded === null) folded = one.folded\n\t}\n\t// Without the record fold there is no state to compute these values from.\n\tif (folded !== null && !env.fold) return miss(folded)\n\tlet allowed: Record<string, unknown>\n\ttry {\n\t\t// The same function the write path runs, on the same current record.\n\t\tallowed = withoutUnchangedFields(\n\t\t\tdefinition,\n\t\t\tbase,\n\t\t\tvalidateUpdateStateMachine(collection, id, definition, base, data),\n\t\t)\n\t} catch {\n\t\treturn miss('state-machine')\n\t}\n\tif (Object.keys(allowed).length === 0) return miss('no-change')\n\ttry {\n\t\tconst { previousData, resolved, atomicOps } = patchForUpdate(\n\t\t\tcollection,\n\t\t\tdefinition,\n\t\t\tbase,\n\t\t\tallowed,\n\t\t)\n\t\tlet materialized: Record<string, unknown> = resolved\n\t\tlet foldState: FoldState | undefined\n\t\tif (folded !== null && env.fold) {\n\t\t\tconst operation: Operation = {\n\t\t\t\tid: 'overlay-prediction',\n\t\t\t\tnodeId: env.nodeId,\n\t\t\t\ttype: 'update',\n\t\t\t\tcollection,\n\t\t\t\trecordId: id,\n\t\t\t\tdata: resolved,\n\t\t\t\tpreviousData,\n\t\t\t\ttimestamp: { wallTime, logical: 0, nodeId: env.nodeId },\n\t\t\t\tsequenceNumber: 0,\n\t\t\t\tcausalDeps: [],\n\t\t\t\tschemaVersion: env.schema.version,\n\t\t\t\t...(Object.keys(atomicOps).length > 0 ? { atomicOps } : {}),\n\t\t\t}\n\t\t\tconst prediction = predictLocalUpdate({\n\t\t\t\tschema: env.schema,\n\t\t\t\top: operation,\n\t\t\t\tcurrent: fieldValues(definition, base),\n\t\t\t\tbaseState,\n\t\t\t\toptions: env.fold.options(),\n\t\t\t})\n\t\t\tif ('declined' in prediction) {\n\t\t\t\treturn miss(\n\t\t\t\t\tprediction.declined === 'array-needs-state'\n\t\t\t\t\t\t? 'no-fold-state'\n\t\t\t\t\t\t: prediction.declined === 'state-mismatch'\n\t\t\t\t\t\t\t? 'fold-state-stale'\n\t\t\t\t\t\t\t: 'merge-strategy',\n\t\t\t\t)\n\t\t\t}\n\t\t\tmaterialized = prediction.values\n\t\t\tif (prediction.state !== null) foldState = prediction.state\n\t\t}\n\t\tconst values: Record<string, unknown> = {}\n\t\tfor (const field of Object.keys(definition.fields)) {\n\t\t\tvalues[field] = field in materialized ? materialized[field] : base[field]\n\t\t}\n\t\tconst record = readShape(definition, id, values, base.createdAt, wallTime)\n\t\tconst patch: Record<string, unknown> = { updatedAt: wallTime }\n\t\tconst previous: Record<string, unknown> = { updatedAt: base.updatedAt }\n\t\tfor (const field of Object.keys(resolved)) {\n\t\t\tpatch[field] = record[field]\n\t\t\tprevious[field] = base[field]\n\t\t}\n\t\treturn {\n\t\t\tpredicted: true,\n\t\t\tkind: 'update',\n\t\t\tcollection,\n\t\t\trecordId: id,\n\t\t\tpatch,\n\t\t\tprevious,\n\t\t\trecord,\n\t\t\t...(foldState ? { foldState } : {}),\n\t\t\t// Predict again from what the transaction really read: its values and, for an\n\t\t\t// array write, the fold state the commit merged into (`priorState`).\n\t\t\treplay: (actual, priorState = null) =>\n\t\t\t\tpredictUpdate(env, collection, id, data, { ...base, ...actual }, wallTime, priorState),\n\t\t}\n\t} catch {\n\t\treturn miss('predictor-error')\n\t}\n}\n\n/**\n * Predict a delete of a record whose current values are `base`: a tombstone.\n *\n * @param env - Schema, node id and the record fold\n * @param collection - The collection\n * @param id - The record id\n * @param base - The record's current values\n */\nexport function predictDelete(\n\tenv: PredictEnv,\n\tcollection: string,\n\tid: string,\n\tbase: CollectionRecord,\n): Prediction {\n\tconst definition = env.schema.collections[collection]\n\tif (!definition) return miss('unsupported-write')\n\tif (!isDeletePredictable(env.schema, collection)) return miss('cascade-target')\n\ttry {\n\t\t// A delete reports the record as it stood: build the row the write path read and\n\t\t// shape it with the one function (`tombstone`) the write path shapes it with.\n\t\tconst row: RawCollectionRow = {\n\t\t\t...serializeRecord(fieldValues(definition, base), definition.fields),\n\t\t\tid,\n\t\t\t_created_at: base.createdAt,\n\t\t\t_updated_at: base.updatedAt,\n\t\t\t_deleted: 0,\n\t\t}\n\t\treturn {\n\t\t\tpredicted: true,\n\t\t\tkind: 'delete',\n\t\t\tcollection,\n\t\t\trecordId: id,\n\t\t\tpatch: null,\n\t\t\trecord: tombstone(definition, row),\n\t\t}\n\t} catch {\n\t\treturn miss('predictor-error')\n\t}\n}\n\nfunction fieldValues(\n\tdefinition: CollectionDefinition,\n\trecord: CollectionRecord,\n): Record<string, unknown> {\n\tconst values: Record<string, unknown> = {}\n\tfor (const field of Object.keys(definition.fields)) values[field] = record[field]\n\treturn values\n}\n\n/** Record fields that may legitimately differ between prediction and commit (5.3d). */\nconst METADATA_FIELDS: ReadonlySet<string> = new Set(['createdAt', 'updatedAt'])\n\n/**\n * Names of the fields on which two records differ, ignoring `createdAt` and\n * `updatedAt` (the only expected, benign difference). Compared structurally, so a\n * `null` and an absent field differ and arrays compare by element.\n */\nexport function divergentFields(\n\tpredicted: CollectionRecord,\n\tcommitted: CollectionRecord,\n): string[] {\n\tconst names = new Set([...Object.keys(predicted), ...Object.keys(committed)])\n\tconst out: string[] = []\n\tfor (const name of names) {\n\t\tif (METADATA_FIELDS.has(name)) continue\n\t\tif (!sameValue(predicted[name], committed[name])) out.push(name)\n\t}\n\treturn out.sort()\n}\n\nexport { sameValue } from '../mutations/same-value'\n","/** Structural equality of two field values (arrays by element, `null` and absent differ). */\nexport function sameValue(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) return true\n\tif (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false\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 (Array.isArray(a) || Array.isArray(b)) {\n\t\tif (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false\n\t\treturn a.every((item, index) => sameValue(item, b[index]))\n\t}\n\tconst left = a as Record<string, unknown>\n\tconst right = b as Record<string, unknown>\n\tconst keys = new Set([...Object.keys(left), ...Object.keys(right)])\n\tfor (const key of keys) if (!sameValue(left[key], right[key])) return false\n\treturn true\n}\n","import type { CollectionDefinition } from '@korajs/core'\nimport { isAtomicOp } from '@korajs/core'\nimport type { CollectionRecord } from '../types'\nimport { sameValue } from './same-value'\n\n/**\n * The fields of an update that would change the record.\n *\n * A field whose new value equals the record's current value writes nothing: for\n * last-write-wins an update equal to its own `previousData` is not a write, so the\n * operation would only add log, upload and download work (an autosave that re-saves the\n * same form hundreds of times left a log where 975 of 983 updates changed nothing, and a\n * new device paid for every one of them). Atomic ops (they resolve against the record),\n * richtext (a CRDT, compared by state, not value) and secret fields (stored hashed or\n * encrypted, so the stored value is not comparable to the input) are always kept.\n *\n * @param definition - The collection's definition\n * @param current - The record as it stands now\n * @param allowed - The validated update, state machine applied\n * @returns The update without its unchanged fields (the same object when nothing was dropped)\n */\nexport function withoutUnchangedFields(\n\tdefinition: CollectionDefinition,\n\tcurrent: CollectionRecord,\n\tallowed: Record<string, unknown>,\n): Record<string, unknown> {\n\tlet changed: Record<string, unknown> | null = null\n\tfor (const [field, value] of Object.entries(allowed)) {\n\t\tconst kind = definition.fields[field]?.kind\n\t\tconst unchanged =\n\t\t\tkind !== undefined &&\n\t\t\tkind !== 'richtext' &&\n\t\t\tkind !== 'secret' &&\n\t\t\t!isAtomicOp(value) &&\n\t\t\tsameValue(current[field], value)\n\t\tif (!unchanged) continue\n\t\tchanged ??= { ...allowed }\n\t\tdelete changed[field]\n\t}\n\treturn changed ?? allowed\n}\n","import type { AtomicOp, CollectionDefinition } from '@korajs/core'\nimport { assertResolvedFieldValue, isAtomicOp, resolveAtomicOp, toAtomicOp } from '@korajs/core'\nimport { encodeRichtextFieldsForOpData } from '../serialization/op-data-encoding'\nimport { deserializeRecord, toRichtextReadShape } from '../serialization/serializer'\nimport type { CollectionRecord, RawCollectionRow } from '../types'\n\n/*\n * The pure, storage-free parts of the local write path (instant-UI stage S2).\n *\n * `write-ops.ts` builds and persists operations inside a storage transaction. What it\n * computes from values it already holds (the body of an insert, the previous and\n * resolved values of an update, the record a write reports) lives here, so the\n * write path and the overlay predictor (`overlay/predict.ts`) call the SAME code and\n * cannot drift apart. Nothing in this file touches storage, a clock or the overlay.\n */\n\n/** An insert whose values are validated and in their at-rest form. */\nexport interface PreparedInsert {\n\treadonly collection: string\n\treadonly recordId: string\n\t/** Record-shaped, at-rest values (secret fields hashed / encrypted). */\n\treadonly data: Record<string, unknown>\n}\n\n/**\n * The `data` of an insert operation: the prepared values with binary richtext tagged as\n * canonical JSON BEFORE hashing, so the hash input, persisted JSON and wire payload are\n * the identical value.\n */\nexport function insertOperationData(\n\tinsert: PreparedInsert,\n\tdefinition: CollectionDefinition,\n): Record<string, unknown> {\n\treturn encodeRichtextFieldsForOpData(insert.data, definition.fields)\n}\n\n/**\n * The record an insert reports: the prepared values plus the operation's wall time as\n * `createdAt` and `updatedAt`. A richtext value written as a string returns as the bytes\n * reads return.\n *\n * @param insert - The prepared insert the transaction wrote\n * @param definition - The collection's definition\n * @param wallTime - `operation.timestamp.wallTime` of the insert operation\n */\nexport function recordForInsert(\n\tinsert: PreparedInsert,\n\tdefinition: CollectionDefinition,\n\twallTime: number,\n): CollectionRecord {\n\treturn {\n\t\tid: insert.recordId,\n\t\t...toRichtextReadShape(insert.data, definition.fields),\n\t\tcreatedAt: wallTime,\n\t\tupdatedAt: wallTime,\n\t}\n}\n\n/** What an update writes, derived from the row's current record. */\nexport interface UpdatePatch {\n\t/** The current values of the fields being written (enables 3-way merge). */\n\treadonly previousData: Record<string, unknown>\n\t/** The values to write: atomic ops resolved against the current record. */\n\treadonly resolved: Record<string, unknown>\n\t/** The atomic intents among the written fields, by field. */\n\treadonly atomicOps: Record<string, AtomicOp>\n}\n\n/**\n * Work out `previousData`, the resolved values and the atomic intents of an update\n * from the record's current values. `allowed` is the state-machine-filtered, schema\n * validated input (it may contain atomic op descriptors).\n *\n * @throws When a resolved atomic value leaves its field's domain (RT-87)\n */\nexport function patchForUpdate(\n\tcollection: string,\n\tdefinition: CollectionDefinition,\n\tcurrentRecord: CollectionRecord,\n\tallowed: Record<string, unknown>,\n): UpdatePatch {\n\tconst previousData: Record<string, unknown> = {}\n\tconst resolved: Record<string, unknown> = {}\n\tconst atomicOps: Record<string, AtomicOp> = {}\n\tfor (const [key, value] of Object.entries(allowed)) {\n\t\tpreviousData[key] = currentRecord[key]\n\t\tif (isAtomicOp(value)) {\n\t\t\tresolved[key] = resolveAtomicOp(currentRecord[key], value)\n\t\t\t// The resolved value must be in the field's domain like any written value\n\t\t\t// (RT-87): `op.increment(0.5)` on a timestamp, an increment past the largest\n\t\t\t// finite number.\n\t\t\tconst descriptor = definition.fields[key]\n\t\t\tif (descriptor) assertResolvedFieldValue(collection, key, descriptor, resolved[key])\n\t\t\tatomicOps[key] = toAtomicOp(value)\n\t\t} else {\n\t\t\tresolved[key] = value\n\t\t}\n\t}\n\treturn { previousData, resolved, atomicOps }\n}\n\n/**\n * The record a delete reports: the record as it stood when it was tombstoned (what the\n * row held, read the way every read shapes it).\n */\nexport function tombstone(\n\tdefinition: CollectionDefinition,\n\trow: RawCollectionRow,\n): CollectionRecord {\n\treturn deserializeRecord(row, definition.fields)\n}\n","import type { Transaction, TransactionStatement } from '../types'\n\n/**\n * Statements buffered before they are sent. Bounds the size of one worker message\n * and how long one batch holds the SQLite worker (follower tabs queue behind it).\n */\nexport const WRITE_BEHIND_MAX_STATEMENTS = 256\n\n/**\n * A {@link Transaction} that buffers writes and sends them in batches.\n *\n * Used where every failing statement aborts the whole unit of work it belongs to, so\n * no caller catches one statement's error and carries on with the same buffer:\n *\n * - the local write path, inside the storage transaction of a write\n *   (`withWriteScope`): a failure aborts the write;\n * - a delivery batch applied in one transaction (`Store.applyRemoteBatch`), one\n *   instance for the whole batch shared by its steps (an operation or a retraction), each\n *   inside its own savepoint: a step that throws is cut out of the buffer\n *   ({@link truncateTo}) or, when its savepoint was already sent, rolled back only after\n *   {@link settled}, so nothing of the step lands after it; a statement that FAILED is\n *   not attributed to a step, it ends the whole batch (see `applyRemoteBatchNow`).\n *\n * That is what makes buffering invisible:\n *\n * - statements reach the database in the order they were issued;\n * - every read ({@link query}) first sends the buffered writes and waits for them,\n *   so reads see them;\n * - {@link flush} runs before the write scope (or the step) ends, so every statement\n *   has been applied before the adapter commits (or the savepoint is released); a\n *   failing statement rejects that flush (or an earlier read or `execute`) and the\n *   whole write (or step) is rolled back, exactly as when the statement's own\n *   `execute` failed. Once a batch failed, nothing more is sent.\n *\n * The only difference a caller can observe is WHICH await rejects: a deferred\n * statement's error surfaces at a later read, `execute` or the end of the write,\n * never after the write resolved. Code that must catch a statement's error and\n * carry on (the migration runner's tolerated DDL) uses the raw handle.\n *\n * A full buffer is sent without waiting for it, so the next statements are built\n * while the worker runs the batch; at most one batch is in flight (a second full\n * buffer waits for the first), which bounds memory.\n *\n * With an adapter that implements {@link Transaction.executeBatch} (SQLite WASM:\n * one worker message per batch instead of one per statement) this removes most\n * worker round trips of a large write; other adapters get the statements one\n * `execute` at a time, in order, as before.\n */\nexport class WriteBehindTransaction implements Transaction {\n\tprivate pending: TransactionStatement[] = []\n\t/** The batch in flight (settles after every earlier batch). */\n\tprivate sending: Promise<void> = Promise.resolve()\n\tprivate inFlight = false\n\tprivate sentAny = false\n\t/** Statements handed to the adapter so far (in flight or done). */\n\tprivate sentCount = 0\n\t/** The first batch failure, recorded as soon as it happens (see {@link execute}). */\n\tprivate failure: { error: unknown } | null = null\n\n\tconstructor(\n\t\tprivate readonly inner: Transaction,\n\t\tprivate readonly maxStatements = WRITE_BEHIND_MAX_STATEMENTS,\n\t) {}\n\n\tasync execute(sql: string, params?: unknown[]): Promise<void> {\n\t\t// A batch already failed: the write is aborted, so say so at the next statement\n\t\t// instead of buffering more work that will never be sent.\n\t\tif (this.failure) throw this.failure.error\n\t\tthis.pending.push(params === undefined ? { sql } : { sql, params })\n\t\tif (this.pending.length < this.maxStatements) return\n\t\t// Backpressure: one batch in flight. Waiting also surfaces its failure here.\n\t\tif (this.inFlight) await this.sending\n\t\tthis.dispatch()\n\t}\n\n\tasync query<T>(sql: string, params?: unknown[]): Promise<T[]> {\n\t\tawait this.flush()\n\t\treturn this.inner.query<T>(sql, params)\n\t}\n\n\tasync executeBatch(statements: readonly TransactionStatement[]): Promise<void> {\n\t\tthis.pending.push(...statements)\n\t\tawait this.flush()\n\t}\n\n\t/** Send every buffered statement and wait until all of them ran (or one failed). */\n\tflush(): Promise<void> {\n\t\tthis.dispatch()\n\t\treturn this.sending\n\t}\n\n\t/**\n\t * A view of this transaction whose `execute` resolves only once its statement ran\n\t * (and rejects with that statement's own error), for code that relies on that, such\n\t * as the public `LocalMutationHandler.beforeLocalDelete` hook. Buffered statements\n\t * are sent first, so order is kept.\n\t */\n\timmediate(): Transaction {\n\t\treturn {\n\t\t\texecute: async (sql, params) => {\n\t\t\t\tawait this.flush()\n\t\t\t\tawait this.inner.execute(sql, params)\n\t\t\t},\n\t\t\tquery: (sql, params) => this.query(sql, params),\n\t\t}\n\t}\n\n\t/**\n\t * Drop the statements not yet sent. Returns whether any statement of this buffer was\n\t * ever sent (so the caller knows what it must undo: with nothing sent, nothing happened).\n\t */\n\tdiscardUnsent(): boolean {\n\t\tthis.pending = []\n\t\treturn this.sentAny\n\t}\n\n\t/** Statements issued so far: sent ones plus the ones still buffered. */\n\tget issued(): number {\n\t\treturn this.sentCount + this.pending.length\n\t}\n\n\t/** Whether a batch failed (every later statement is refused). */\n\tget failed(): boolean {\n\t\treturn this.failure !== null\n\t}\n\n\t/**\n\t * Drop the buffered statements issued after the first `issued` ones, for a unit of work\n\t * that shares this buffer with others and is undone on its own. Returns false when some\n\t * of the dropped statements were already sent (the caller must roll the unit back in the\n\t * database instead); nothing is dropped then.\n\t */\n\ttruncateTo(issued: number): boolean {\n\t\tif (this.sentCount > issued) return false\n\t\tthis.pending.length = Math.min(this.pending.length, issued - this.sentCount)\n\t\treturn true\n\t}\n\n\t/** Resolves once every batch already sent has settled (never rejects). */\n\tsettled(): Promise<void> {\n\t\treturn this.sending.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t)\n\t}\n\n\tprivate dispatch(): void {\n\t\tif (this.pending.length === 0) return\n\t\tconst batch = this.pending\n\t\tthis.pending = []\n\t\tthis.sentAny = true\n\t\tthis.sentCount += batch.length\n\t\tthis.inFlight = true\n\t\t// Chained: batches run in issue order, and after a failed batch every later one\n\t\t// is skipped and every later flush rejects with that failure.\n\t\tconst next = this.sending.then(() => this.send(batch))\n\t\tthis.sending = next\n\t\tnext.then(\n\t\t\t() => {\n\t\t\t\tif (this.sending === next) this.inFlight = false\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\t// Recorded at once, so the next execute throws; also observed by the next\n\t\t\t\t// query or flush. Marked handled here so a failure is not reported as\n\t\t\t\t// unhandled while the caller builds the next statement.\n\t\t\t\tif (!this.failure) this.failure = { error }\n\t\t\t},\n\t\t)\n\t}\n\n\tprivate async send(batch: readonly TransactionStatement[]): Promise<void> {\n\t\tif (this.inner.executeBatch) {\n\t\t\tawait this.inner.executeBatch(batch)\n\t\t\treturn\n\t\t}\n\t\tfor (const statement of batch) {\n\t\t\tawait this.inner.execute(statement.sql, statement.params)\n\t\t}\n\t}\n}\n","import type {\n\tCausalTracker,\n\tHybridLogicalClock,\n\tOperation,\n\tSchemaDefinition,\n\tSecretKeyProvider,\n} from '@korajs/core'\nimport { KoraError } from '@korajs/core'\nimport type { RecordFolder } from '../fold/record-folder'\nimport type { RelationEnforcer } from '../relations/relation-enforcer'\nimport { WriteBehindTransaction } from '../transaction/write-behind'\nimport type { Transaction } from '../types'\n\n/**\n * Called inside the write transaction for every local delete, after the delete\n * operation is built and before referential side effects run. Lets the unified\n * apply pipeline run its referential checks (and emit their traces) against the\n * rows the transaction sees. Throwing aborts the whole write.\n */\nexport type LocalDeleteHook = (operation: Operation, tx: Transaction) => Promise<void>\n\n/**\n * Everything the single local write path needs to build and persist an\n * operation inside a storage transaction. One environment serves single-record\n * writes, `app.transaction` commits and referential cascades, so every local\n * operation is built the same way (W6).\n */\nexport interface WriteEnv {\n\treadonly schema: SchemaDefinition\n\treadonly clock: HybridLogicalClock\n\treadonly nodeId: string\n\treadonly relationEnforcer: RelationEnforcer | null\n\treadonly secretKeyProvider?: SecretKeyProvider\n\t/** Shared by every operation of an `app.transaction` / `app.mutation` commit. */\n\treadonly transactionId?: string\n\t/** Human-readable mutation name propagated to every operation (DevTools). */\n\treadonly mutationName?: string\n\t/** See {@link LocalDeleteHook}. */\n\treadonly beforeLocalDelete?: LocalDeleteHook\n\t/**\n\t * The W7 record fold. When set, a local write appends its operation and then\n\t * merges it into the record's fold state, which re-materializes the row (the\n\t * same path remote operations take). Absent only while a pre-W7 database is migrated, before its\n\t * re-materialization, and in the store tests that build such a database: the row is\n\t * then written directly, as in beta.12.\n\t */\n\treadonly fold?: RecordFolder\n\t/**\n\t * Largest operation a local write may produce (RT-86), the server's\n\t * `maxOperationBytes`. Default `DEFAULT_MAX_OPERATION_BYTES` (256 KiB).\n\t */\n\treadonly maxOperationBytes?: number\n\t/**\n\t * Throws when local writes are not allowed right now: the store's pinned node\n\t * belongs to another user than the one signed in (F9). Called before every local\n\t * operation is built.\n\t */\n\treadonly assertLocalWriteAllowed?: () => void\n\t/**\n\t * The signed-in user's id, or null when the app does not know it yet. Fills fields\n\t * declared `t.string().stamp('userId')` on insert.\n\t */\n\treadonly signedInUser?: () => string | null\n}\n\n/**\n * Causal bookkeeping for the operations built inside ONE storage transaction.\n *\n * Dependencies are computed from the committed causal heads (the shared\n * {@link CausalTracker}) overlaid with the operations already built in this\n * transaction. Heads are published to the shared tracker only after the\n * transaction commits, so a rolled-back write never leaves a dependency on an\n * operation that does not exist.\n */\nexport class CausalScope {\n\tprivate readonly lastByCollection = new Map<string, string>()\n\tprivate lastInScope: string | null = null\n\tprivate readonly recorded: Array<{ collection: string; id: string }> = []\n\n\tconstructor(\n\t\tprivate readonly tracker: CausalTracker | null,\n\t\t/** When true, every operation also depends on the previous one in this scope. */\n\t\tprivate readonly chainOperations: boolean,\n\t) {}\n\n\t/**\n\t * Direct causal parents for the next operation in `collection`.\n\t *\n\t * @param collection - Collection of the operation being built\n\t * @param extra - Explicit parents (e.g. the delete that caused a cascade)\n\t */\n\tdepsFor(collection: string, extra: readonly string[] = []): string[] {\n\t\tconst deps: string[] = []\n\t\tconst add = (id: string | undefined | null): void => {\n\t\t\tif (id && !deps.includes(id)) deps.push(id)\n\t\t}\n\t\tfor (const id of extra) add(id)\n\t\tconst local = this.lastByCollection.get(collection)\n\t\tif (local !== undefined) {\n\t\t\tadd(local)\n\t\t} else {\n\t\t\tfor (const id of this.tracker?.nextCausalDeps(collection, false) ?? []) add(id)\n\t\t}\n\t\tif (this.chainOperations) add(this.lastInScope)\n\t\treturn deps\n\t}\n\n\t/** Record an operation built in this scope. */\n\trecord(collection: string, operationId: string): void {\n\t\tthis.lastByCollection.set(collection, operationId)\n\t\tthis.lastInScope = operationId\n\t\tthis.recorded.push({ collection, id: operationId })\n\t}\n\n\t/** Publish this scope's heads to the shared tracker. Call only after commit. */\n\tpublish(): void {\n\t\tfor (const { collection, id } of this.recorded) {\n\t\t\tthis.tracker?.afterOperation(collection, id, false)\n\t\t}\n\t}\n}\n\n/**\n * The sequence-number block of ONE write transaction.\n *\n * The first number is reserved with one `UPSERT ... RETURNING` on\n * `_kora_version_vector`, inside the transaction; later numbers continue the block\n * in memory, and {@link SequenceBlock.close} persists the block's end with one\n * write before the transaction commits. Write transactions are serialized and no\n * code path allocates numbers outside one, so the block is contiguous and never\n * shared; the UNIQUE `(node_id, sequence_number)` index on every op table is the\n * backstop. A rollback discards the reservation with everything else.\n */\nexport class SequenceBlock {\n\tprivate last: number | null = null\n\tprivate persisted = 0\n\n\tconstructor(\n\t\tprivate readonly tx: Transaction,\n\t\tprivate readonly nodeId: string,\n\t) {}\n\n\t/** The next number of the block. */\n\tasync take(): Promise<number> {\n\t\tif (this.last === null) {\n\t\t\tconst rows = await this.tx.query<{ sequence_number: number }>(\n\t\t\t\t`INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, 1)\n     ON CONFLICT(node_id) DO UPDATE SET sequence_number = sequence_number + 1\n     RETURNING sequence_number`,\n\t\t\t\t[this.nodeId],\n\t\t\t)\n\t\t\tconst first = rows[0]?.sequence_number\n\t\t\tif (first === undefined) {\n\t\t\t\tthrow new KoraError(\n\t\t\t\t\t`Failed to reserve a sequence number for node \"${this.nodeId}\"`,\n\t\t\t\t\t'SEQUENCE_RESERVATION_FAILED',\n\t\t\t\t\t{ nodeId: this.nodeId },\n\t\t\t\t)\n\t\t\t}\n\t\t\tthis.last = first\n\t\t\tthis.persisted = first\n\t\t\treturn first\n\t\t}\n\t\tthis.last += 1\n\t\treturn this.last\n\t}\n\n\t/** Persist the end of the block. Must run inside the transaction, before commit. */\n\tasync close(): Promise<void> {\n\t\tif (this.last === null || this.last === this.persisted) return\n\t\tawait this.tx.execute(\n\t\t\t'UPDATE _kora_version_vector SET sequence_number = MAX(sequence_number, ?) WHERE node_id = ?',\n\t\t\t[this.last, this.nodeId],\n\t\t)\n\t\tthis.persisted = this.last\n\t}\n}\n\n/**\n * The per-transaction state of a local write: the transaction handle, its\n * sequence block and its causal scope. Every operation built in one transaction\n * takes the next number of the same contiguous block.\n */\nexport interface WriteScope {\n\treadonly tx: Transaction\n\t/**\n\t * The same transaction, unbuffered: `await execute(...)` means the statement ran.\n\t * Handed to extension hooks (`beforeLocalDelete`) that may rely on that.\n\t */\n\treadonly immediateTx: Transaction\n\treadonly sequence: SequenceBlock\n\treadonly causal: CausalScope\n}\n\n/**\n * Run `write` with a fresh {@link WriteScope} on `tx`, then close the sequence\n * block and send every buffered statement (still inside the transaction).\n *\n * The scope's `tx` buffers writes ({@link WriteBehindTransaction}): statements are\n * sent in issue order, in batches, before any read and before this function\n * returns, so the caller's commit always follows every statement of the write. A\n * failing statement rejects this function (or the read or full-buffer `execute`\n * that sent it) and the caller's storage transaction rolls back as before.\n */\nexport async function withWriteScope<T>(\n\ttx: Transaction,\n\tnodeId: string,\n\tcausal: CausalScope,\n\twrite: (scope: WriteScope) => Promise<T>,\n): Promise<T> {\n\tconst buffered = new WriteBehindTransaction(tx)\n\tconst scope: WriteScope = {\n\t\ttx: buffered,\n\t\timmediateTx: buffered.immediate(),\n\t\tsequence: new SequenceBlock(buffered, nodeId),\n\t\tcausal,\n\t}\n\ttry {\n\t\tconst result = await write(scope)\n\t\tawait scope.sequence.close()\n\t\tawait buffered.flush()\n\t\treturn result\n\t} catch (error) {\n\t\t// Let a batch that is still on its way settle before the caller rolls back, so\n\t\t// ROLLBACK never overtakes a statement of this transaction.\n\t\tawait buffered.settled()\n\t\tthrow error\n\t}\n}\n\n/**\n * Whether a storage error means the device ran out of space: SQLite's\n * `SQLITE_FULL` (\"database or disk is full\") or a browser quota error from OPFS /\n * IndexedDB. The store maps these to a `store:quota-exceeded` event (STORE-15).\n */\nexport function isStorageFullError(error: unknown): boolean {\n\tif (error === null || typeof error !== 'object') return false\n\tconst candidate = error as { name?: unknown; code?: unknown; message?: unknown; cause?: unknown }\n\tif (candidate.name === 'QuotaExceededError') return true\n\tif (candidate.code === 'SQLITE_FULL' || candidate.code === 'QUOTA_EXCEEDED') return true\n\tconst message = typeof candidate.message === 'string' ? candidate.message : ''\n\tif (/SQLITE_FULL|database or disk is full|quota ?exceeded/i.test(message)) return true\n\treturn candidate.cause !== undefined && candidate.cause !== error\n\t\t? isStorageFullError(candidate.cause)\n\t\t: false\n}\n\n/**\n * Wait while a rewrite of operation ids holds local writes back (see `CausalTracker.hold`).\n * Call right before starting the storage transaction, with nothing awaited between: a rewrite\n * that starts after this resolves holds the next check, not this write.\n */\nexport async function waitForCausalHeads(tracker: CausalTracker | null): Promise<void> {\n\twhile (tracker?.settling) await tracker.settling\n}\n","import { EMPTY_ROW_VERSION } from './row-version'\n\n/**\n * Per-field last-writer versions for a materialized row.\n *\n * Each entry maps a field name to a serialized HLC timestamp (the same\n * lexicographically-sortable form used by the row `_version` column). Because\n * the serialized form sorts identically to {@link HybridLogicalClock.compare},\n * per-field last-write-wins is a plain string comparison: the greater string is\n * the newer writer. This makes field-level convergence deterministic and\n * independent of the order operations happen to arrive in.\n */\nexport type FieldVersions = Record<string, string>\n\n/**\n * Parse the `_field_versions` JSON column into a map. Tolerates null, empty,\n * and malformed values by returning an empty map — a row that predates\n * per-field tracking simply has no field versions and falls back to `_version`.\n */\nexport function parseFieldVersions(raw: unknown): FieldVersions {\n\tif (typeof raw !== 'string' || raw.length === 0) {\n\t\treturn {}\n\t}\n\ttry {\n\t\tconst parsed = JSON.parse(raw) as unknown\n\t\tif (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n\t\t\treturn {}\n\t\t}\n\t\tconst result: FieldVersions = {}\n\t\tfor (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {\n\t\t\tif (typeof value === 'string') {\n\t\t\t\tresult[key] = value\n\t\t\t}\n\t\t}\n\t\treturn result\n\t} catch {\n\t\treturn {}\n\t}\n}\n\n/**\n * Serialize a field-version map for storage in the `_field_versions` column.\n */\nexport function serializeFieldVersions(versions: FieldVersions): string {\n\treturn JSON.stringify(versions)\n}\n\n/**\n * Build the initial field-version map for an insert: every supplied field is\n * stamped with the operation's version.\n */\nexport function fieldVersionsForFields(\n\tfieldNames: Iterable<string>,\n\tversion: string,\n): FieldVersions {\n\tconst versions: FieldVersions = {}\n\tfor (const field of fieldNames) {\n\t\tversions[field] = version\n\t}\n\treturn versions\n}\n\n/**\n * The effective stored version for a field: its own tracked version if present,\n * otherwise the row-level `_version` (so rows written before per-field tracking\n * still compare correctly), otherwise the empty sentinel (older than anything).\n */\nexport function effectiveFieldVersion(\n\tcurrent: FieldVersions,\n\tfield: string,\n\trowVersion: string | undefined,\n): string {\n\tconst own = current[field]\n\tif (own !== undefined) {\n\t\treturn own\n\t}\n\treturn rowVersion ?? EMPTY_ROW_VERSION\n}\n\n/**\n * Result of resolving an incoming operation against the current per-field\n * versions of a row.\n */\nexport interface PerFieldLwwResult {\n\t/** Fields the incoming operation wins (strictly newer than the stored version). */\n\twinners: string[]\n\t/** The merged field-version map to persist (winners advanced to `incomingVersion`). */\n\tmerged: FieldVersions\n}\n\n/**\n * Resolve per-field last-write-wins for an incoming operation.\n *\n * For each incoming field, the operation wins only when its version is strictly\n * greater than the field's effective stored version. Ties (identical version,\n * i.e. the same operation re-applied) are losses, keeping the resolution\n * idempotent. The comparison is a total order, so every node resolves the same\n * winner regardless of the order operations arrive.\n *\n * @param current - Parsed `_field_versions` of the target row\n * @param incomingFields - Field names carried by the incoming operation\n * @param incomingVersion - Serialized HLC version of the incoming operation\n * @param rowVersion - The row's `_version` (fallback for untracked fields)\n */\nexport function resolvePerFieldLww(\n\tcurrent: FieldVersions,\n\tincomingFields: Iterable<string>,\n\tincomingVersion: string,\n\trowVersion: string | undefined,\n): PerFieldLwwResult {\n\tconst winners: string[] = []\n\tconst merged: FieldVersions = { ...current }\n\tfor (const field of incomingFields) {\n\t\tconst stored = effectiveFieldVersion(current, field, rowVersion)\n\t\tif (incomingVersion > stored) {\n\t\t\twinners.push(field)\n\t\t\tmerged[field] = incomingVersion\n\t\t}\n\t\t// Losing fields are left untouched: their existing tracked version (or the\n\t\t// row-level `_version` fallback) already reflects the newer writer.\n\t}\n\treturn { winners, merged }\n}\n\n/**\n * Stamp `fields` with `version` on top of a stored `_field_versions` value and\n * return the serialized column. This is the one per-field stamp every local\n * write uses (insert, update, transaction entries, cascades), so every field a\n * device writes carries the HLC of the operation that wrote it.\n *\n * Stamps only move forward: a field already holding a newer version keeps it.\n * The map is keyed by field name with one HLC register per field, the shape the\n * per-field fold (W7) builds on.\n *\n * @param currentRaw - The stored `_field_versions` column (or null for a new row)\n * @param fields - Field names this write sets\n * @param version - The writing operation's serialized HLC version\n */\nexport function stampFieldVersions(\n\tcurrentRaw: unknown,\n\tfields: Iterable<string>,\n\tversion: string,\n): string {\n\tconst versions = parseFieldVersions(currentRaw)\n\tfor (const field of fields) {\n\t\tconst existing = versions[field]\n\t\tif (existing === undefined || existing < version) {\n\t\t\tversions[field] = version\n\t\t}\n\t}\n\treturn serializeFieldVersions(versions)\n}\n","import type { Operation } from '@korajs/core'\nimport { currentWriteObserver } from '@korajs/core/internal'\nimport { activePhaseTimers } from '../instrumentation/phase-timers'\nimport { isDeletePredictable } from '../overlay/predict'\nimport {\n\ttype WriteTracker,\n\treadBaseIfNeeded,\n\trecordKey,\n\ttrackDelete,\n} from '../overlay/write-overlay'\nimport { type WriteOptions, readFixedWrite } from '../types'\nimport { runLocalWrite } from './run-local-write'\nimport type { LocalMutationContext } from './types'\nimport { writeDeleteInTx } from './write-ops'\n\nexport interface ExecuteDeleteOptions extends WriteOptions {\n\t/** When true, skip referential checks and cascades (caller already enforced them). */\n\tskipReferentialEnforcement?: boolean\n}\n\n/**\n * Soft-delete a record and persist the operation log entry atomically, together\n * with any referential side effects (cascades / set-null), in one transaction.\n * Returns the primary delete operation followed by the side-effect operations.\n */\nexport async function executeDelete(\n\tctx: LocalMutationContext,\n\tid: string,\n\toptions?: ExecuteDeleteOptions,\n): Promise<Operation[]> {\n\tactivePhaseTimers()?.begin('delete')\n\t// Captured before the first await: the observer is only current synchronously.\n\tconst observer = currentWriteObserver()\n\t// Off unless the store was built with `instantUpdates`; see executeInsert. A delete\n\t// that skips referential enforcement is a system write (a cascade the caller already\n\t// decided), never predicted.\n\tconst overlay = ctx.overlay\n\tlet tracker: WriteTracker | null = null\n\t// See executeUpdate: a write that reads before it is predicted holds a turn.\n\tconst turn = overlay\n\t\t? overlay.registry.order.enter([recordKey(ctx.collection, id)], { all: true })\n\t\t: null\n\ttry {\n\t\tif (overlay && options?.skipReferentialEnforcement !== true) {\n\t\t\tif (turn?.wait) await turn.wait\n\t\t\t// No read for a delete the schema never predicts (a cascade target) or `durable`.\n\t\t\tconst read =\n\t\t\t\toptions?.durable === true || !isDeletePredictable(ctx.schema, ctx.collection)\n\t\t\t\t\t? ({ status: 'skipped' } as const)\n\t\t\t\t\t: readBaseIfNeeded(ctx, overlay, ctx.collection, id)\n\t\t\tif (read instanceof Promise) turn?.hold()\n\t\t\ttracker = trackDelete(ctx, overlay, id, read instanceof Promise ? await read : read, options)\n\t\t} else if (turn?.wait) {\n\t\t\tawait turn.wait\n\t\t}\n\t\tconst started = runLocalWrite(\n\t\t\tctx,\n\t\t\t(scope) =>\n\t\t\t\twriteDeleteInTx(ctx, scope, ctx.collection, id, {\n\t\t\t\t\tskipReferentialEnforcement: options?.skipReferentialEnforcement ?? false,\n\t\t\t\t\textraCausalDeps: ctx.extraCausalDeps ?? [],\n\t\t\t\t}),\n\t\t\t{\n\t\t\t\tobserver,\n\t\t\t\topKey: readFixedWrite(options)?.opKey,\n\t\t\t\t...(tracker\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tonCommitted: (results) => tracker?.committed(results),\n\t\t\t\t\t\t\tonCommitUnknown: (lookup, _error, results) => {\n\t\t\t\t\t\t\t\tif (lookup.outcome === 'committed') tracker?.committed(results)\n\t\t\t\t\t\t\t\telse if (lookup.outcome === 'unknown') tracker?.unknown(lookup.operationId)\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},\n\t\t)\n\t\tturn?.release()\n\t\tconst result = await started\n\t\treturn result.operation ? [result.operation, ...result.sideEffects] : result.sideEffects\n\t} catch (error) {\n\t\ttracker?.failed(error)\n\t\tthrow error\n\t} finally {\n\t\tturn?.release()\n\t}\n}\n","import type {\n\tApplyResult,\n\tHLCTimestamp,\n\tKoraEventEmitter,\n\tOfflineCompletion,\n\tOperation,\n\tOperationTransform,\n\tSchemaDefinition,\n\tSecretKeyProvider,\n} from '@korajs/core'\nimport type { UnappliedOperation } from './sync/sync-durability'\n\n/**\n * Transaction interface for executing multiple operations atomically.\n */\n/** Options of `StorageAdapter.transaction`. */\nexport interface TransactionOptions {\n\t/** Take the write lock when the transaction begins (see `StorageAdapter.transaction`). */\n\timmediate?: boolean\n}\n\nexport interface Transaction {\n\texecute(sql: string, params?: unknown[]): Promise<void>\n\tquery<T>(sql: string, params?: unknown[]): Promise<T[]>\n\t/**\n\t * Optional: run several write statements of this transaction, in order, in one\n\t * call (one worker message for the SQLite WASM adapter). Stops at the first\n\t * failing statement and rejects; statements before it ran inside the\n\t * transaction, which the caller then rolls back like after any failed\n\t * `execute`. Adapters without it get the statements one `execute` at a time.\n\t */\n\texecuteBatch?(statements: readonly TransactionStatement[]): Promise<void>\n}\n\n/** One write statement of {@link Transaction.executeBatch}. */\nexport interface TransactionStatement {\n\treadonly sql: string\n\treadonly params?: unknown[]\n}\n\n/**\n * Migration plan containing SQL statements and optional data transforms.\n */\nexport interface MigrationPlan {\n\tstatements: string[]\n\ttransforms?: Array<(row: Record<string, unknown>) => Record<string, unknown>>\n}\n\nexport type StorageFallbackReason = 'lock-conflict' | 'timeout' | 'unsupported'\n\nexport interface StorageOpenState {\n\t/** True when the selected adapter can survive reload/browser restart. */\n\tpersistent: boolean\n\t/** The concrete storage mode the adapter is using after open. */\n\tmode: 'opfs' | 'indexeddb' | 'memory' | 'native' | 'unknown'\n\t/** Present when a primary storage mode degraded during open. */\n\tfallbackReason?: StorageFallbackReason\n\t/** OPFS pool that owns the database file (one pool per database), when known. */\n\tpoolName?: string\n\t/**\n\t * SQLite journal mode the database actually runs with, when known (NEW-STORE-11).\n\t * OPFS (opfs-sahpool): `delete`, the rollback journal; WAL is not available on\n\t * that VFS. In-memory fallback: `memory`. Native better-sqlite3: `wal`.\n\t */\n\tjournalMode?: string\n}\n\n/**\n * Storage adapter interface. All storage backends must implement this.\n * Operations are async to support both sync (better-sqlite3) and async (IndexedDB, WASM) backends.\n */\nexport interface StorageAdapter {\n\t/** Open or create the database */\n\topen(schema: SchemaDefinition): Promise<void>\n\n\t/** Close the database and release resources */\n\tclose(): Promise<void>\n\n\t/** Execute a write query (INSERT, UPDATE, DELETE) within a transaction */\n\texecute(sql: string, params?: unknown[]): Promise<void>\n\n\t/** Execute a read query (SELECT) */\n\tquery<T>(sql: string, params?: unknown[]): Promise<T[]>\n\n\t/**\n\t * Execute multiple operations atomically.\n\t *\n\t * `options.immediate` asks for the write lock at the start (SQLite `BEGIN IMMEDIATE`) for a\n\t * transaction that reads and then writes, so two connections to one file (two processes)\n\t * queue up instead of failing with `database is locked`. Adapters with a single connection\n\t * ignore it.\n\t */\n\ttransaction(fn: (tx: Transaction) => Promise<void>, options?: TransactionOptions): Promise<void>\n\n\t/** Apply a schema migration */\n\tmigrate(from: number, to: number, migration: MigrationPlan): Promise<void>\n\n\t/**\n\t * Optional post-open storage state. Adapters that can silently degrade at\n\t * runtime should expose this so higher-level runtimes can promote to a durable\n\t * fallback before app code starts reading or writing user data.\n\t */\n\tgetStorageOpenState?(): StorageOpenState | null\n\n\t/**\n\t * Optional: true while the adapter refuses every write (it has no durable storage and\n\t * the app did not opt into that, `StorageDurabilityError`). The instant-updates overlay\n\t * asks before it shows a write, so it never shows one the adapter will refuse.\n\t */\n\trefusesWrites?(): boolean\n\n\t/**\n\t * Optional durability barrier (RT-35): resolve once every write committed before the\n\t * call is durable, reject when it cannot be made durable. Adapters whose commits are\n\t * durable when they resolve (SQLite on a file or OPFS) omit it; an adapter that\n\t * persists asynchronously (the IndexedDB snapshot fallback) must implement it.\n\t */\n\tensureDurable?(): Promise<void>\n\n\t/**\n\t * Optional: resolves once every write committed so far is in a persisted snapshot,\n\t * WITHOUT forcing one (it waits for the next debounced snapshot). Adapters whose writes\n\t * are durable on commit omit it. Used to know when a completion mark reached disk.\n\t */\n\twhenPersisted?(): Promise<void>\n\n\t/**\n\t * Optional: the version gate this adapter's tab declares (browser adapters). The store\n\t * closes its write gate when the tab is superseded and drains its writes as the first\n\t * retirement step; the app adds its own steps (prompt, sync).\n\t */\n\tgetVersionGate?(): import('./multi-tab/version-gate').VersionGate | null\n\n\t/**\n\t * Optional: the evidence kept outside the database that it existed (storage manifest and\n\t * `localStorage` marker), captured when it was opened. Browser adapters that persist\n\t * durably return one; the store uses it to tell a vanished database from a first visit\n\t * and to keep the records current.\n\t */\n\tgetStorageEvidence?(): import('./adapters/storage-evidence').StorageEvidence | null\n\n\t/**\n\t * Optional: a new, empty scratch database of the same engine, in memory, that the\n\t * store replicates a large first sync into before merging it into this database\n\t * (`docs/design/first-visit-parity.md` 6). The caller opens and closes it.\n\t * Memory, not a file: nothing of it survives a crash or a reload (a torn staging\n\t * database can never be trusted, decision D10), it needs no pool slot, and its journal\n\t * lives in memory. Adapters without a cheap scratch database omit it; the store then\n\t * replicates straight into this database, as before.\n\t */\n\tcreateStagingAdapter?(): Promise<StorageAdapter | null>\n\t/**\n\t * Whether staged replication pays off on this adapter without being asked for. Browser\n\t * OPFS databases pay a journaled commit per batch that a memory replica avoids; native\n\t * SQLite has no such cost, so a second pass only adds work and it stages only when the\n\t * app opts in (`sync.bulkReplication: true` or an object). Absent means true.\n\t */\n\treadonly prefersStaging?: boolean\n}\n\n/**\n * Routes local mutations through a unified apply pipeline (korajs ApplyPipeline).\n *\n * Every local write — including each entry of an `app.transaction` commit — is\n * built and persisted by the store's single local write path; the handler adds\n * pipeline behaviour around it.\n */\nexport interface LocalMutationHandler {\n\tinsert(\n\t\tcollection: string,\n\t\tdata: Record<string, unknown>,\n\t\toptions?: WriteOptions,\n\t): Promise<CollectionRecord>\n\t/**\n\t * Insert several records in one storage transaction, all or none (see\n\t * `CollectionAccessor.insertMany`). Optional: without it the store writes the\n\t * batch through its own local write path.\n\t */\n\tinsertMany?(\n\t\tcollection: string,\n\t\trows: readonly Record<string, unknown>[],\n\t\toptions?: WriteOptions,\n\t): Promise<CollectionRecord[]>\n\tupdate(\n\t\tcollection: string,\n\t\tid: string,\n\t\tdata: Record<string, unknown>,\n\t\toptions?: WriteOptions,\n\t): Promise<CollectionRecord>\n\tdelete(collection: string, id: string, options?: WriteOptions): Promise<void>\n\t/**\n\t * Called inside the write transaction for every local delete (single-record,\n\t * transactional and cascaded), after the delete operation is built and before\n\t * referential side effects run. Reads must go through `tx`. Throwing aborts\n\t * the whole write.\n\t */\n\tbeforeLocalDelete?(operation: Operation, tx: Transaction): Promise<void>\n}\n\nexport type StoreIsolation = 'shared' | 'per-tab'\n\n/**\n * The key under which the journal of writes made before the store opened passes the ids and\n * the time it fixed when the user acted (see {@link FixedWrite}). A symbol, not a field, so it\n * is not part of `WriteOptions`: no caller can pick a record id or back-date an auto timestamp\n * through the public types. `korajs` builds the same key with `Symbol.for`.\n */\nexport const FIXED_WRITE_KEY: symbol = Symbol.for('korajs.store.fixedWrite')\n\n/** What the journal fixes when the user acts, so replaying a write after a crash lands on the same record. */\nexport interface FixedWrite {\n\t/** The id of an insert. */\n\trecordId?: string\n\t/** One id per row of an `insertMany`, in input order. */\n\trecordIds?: readonly string[]\n\t/** The time the user made the write; auto timestamps use it. */\n\twrittenAt?: number\n\t/**\n\t * Identity of the journaled write. The store records it in the SAME transaction as the write\n\t * (`_kora_journal_applied`, local only, never synced), so a replay can ask whether the write\n\t * already happened instead of guessing from the operation log.\n\t */\n\topKey?: string\n}\n\n/** Read the fixed ids and time off the options of a write, if the journal set them. */\nexport function readFixedWrite(options: WriteOptions | undefined): FixedWrite | undefined {\n\treturn (options as { [FIXED_WRITE_KEY]?: FixedWrite } | undefined)?.[FIXED_WRITE_KEY]\n}\n\n/**\n * Per-write options of `insert`, `insertMany`, `update` and `delete`.\n */\nexport interface WriteOptions {\n\t/**\n\t * Wait for the commit before this write is shown: no instant-updates prediction for\n\t * this one write, so live queries show it when its transaction has committed, exactly\n\t * as with `store.instantUpdates` off. It adds no durability: the write is stored the\n\t * same way either way, and its promise resolves at the same point. Has no effect when\n\t * instant updates are off.\n\t */\n\tdurable?: boolean\n}\n\n/**\n * Options of `createApp({ store: { instantUpdates } })`: show this tab's own writes in\n * its live queries before their storage transaction commits.\n *\n * The write path is unchanged (same operations, ids and order); the view is a tab-local\n * prediction that the database overwrites at commit, and that disappears if the write\n * fails. A row shown this way is NOT saved: only the write's promise resolving means\n * that. Off by default in beta.15.\n */\nexport interface InstantUpdatesOptions {\n\t/** Writes shown but not yet committed, per tab. Beyond it, writes wait for the commit. Default 256. */\n\tmaxPendingWrites?: number\n\t/** Estimated bytes of pending and settling writes. Default 8 MiB. */\n\tmaxPendingBytes?: number\n\t/** Largest number of records one write may touch and still be shown early. Default 100. */\n\tmaxRecordsPerWrite?: number\n}\n\nexport interface StoreConfig {\n\tschema: SchemaDefinition\n\tadapter: StorageAdapter\n\t/**\n\t * The version gate of this database when the adapter does not own one (an adapter that\n\t * ignores it, an embedder that opens the gate itself). Defaults to\n\t * `adapter.getVersionGate()`.\n\t */\n\tversionGate?: import('./multi-tab/version-gate').VersionGate | null\n\t/** Database name used for per-tab node id keys. Defaults to 'kora-db'. */\n\tdbName?: string\n\t/**\n\t * `shared` (default): one node id per database in `_kora_meta`.\n\t * `per-tab`: unique node id per browser tab via sessionStorage.\n\t */\n\tisolation?: StoreIsolation\n\t/** Optional node ID. If omitted, one is generated or loaded from the database. */\n\tnodeId?: string\n\t/**\n\t * The one user this database belongs to: it is opened only for them (`createApp` sets\n\t * it with `store.namespaceByAuthUser`). With a pinned {@link nodeId}, a database whose\n\t * pinned node moved retires the previous one: its writes are this user's, and those the\n\t * sync server does not hold are re-authored under this user's node (a browser shared\n\t * between accounts gives each account a device id, and so a node, of its own).\n\t */\n\tdatabaseOwner?: string\n\t/** Optional event emitter. When provided, local mutations emit 'operation:created' events. */\n\temitter?: KoraEventEmitter\n\t/** Routes local mutations through a unified apply pipeline when provided. */\n\tlocalMutationHandler?: LocalMutationHandler\n\t/** Called when a reactive query subscription is registered (for sync query subsets). */\n\tonQuerySubscribed?: (descriptor: QueryDescriptor) => () => void\n\t/**\n\t * Supplies the key used to encrypt `encrypted` secret fields at write time.\n\t * Required only when the schema declares encrypted secret fields.\n\t */\n\tsecretKeyProvider?: SecretKeyProvider\n\t/**\n\t * How rows are materialized. `'fold'` (default, W7): every write merges into the\n\t * record's per-field CRDT fold state, which re-materializes the row. `'legacy'`:\n\t * the beta.12 per-field LWW write paths, kept only so tests can build the database a\n\t * beta.12 device left behind and prove it is repaired. Applications never set it.\n\t * Switching modes on an existing database re-materializes it on open.\n\t */\n\tmaterialization?: 'fold' | 'legacy'\n\t/**\n\t * Schema transforms applied at fold time (RT-84): an operation authored under an\n\t * older schema version is stored exactly as written and folded as\n\t * `operationSchemaView(op, schema.version, transforms)` reads it. Pass the same list\n\t * as the sync engine's `operationTransforms` (`createApp` does). Transforms must be\n\t * pure and deterministic; they are part of the fold plan fingerprint, so changing\n\t * them re-folds once.\n\t */\n\toperationTransforms?: readonly OperationTransform[]\n\t/**\n\t * Largest serialized operation a local write may produce, in bytes (RT-86). Set it to\n\t * the sync server's `maxOperationBytes`. A write over it is refused with\n\t * `OperationTooLargeError` and nothing is written. Default 256 KiB, the server's\n\t * default.\n\t */\n\tmaxOperationBytes?: number\n\t/**\n\t * Show this store's own local writes in its live queries before their transaction\n\t * commits (`true`, or limits). Per store, default off. See {@link InstantUpdatesOptions}.\n\t */\n\tinstantUpdates?: boolean | InstantUpdatesOptions\n\t/**\n\t * Test and benchmark hooks of the instant-updates overlay. Internal: not part of the\n\t * public API and free to change.\n\t *\n\t * @internal\n\t */\n\tinstantUpdatesInternals?: import('./overlay/overlay-controller').OverlayControllerInternals\n}\n\n/**\n * Operators for where clause conditions.\n */\nexport interface WhereOperators {\n\t$eq?: unknown\n\t$ne?: unknown\n\t$gt?: number | string\n\t$gte?: number | string\n\t$lt?: number | string\n\t$lte?: number | string\n\t$in?: unknown[]\n}\n\n/**\n * Where clause: field name to value (shorthand for $eq) or WhereOperators.\n */\nexport type WhereClause = Record<string, unknown | WhereOperators>\n\n/**\n * Order direction for sorting query results.\n */\nexport type OrderByDirection = 'asc' | 'desc'\n\n/**\n * Order-by clause: field name and optional direction.\n */\nexport interface OrderByClause {\n\tfield: string\n\tdirection: OrderByDirection\n}\n\n/**\n * Internal representation of a query to be compiled to SQL.\n */\nexport interface QueryDescriptor {\n\tcollection: string\n\twhere: WhereClause\n\torderBy: OrderByClause[]\n\tlimit?: number\n\toffset?: number\n\t/** Relation names to include in results (for relational queries). */\n\tinclude?: string[]\n\t/** Resolved collection names for included relations (for subscription tracking). */\n\tincludeCollections?: string[]\n}\n\n/**\n * Callback for reactive subscriptions. Receives the current result set.\n */\nexport type SubscriptionCallback<T> = (results: T[]) => void\n\n/**\n * Where a subscription failure happened.\n * - `initial`: the first run of the query, before any result was delivered.\n * - `refresh`: a re-run after a write to a collection the query reads.\n * - `callback`: the query succeeded but the subscriber's own callback threw.\n */\nexport type QueryErrorPhase = 'initial' | 'refresh' | 'callback'\n\n/**\n * A failure delivered to a subscriber's `onError` (STORE-12). The previous result\n * set stays current; the subscription stays registered and is re-run on the next\n * write, and a later success is delivered even if it equals the last results.\n */\nexport interface QuerySubscriptionError {\n\t/** The error thrown by the query or the callback. */\n\terror: Error\n\tphase: QueryErrorPhase\n\t/** The collection the query reads. */\n\tcollection: string\n\t/** Subscription id, the same `queryId` carried by the `query:error` event. */\n\tqueryId: string\n}\n\n/**\n * Options for `QueryBuilder.subscribe()`.\n */\n/**\n * Where a subscription's rows come from and whether they are the whole answer.\n * - `server`: an answer read from the server before the local store opened (complete for the query).\n * - `local`: the local store; `complete` is false until the device holds the full scope\n *   (a first visit that is still replicating shows only what it holds so far).\n * - `pending`: no result yet.\n */\nexport interface QueryCoverage {\n\tsource: 'local' | 'server' | 'pending'\n\tcomplete: boolean\n}\n\nexport interface SubscribeOptions {\n\t/**\n\t * Called with the coverage of the rows delivered to the callback, when it changes. A query\n\t * that reports nothing is a plain local query: `{ source: 'local', complete: true }`.\n\t */\n\tonCoverage?: (coverage: QueryCoverage) => void\n\t/**\n\t * Called when the query fails (or the callback throws) instead of the failure\n\t * becoming an unhandled rejection. Every failure is also emitted as a\n\t * `query:error` event; without `onError` it is additionally logged.\n\t */\n\tonError?: (failure: QuerySubscriptionError) => void\n}\n\n/**\n * Serialized row in the operations log table.\n */\nexport interface OperationRow {\n\tid: string\n\tnode_id: string\n\ttype: string\n\trecord_id: string\n\tdata: string | null\n\tprevious_data: string | null\n\ttimestamp: string\n\tsequence_number: number\n\tcausal_deps: string\n\tschema_version: number\n}\n\n/**\n * Record type returned from collection queries.\n * Includes the id and mapped metadata fields.\n */\nexport interface CollectionRecord {\n\tid: string\n\tcreatedAt: number\n\tupdatedAt: number\n\t[key: string]: unknown\n}\n\nexport type { ReplaySnapshot } from './replay/replay-to'\n\n/**\n * Internal row shape returned from SQL queries on collection tables.\n */\nexport interface RawCollectionRow {\n\tid: string\n\t_created_at: number\n\t_updated_at: number\n\t_version?: string\n\t/** JSON map of per-field last-writer HLC versions: { field -> serialized HLC }. */\n\t_field_versions?: string\n\t_deleted: number\n\t[key: string]: unknown\n}\n\n/**\n * A registered subscription tracked by the SubscriptionManager.\n */\nexport interface Subscription<T = CollectionRecord> {\n\tid: string\n\tdescriptor: QueryDescriptor\n\tcallback: SubscriptionCallback<T>\n\texecuteFn: () => Promise<T[]>\n\tlastResults: T[]\n\t/** Result-set comparator (structural, per field kind). */\n\tresultsEqual?: (prev: readonly T[], next: readonly T[]) => boolean\n\tonError?: (failure: QuerySubscriptionError) => void\n\t/** Monotonic run counter: a slower, older run never overwrites a newer result. */\n\trunsStarted?: number\n\tlastAppliedRun?: number\n\t/** True after a failure until the next successful delivery. */\n\terrored?: boolean\n\t/** True once a result set has been delivered to the callback. */\n\tdelivered?: boolean\n\t/**\n\t * Instant-UI overlay (S3). The last authoritative (SQL) result, before any pending\n\t * write was applied; null until the first result arrives. `lastResults` is what was\n\t * last delivered to the callback (the design's `displayed`).\n\t */\n\tbase?: T[] | null\n\t/** Overlay epoch when the read that produced `base` was issued (design 5.5). */\n\tbaseIssuedAt?: number\n\t/** Whether the evaluator may patch this query (decided once, on first use). */\n\tpatchable?: boolean\n\t/**\n\t * Pending writes the last patch could not apply to this query (limit pages, ties):\n\t * its display did not include them, so the settle check does not compare them.\n\t */\n\tskippedWrites?: ReadonlySet<string>\n}\n\nexport type { ApplyResult } from '@korajs/core'\n\n/**\n * Options for applying a remote operation to materialized storage.\n */\nexport interface ApplyRemoteOptions {\n\t/**\n\t * W7: receives the merge traces of the operation (conflicting field decisions),\n\t * after commit. The store also emits them as `merge:*` events.\n\t */\n\tonMergeTraces?: (traces: import('@korajs/core').MergeTrace[]) => void\n\t/** When true, a winning remote update clears soft-delete on the row. */\n\treactivateIfDeleted?: boolean\n\t/**\n\t * Where in the server's delivery stream this operation was delivered. Decides whether\n\t * it shows a record a scope retraction hid: only when it comes after the retraction.\n\t * Usually supplied by the sync engine through `Store.noteDeliveryPosition` instead.\n\t */\n\tdeliveryPosition?: number\n\t/**\n\t * When true, materialize the update unconditionally, bypassing the LWW\n\t * version guard. Used only for authoritative three-way merge results: the\n\t * merged value already incorporates the current local row, so it must be\n\t * written even when its timestamp ties the current row version (which\n\t * happens on the device that authored the newer of two concurrent edits —\n\t * without this, that device's CRDT/merge result is silently dropped).\n\t */\n\tforceMaterialize?: boolean\n\t/**\n\t * Data to materialize into the row INSTEAD of `op.data`, without altering\n\t * what is stored in the append-only operation log. Merge results must never\n\t * be persisted under the original operation's content-addressed id (ops are\n\t * immutable); the pipeline passes the merged values here so the log keeps\n\t * the canonical operation while the row reflects the merge.\n\t */\n\tmaterializeData?: Record<string, unknown>\n\t/**\n\t * Version timestamp to stamp on the materialized row INSTEAD of\n\t * `op.timestamp` (e.g. max(local, remote) for a merge result). The logged\n\t * operation keeps its own timestamp.\n\t */\n\tmaterializeTimestamp?: HLCTimestamp\n\t/**\n\t * Optimistic-concurrency guard: the row version state the caller observed\n\t * when it computed the data it is now applying. Inside the write\n\t * transaction, if the row's current `_version` / `_field_versions` no longer\n\t * match this snapshot, the apply throws `OptimisticLockError` (rolling back,\n\t * writing nothing) so the caller can recompute against fresh state.\n\t */\n\tguardRowState?: RowVersionState\n\t/**\n\t * When true, append the operation to the log (advancing the version vector and\n\t * enabling dedup) WITHOUT materializing anything into the row. Used when a fold\n\t * of the record's log has determined the operation does not change the\n\t * authoritative row state (e.g. a stale update that loses to a newer delete):\n\t * the op must still be persisted so a later fold — for example an atomic\n\t * resurrection composing this op's delta — is complete, but the row (a clean\n\t * tombstone) must be left untouched, with no zombie fields and no version regression.\n\t */\n\tlogOnly?: boolean\n}\n\n/**\n * Raw version state of a materialized row, used for optimistic-concurrency\n * guarded applies. `null` means the row (or column value) was absent.\n */\nexport interface RowVersionState {\n\tversion: string | null\n\tfieldVersions: string | null\n}\n\n/** A cascade or set-null a remote delete derived, folded as a provisional effect (RT-69). */\nexport interface ProvisionalSideEffect {\n\ttype: 'delete' | 'update'\n\tcollection: string\n\trecordId: string\n\tdata: Record<string, unknown> | null\n\tpreviousData: Record<string, unknown> | null\n\truleId: string\n}\n\n/** Reads of one collection through a remote batch's transaction (see `RemoteApplyBatch.read`). */\nexport interface RemoteBatchCollectionReader {\n\tfindById(id: string): Promise<CollectionRecord | null>\n\twhere(conditions: WhereClause): {\n\t\texec(): Promise<CollectionRecord[]>\n\t\tcount(): Promise<number>\n\t}\n}\n\n/**\n * One delivery batch being applied in a single storage transaction (C3,\n * `Store.applyRemoteBatch`). Every write goes through {@link tx}; every operation and\n * retraction runs in its own savepoint, so a failing one is undone alone. Nothing is\n * published (notifications, events, version vector) until the transaction commits.\n */\nexport interface RemoteApplyBatch {\n\t/** The batch's transaction, for reads that must see the batch's own writes. */\n\treadonly tx: Transaction\n\t/**\n\t * Optional (C3b): tell the batch which operations it is about to apply, so it reads\n\t * what they need (log, fold states, rows) in a few queries instead of a dozen per\n\t * operation. An operation not announced is applied exactly as before. Call it before\n\t * the first `applyRemoteOperation` of those operations.\n\t */\n\tprefetch(operations: readonly Operation[]): Promise<void>\n\t/**\n\t * Write every statement the batch has buffered (steps whose writes cannot fail share one\n\t * buffer and are sent together). Call it before a check that decides whether the batch may\n\t * still commit: a check made before it does not cover the writes that are still waiting.\n\t */\n\tflush(): Promise<void>\n\t/**\n\t * Append and fold one remote operation (W7) in a savepoint. Rejects (with only this\n\t * operation rolled back) when it cannot be applied.\n\t */\n\tapplyRemoteOperation(\n\t\top: Operation,\n\t\toptions?: Pick<ApplyRemoteOptions, 'onMergeTraces' | 'deliveryPosition'>,\n\t): Promise<ApplyResult>\n\t/** Hide a record a scope retraction removed from this view (see `Store.applyScopeRetraction`). */\n\tapplyScopeRetraction(collection: string, recordId: string, position?: number): Promise<void>\n\t/** Fold a remote delete's provisional side effects (see `Store.applyProvisionalSideEffects`). */\n\tapplyProvisionalSideEffects(\n\t\tparent: Operation,\n\t\teffects: ReadonlyArray<ProvisionalSideEffect>,\n\t): Promise<number>\n\t/** A materialized row as the batch sees it (its own writes included). */\n\tfindMaterializedRow(collection: string, recordId: string): Promise<MaterializedRowSnapshot | null>\n\t/**\n\t * Read a collection as the batch sees it (its own writes included), with exactly the\n\t * queries `store.collection(name)` runs: `findById` (live records only) and\n\t * `where(conditions).exec()` / `.count()`. For checks that must see the state right\n\t * after one operation of the batch (the optimistic constraint check).\n\t */\n\tread(collection: string): RemoteBatchCollectionReader\n\t/** Record quarantined operations (and the watermark advance) in the batch's transaction. */\n\tsaveInboundQuarantine(\n\t\tentries: UnappliedOperation[],\n\t\twatermark?: { signature: string; watermark: number; completion?: OfflineCompletion },\n\t): Promise<void>\n\t/**\n\t * Persist a view's delivery watermark in the batch's transaction, with the completion\n\t * mark of a final batch (set in the same transaction).\n\t */\n\tsaveDeliveryWatermark(\n\t\tsignature: string,\n\t\twatermark: number,\n\t\tcompletion?: OfflineCompletion,\n\t): Promise<void>\n\t/**\n\t * Run `effect` once the batch committed, in registration order with the store's own\n\t * notifications. Dropped when the step that registered it (or the batch) rolls back.\n\t */\n\tafterCommit(effect: () => void): void\n}\n\n/**\n * Snapshot of a materialized row, including soft-deleted records.\n */\nexport interface MaterializedRowSnapshot {\n\t/** Deserialized application record (excludes tombstone metadata). */\n\trecord: CollectionRecord\n\t/** Whether the row is soft-deleted (_deleted = 1). */\n\tdeleted: boolean\n}\n\n/**\n * Metadata row from _kora_meta table.\n */\nexport interface MetaRow {\n\tkey: string\n\tvalue: string\n}\n\n/**\n * Version vector row from _kora_version_vector table.\n */\nexport interface VersionVectorRow {\n\tnode_id: string\n\tsequence_number: number\n}\n\n/**\n * Whether resolved local writes are durable (`app.storage.writes`). `failing` after a\n * committed write could not be confirmed on durable storage (IndexedDB fallback only);\n * `permanent` means its snapshot lineage was superseded and nothing in this page can\n * prove it saved: reload before making more changes.\n */\nexport type WriteDurabilityState =\n\t| { readonly state: 'durable' }\n\t| {\n\t\t\treadonly state: 'failing'\n\t\t\treadonly permanent: boolean\n\t\t\treadonly since: number\n\t\t\treadonly message: string\n\t  }\n","import type { Operation } from '@korajs/core'\nimport { KoraError } from '@korajs/core'\nimport { type WriteObserver, notifyWriteObserver } from '@korajs/core/internal'\nimport { activePhaseTimers } from '../instrumentation/phase-timers'\nimport { type CommitLookup, lookupCommit } from './commit-outcome'\nimport type { LocalMutationContext } from './types'\nimport { CausalScope, type WriteScope, waitForCausalHeads, withWriteScope } from './write-context'\nimport type { WriteResult } from './write-ops'\n\n/** Thrown inside the transaction to roll it back when the journaled write already landed. */\nconst ALREADY_APPLIED = Symbol('journal-already-applied')\n\n/** Options for {@link runLocalWrite}. */\nexport interface RunLocalWriteOptions {\n\t/**\n\t * Every operation of the write also depends on the previous one (as in\n\t * `store.transaction`). Used by multi-record writes such as `insertMany`.\n\t */\n\treadonly chainOperations?: boolean\n\t/**\n\t * Identity of a journaled write: recorded in `_kora_journal_applied` inside the write's own\n\t * transaction, so \"the write is in the store\" and \"the journal knows it\" cannot diverge.\n\t */\n\treadonly opKey?: string | undefined\n\t/**\n\t * The binding that started this write (captured synchronously by the caller). It\n\t * learns the write's operation ids after the commit and before they reach sync.\n\t */\n\treadonly observer?: WriteObserver | null\n\t/**\n\t * Called once, right after the transaction commits and before the operations are\n\t * published (and before any durability barrier): the overlay's commit signal\n\t * (instant-UI S2). It must not throw and is never read back: the write path does not\n\t * depend on what it does.\n\t */\n\treadonly onCommitted?: (results: readonly WriteResult[]) => void\n\t/**\n\t * M2 for local writes. Present only when the caller wants a lost COMMIT answer decided\n\t * (the instant-updates overlay): if the transaction rejects after its body finished,\n\t * the write is looked up by the content-addressed id of its operation. `committed`:\n\t * the write landed, so it is published and resolved as if the commit had answered\n\t * (`onCommitted` runs). `absent`: nothing landed, the error propagates. `unknown`:\n\t * the lookup itself failed; the error propagates and this is told so the caller does\n\t * not treat the write as rolled back. Without this option a rejected transaction\n\t * rejects the write, as it always did.\n\t */\n\treadonly onCommitUnknown?: (\n\t\tlookup: CommitLookup,\n\t\terror: unknown,\n\t\tresults: readonly WriteResult[],\n\t) => void\n}\n\n/**\n * Run one local write in its own storage transaction, then publish it.\n *\n * Post-commit work (causal heads, in-memory version vector, subscriptions,\n * `operation:created`) runs only after the transaction commits, so nothing\n * observable ever points at an operation that was rolled back (STORE-15).\n *\n * `write` may return one result or several (a multi-record write); the\n * operations of every result are published in order.\n */\nexport async function runLocalWrite<R extends WriteResult | readonly WriteResult[]>(\n\tctx: LocalMutationContext,\n\twrite: (scope: WriteScope) => Promise<R>,\n\toptions: RunLocalWriteOptions = {},\n): Promise<R> {\n\tconst causal = new CausalScope(ctx.causalTracker, options.chainOperations === true)\n\tlet result: R | undefined\n\tconst timers = activePhaseTimers()\n\tconst txCalledAt = timers ? performance.now() : 0\n\tlet bodyStartedAt = 0\n\tlet bodyEndedAt = 0\n\t// Not while a clock rebase rewrites operation ids: this write's causalDeps would name them.\n\tawait waitForCausalHeads(ctx.causalTracker)\n\ttry {\n\t\tawait ctx.adapter.transaction(\n\t\t\tasync (tx) => {\n\t\t\t\tbodyStartedAt = timers ? performance.now() : 0\n\t\t\t\tif (options.opKey !== undefined) {\n\t\t\t\t\t// The claim is atomic with the write: a second tab replaying the same journal entry\n\t\t\t\t\t// (no Web Locks to keep them apart) finds the key here and writes nothing.\n\t\t\t\t\tconst seen = await tx.query('SELECT 1 FROM _kora_journal_applied WHERE op_key = ?', [\n\t\t\t\t\t\toptions.opKey,\n\t\t\t\t\t])\n\t\t\t\t\tif (seen.length > 0) throw ALREADY_APPLIED\n\t\t\t\t}\n\t\t\t\tresult = await withWriteScope(tx, ctx.nodeId, causal, write)\n\t\t\t\tif (options.opKey !== undefined) {\n\t\t\t\t\tawait tx.execute(\n\t\t\t\t\t\t'INSERT OR IGNORE INTO _kora_journal_applied (op_key, applied_at) VALUES (?, ?)',\n\t\t\t\t\t\t// Pruning bookkeeping only; never used to order anything.\n\t\t\t\t\t\t[options.opKey, Date.now()],\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tbodyEndedAt = timers ? performance.now() : 0\n\t\t\t},\n\t\t\t// A journaled write reads its key and then writes: take the write lock at once so two\n\t\t\t// processes on one native database queue instead of deadlocking on the lock upgrade.\n\t\t\t{ immediate: options.opKey !== undefined },\n\t\t)\n\t} catch (error) {\n\t\tif (error === ALREADY_APPLIED) {\n\t\t\tthrow new KoraError(\n\t\t\t\t'This journaled write was already applied by another tab.',\n\t\t\t\t'JOURNAL_ALREADY_APPLIED',\n\t\t\t\t{ collection: ctx.collection },\n\t\t\t)\n\t\t}\n\t\t// The body finished, so the failure came with the COMMIT (or the flush before it):\n\t\t// whether it landed is not known from the error alone (M2).\n\t\tconst finished = (): R | undefined => result\n\t\tconst built = finished()\n\t\tif (options.onCommitUnknown && built !== undefined) {\n\t\t\tconst written: readonly WriteResult[] = isResultList(built) ? built : [built]\n\t\t\tconst lookup = await lookupCommit(ctx.adapter, written)\n\t\t\toptions.onCommitUnknown(lookup, error, written)\n\t\t\tif (lookup.outcome !== 'committed') {\n\t\t\t\tctx.onStorageError?.(error)\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\t// It landed: continue as if COMMIT had answered.\n\t\t} else {\n\t\t\tctx.onStorageError?.(error)\n\t\t\tthrow error\n\t\t}\n\t}\n\tif (!result) {\n\t\tthrow new KoraError('Local write transaction completed without a result', 'WRITE_INCOMPLETE', {\n\t\t\tcollection: ctx.collection,\n\t\t})\n\t}\n\tconst committedAt = timers ? performance.now() : 0\n\tif (timers) {\n\t\ttimers.add('txOpen', bodyStartedAt - txCalledAt)\n\t\ttimers.add('body', bodyEndedAt - bodyStartedAt)\n\t\ttimers.add('commit', committedAt - bodyEndedAt)\n\t}\n\tcausal.publish()\n\tconst results: readonly WriteResult[] = isResultList(result) ? result : [result]\n\t// The observer (the binding that started this write) learns every operation id of the\n\t// write before they reach sync, so a refusal can never arrive before the write is tracked.\n\tnotifyWriteObserver(\n\t\toptions.observer ?? null,\n\t\tresults.flatMap((one) => [...(one.operation ? [one.operation] : []), ...one.sideEffects]),\n\t)\n\toptions.onCommitted?.(results)\n\tfor (const one of results) publishOperations(ctx, one)\n\tif (timers) {\n\t\tconst publishedAt = performance.now()\n\t\ttimers.add('publish', publishedAt - committedAt)\n\t\ttimers.notePublished(publishedAt)\n\t}\n\n\t// IndexedDB fallback commits first to the live in-memory SQLite database and\n\t// persists a snapshot asynchronously. A resolved write promise is a durability\n\t// promise, so wait for the adapter's group-commit barrier after publishing the\n\t// committed operations. Native and OPFS adapters have no barrier and pay nothing.\n\tif (ctx.adapter.ensureDurable) {\n\t\tconst operationIds = results.flatMap((one) => [\n\t\t\t...(one.operation ? [one.operation.id] : []),\n\t\t\t...one.sideEffects.map((operation) => operation.id),\n\t\t])\n\t\ttry {\n\t\t\tawait ctx.adapter.ensureDurable()\n\t\t\tctx.onWriteDurable?.()\n\t\t} catch (error) {\n\t\t\tctx.onStorageError?.(error)\n\t\t\tthrow ctx.onWriteDurabilityError?.(error, operationIds) ?? error\n\t\t}\n\t}\n\treturn result\n}\n\nfunction isResultList(\n\tvalue: WriteResult | readonly WriteResult[],\n): value is readonly WriteResult[] {\n\treturn Array.isArray(value)\n}\n\n/** Notify the store about every operation of a committed write, in creation order. */\nfunction publishOperations(ctx: LocalMutationContext, result: WriteResult): void {\n\tconst ops: Operation[] = []\n\tif (result.operation) ops.push(result.operation)\n\tops.push(...result.sideEffects)\n\tfor (const op of ops) {\n\t\tctx.onMutation(op.collection, op)\n\t}\n}\n","import { quoteIdent } from '@korajs/core'\nimport type { StorageAdapter } from '../types'\nimport type { WriteResult } from './write-ops'\n\n/*\n * M2, for local writes (docs/design/instant-ui-updates.md 7; plan item M2): when a write\n * transaction rejects AFTER its body finished, the answer to COMMIT was lost (a leader\n * change cut the reply, a bridge died) and the commit may have landed. Operation ids are\n * content-addressed, so the write's own primary operation id is a witness: the\n * transaction is atomic, so if that operation is in the log, everything else landed too.\n */\n\n/** What the lookup found. */\nexport type CommitLookup =\n\t/** The operation is in the log: the commit landed. */\n\t| { readonly outcome: 'committed' }\n\t/** The log was read and the operation is not in it: nothing was committed. */\n\t| { readonly outcome: 'absent' }\n\t/**\n\t * The log could not be read (the adapter is still unavailable), or the write has no\n\t * operation to look for. `operationId` is the witness to try again later, when known.\n\t */\n\t| {\n\t\t\treadonly outcome: 'unknown'\n\t\t\treadonly operationId: string | null\n\t\t\treadonly collection: string | null\n\t  }\n\n/** The operation whose presence in the log proves the write landed. */\nexport function witnessOperation(\n\tresults: readonly WriteResult[],\n): { readonly id: string; readonly collection: string } | null {\n\tfor (const result of results) {\n\t\tconst operation = result.operation ?? result.sideEffects[0]\n\t\tif (operation) return { id: operation.id, collection: operation.collection }\n\t}\n\treturn null\n}\n\n/**\n * Ask the operation log whether a write whose commit answer was lost landed. Never\n * throws: a failed read is `unknown`, not a guess either way.\n *\n * @param adapter - The store's adapter\n * @param results - The write's results, as built inside the (rejected) transaction\n */\nexport async function lookupCommit(\n\tadapter: StorageAdapter,\n\tresults: readonly WriteResult[],\n): Promise<CommitLookup> {\n\tconst witness = witnessOperation(results)\n\tif (!witness) return { outcome: 'unknown', operationId: null, collection: null }\n\treturn lookupOperation(adapter, witness.collection, witness.id)\n}\n\n/** {@link lookupCommit} for a witness already known (a later retry). */\nexport async function lookupOperation(\n\tadapter: StorageAdapter,\n\tcollection: string,\n\toperationId: string,\n): Promise<CommitLookup> {\n\ttry {\n\t\tconst rows = await adapter.query<{ id: string }>(\n\t\t\t`SELECT id FROM ${quoteIdent(`_kora_ops_${collection}`)} WHERE id = ? LIMIT 1`,\n\t\t\t[operationId],\n\t\t)\n\t\treturn rows.length > 0 ? { outcome: 'committed' } : { outcome: 'absent' }\n\t} catch {\n\t\treturn { outcome: 'unknown', operationId, collection }\n\t}\n}\n","import type { AtomicOp, CollectionDefinition, FoldState, Operation } from '@korajs/core'\nimport {\n\tDEFAULT_MAX_OPERATION_BYTES,\n\tKoraError,\n\tOperationTooLargeError,\n\tcreateOperation,\n\tgenerateUUIDv7,\n\tmeasureOperationBytes,\n\tquoteIdent,\n\tvalidateRecord,\n} from '@korajs/core'\nimport { RecordNotFoundError, StampedFieldError } from '../errors'\nimport { activePhaseTimers } from '../instrumentation/phase-timers'\nimport { stampFieldVersions } from '../lww/field-versions'\nimport { serializeRowVersion } from '../lww/row-version'\nimport { buildInsertQuery, buildSoftDeleteQuery, buildUpdateQuery } from '../query/sql-builder'\nimport { encodeRichtextFieldsForOpData } from '../serialization/op-data-encoding'\nimport { deserializeRecord, serializeOperation, serializeRecord } from '../serialization/serializer'\nimport { validateUpdateStateMachine } from '../state-machine/state-validator'\nimport type { CollectionRecord, RawCollectionRow } from '../types'\nimport { toAtRestWriteData } from './secret-write'\nimport { withoutUnchangedFields } from './unchanged-fields'\nimport type { WriteEnv, WriteScope } from './write-context'\nimport {\n\ttype PreparedInsert,\n\tinsertOperationData,\n\tpatchForUpdate,\n\trecordForInsert,\n\ttombstone,\n} from './write-shapes'\n\nexport type { PreparedInsert }\n\n/*\n * THE local write path (W6). Every local operation — a single-record write, each\n * entry of an `app.transaction` / `app.mutation` commit, and every referential\n * cascade — is built and persisted by the functions in this file, inside the\n * storage transaction that commits it:\n *\n * 1. the current row is read through the transaction handle, so validation\n *    (existence, state machine) and atomic ops resolve against committed state;\n * 2. the sequence number comes from the transaction's SequenceBlock (reserved\n *    with UPSERT ... RETURNING on `_kora_version_vector` inside the transaction,\n *    end persisted before commit); transactions are serialized, so the numbers of\n *    one commit form one contiguous block and two commits can never share one;\n * 3. the operation is built only AFTER its sequence number is reserved, and is\n *    never re-stamped (protocol v2 hashes the sequence number into the id);\n * 4. the row is written with per-field version stamps and the operation row is\n *    appended, in the same transaction.\n */\n\n/**\n * Validate insert data, fill auto fields and transform secrets. Pure with\n * respect to storage, so `app.transaction` can do it when the developer calls\n * `insert` (returning the new id immediately) and write it at commit.\n */\nexport async function prepareInsert(\n\tenv: WriteEnv,\n\tcollection: string,\n\tdata: Record<string, unknown>,\n\tfixed?: { recordId?: string | undefined; at?: number | undefined },\n): Promise<PreparedInsert> {\n\tconst definition = requireDefinition(env, collection)\n\tconst validated = validateRecord(collection, definition, data, 'insert')\n\tconst now = fixed?.at ?? Date.now()\n\tfor (const [fieldName, descriptor] of Object.entries(definition.fields)) {\n\t\tif (descriptor.auto && descriptor.kind === 'timestamp') {\n\t\t\tvalidated[fieldName] = now\n\t\t}\n\t\tif (descriptor.stamp === 'userId') stampUserField(env, collection, fieldName, validated)\n\t}\n\t// Secret fields reach their at-rest form BEFORE the operation is built, so\n\t// plaintext never enters the op log, the row, or the wire (STORE-4).\n\tconst writeData = await toAtRestWriteData(validated, definition, env.secretKeyProvider)\n\treturn { collection, recordId: fixed?.recordId ?? generateUUIDv7(), data: writeData }\n}\n\n/**\n * Fill a `stamp('userId')` field with the signed-in user, as the server requires: the\n * server refuses an insert whose stamped field is missing or names another user.\n * Refusing here keeps the write from being made at all, rather than refused on upload.\n */\nfunction stampUserField(\n\tenv: WriteEnv,\n\tcollection: string,\n\tfieldName: string,\n\tvalues: Record<string, unknown>,\n): void {\n\tconst user = env.signedInUser?.() ?? null\n\tconst given = values[fieldName]\n\tif (user === null) {\n\t\tif (typeof given === 'string') return\n\t\tthrow new StampedFieldError(\n\t\t\t`\"${collection}.${fieldName}\" is stamped with the signed-in user, but Kora does not know who is signed in. Configure sync with an authClient (or a principal) so the app knows the user before writing, or pass \"${fieldName}\" yourself.`,\n\t\t\t'STAMP_USER_UNKNOWN',\n\t\t\t{ collection, field: fieldName },\n\t\t)\n\t}\n\tif (given !== undefined && given !== null && given !== user) {\n\t\tthrow new StampedFieldError(\n\t\t\t`\"${collection}.${fieldName}\" is stamped with the signed-in user (\"${user}\"); an insert cannot set it to \"${String(given)}\". Leave it out and Kora fills it.`,\n\t\t\t'STAMP_MISMATCH',\n\t\t\t{ collection, field: fieldName, user },\n\t\t)\n\t}\n\tvalues[fieldName] = user\n}\n\n/** Result of writing one local operation. */\nexport interface WriteResult {\n\t/** The operation, or null when the write turned out to be a no-op. */\n\treadonly operation: Operation | null\n\t/** The record as stored after the write. */\n\treadonly record: CollectionRecord\n\t/** Operations created as side effects (referential cascades), in creation order. */\n\treadonly sideEffects: Operation[]\n\t/**\n\t * An update's record fold state as the merge read it, before the operation (record fold\n\t * only). The overlay re-predicts an array write from it when it checks the commit.\n\t */\n\treadonly priorFoldState?: FoldState\n}\n\n/**\n * Write a prepared insert inside `scope.tx`.\n */\nexport async function writeInsertInTx(\n\tenv: WriteEnv,\n\tscope: WriteScope,\n\tinsert: PreparedInsert,\n\textraCausalDeps: readonly string[] = [],\n): Promise<WriteResult> {\n\tconst definition = requireDefinition(env, insert.collection)\n\tconst operation = await buildLocalOperation(env, scope, {\n\t\ttype: 'insert',\n\t\tcollection: insert.collection,\n\t\trecordId: insert.recordId,\n\t\tdata: insertOperationData(insert, definition),\n\t\tpreviousData: null,\n\t\textraCausalDeps,\n\t})\n\n\tif (env.fold) {\n\t\t// Append, then merge: the row is the materialization of the record's state.\n\t\tawait appendOperationRow(scope, operation)\n\t\tawait env.fold.applyInTx(scope.tx, operation, 'local')\n\t} else {\n\t\tconst serialized = serializeRecord(insert.data, definition.fields)\n\t\tconst version = serializeRowVersion(operation.timestamp)\n\t\tconst row: Record<string, unknown> = {\n\t\t\tid: insert.recordId,\n\t\t\t...serialized,\n\t\t\t_created_at: operation.timestamp.wallTime,\n\t\t\t_updated_at: operation.timestamp.wallTime,\n\t\t\t_version: version,\n\t\t\t// Every inserted field is stamped with this operation's version, so later\n\t\t\t// per-field LWW compares against a real writer, not the row fallback.\n\t\t\t_field_versions: stampFieldVersions(null, Object.keys(serialized), version),\n\t\t}\n\t\tconst rowInsert = buildInsertQuery(insert.collection, row)\n\t\tawait scope.tx.execute(rowInsert.sql, rowInsert.params)\n\t\tawait appendOperationRow(scope, operation)\n\t}\n\n\treturn {\n\t\toperation,\n\t\trecord: recordForInsert(insert, definition, operation.timestamp.wallTime),\n\t\tsideEffects: [],\n\t}\n}\n\n/**\n * Write a local update inside `scope.tx`.\n *\n * `data` must already be schema-validated (it may contain atomic op descriptors).\n * The state machine, atomic ops and `previousData` are all resolved against the\n * row read through the transaction, so concurrent writers serialize correctly\n * (STORE-9, NEW-STORE-2).\n */\nexport async function writeUpdateInTx(\n\tenv: WriteEnv,\n\tscope: WriteScope,\n\tcollection: string,\n\tid: string,\n\tdata: Record<string, unknown>,\n\textraCausalDeps: readonly string[] = [],\n): Promise<WriteResult> {\n\tconst definition = requireDefinition(env, collection)\n\tconst currentRow = await readLiveRow(scope, collection, id)\n\tif (!currentRow) {\n\t\tthrow new RecordNotFoundError(collection, id)\n\t}\n\tconst currentRecord = deserializeRecord(currentRow, definition.fields)\n\tconst allowed = withoutUnchangedFields(\n\t\tdefinition,\n\t\tcurrentRecord,\n\t\tvalidateUpdateStateMachine(collection, id, definition, currentRecord, data),\n\t)\n\tif (Object.keys(allowed).length === 0) {\n\t\treturn { operation: null, record: currentRecord, sideEffects: [] }\n\t}\n\n\tconst { previousData, resolved, atomicOps } = patchForUpdate(\n\t\tcollection,\n\t\tdefinition,\n\t\tcurrentRecord,\n\t\tallowed,\n\t)\n\t// previousData already holds the stored (at-rest) values, so only the new\n\t// values need the secret transform.\n\tconst writeData = await toAtRestWriteData(resolved, definition, env.secretKeyProvider)\n\n\tconst operation = await buildLocalOperation(env, scope, {\n\t\ttype: 'update',\n\t\tcollection,\n\t\trecordId: id,\n\t\tdata: encodeRichtextFieldsForOpData(writeData, definition.fields),\n\t\tpreviousData: encodeRichtextFieldsForOpData(previousData, definition.fields),\n\t\textraCausalDeps,\n\t\t...(Object.keys(atomicOps).length > 0 ? { atomicOps } : {}),\n\t})\n\n\tlet priorFoldState: FoldState | undefined\n\tif (env.fold) {\n\t\tawait appendOperationRow(scope, operation)\n\t\tpriorFoldState = (await env.fold.applyInTx(scope.tx, operation, 'local')).priorState\n\t} else {\n\t\tconst serializedChanges = serializeRecord(writeData, definition.fields)\n\t\tconst version = serializeRowVersion(operation.timestamp)\n\t\t// A local edit is the newest writer of every field it touches (the HLC is past\n\t\t// every timestamp this device has seen), so each changed field gets its stamp.\n\t\tconst rowUpdate = buildUpdateQuery(collection, id, {\n\t\t\t...serializedChanges,\n\t\t\t_updated_at: operation.timestamp.wallTime,\n\t\t\t_version: version,\n\t\t\t_field_versions: stampFieldVersions(\n\t\t\t\tcurrentRow._field_versions,\n\t\t\t\tObject.keys(serializedChanges),\n\t\t\t\tversion,\n\t\t\t),\n\t\t})\n\t\tawait scope.tx.execute(rowUpdate.sql, rowUpdate.params)\n\t\tawait appendOperationRow(scope, operation)\n\t}\n\n\tconst updatedRow = await readLiveRow(scope, collection, id)\n\tif (!updatedRow) {\n\t\tthrow new RecordNotFoundError(collection, id)\n\t}\n\treturn {\n\t\toperation,\n\t\trecord: deserializeRecord(updatedRow, definition.fields),\n\t\tsideEffects: [],\n\t\t...(priorFoldState ? { priorFoldState } : {}),\n\t}\n}\n\n/** Options for {@link writeDeleteInTx}. */\nexport interface WriteDeleteOptions {\n\t/** Skip referential checks and cascades (the caller already applied them). */\n\treadonly skipReferentialEnforcement?: boolean\n\t/** Explicit causal parents (e.g. the delete that caused this cascade). */\n\treadonly extraCausalDeps?: readonly string[]\n}\n\n/**\n * Soft-delete a record inside `scope.tx`, then apply the schema's referential\n * policies (cascade, set-null, restrict) in the same transaction. Cascaded\n * operations are built through this same write path, after the parent, so their\n * sequence numbers follow the parent's in the commit's block (STORE-2).\n */\nexport async function writeDeleteInTx(\n\tenv: WriteEnv,\n\tscope: WriteScope,\n\tcollection: string,\n\tid: string,\n\toptions: WriteDeleteOptions = {},\n): Promise<WriteResult> {\n\tconst definition = requireDefinition(env, collection)\n\tconst currentRow = await readLiveRow(scope, collection, id)\n\tif (!currentRow) {\n\t\tthrow new RecordNotFoundError(collection, id)\n\t}\n\tconst operation = await buildLocalOperation(env, scope, {\n\t\ttype: 'delete',\n\t\tcollection,\n\t\trecordId: id,\n\t\tdata: null,\n\t\tpreviousData: null,\n\t\textraCausalDeps: options.extraCausalDeps ?? [],\n\t})\n\n\tif (!options.skipReferentialEnforcement && env.beforeLocalDelete) {\n\t\t// A public hook: it gets a transaction where `await tx.execute(...)` still means\n\t\t// the statement ran, so a handler that catches an expected failure and carries on\n\t\t// keeps working (a buffered failure would surface later and abort the delete).\n\t\tawait env.beforeLocalDelete(operation, scope.immediateTx)\n\t}\n\n\t// The row is tombstoned BEFORE side effects run, so a reference cycle\n\t// (self-referencing or mutually-referencing records) cannot cascade back\n\t// into this record.\n\tif (env.fold) {\n\t\tawait appendOperationRow(scope, operation)\n\t\tawait env.fold.applyInTx(scope.tx, operation, 'local')\n\t} else {\n\t\tconst version = serializeRowVersion(operation.timestamp)\n\t\tconst softDelete = buildSoftDeleteQuery(collection, id, operation.timestamp.wallTime, version)\n\t\tawait scope.tx.execute(softDelete.sql, softDelete.params)\n\t\tawait appendOperationRow(scope, operation)\n\t}\n\n\tconst sideEffects: Operation[] = []\n\tif (!options.skipReferentialEnforcement && env.relationEnforcer) {\n\t\tconst result = await env.relationEnforcer.enforceDelete(\n\t\t\tcollection,\n\t\t\tid,\n\t\t\tscope,\n\t\t\tenv,\n\t\t\toperation.id,\n\t\t)\n\t\tsideEffects.push(...result.operations)\n\t}\n\n\treturn {\n\t\toperation,\n\t\trecord: tombstone(definition, currentRow),\n\t\tsideEffects,\n\t}\n}\n\ninterface LocalOperationInput {\n\ttype: Operation['type']\n\tcollection: string\n\trecordId: string\n\tdata: Record<string, unknown> | null\n\tpreviousData: Record<string, unknown> | null\n\textraCausalDeps: readonly string[]\n\tatomicOps?: Record<string, AtomicOp>\n}\n\n/**\n * Reserve the next sequence number through the transaction, THEN build the\n * operation. The order matters: the operation is final the moment it exists.\n */\nasync function buildLocalOperation(\n\tenv: WriteEnv,\n\tscope: WriteScope,\n\tinput: LocalOperationInput,\n): Promise<Operation> {\n\tenv.assertLocalWriteAllowed?.()\n\tconst timers = activePhaseTimers()\n\tconst sequenceStartedAt = timers ? performance.now() : 0\n\tconst sequenceNumber = await scope.sequence.take()\n\ttimers?.add('sequence', performance.now() - sequenceStartedAt)\n\tconst causalDeps = scope.causal.depsFor(input.collection, input.extraCausalDeps)\n\tconst operation = await createOperation(\n\t\t{\n\t\t\tnodeId: env.nodeId,\n\t\t\ttype: input.type,\n\t\t\tcollection: input.collection,\n\t\t\trecordId: input.recordId,\n\t\t\tdata: input.data,\n\t\t\tpreviousData: input.previousData,\n\t\t\tsequenceNumber,\n\t\t\tcausalDeps,\n\t\t\tschemaVersion: env.schema.version,\n\t\t\t...(input.atomicOps !== undefined ? { atomicOps: input.atomicOps } : {}),\n\t\t\t...(env.transactionId !== undefined ? { transactionId: env.transactionId } : {}),\n\t\t\t...(env.mutationName !== undefined ? { mutationName: env.mutationName } : {}),\n\t\t},\n\t\tenv.clock,\n\t)\n\t// Every operation must fit the server's maxOperationBytes (RT-86): refused here, in\n\t// the write's transaction (nothing is written), rather than accepted and then refused\n\t// by the server.\n\tconst maxBytes = env.maxOperationBytes ?? DEFAULT_MAX_OPERATION_BYTES\n\tconst bytes = measureOperationBytes(operation)\n\tif (bytes > maxBytes) {\n\t\tthrow new OperationTooLargeError(input.collection, input.recordId, bytes, maxBytes)\n\t}\n\tscope.causal.record(input.collection, operation.id)\n\treturn operation\n}\n\nasync function appendOperationRow(scope: WriteScope, operation: Operation): Promise<void> {\n\tconst opInsert = buildInsertQuery(\n\t\t`_kora_ops_${operation.collection}`,\n\t\tserializeOperation(operation) as unknown as Record<string, unknown>,\n\t)\n\tawait scope.tx.execute(opInsert.sql, opInsert.params)\n}\n\nasync function readLiveRow(\n\tscope: WriteScope,\n\tcollection: string,\n\tid: string,\n): Promise<RawCollectionRow | undefined> {\n\tconst rows = await scope.tx.query<RawCollectionRow>(\n\t\t`SELECT * FROM ${quoteIdent(collection)} WHERE id = ? AND _deleted = 0`,\n\t\t[id],\n\t)\n\treturn rows[0]\n}\n\nfunction requireDefinition(env: WriteEnv, collection: string): CollectionDefinition {\n\tconst definition = env.schema.collections[collection]\n\tif (!definition) {\n\t\tthrow new KoraError(\n\t\t\t`Unknown collection \"${collection}\". Available: ${Object.keys(env.schema.collections).join(', ')}`,\n\t\t\t'UNKNOWN_COLLECTION',\n\t\t\t{ collection },\n\t\t)\n\t}\n\treturn definition\n}\n","import type { CollectionDefinition, SecretKeyProvider } from '@korajs/core'\nimport { transformSecretFieldsForWrite } from '@korajs/core'\n\n/**\n * Convert the values a local write is about to persist into their at-rest form.\n *\n * Every local write path (single-record insert/update and the buffered\n * `TransactionContext` used by `app.transaction` / `app.mutation`) MUST route\n * its data through this helper BEFORE the operation is built, so plaintext\n * secrets never reach the operation log, the materialized row, or the wire.\n * Keeping one helper means a new write path cannot forget the transform\n * without also bypassing this function (STORE-4).\n *\n * @param data - Validated (and atomic-op-resolved) field values for the write\n * @param definition - The collection definition, used to find secret fields\n * @param secretKeyProvider - Key provider for `t.secret()` encrypted fields\n * @returns A copy of `data` with secret fields hashed or encrypted\n */\nexport function toAtRestWriteData(\n\tdata: Record<string, unknown>,\n\tdefinition: CollectionDefinition,\n\tsecretKeyProvider: SecretKeyProvider | undefined,\n): Promise<Record<string, unknown>> {\n\treturn transformSecretFieldsForWrite(data, definition, secretKeyProvider)\n}\n","import { generateUUIDv7 } from '@korajs/core'\nimport { currentWriteObserver } from '@korajs/core/internal'\nimport { activePhaseTimers } from '../instrumentation/phase-timers'\nimport { trackInsert, trackInsertMany } from '../overlay/write-overlay'\nimport { type CollectionRecord, type WriteOptions, readFixedWrite } from '../types'\nimport { runLocalWrite } from './run-local-write'\nimport type { LocalMutationContext } from './types'\nimport { type PreparedInsert, prepareInsert, writeInsertInTx } from './write-ops'\n\n/**\n * Insert a record and persist its operation, atomically, through the single\n * local write path (sequence reserved and operation built inside the write\n * transaction).\n *\n * @param options - `durable: true` shows the record only once it has committed (no\n *   instant-updates prediction for this write)\n */\nexport async function executeInsert(\n\tctx: LocalMutationContext,\n\tdata: Record<string, unknown>,\n\toptions?: WriteOptions,\n): Promise<CollectionRecord> {\n\t// Captured before the first await: the observer is only current synchronously.\n\tconst observer = currentWriteObserver()\n\tconst timers = activePhaseTimers()\n\ttimers?.begin('insert')\n\tconst preparedAt = timers ? performance.now() : 0\n\tconst prepared = await prepareInsert(ctx, ctx.collection, data, {\n\t\trecordId: readFixedWrite(options)?.recordId,\n\t\tat: readFixedWrite(options)?.writtenAt,\n\t})\n\ttimers?.add('prepare', performance.now() - preparedAt)\n\t// Off unless the store was built with `instantUpdates`. The SAME prepared object is\n\t// predicted here and written below (I4); the write path itself never reads the\n\t// overlay (I1).\n\tconst tracker = ctx.overlay ? trackInsert(ctx, ctx.overlay, prepared, options) : null\n\ttry {\n\t\tconst result = await runLocalWrite(\n\t\t\tctx,\n\t\t\t(scope) => writeInsertInTx(ctx, scope, prepared, ctx.extraCausalDeps ?? []),\n\t\t\t{\n\t\t\t\tobserver,\n\t\t\t\topKey: readFixedWrite(options)?.opKey,\n\t\t\t\t...(tracker\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tonCommitted: (results) => tracker.committed(results),\n\t\t\t\t\t\t\tonCommitUnknown: (lookup, _error, results) => {\n\t\t\t\t\t\t\t\tif (lookup.outcome === 'committed') tracker.committed(results)\n\t\t\t\t\t\t\t\telse if (lookup.outcome === 'unknown') tracker.unknown(lookup.operationId)\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},\n\t\t)\n\t\treturn result.record\n\t} catch (error) {\n\t\ttracker?.failed(error)\n\t\tthrow error\n\t}\n}\n\n/**\n * Insert several records of one collection in ONE storage transaction: all of them\n * or none.\n *\n * Every row is validated (and its secret fields transformed) before the\n * transaction starts, so an invalid row refuses the whole call without writing\n * anything. Each row then becomes its own insert operation through the single\n * local write path, in input order: consecutive sequence numbers from the\n * transaction's block, increasing HLC timestamps, each operation causally after\n * the previous one, and one shared `transactionId`, exactly like the same inserts\n * made in `store.transaction`. Subscriptions and `operation:created` see the\n * operations only after the commit, in that order.\n *\n * With instant updates on, a batch within the per-write record cap is shown at once as\n * one entry per record (all together or none); a larger batch waits for the commit.\n *\n * @returns The inserted records, in input order\n */\nexport async function executeInsertMany(\n\tctx: LocalMutationContext,\n\trows: readonly Record<string, unknown>[],\n\toptions?: WriteOptions,\n): Promise<CollectionRecord[]> {\n\tif (rows.length === 0) return []\n\t// Captured before the first await: the observer is only current synchronously.\n\tconst observer = currentWriteObserver()\n\tconst prepared: PreparedInsert[] = []\n\tfor (const [index, data] of rows.entries()) {\n\t\tprepared.push(\n\t\t\tawait prepareInsert(ctx, ctx.collection, data, {\n\t\t\t\trecordId: readFixedWrite(options)?.recordIds?.[index],\n\t\t\t\tat: readFixedWrite(options)?.writtenAt,\n\t\t\t}),\n\t\t)\n\t}\n\tconst env = { ...ctx, transactionId: ctx.transactionId ?? generateUUIDv7() }\n\tconst tracker = ctx.overlay ? trackInsertMany(ctx, ctx.overlay, prepared, options) : null\n\ttry {\n\t\tconst results = await runLocalWrite(\n\t\t\tenv,\n\t\t\tasync (scope) => {\n\t\t\t\tconst written = []\n\t\t\t\tfor (const insert of prepared) {\n\t\t\t\t\twritten.push(await writeInsertInTx(env, scope, insert, ctx.extraCausalDeps ?? []))\n\t\t\t\t}\n\t\t\t\treturn written\n\t\t\t},\n\t\t\t{\n\t\t\t\tchainOperations: true,\n\t\t\t\tobserver,\n\t\t\t\topKey: readFixedWrite(options)?.opKey,\n\t\t\t\t...(tracker\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tonCommitted: (written) => tracker.committed(written),\n\t\t\t\t\t\t\tonCommitUnknown: (lookup, _error, written) => {\n\t\t\t\t\t\t\t\tif (lookup.outcome === 'committed') tracker.committed(written)\n\t\t\t\t\t\t\t\telse if (lookup.outcome === 'unknown') tracker.unknown(lookup.operationId)\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},\n\t\t)\n\t\treturn results.map((result) => result.record)\n\t} catch (error) {\n\t\ttracker?.failed(error)\n\t\tthrow error\n\t}\n}\n","import { validateRecord } from '@korajs/core'\nimport { currentWriteObserver } from '@korajs/core/internal'\nimport { activePhaseTimers } from '../instrumentation/phase-timers'\nimport { updateNeedsFoldState } from '../overlay/predict'\nimport {\n\ttype WriteTracker,\n\treadBaseIfNeeded,\n\trecordKey,\n\ttrackUpdate,\n} from '../overlay/write-overlay'\nimport { type CollectionRecord, type WriteOptions, readFixedWrite } from '../types'\nimport { runLocalWrite } from './run-local-write'\nimport type { LocalMutationContext } from './types'\nimport { writeUpdateInTx } from './write-ops'\n\n/**\n * Update a record and persist its operation, atomically. The row read, the\n * state-machine check and atomic-op resolution all happen inside the write\n * transaction, so concurrent increments compose (STORE-9).\n *\n * @param options - `durable: true` shows the change only once it has committed (no\n *   instant-updates prediction for this write)\n */\nexport async function executeUpdate(\n\tctx: LocalMutationContext,\n\tid: string,\n\tdata: Record<string, unknown>,\n\toptions?: WriteOptions,\n): Promise<CollectionRecord> {\n\tconst observer = currentWriteObserver()\n\tconst timers = activePhaseTimers()\n\ttimers?.begin('update')\n\tconst preparedAt = timers ? performance.now() : 0\n\tconst validated = validateRecord(ctx.collection, ctx.definition, data, 'update')\n\ttimers?.add('prepare', performance.now() - preparedAt)\n\t// Off unless the store was built with `instantUpdates`; see executeInsert.\n\tconst overlay = ctx.overlay\n\tlet tracker: WriteTracker | null = null\n\t// Held while this write reads before it can be predicted: updates, deletes and\n\t// transactions called meanwhile wait, so writes start in call order (see write-order.ts).\n\tconst turn = overlay ? overlay.registry.order.enter([recordKey(ctx.collection, id)]) : null\n\ttry {\n\t\tif (overlay) {\n\t\t\tif (turn?.wait) await turn.wait\n\t\t\t// Registration and the write below happen in one synchronous step unless the base\n\t\t\t// record has to be read first, so overlapping writes register in transaction order.\n\t\t\t// A `durable` write needs no base: it is not predicted at all.\n\t\t\tconst read =\n\t\t\t\toptions?.durable === true\n\t\t\t\t\t? ({ status: 'skipped' } as const)\n\t\t\t\t\t: readBaseIfNeeded(\n\t\t\t\t\t\t\tctx,\n\t\t\t\t\t\t\toverlay,\n\t\t\t\t\t\t\tctx.collection,\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tupdateNeedsFoldState(ctx, ctx.collection, validated),\n\t\t\t\t\t\t)\n\t\t\tif (read instanceof Promise) turn?.hold()\n\t\t\ttracker = trackUpdate(\n\t\t\t\tctx,\n\t\t\t\toverlay,\n\t\t\t\tid,\n\t\t\t\tvalidated,\n\t\t\t\tread instanceof Promise ? await read : read,\n\t\t\t\toptions,\n\t\t\t)\n\t\t}\n\t\tconst started = runLocalWrite(\n\t\t\tctx,\n\t\t\t(scope) =>\n\t\t\t\twriteUpdateInTx(ctx, scope, ctx.collection, id, validated, ctx.extraCausalDeps ?? []),\n\t\t\t{\n\t\t\t\tobserver,\n\t\t\t\topKey: readFixedWrite(options)?.opKey,\n\t\t\t\t...(tracker\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tonCommitted: (results) => tracker?.committed(results),\n\t\t\t\t\t\t\tonCommitUnknown: (lookup, _error, results) => {\n\t\t\t\t\t\t\t\tif (lookup.outcome === 'committed') tracker?.committed(results)\n\t\t\t\t\t\t\t\telse if (lookup.outcome === 'unknown') tracker?.unknown(lookup.operationId)\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},\n\t\t)\n\t\t// The storage transaction is queued: later writes of this record may now start.\n\t\tturn?.release()\n\t\tconst result = await started\n\t\treturn result.record\n\t} catch (error) {\n\t\ttracker?.failed(error)\n\t\tthrow error\n\t} finally {\n\t\tturn?.release()\n\t}\n}\n"]}