{
  "version": 3,
  "sources": ["../../src/lib/TLSyncStorage.ts"],
  "sourcesContent": ["import { StoreSchema, SynchronousStorage, UnknownRecord } from '@tldraw/store'\nimport { TLStoreSnapshot } from '@tldraw/tlschema'\nimport { assert, isEqual, objectMapEntriesIterable, objectMapValues } from '@tldraw/utils'\nimport { diffRecord, NetworkDiff, RecordOpType } from './diff'\nimport { RoomSnapshot } from './TLSyncRoom'\n\n/**\n * Transaction interface for storage operations. Provides methods to read and modify\n * documents, tombstones, and metadata within a transaction.\n *\n * @public\n */\nexport interface TLSyncStorageTransaction<R extends UnknownRecord> extends SynchronousStorage<R> {\n\t/**\n\t * Get the current clock value.\n\t * If the clock has incremented during the transaction,\n\t * the incremented value will be returned.\n\t *\n\t * @returns The current clock value\n\t */\n\tgetClock(): number\n\n\t/**\n\t * Get all changes (document updates and deletions) since a given clock time.\n\t * This is the main method for calculating diffs for client sync.\n\t *\n\t * @param sinceClock - The clock time to get changes since\n\t * @returns Changes since the specified clock time\n\t */\n\tgetChangesSince(sinceClock: number): TLSyncStorageGetChangesSinceResult<R> | undefined\n}\n\n/**\n * Options for a transaction.\n * @public\n */\nexport interface TLSyncStorageTransactionOptions {\n\t/**\n\t * Use this if you need to identify the transaction for logging or debugging purposes\n\t * or for ignoring certain changes in onChange callbacks\n\t */\n\tid?: string\n\t/**\n\t * Controls when the storage layer should emit the actual changes that occurred during the transaction.\n\t *\n\t * - `'always'` - Always emit the changes, regardless of whether they were applied verbatim\n\t * - `'when-different'` - Only emit changes if the storage layer modified/embellished the records\n\t *   (e.g., added server timestamps, normalized data, etc.)\n\t *\n\t * When changes are emitted, they will be available in the `changes` field of the transaction result.\n\t * This is useful when the storage layer may transform records and the caller needs to know\n\t * what actually changed rather than what was requested.\n\t */\n\temitChanges?: 'always' | 'when-different'\n}\n\n/**\n * Callback type for a transaction.\n * The conditional return type ensures that the callback is synchronous.\n * @public\n */\nexport type TLSyncStorageTransactionCallback<R extends UnknownRecord, T> = (\n\ttxn: TLSyncStorageTransaction<R>\n) => T extends Promise<any>\n\t? {\n\t\t\t__error: 'Transaction callbacks cannot be async. Use synchronous operations only.'\n\t\t}\n\t: T\n\n/**\n * Pluggable synchronous transactional storage layer for TLSyncRoom.\n * Provides methods for managing documents, tombstones, and clocks within transactions.\n *\n * @public\n */\nexport interface TLSyncStorage<R extends UnknownRecord> {\n\ttransaction<T>(\n\t\tcallback: TLSyncStorageTransactionCallback<R, T>,\n\t\topts?: TLSyncStorageTransactionOptions\n\t): TLSyncStorageTransactionResult<T, R>\n\n\tgetClock(): number\n\n\tonChange(callback: (arg: TLSyncStorageOnChangeCallbackProps) => unknown): () => void\n\n\t/** A snapshot of the document lane only \u2014 never contains object-store lane records. */\n\tgetSnapshot?(): RoomSnapshot\n\n\t/**\n\t * A snapshot of the object-store lane (see `objectTypes` on the storage), for hosts that\n\t * persist object-lane records separately from the document. Same entry shape as\n\t * `RoomSnapshot['documents']` so a lane can be persisted and re-seeded via a merged snapshot.\n\t */\n\tgetObjectsSnapshot?(): RoomSnapshot['documents']\n\n\t/**\n\t * The same entries for the given ids, for callers that need a handful of records rather than the\n\t * whole (parsed) lane. Ids with no object-lane record are omitted \u2014 document-lane ids included \u2014\n\t * and duplicates yield one entry.\n\t */\n\tgetObjectsByIds?(ids: Iterable<string>): RoomSnapshot['documents']\n}\n\n/**\n * Properties passed to the onChange callback.\n * @public\n */\nexport interface TLSyncStorageOnChangeCallbackProps {\n\t/**\n\t * The ID of the transaction that caused the change.\n\t * This is useful for ignoring certain changes in onChange callbacks.\n\t */\n\tid?: string\n\tdocumentClock: number\n}\n\n/**\n * Result returned from a storage transaction.\n * @public\n */\nexport interface TLSyncStorageTransactionResult<T, R extends UnknownRecord = UnknownRecord> {\n\tdocumentClock: number\n\tdidChange: boolean\n\tresult: T\n\t/**\n\t * The actual changes that occurred during the transaction, if requested via `emitChanges` option.\n\t * This is a RecordsDiff where:\n\t * - `added` contains records that were put (we don't have \"from\" state for emitted changes)\n\t * - `removed` contains records that were deleted (with placeholder values since we only have IDs)\n\t * - `updated` is empty (emitted changes don't track before/after pairs)\n\t *\n\t * Only populated when:\n\t * - `emitChanges: 'always'` was specified, or\n\t * - `emitChanges: 'when-different'` was specified and the storage layer modified records\n\t */\n\tchanges?: TLSyncForwardDiff<R>\n}\n\n/**\n * Respresents a diff of puts and deletes.\n * @public\n */\nexport interface TLSyncForwardDiff<R extends UnknownRecord> {\n\tputs: Record<string, R | [before: R, after: R]>\n\tdeletes: string[]\n}\n\n/**\n * @internal\n */\nexport function toNetworkDiff<R extends UnknownRecord>(diff: TLSyncForwardDiff<R>): NetworkDiff<R> {\n\tconst networkDiff: NetworkDiff<R> = {}\n\tfor (const [id, put] of objectMapEntriesIterable(diff.puts)) {\n\t\tif (Array.isArray(put)) {\n\t\t\tconst patch = diffRecord(put[0], put[1])\n\t\t\tif (patch) {\n\t\t\t\tnetworkDiff[id] = [RecordOpType.Patch, patch]\n\t\t\t}\n\t\t} else {\n\t\t\tnetworkDiff[id] = [RecordOpType.Put, put]\n\t\t}\n\t}\n\tfor (const id of diff.deletes) {\n\t\tnetworkDiff[id] = [RecordOpType.Remove]\n\t}\n\treturn networkDiff\n}\n\n/**\n * Result returned from getChangesSince, containing all changes since a given clock time.\n * @public\n */\nexport interface TLSyncStorageGetChangesSinceResult<R extends UnknownRecord> {\n\t/**\n\t * The changes as a TLSyncForwardDiff.\n\t */\n\tdiff: TLSyncForwardDiff<R>\n\t/**\n\t * If true, the client should wipe all local data and replace with the server's state.\n\t * This happens when the client's clock is too old and we've lost tombstone history.\n\t */\n\twipeAll: boolean\n}\n\n/**\n * Loads a snapshot into storage during a transaction.\n * Migrates the snapshot to the current schema and loads it into storage.\n *\n * @public\n * @param txn - The transaction to load the snapshot into\n * @param schema - The current schema\n * @param snapshot - The snapshot to load\n */\nexport function loadSnapshotIntoStorage<R extends UnknownRecord>(\n\ttxn: TLSyncStorageTransaction<R>,\n\tschema: StoreSchema<R, any>,\n\tsnapshot: RoomSnapshot | TLStoreSnapshot\n) {\n\tsnapshot = convertStoreSnapshotToRoomSnapshot(snapshot)\n\tassert(snapshot.schema, 'Schema is required')\n\tconst docIds = new Set<string>()\n\tfor (const doc of snapshot.documents) {\n\t\tdocIds.add(doc.state.id)\n\t\tconst existing = txn.get(doc.state.id)\n\t\tif (isEqual(existing, doc.state)) continue\n\t\ttxn.set(doc.state.id, doc.state as R)\n\t}\n\t// materialize the keys first: some SQLite drivers (better-sqlite3) refuse writes while a\n\t// statement iterator is open, so deleting during `keys()` would throw\n\tfor (const id of Array.from(txn.keys())) {\n\t\tif (!docIds.has(id)) {\n\t\t\ttxn.delete(id)\n\t\t}\n\t}\n\ttxn.setSchema(snapshot.schema)\n\tschema.migrateStorage(txn)\n}\n\nexport function convertStoreSnapshotToRoomSnapshot(\n\tsnapshot: RoomSnapshot | TLStoreSnapshot\n): RoomSnapshot {\n\tif ('documents' in snapshot) return snapshot\n\treturn {\n\t\tclock: 0,\n\t\tdocumentClock: 0,\n\t\tdocuments: objectMapValues(snapshot.store).map((state) => ({\n\t\t\tstate,\n\t\t\tlastChangedClock: 0,\n\t\t})),\n\t\tschema: snapshot.schema,\n\t\ttombstones: {},\n\t}\n}\n"],
  "mappings": "AAEA,SAAS,QAAQ,SAAS,0BAA0B,uBAAuB;AAC3E,SAAS,YAAyB,oBAAoB;AAmJ/C,SAAS,cAAuC,MAA4C;AAClG,QAAM,cAA8B,CAAC;AACrC,aAAW,CAAC,IAAI,GAAG,KAAK,yBAAyB,KAAK,IAAI,GAAG;AAC5D,QAAI,MAAM,QAAQ,GAAG,GAAG;AACvB,YAAM,QAAQ,WAAW,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AACvC,UAAI,OAAO;AACV,oBAAY,EAAE,IAAI,CAAC,aAAa,OAAO,KAAK;AAAA,MAC7C;AAAA,IACD,OAAO;AACN,kBAAY,EAAE,IAAI,CAAC,aAAa,KAAK,GAAG;AAAA,IACzC;AAAA,EACD;AACA,aAAW,MAAM,KAAK,SAAS;A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