@ibodr/store 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +3327 -0
- package/dist/index.mjs +4367 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +40 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/ImmutableMap.ts","../src/lib/AtomMap.ts","../src/lib/AtomSet.ts","../src/lib/isDev.ts","../src/lib/devFreeze.ts","../src/lib/IncrementalSetConstructor.ts","../src/lib/migrate.ts","../src/lib/RecordsDiff.ts","../src/lib/RecordType.ts","../src/lib/setUtils.ts","../src/lib/executeQuery.ts","../src/lib/StoreQueries.ts","../src/lib/StoreSideEffects.ts","../src/lib/Store.ts","../src/lib/StoreSchema.ts","../src/index.ts"],"names":["hash","nextHash","atoms","assert","objectMapEntries","remove","atom","uniqueId","id","objectMapValues","transact","computed","isEqual","prevSideEffectsEnabled","chunk","getOwnProperty","result","structuredClone"],"mappings":";;;;;;AAKA,SAAS,IAAI,GAAA,EAAa;AACzB,EAAA,OAAS,GAAA,KAAQ,CAAA,GAAK,UAAA,GAAe,GAAA,GAAM,UAAA;AAC5C;AAEA,IAAM,cAAA,GAAiB,OAAO,SAAA,CAAU,OAAA;AAExC,SAAS,KAAK,CAAA,EAAQ;AACrB,EAAA,IAAI,KAAK,IAAA,EAAM;AACd,IAAA,OAAO,YAAY,CAAC,CAAA;AAAA,EACrB;AAEA,EAAA,IAAI,OAAO,CAAA,CAAE,QAAA,KAAa,UAAA,EAAY;AAErC,IAAA,OAAO,GAAA,CAAI,CAAA,CAAE,QAAA,CAAS,CAAC,CAAC,CAAA;AAAA,EACzB;AAEA,EAAA,MAAM,CAAA,GAAI,QAAQ,CAAC,CAAA;AAEnB,EAAA,IAAI,KAAK,IAAA,EAAM;AACd,IAAA,OAAO,YAAY,CAAC,CAAA;AAAA,EACrB;AAEA,EAAA,QAAQ,OAAO,CAAA;AAAG,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WAAA;AAAA,QACjB,MAAA,CAAO,MAAA,CAAO,IAAA,CAAK,UAAU,CAAA,CAAE,GAAA,CAAI,CAAC,EAAE,UAAA,EAAW,KAAM,CAAC,UAAA,EAAY,CAAC,CAAC;AAAA;AACvE,KACD;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBA,QAAQ,QAAA,EAAkB;AACzB,IAAA,MAAM,IAAA,GAAOW,cAAAA,CAAe,IAAA,CAAK,KAAA,EAAO,QAAQ,CAAA;AAChD,IAAAZ,MAAAA,CAAO,MAAM,6BAA6B,CAAA;AAC1C,IAAA,OAAO,IAAA;AAAA,EACR;AACD;;;ACruBA,0BAAA;AAAA,EACE,cAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA","file":"index.mjs","sourcesContent":["/*!\n * This file was lovingly and delicately extracted from Immutable.js\n * MIT License: https://github.com/immutable-js/immutable-js/blob/main/LICENSE\n * Copyright (c) 2014-present, Lee Byron and other contributors.\n */\nfunction smi(i32: number) {\n\treturn ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff)\n}\n\nconst defaultValueOf = Object.prototype.valueOf\n\nfunction hash(o: any) {\n\tif (o == null) {\n\t\treturn hashNullish(o)\n\t}\n\n\tif (typeof o.hashCode === 'function') {\n\t\t// Drop any high bits from accidentally long hash codes.\n\t\treturn smi(o.hashCode(o))\n\t}\n\n\tconst v = valueOf(o)\n\n\tif (v == null) {\n\t\treturn hashNullish(v)\n\t}\n\n\tswitch (typeof v) {\n\t\tcase 'boolean':\n\t\t\t// The hash values for built-in constants are a 1 value for each 5-byte\n\t\t\t// shift region expect for the first, which encodes the value. This\n\t\t\t// reduces the odds of a hash collision for these common values.\n\t\t\treturn v ? 0x42108421 : 0x42108420\n\t\tcase 'number':\n\t\t\treturn hashNumber(v)\n\t\tcase 'string':\n\t\t\treturn cachedHashString(v)\n\t\tcase 'object':\n\t\tcase 'function':\n\t\t\treturn hashJSObj(v)\n\t\tcase 'symbol':\n\t\t\treturn hashSymbol(v)\n\t\tdefault:\n\t\t\tif (typeof v.toString === 'function') {\n\t\t\t\treturn hashString(v.toString())\n\t\t\t}\n\t\t\tthrow new Error('Value type ' + typeof v + ' cannot be hashed.')\n\t}\n}\n\nfunction hashNullish(nullish: null | undefined) {\n\treturn nullish === null ? 0x42108422 : /* undefined */ 0x42108423\n}\n\n// Compress arbitrarily large numbers into smi hashes.\nfunction hashNumber(n: number) {\n\tif (n !== n || n === Infinity) {\n\t\treturn 0\n\t}\n\tlet hash = n | 0\n\tif (hash !== n) {\n\t\thash ^= n * 0xffffffff\n\t}\n\twhile (n > 0xffffffff) {\n\t\tn /= 0xffffffff\n\t\thash ^= n\n\t}\n\treturn smi(hash)\n}\n\nfunction cachedHashString(string: string) {\n\tlet hashed = stringHashCache[string]\n\tif (hashed === undefined) {\n\t\thashed = hashString(string)\n\t\tif (stringHashCacheCount === STRING_HASH_CACHE_SIZE) {\n\t\t\tstringHashCacheCount = 0\n\t\t\tstringHashCache = {}\n\t\t}\n\t\tstringHashCache[string] = hashed\n\t\tstringHashCacheCount++\n\t}\n\treturn hashed\n}\n\n// http://jsperf.com/hashing-strings\nfunction hashString(string: string) {\n\t// This is the hash from JVM\n\t// The hash code for a string is computed as\n\t// s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],\n\t// where s[i] is the ith character of the string and n is the length of\n\t// the string. We \"mod\" the result to make it between 0 (inclusive) and 2^31\n\t// (exclusive) by dropping high bits.\n\tlet hashed = 0\n\tfor (let ii = 0; ii < string.length; ii++) {\n\t\thashed = (31 * hashed + string.charCodeAt(ii)) | 0\n\t}\n\treturn smi(hashed)\n}\n\nfunction hashSymbol(sym: symbol) {\n\tlet hashed = symbolMap[sym]\n\tif (hashed !== undefined) {\n\t\treturn hashed\n\t}\n\n\thashed = nextHash()\n\n\tsymbolMap[sym] = hashed\n\n\treturn hashed\n}\n\nfunction hashJSObj(obj: object) {\n\tlet hashed = weakMap.get(obj)\n\tif (hashed !== undefined) {\n\t\treturn hashed\n\t}\n\n\thashed = nextHash()\n\n\tweakMap.set(obj, hashed)\n\n\treturn hashed\n}\n\nfunction valueOf(obj: any) {\n\treturn obj.valueOf !== defaultValueOf && typeof obj.valueOf === 'function'\n\t\t? obj.valueOf(obj)\n\t\t: obj\n}\n\nfunction nextHash() {\n\tconst nextHash = ++_objHashUID\n\tif (_objHashUID & 0x40000000) {\n\t\t_objHashUID = 0\n\t}\n\treturn nextHash\n}\n\n// If possible, use a WeakMap.\nconst weakMap = new WeakMap()\n\nconst symbolMap = Object.create(null)\n\nlet _objHashUID = 0\n\nlet stringHashCache: Record<string, number> = {}\nlet stringHashCacheCount = 0\nconst STRING_HASH_CACHE_SIZE = 24_000\n\n// Constants describing the size of trie nodes.\nconst SHIFT = 5 // Resulted in best performance after ______?\nconst SIZE = 1 << SHIFT\nconst MASK = SIZE - 1\n\n// A consistent shared value representing \"not set\" which equals nothing other\n// than itself, and nothing that could be provided externally.\nconst NOT_SET = {}\n\ninterface Ref {\n\tvalue: boolean\n}\n\n// Boolean references, Rough equivalent of `bool &`.\nfunction MakeRef(): Ref {\n\treturn { value: false }\n}\n\nfunction SetRef(ref?: Ref): void {\n\tif (ref) {\n\t\tref.value = true\n\t}\n}\n\nfunction arrCopy<I>(arr: Array<I>, offset = 0): Array<I> {\n\treturn arr.slice(offset)\n}\n\nclass OwnerID {}\n\n/**\n * A persistent immutable map implementation based on a Hash Array Mapped Trie (HAMT) data structure.\n * Provides efficient operations for creating, reading, updating, and deleting key-value pairs while\n * maintaining structural sharing to minimize memory usage and maximize performance.\n *\n * This implementation is extracted and adapted from Immutable.js, optimized for tldraw's store needs.\n * All operations return new instances rather than modifying existing ones, ensuring immutability.\n *\n * @public\n * @example\n * ```ts\n * // Create a new map\n * const map = new ImmutableMap([\n * ['key1', 'value1'],\n * ['key2', 'value2']\n * ])\n *\n * // Add or update values\n * const updated = map.set('key3', 'value3')\n *\n * // Get values\n * const value = map.get('key1') // 'value1'\n *\n * // Delete values\n * const smaller = map.delete('key1')\n * ```\n */\nexport class ImmutableMap<K, V> {\n\t// @pragma Construction\n\t// @ts-ignore\n\t_root: MapNode<K, V>\n\t// @ts-ignore\n\tsize: number\n\t// @ts-ignore\n\t__ownerID: OwnerID\n\t// @ts-ignore\n\t__hash: number | undefined\n\t// @ts-ignore\n\t__altered: boolean\n\n\t/**\n\t * Creates a new ImmutableMap instance.\n\t *\n\t * @param value - An iterable of key-value pairs to populate the map, or null/undefined for an empty map\n\t * @example\n\t * ```ts\n\t * // Create from array of pairs\n\t * const map1 = new ImmutableMap([['a', 1], ['b', 2]])\n\t *\n\t * // Create empty map\n\t * const map2 = new ImmutableMap()\n\t *\n\t * // Create from another map\n\t * const map3 = new ImmutableMap(map1)\n\t * ```\n\t */\n\tconstructor(value?: Iterable<[K, V]> | null | undefined) {\n\t\t// @ts-ignore\n\t\treturn value === undefined || value === null\n\t\t\t? emptyMap()\n\t\t\t: value instanceof ImmutableMap\n\t\t\t\t? value\n\t\t\t\t: emptyMap().withMutations((map) => {\n\t\t\t\t\t\tfor (const [k, v] of value) {\n\t\t\t\t\t\t\tmap.set(k, v)\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t}\n\n\t/**\n\t * Gets the value associated with the specified key.\n\t *\n\t * @param k - The key to look up\n\t * @returns The value associated with the key, or undefined if not found\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['key1', 'value1']])\n\t * console.log(map.get('key1')) // 'value1'\n\t * console.log(map.get('missing')) // undefined\n\t * ```\n\t */\n\tget(k: K): V | undefined\n\t/**\n\t * Gets the value associated with the specified key, with a fallback value.\n\t *\n\t * @param k - The key to look up\n\t * @param notSetValue - The value to return if the key is not found\n\t * @returns The value associated with the key, or the fallback value if not found\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['key1', 'value1']])\n\t * console.log(map.get('key1', 'default')) // 'value1'\n\t * console.log(map.get('missing', 'default')) // 'default'\n\t * ```\n\t */\n\tget(k: K, notSetValue?: V): V {\n\t\treturn this._root ? this._root.get(0, undefined as any, k, notSetValue)! : notSetValue!\n\t}\n\n\t/**\n\t * Returns a new ImmutableMap with the specified key-value pair added or updated.\n\t * If the key already exists, its value is replaced. Otherwise, a new entry is created.\n\t *\n\t * @param k - The key to set\n\t * @param v - The value to associate with the key\n\t * @returns A new ImmutableMap with the key-value pair set\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['a', 1]])\n\t * const updated = map.set('b', 2) // New map with both 'a' and 'b'\n\t * const replaced = map.set('a', 10) // New map with 'a' updated to 10\n\t * ```\n\t */\n\tset(k: K, v: V) {\n\t\treturn updateMap(this, k, v)\n\t}\n\n\t/**\n\t * Returns a new ImmutableMap with the specified key removed.\n\t * If the key doesn't exist, returns the same map instance.\n\t *\n\t * @param k - The key to remove\n\t * @returns A new ImmutableMap with the key removed, or the same instance if key not found\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['a', 1], ['b', 2]])\n\t * const smaller = map.delete('a') // New map with only 'b'\n\t * const same = map.delete('missing') // Returns original map\n\t * ```\n\t */\n\tdelete(k: K) {\n\t\treturn updateMap(this, k, NOT_SET as any)\n\t}\n\n\t/**\n\t * Returns a new ImmutableMap with all specified keys removed.\n\t * This is more efficient than calling delete() multiple times.\n\t *\n\t * @param keys - An iterable of keys to remove\n\t * @returns A new ImmutableMap with all specified keys removed\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['a', 1], ['b', 2], ['c', 3]])\n\t * const smaller = map.deleteAll(['a', 'c']) // New map with only 'b'\n\t * ```\n\t */\n\tdeleteAll(keys: Iterable<K>) {\n\t\treturn this.withMutations((map) => {\n\t\t\tfor (const key of keys) {\n\t\t\t\tmap.delete(key)\n\t\t\t}\n\t\t})\n\t}\n\n\t__ensureOwner(ownerID: OwnerID) {\n\t\tif (ownerID === this.__ownerID) {\n\t\t\treturn this\n\t\t}\n\t\tif (!ownerID) {\n\t\t\tif (this.size === 0) {\n\t\t\t\treturn emptyMap()\n\t\t\t}\n\t\t\tthis.__ownerID = ownerID\n\t\t\tthis.__altered = false\n\t\t\treturn this\n\t\t}\n\t\treturn makeMap(this.size, this._root, ownerID, this.__hash)\n\t}\n\n\t/**\n\t * Applies multiple mutations efficiently by creating a mutable copy,\n\t * applying all changes, then returning an immutable result.\n\t * This is more efficient than chaining multiple set/delete operations.\n\t *\n\t * @param fn - Function that receives a mutable copy and applies changes\n\t * @returns A new ImmutableMap with all mutations applied, or the same instance if no changes\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['a', 1]])\n\t * const updated = map.withMutations(mutable => {\n\t * mutable.set('b', 2)\n\t * mutable.set('c', 3)\n\t * mutable.delete('a')\n\t * }) // Efficiently applies all changes at once\n\t * ```\n\t */\n\twithMutations(fn: (mutable: this) => void): this {\n\t\tconst mutable = this.asMutable()\n\t\tfn(mutable)\n\t\treturn mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this\n\t}\n\n\t/**\n\t * Checks if this map instance has been altered during a mutation operation.\n\t * This is used internally to optimize mutations.\n\t *\n\t * @returns True if the map was altered, false otherwise\n\t * @internal\n\t */\n\twasAltered() {\n\t\treturn this.__altered\n\t}\n\n\t/**\n\t * Returns a mutable copy of this map that can be efficiently modified.\n\t * Multiple changes to the mutable copy are batched together.\n\t *\n\t * @returns A mutable copy of this map\n\t * @internal\n\t */\n\tasMutable() {\n\t\treturn this.__ownerID ? this : this.__ensureOwner(new OwnerID())\n\t}\n\n\t/**\n\t * Makes the map iterable, yielding key-value pairs.\n\t *\n\t * @returns An iterator over [key, value] pairs\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['a', 1], ['b', 2]])\n\t * for (const [key, value] of map) {\n\t * console.log(key, value) // 'a' 1, then 'b' 2\n\t * }\n\t * ```\n\t */\n\t[Symbol.iterator](): Iterator<[K, V]> {\n\t\treturn this.entries()[Symbol.iterator]()\n\t}\n\n\t/**\n\t * Returns an iterable of key-value pairs.\n\t *\n\t * @returns An iterable over [key, value] pairs\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['a', 1], ['b', 2]])\n\t * const entries = Array.from(map.entries()) // [['a', 1], ['b', 2]]\n\t * ```\n\t */\n\tentries(): Iterable<[K, V]> {\n\t\treturn new MapIterator(this, ITERATE_ENTRIES, false)\n\t}\n\n\t/**\n\t * Returns an iterable of keys.\n\t *\n\t * @returns An iterable over keys\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['a', 1], ['b', 2]])\n\t * const keys = Array.from(map.keys()) // ['a', 'b']\n\t * ```\n\t */\n\tkeys(): Iterable<K> {\n\t\treturn new MapIterator(this, ITERATE_KEYS, false)\n\t}\n\n\t/**\n\t * Returns an iterable of values.\n\t *\n\t * @returns An iterable over values\n\t * @example\n\t * ```ts\n\t * const map = new ImmutableMap([['a', 1], ['b', 2]])\n\t * const values = Array.from(map.values()) // [1, 2]\n\t * ```\n\t */\n\tvalues(): Iterable<V> {\n\t\treturn new MapIterator(this, ITERATE_VALUES, false)\n\t}\n}\n\ntype MapNode<K, V> =\n\t| ArrayMapNode<K, V>\n\t| BitmapIndexedNode<K, V>\n\t| HashArrayMapNode<K, V>\n\t| HashCollisionNode<K, V>\n\t| ValueNode<K, V>\n\n// #pragma Trie Nodes\n\nclass ArrayMapNode<K, V> {\n\tconstructor(\n\t\tpublic ownerID: OwnerID,\n\t\tpublic entries: Array<[K, V]>\n\t) {}\n\n\tget(_shift: unknown, _keyHash: unknown, key: K, notSetValue?: V) {\n\t\tconst entries = this.entries\n\t\tfor (let ii = 0, len = entries.length; ii < len; ii++) {\n\t\t\tif (Object.is(key, entries[ii][0])) {\n\t\t\t\treturn entries[ii][1]\n\t\t\t}\n\t\t}\n\t\treturn notSetValue\n\t}\n\n\tupdate(\n\t\townerID: OwnerID,\n\t\t_shift: unknown,\n\t\t_keyHash: unknown,\n\t\tkey: K,\n\t\tvalue: V,\n\t\tdidChangeSize?: Ref,\n\t\tdidAlter?: Ref\n\t): MapNode<K, V> | undefined {\n\t\tconst removed = value === NOT_SET\n\n\t\tconst entries = this.entries\n\t\tlet idx = 0\n\t\tconst len = entries.length\n\t\tfor (; idx < len; idx++) {\n\t\t\tif (Object.is(key, entries[idx][0])) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tconst exists = idx < len\n\n\t\tif (exists ? entries[idx][1] === value : removed) {\n\t\t\treturn this\n\t\t}\n\n\t\tSetRef(didAlter)\n\t\tif (removed || !exists) SetRef(didChangeSize)\n\n\t\tif (removed && entries.length === 1) {\n\t\t\treturn // undefined\n\t\t}\n\n\t\tif (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {\n\t\t\treturn createNodes(ownerID, entries, key, value)\n\t\t}\n\n\t\tconst isEditable = ownerID && ownerID === this.ownerID\n\t\tconst newEntries = isEditable ? entries : arrCopy(entries)\n\n\t\tif (exists) {\n\t\t\tif (removed) {\n\t\t\t\tif (idx === len - 1) {\n\t\t\t\t\tnewEntries.pop()\n\t\t\t\t} else {\n\t\t\t\t\tnewEntries[idx] = newEntries.pop()!\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewEntries[idx] = [key, value]\n\t\t\t}\n\t\t} else {\n\t\t\tnewEntries.push([key, value])\n\t\t}\n\n\t\tif (isEditable) {\n\t\t\tthis.entries = newEntries\n\t\t\treturn this\n\t\t}\n\n\t\treturn new ArrayMapNode(ownerID, newEntries)\n\t}\n}\n\nclass BitmapIndexedNode<K, V> {\n\tconstructor(\n\t\tpublic ownerID: OwnerID,\n\t\tpublic bitmap: number,\n\t\tpublic nodes: Array<MapNode<K, V>>\n\t) {}\n\n\tget(shift: number, keyHash: number, key: K, notSetValue?: V): V | undefined {\n\t\tif (keyHash === undefined) {\n\t\t\tkeyHash = hash(key)\n\t\t}\n\t\tconst bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK)\n\t\tconst bitmap = this.bitmap\n\t\treturn (bitmap & bit) === 0\n\t\t\t? notSetValue\n\t\t\t: this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue)\n\t}\n\n\tupdate(\n\t\townerID: OwnerID,\n\t\tshift: number,\n\t\tkeyHash: number,\n\t\tkey: K,\n\t\tvalue: V,\n\t\tdidChangeSize?: Ref,\n\t\tdidAlter?: Ref\n\t): MapNode<K, V> | undefined {\n\t\tif (keyHash === undefined) {\n\t\t\tkeyHash = hash(key)\n\t\t}\n\t\tconst keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK\n\t\tconst bit = 1 << keyHashFrag\n\t\tconst bitmap = this.bitmap\n\t\tconst exists = (bitmap & bit) !== 0\n\n\t\tif (!exists && value === NOT_SET) {\n\t\t\treturn this\n\t\t}\n\n\t\tconst idx = popCount(bitmap & (bit - 1))\n\t\tconst nodes = this.nodes\n\t\tconst node = exists ? nodes[idx] : undefined\n\t\tconst newNode = updateNode(\n\t\t\tnode,\n\t\t\townerID,\n\t\t\tshift + SHIFT,\n\t\t\tkeyHash,\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\tdidChangeSize,\n\t\t\tdidAlter\n\t\t)\n\n\t\tif (newNode === node) {\n\t\t\treturn this\n\t\t}\n\n\t\tif (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {\n\t\t\treturn expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode)\n\t\t}\n\n\t\tif (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) {\n\t\t\treturn nodes[idx ^ 1]\n\t\t}\n\n\t\tif (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {\n\t\t\treturn newNode\n\t\t}\n\n\t\tconst isEditable = ownerID && ownerID === this.ownerID\n\t\tconst newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit\n\t\tconst newNodes = exists\n\t\t\t? newNode\n\t\t\t\t? setAt(nodes, idx, newNode, isEditable)\n\t\t\t\t: spliceOut(nodes, idx, isEditable)\n\t\t\t: spliceIn(nodes, idx, newNode, isEditable)\n\n\t\tif (isEditable) {\n\t\t\tthis.bitmap = newBitmap\n\t\t\tthis.nodes = newNodes\n\t\t\treturn this\n\t\t}\n\n\t\treturn new BitmapIndexedNode(ownerID, newBitmap, newNodes)\n\t}\n}\n\nclass HashArrayMapNode<K, V> {\n\tconstructor(\n\t\tpublic ownerID: OwnerID,\n\t\tpublic count: number,\n\t\tpublic nodes: Array<MapNode<K, V>>\n\t) {}\n\n\tget(shift: number, keyHash: number, key: K, notSetValue?: V): V | undefined {\n\t\tif (keyHash === undefined) {\n\t\t\tkeyHash = hash(key)\n\t\t}\n\t\tconst idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK\n\t\tconst node = this.nodes[idx]\n\t\treturn node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue\n\t}\n\n\tupdate(\n\t\townerID: OwnerID,\n\t\tshift: number,\n\t\tkeyHash: number,\n\t\tkey: K,\n\t\tvalue: V,\n\t\tdidChangeSize?: Ref,\n\t\tdidAlter?: Ref\n\t) {\n\t\tif (keyHash === undefined) {\n\t\t\tkeyHash = hash(key)\n\t\t}\n\t\tconst idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK\n\t\tconst removed = value === NOT_SET\n\t\tconst nodes = this.nodes\n\t\tconst node = nodes[idx]\n\n\t\tif (removed && !node) {\n\t\t\treturn this\n\t\t}\n\n\t\tconst newNode = updateNode(\n\t\t\tnode,\n\t\t\townerID,\n\t\t\tshift + SHIFT,\n\t\t\tkeyHash,\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\tdidChangeSize,\n\t\t\tdidAlter\n\t\t)\n\t\tif (newNode === node) {\n\t\t\treturn this\n\t\t}\n\n\t\tlet newCount = this.count\n\t\tif (!node) {\n\t\t\tnewCount++\n\t\t} else if (!newNode) {\n\t\t\tnewCount--\n\t\t\tif (newCount < MIN_HASH_ARRAY_MAP_SIZE) {\n\t\t\t\treturn packNodes(ownerID, nodes, newCount, idx)\n\t\t\t}\n\t\t}\n\n\t\tconst isEditable = ownerID && ownerID === this.ownerID\n\t\tconst newNodes = setAt(nodes, idx, newNode!, isEditable)\n\n\t\tif (isEditable) {\n\t\t\tthis.count = newCount\n\t\t\tthis.nodes = newNodes\n\t\t\treturn this\n\t\t}\n\n\t\treturn new HashArrayMapNode(ownerID, newCount, newNodes)\n\t}\n}\n\nclass HashCollisionNode<K, V> {\n\tconstructor(\n\t\tpublic ownerID: OwnerID,\n\t\tpublic keyHash: number,\n\t\tpublic entries: Array<[K, V]>\n\t) {}\n\n\tget(shift: number, keyHash: number, key: K, notSetValue?: V) {\n\t\tconst entries = this.entries\n\t\tfor (let ii = 0, len = entries.length; ii < len; ii++) {\n\t\t\tif (Object.is(key, entries[ii][0])) {\n\t\t\t\treturn entries[ii][1]\n\t\t\t}\n\t\t}\n\t\treturn notSetValue\n\t}\n\n\tupdate(\n\t\townerID: OwnerID,\n\t\tshift: number,\n\t\tkeyHash: number,\n\t\tkey: K,\n\t\tvalue: V,\n\t\tdidChangeSize?: Ref,\n\t\tdidAlter?: Ref\n\t): MapNode<K, V> {\n\t\tif (keyHash === undefined) {\n\t\t\tkeyHash = hash(key)\n\t\t}\n\n\t\tconst removed = value === NOT_SET\n\n\t\tif (keyHash !== this.keyHash) {\n\t\t\tif (removed) {\n\t\t\t\treturn this\n\t\t\t}\n\t\t\tSetRef(didAlter)\n\t\t\tSetRef(didChangeSize)\n\t\t\treturn mergeIntoNode(this, ownerID, shift, keyHash, [key, value])\n\t\t}\n\n\t\tconst entries = this.entries\n\t\tlet idx = 0\n\t\tconst len = entries.length\n\t\tfor (; idx < len; idx++) {\n\t\t\tif (Object.is(key, entries[idx][0])) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tconst exists = idx < len\n\n\t\tif (exists ? entries[idx][1] === value : removed) {\n\t\t\treturn this\n\t\t}\n\n\t\tSetRef(didAlter)\n\t\tif (removed || !exists) SetRef(didChangeSize)\n\n\t\tif (removed && len === 2) {\n\t\t\treturn new ValueNode(ownerID, this.keyHash, entries[idx ^ 1])\n\t\t}\n\n\t\tconst isEditable = ownerID && ownerID === this.ownerID\n\t\tconst newEntries = isEditable ? entries : arrCopy(entries)\n\n\t\tif (exists) {\n\t\t\tif (removed) {\n\t\t\t\tif (idx === len - 1) {\n\t\t\t\t\tnewEntries.pop()\n\t\t\t\t} else {\n\t\t\t\t\tnewEntries[idx] = newEntries.pop()!\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewEntries[idx] = [key, value]\n\t\t\t}\n\t\t} else {\n\t\t\tnewEntries.push([key, value])\n\t\t}\n\n\t\tif (isEditable) {\n\t\t\tthis.entries = newEntries\n\t\t\treturn this\n\t\t}\n\n\t\treturn new HashCollisionNode(ownerID, this.keyHash, newEntries)\n\t}\n}\n\nclass ValueNode<K, V> {\n\tconstructor(\n\t\tpublic ownerID: OwnerID,\n\t\tpublic keyHash: number | undefined,\n\t\tpublic entry: [K, V]\n\t) {}\n\n\tget(shift: number, keyHash: number, key: K, notSetValue?: V) {\n\t\treturn Object.is(key, this.entry[0]) ? this.entry[1] : notSetValue\n\t}\n\n\tupdate(\n\t\townerID: OwnerID,\n\t\tshift: number,\n\t\tkeyHash: number | undefined,\n\t\tkey: K,\n\t\tvalue: V,\n\t\tdidChangeSize?: Ref,\n\t\tdidAlter?: Ref\n\t) {\n\t\tconst removed = value === NOT_SET\n\t\tconst keyMatch = Object.is(key, this.entry[0])\n\t\tif (keyMatch ? value === this.entry[1] : removed) {\n\t\t\treturn this\n\t\t}\n\n\t\tSetRef(didAlter)\n\n\t\tif (removed) {\n\t\t\tSetRef(didChangeSize)\n\t\t\treturn // undefined\n\t\t}\n\n\t\tif (keyMatch) {\n\t\t\tif (ownerID && ownerID === this.ownerID) {\n\t\t\t\tthis.entry[1] = value\n\t\t\t\treturn this\n\t\t\t}\n\t\t\treturn new ValueNode(ownerID, this.keyHash, [key, value])\n\t\t}\n\n\t\tSetRef(didChangeSize)\n\t\treturn mergeIntoNode(this, ownerID, shift, hash(key), [key, value])\n\t}\n}\n\n// #pragma Iterators\n\nclass MapIterator<K, V> implements Iterator<any>, Iterable<any> {\n\t_stack\n\n\tconstructor(\n\t\tmap: ImmutableMap<K, V>,\n\t\tpublic _type: IterationType,\n\t\tpublic _reverse: boolean\n\t) {\n\t\tthis._stack = map._root && mapIteratorFrame<K, V>(map._root)\n\t}\n\n\t[Symbol.iterator](): Iterator<any> {\n\t\treturn this\n\t}\n\n\tnext() {\n\t\tconst type = this._type\n\t\tlet stack = this._stack\n\t\twhile (stack) {\n\t\t\tconst node = stack.node as any\n\t\t\tconst index = stack.index++\n\t\t\tlet maxIndex\n\t\t\tif (node.entry) {\n\t\t\t\tif (index === 0) {\n\t\t\t\t\treturn mapIteratorValue(type, node.entry)\n\t\t\t\t}\n\t\t\t} else if ('entries' in node && node.entries) {\n\t\t\t\tmaxIndex = node.entries.length - 1\n\t\t\t\tif (index <= maxIndex) {\n\t\t\t\t\treturn mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmaxIndex = node.nodes.length - 1\n\t\t\t\tif (index <= maxIndex) {\n\t\t\t\t\tconst subNode = node.nodes[this._reverse ? maxIndex - index : index]\n\t\t\t\t\tif (subNode) {\n\t\t\t\t\t\tif (subNode.entry) {\n\t\t\t\t\t\t\treturn mapIteratorValue(type, subNode.entry)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstack = this._stack = mapIteratorFrame(subNode, stack)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tstack = this._stack = this._stack.__prev!\n\t\t}\n\t\treturn iteratorDone() as any\n\t}\n}\n\nfunction mapIteratorValue<K, V>(type: IterationType, entry: [K, V]) {\n\treturn iteratorValue(type, entry[0], entry[1])\n}\n\ninterface IStack {\n\tnode: MapNode<unknown, unknown>\n\tindex: number\n\t__prev?: IStack\n}\n\nfunction mapIteratorFrame<K, V>(\n\tnode: MapNode<K, V>,\n\tprev?: { node: MapNode<K, V>; index: number; __prev?: IStack }\n): IStack {\n\treturn {\n\t\tnode: node,\n\t\tindex: 0,\n\t\t__prev: prev,\n\t}\n}\n\nconst ITERATE_KEYS = 0\nconst ITERATE_VALUES = 1\nconst ITERATE_ENTRIES = 2\n\ntype IterationType = typeof ITERATE_KEYS | typeof ITERATE_VALUES | typeof ITERATE_ENTRIES\n\nfunction iteratorValue<K, V>(\n\ttype: IterationType,\n\tk: K,\n\tv: V,\n\titeratorResult?: IteratorResult<any>\n) {\n\tconst value = type === ITERATE_KEYS ? k : type === ITERATE_VALUES ? v : [k, v]\n\tif (iteratorResult) {\n\t\titeratorResult.value = value\n\t} else {\n\t\titeratorResult = { value, done: false }\n\t}\n\treturn iteratorResult\n}\n\n/**\n * Creates a completed iterator result object indicating iteration is finished.\n * Used internally by map iterators to signal the end of iteration.\n *\n * @returns An IteratorResult object with done set to true and value as undefined\n * @public\n * @example\n * ```ts\n * // Used internally by iterators\n * const result = iteratorDone()\n * console.log(result) // { value: undefined, done: true }\n * ```\n */\nexport function iteratorDone() {\n\treturn { value: undefined, done: true }\n}\n\nfunction makeMap<K, V>(size: number, root?: MapNode<K, V>, ownerID?: OwnerID, hash?: number) {\n\tconst map = Object.create(ImmutableMap.prototype)\n\tmap.size = size\n\tmap._root = root\n\tmap.__ownerID = ownerID\n\tmap.__hash = hash\n\tmap.__altered = false\n\treturn map\n}\n\nlet EMPTY_MAP: ImmutableMap<unknown, unknown>\n/**\n * Returns a singleton empty ImmutableMap instance.\n * This function is optimized to return the same empty map instance for all calls,\n * saving memory when working with many empty maps.\n *\n * @returns An empty ImmutableMap instance\n * @public\n * @example\n * ```ts\n * // Get an empty map\n * const empty = emptyMap<string, number>()\n * console.log(empty.size) // 0\n *\n * // All empty maps are the same instance\n * const empty1 = emptyMap()\n * const empty2 = emptyMap()\n * console.log(empty1 === empty2) // true\n * ```\n */\nexport function emptyMap<K, V>(): ImmutableMap<K, V> {\n\treturn (EMPTY_MAP as any) || (EMPTY_MAP = makeMap(0))\n}\n\nfunction updateMap<K, V>(map: ImmutableMap<K, V>, k: K, v: V) {\n\tlet newRoot\n\tlet newSize\n\tif (!map._root) {\n\t\tif (v === NOT_SET) {\n\t\t\treturn map\n\t\t}\n\t\tnewSize = 1\n\t\tnewRoot = new ArrayMapNode(map.__ownerID, [[k, v]])\n\t} else {\n\t\tconst didChangeSize = MakeRef()\n\t\tconst didAlter = MakeRef()\n\t\tnewRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter)\n\t\tif (!didAlter.value) {\n\t\t\treturn map\n\t\t}\n\t\tnewSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0)\n\t}\n\tif (map.__ownerID) {\n\t\tmap.size = newSize\n\t\tmap._root = newRoot as any\n\t\tmap.__hash = undefined\n\t\tmap.__altered = true\n\t\treturn map\n\t}\n\treturn newRoot ? makeMap(newSize, newRoot) : emptyMap()\n}\n\nfunction updateNode<K, V>(\n\tnode: MapNode<K, V> | undefined,\n\townerID: OwnerID,\n\tshift: number,\n\tkeyHash: number | undefined,\n\tkey: K,\n\tvalue: V,\n\tdidChangeSize?: Ref,\n\tdidAlter?: Ref\n): MapNode<K, V> | undefined {\n\tif (!node) {\n\t\tif (value === NOT_SET) {\n\t\t\treturn node\n\t\t}\n\t\tSetRef(didAlter)\n\t\tSetRef(didChangeSize)\n\t\treturn new ValueNode(ownerID, keyHash, [key, value])\n\t}\n\treturn node.update(ownerID, shift, keyHash!, key, value, didChangeSize, didAlter) as any\n}\n\nfunction isLeafNode(node: MapNode<unknown, unknown>) {\n\treturn node.constructor === ValueNode || node.constructor === HashCollisionNode\n}\n\nfunction mergeIntoNode<K, V>(\n\tnode: any,\n\townerID: OwnerID,\n\tshift: number,\n\tkeyHash: number,\n\tentry: [K, V]\n): MapNode<K, V> {\n\tif (node.keyHash === keyHash) {\n\t\treturn new HashCollisionNode(ownerID, keyHash, [node.entry, entry])\n\t}\n\n\tconst idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK\n\tconst idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK\n\n\tlet newNode\n\tconst nodes =\n\t\tidx1 === idx2\n\t\t\t? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)]\n\t\t\t: ((newNode = new ValueNode(ownerID, keyHash, entry)),\n\t\t\t\tidx1 < idx2 ? [node, newNode] : [newNode, node])\n\n\treturn new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes)\n}\n\nfunction createNodes<K, V>(ownerID: OwnerID, entries: [K, V][], key: K, value: V) {\n\tif (!ownerID) {\n\t\townerID = new OwnerID()\n\t}\n\tlet node: MapNode<K, V> = new ValueNode(ownerID, hash(key), [key, value])\n\tfor (let ii = 0; ii < entries.length; ii++) {\n\t\tconst entry = entries[ii]\n\t\tnode = node.update(ownerID, 0, undefined as any as number, entry[0], entry[1]) as any\n\t}\n\treturn node\n}\n\nfunction packNodes<K, V>(\n\townerID: OwnerID,\n\tnodes: MapNode<K, V>[],\n\tcount: number,\n\texcluding: number\n) {\n\tlet bitmap = 0\n\tlet packedII = 0\n\tconst packedNodes = new Array(count)\n\tfor (let ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {\n\t\tconst node = nodes[ii]\n\t\tif (node !== undefined && ii !== excluding) {\n\t\t\tbitmap |= bit\n\t\t\tpackedNodes[packedII++] = node\n\t\t}\n\t}\n\treturn new BitmapIndexedNode(ownerID, bitmap, packedNodes)\n}\n\nfunction expandNodes<K, V>(\n\townerID: OwnerID,\n\tnodes: MapNode<K, V>[],\n\tbitmap: number,\n\tincluding: number,\n\tnode: MapNode<K, V>\n): MapNode<K, V> {\n\tlet count = 0\n\tconst expandedNodes = new Array(SIZE)\n\tfor (let ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {\n\t\texpandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined\n\t}\n\texpandedNodes[including] = node\n\treturn new HashArrayMapNode(ownerID, count + 1, expandedNodes)\n}\n\nfunction popCount(x: number) {\n\tx -= (x >> 1) & 0x55555555\n\tx = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n\tx = (x + (x >> 4)) & 0x0f0f0f0f\n\tx += x >> 8\n\tx += x >> 16\n\treturn x & 0x7f\n}\n\nfunction setAt<T>(array: T[], idx: number, val: T, canEdit: boolean): T[] {\n\tconst newArray = canEdit ? array : arrCopy(array)\n\tnewArray[idx] = val\n\treturn newArray\n}\n\nfunction spliceIn<T>(array: T[], idx: number, val: T, canEdit: boolean): T[] {\n\tconst newLen = array.length + 1\n\tif (canEdit && idx + 1 === newLen) {\n\t\tarray[idx] = val\n\t\treturn array\n\t}\n\tconst newArray = new Array<T>(newLen)\n\tlet after = 0\n\tfor (let ii = 0; ii < newLen; ii++) {\n\t\tif (ii === idx) {\n\t\t\tnewArray[ii] = val\n\t\t\tafter = -1\n\t\t} else {\n\t\t\tnewArray[ii] = array[ii + after]\n\t\t}\n\t}\n\treturn newArray\n}\n\nfunction spliceOut<T>(array: T[], idx: number, canEdit: boolean) {\n\tconst newLen = array.length - 1\n\tif (canEdit && idx === newLen) {\n\t\tarray.pop()\n\t\treturn array\n\t}\n\tconst newArray = new Array(newLen)\n\tlet after = 0\n\tfor (let ii = 0; ii < newLen; ii++) {\n\t\tif (ii === idx) {\n\t\t\tafter = 1\n\t\t}\n\t\tnewArray[ii] = array[ii + after]\n\t}\n\treturn newArray\n}\n\nconst MAX_ARRAY_MAP_SIZE = SIZE / 4\nconst MAX_BITMAP_INDEXED_SIZE = SIZE / 2\nconst MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4\n","import { atom, Atom, transact, UNINITIALIZED } from '@ibodr/state'\nimport { assert } from '@ibodr/utils'\nimport { emptyMap, ImmutableMap } from './ImmutableMap'\n\n/**\n * A drop-in replacement for Map that stores values in atoms and can be used in reactive contexts.\n * @public\n */\nexport class AtomMap<K, V> implements Map<K, V> {\n\tprivate atoms: Atom<ImmutableMap<K, Atom<V | UNINITIALIZED>>>\n\n\t/**\n\t * Creates a new AtomMap instance.\n\t *\n\t * name - A unique name for this map, used for atom identification\n\t * entries - Optional initial entries to populate the map with\n\t * @example\n\t * ```ts\n\t * // Create an empty map\n\t * const map = new AtomMap('userMap')\n\t *\n\t * // Create a map with initial data\n\t * const initialData: [string, number][] = [['a', 1], ['b', 2]]\n\t * const mapWithData = new AtomMap('numbersMap', initialData)\n\t * ```\n\t */\n\tconstructor(\n\t\tprivate readonly name: string,\n\t\tentries?: Iterable<readonly [K, V]>\n\t) {\n\t\tlet atoms = emptyMap<K, Atom<V>>()\n\t\tif (entries) {\n\t\t\tatoms = atoms.withMutations((atoms) => {\n\t\t\t\tfor (const [k, v] of entries) {\n\t\t\t\t\tatoms.set(k, atom(`${name}:${String(k)}`, v))\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tthis.atoms = atom(`${name}:atoms`, atoms)\n\t}\n\n\t/**\n\t * Retrieves the underlying atom for a given key.\n\t *\n\t * @param key - The key to retrieve the atom for\n\t * @returns The atom containing the value, or undefined if the key doesn't exist\n\t * @internal\n\t */\n\tgetAtom(key: K): Atom<V | UNINITIALIZED> | undefined {\n\t\tconst valueAtom = this.atoms.__unsafe__getWithoutCapture().get(key)\n\t\tif (!valueAtom) {\n\t\t\t// if the value is missing, we want to track whether it's in the present keys set\n\t\t\tthis.atoms.get()\n\t\t\treturn undefined\n\t\t}\n\t\treturn valueAtom\n\t}\n\n\t/**\n\t * Gets the value associated with a key. Returns undefined if the key doesn't exist.\n\t * This method is reactive and will cause reactive contexts to update when the value changes.\n\t *\n\t * @param key - The key to retrieve the value for\n\t * @returns The value associated with the key, or undefined if not found\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('name', 'Alice')\n\t * console.log(map.get('name')) // 'Alice'\n\t * console.log(map.get('missing')) // undefined\n\t * ```\n\t */\n\tget(key: K): V | undefined {\n\t\tconst value = this.getAtom(key)?.get()\n\t\tassert(value !== UNINITIALIZED)\n\t\treturn value\n\t}\n\n\t/**\n\t * Gets the value associated with a key without creating reactive dependencies.\n\t * This method will not cause reactive contexts to update when the value changes.\n\t *\n\t * @param key - The key to retrieve the value for\n\t * @returns The value associated with the key, or undefined if not found\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('count', 42)\n\t * const value = map.__unsafe__getWithoutCapture('count') // No reactive subscription\n\t * ```\n\t */\n\t__unsafe__getWithoutCapture(key: K): V | undefined {\n\t\tconst valueAtom = this.atoms.__unsafe__getWithoutCapture().get(key)\n\t\tif (!valueAtom) return undefined\n\t\tconst value = valueAtom.__unsafe__getWithoutCapture()\n\t\tassert(value !== UNINITIALIZED)\n\t\treturn value\n\t}\n\n\t/**\n\t * Checks whether a key exists in the map.\n\t * This method is reactive and will cause reactive contexts to update when keys are added or removed.\n\t *\n\t * @param key - The key to check for\n\t * @returns True if the key exists in the map, false otherwise\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * console.log(map.has('name')) // false\n\t * map.set('name', 'Alice')\n\t * console.log(map.has('name')) // true\n\t * ```\n\t */\n\thas(key: K): boolean {\n\t\tconst valueAtom = this.getAtom(key)\n\t\tif (!valueAtom) {\n\t\t\treturn false\n\t\t}\n\t\treturn valueAtom.get() !== UNINITIALIZED\n\t}\n\n\t/**\n\t * Checks whether a key exists in the map without creating reactive dependencies.\n\t * This method will not cause reactive contexts to update when keys are added or removed.\n\t *\n\t * @param key - The key to check for\n\t * @returns True if the key exists in the map, false otherwise\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('active', true)\n\t * const exists = map.__unsafe__hasWithoutCapture('active') // No reactive subscription\n\t * ```\n\t */\n\t__unsafe__hasWithoutCapture(key: K): boolean {\n\t\tconst valueAtom = this.atoms.__unsafe__getWithoutCapture().get(key)\n\t\tif (!valueAtom) return false\n\t\tassert(valueAtom.__unsafe__getWithoutCapture() !== UNINITIALIZED)\n\t\treturn true\n\t}\n\n\t/**\n\t * Sets a value for the given key. If the key already exists, its value is updated.\n\t * If the key doesn't exist, a new entry is created.\n\t *\n\t * @param key - The key to set the value for\n\t * @param value - The value to associate with the key\n\t * @returns This AtomMap instance for method chaining\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('name', 'Alice').set('age', 30)\n\t * ```\n\t */\n\tset(key: K, value: V) {\n\t\tconst existingAtom = this.atoms.__unsafe__getWithoutCapture().get(key)\n\t\tif (existingAtom) {\n\t\t\texistingAtom.set(value)\n\t\t} else {\n\t\t\tthis.atoms.update((atoms) => {\n\t\t\t\treturn atoms.set(key, atom(`${this.name}:${String(key)}`, value))\n\t\t\t})\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Updates an existing value using an updater function.\n\t *\n\t * @param key - The key of the value to update\n\t * @param updater - A function that receives the current value and returns the new value\n\t * @throws Error if the key doesn't exist in the map\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('count', 5)\n\t * map.update('count', count => count + 1) // count is now 6\n\t * ```\n\t */\n\tupdate(key: K, updater: (value: V) => V) {\n\t\tconst valueAtom = this.atoms.__unsafe__getWithoutCapture().get(key)\n\t\tif (!valueAtom) {\n\t\t\tthrow new Error(`AtomMap: key ${key} not found`)\n\t\t}\n\t\tconst value = valueAtom.__unsafe__getWithoutCapture()\n\t\tassert(value !== UNINITIALIZED)\n\t\tvalueAtom.set(updater(value))\n\t}\n\n\t/**\n\t * Removes a key-value pair from the map.\n\t *\n\t * @param key - The key to remove\n\t * @returns True if the key existed and was removed, false if it didn't exist\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('temp', 'value')\n\t * console.log(map.delete('temp')) // true\n\t * console.log(map.delete('missing')) // false\n\t * ```\n\t */\n\tdelete(key: K) {\n\t\tconst valueAtom = this.atoms.__unsafe__getWithoutCapture().get(key)\n\t\tif (!valueAtom) {\n\t\t\treturn false\n\t\t}\n\n\t\ttransact(() => {\n\t\t\tvalueAtom.set(UNINITIALIZED)\n\t\t\tthis.atoms.update((atoms) => {\n\t\t\t\treturn atoms.delete(key)\n\t\t\t})\n\t\t})\n\t\treturn true\n\t}\n\n\t/**\n\t * Removes multiple key-value pairs from the map in a single transaction.\n\t *\n\t * @param keys - An iterable of keys to remove\n\t * @returns An array of [key, value] pairs that were actually deleted\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('a', 1).set('b', 2).set('c', 3)\n\t * const deleted = map.deleteMany(['a', 'c', 'missing'])\n\t * console.log(deleted) // [['a', 1], ['c', 3]]\n\t * ```\n\t */\n\tdeleteMany(keys: Iterable<K>): [K, V][] {\n\t\treturn transact(() => {\n\t\t\tconst deleted: [K, V][] = []\n\t\t\tconst newAtoms = this.atoms.get().withMutations((atoms) => {\n\t\t\t\tfor (const key of keys) {\n\t\t\t\t\tconst valueAtom = atoms.get(key)\n\t\t\t\t\tif (!valueAtom) continue\n\t\t\t\t\tconst oldValue = valueAtom.get()\n\t\t\t\t\tassert(oldValue !== UNINITIALIZED)\n\n\t\t\t\t\tdeleted.push([key, oldValue])\n\n\t\t\t\t\tatoms.delete(key)\n\t\t\t\t\tvalueAtom.set(UNINITIALIZED)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tif (deleted.length) {\n\t\t\t\tthis.atoms.set(newAtoms)\n\t\t\t}\n\n\t\t\treturn deleted\n\t\t})\n\t}\n\n\t/**\n\t * Removes all key-value pairs from the map.\n\t *\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('a', 1).set('b', 2)\n\t * map.clear()\n\t * console.log(map.size) // 0\n\t * ```\n\t */\n\tclear() {\n\t\treturn transact(() => {\n\t\t\tfor (const valueAtom of this.atoms.__unsafe__getWithoutCapture().values()) {\n\t\t\t\tvalueAtom.set(UNINITIALIZED)\n\t\t\t}\n\t\t\tthis.atoms.set(emptyMap())\n\t\t})\n\t}\n\n\t/**\n\t * Returns an iterator that yields [key, value] pairs for each entry in the map.\n\t * This method is reactive and will cause reactive contexts to update when entries change.\n\t *\n\t * @returns A generator that yields [key, value] tuples\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('a', 1).set('b', 2)\n\t * for (const [key, value] of map.entries()) {\n\t * console.log(`${key}: ${value}`)\n\t * }\n\t * ```\n\t */\n\t*entries(): Generator<[K, V], undefined, unknown> {\n\t\tfor (const [key, valueAtom] of this.atoms.get()) {\n\t\t\tconst value = valueAtom.get()\n\t\t\tassert(value !== UNINITIALIZED)\n\t\t\tyield [key, value]\n\t\t}\n\t}\n\n\t/**\n\t * Returns an iterator that yields all keys in the map.\n\t * This method is reactive and will cause reactive contexts to update when keys change.\n\t *\n\t * @returns A generator that yields keys\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('name', 'Alice').set('age', 30)\n\t * for (const key of map.keys()) {\n\t * console.log(key) // 'name', 'age'\n\t * }\n\t * ```\n\t */\n\t*keys(): Generator<K, undefined, unknown> {\n\t\tfor (const key of this.atoms.get().keys()) {\n\t\t\tyield key\n\t\t}\n\t}\n\n\t/**\n\t * Returns an iterator that yields all values in the map.\n\t * This method is reactive and will cause reactive contexts to update when values change.\n\t *\n\t * @returns A generator that yields values\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('name', 'Alice').set('age', 30)\n\t * for (const value of map.values()) {\n\t * console.log(value) // 'Alice', 30\n\t * }\n\t * ```\n\t */\n\t*values(): Generator<V, undefined, unknown> {\n\t\tfor (const valueAtom of this.atoms.get().values()) {\n\t\t\tconst value = valueAtom.get()\n\t\t\tassert(value !== UNINITIALIZED)\n\t\t\tyield value\n\t\t}\n\t}\n\n\t/**\n\t * The number of key-value pairs in the map.\n\t * This property is reactive and will cause reactive contexts to update when the size changes.\n\t *\n\t * @returns The number of entries in the map\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * console.log(map.size) // 0\n\t * map.set('a', 1)\n\t * console.log(map.size) // 1\n\t * ```\n\t */\n\t// eslint-disable-next-line tldraw/no-setter-getter\n\tget size() {\n\t\treturn this.atoms.get().size\n\t}\n\n\t/**\n\t * Executes a provided function once for each key-value pair in the map.\n\t * This method is reactive and will cause reactive contexts to update when entries change.\n\t *\n\t * @param callbackfn - Function to execute for each entry\n\t * - value - The value of the current entry\n\t * - key - The key of the current entry\n\t * - map - The AtomMap being traversed\n\t * @param thisArg - Value to use as `this` when executing the callback\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('a', 1).set('b', 2)\n\t * map.forEach((value, key) => {\n\t * console.log(`${key} = ${value}`)\n\t * })\n\t * ```\n\t */\n\tforEach(callbackfn: (value: V, key: K, map: AtomMap<K, V>) => void, thisArg?: any): void {\n\t\tfor (const [key, value] of this.entries()) {\n\t\t\tcallbackfn.call(thisArg, value, key, this)\n\t\t}\n\t}\n\n\t/**\n\t * Returns the default iterator for the map, which is the same as entries().\n\t * This allows the map to be used in for...of loops and other iterable contexts.\n\t *\n\t * @returns The same iterator as entries()\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * map.set('a', 1).set('b', 2)\n\t *\n\t * // These are equivalent:\n\t * for (const [key, value] of map) {\n\t * console.log(`${key}: ${value}`)\n\t * }\n\t *\n\t * for (const [key, value] of map.entries()) {\n\t * console.log(`${key}: ${value}`)\n\t * }\n\t * ```\n\t */\n\t[Symbol.iterator]() {\n\t\treturn this.entries()\n\t}\n\n\t/**\n\t * The string tag used by Object.prototype.toString for this class.\n\t *\n\t * @example\n\t * ```ts\n\t * const map = new AtomMap('myMap')\n\t * console.log(Object.prototype.toString.call(map)) // '[object AtomMap]'\n\t * ```\n\t */\n\t[Symbol.toStringTag] = 'AtomMap'\n}\n","import { AtomMap } from './AtomMap'\n\n/**\n * A drop-in replacement for Set that stores values in atoms and can be used in reactive contexts.\n * @public\n */\nexport class AtomSet<T> {\n\tprivate readonly map: AtomMap<T, T>\n\tconstructor(\n\t\tprivate readonly name: string,\n\t\tkeys?: Iterable<T>\n\t) {\n\t\tconst entries = keys ? Array.from(keys, (k) => [k, k] as const) : undefined\n\t\tthis.map = new AtomMap(name, entries)\n\t}\n\n\tadd(value: T): this {\n\t\tthis.map.set(value, value)\n\t\treturn this\n\t}\n\tclear(): void {\n\t\tthis.map.clear()\n\t}\n\tdelete(value: T): boolean {\n\t\treturn this.map.delete(value)\n\t}\n\tforEach(callbackfn: (value: T, value2: T, set: AtomSet<T>) => void, thisArg?: any): void {\n\t\tfor (const value of this) {\n\t\t\tcallbackfn.call(thisArg, value, value, this)\n\t\t}\n\t}\n\thas(value: T): boolean {\n\t\treturn this.map.has(value)\n\t}\n\t// eslint-disable-next-line tldraw/no-setter-getter\n\tget size(): number {\n\t\treturn this.map.size\n\t}\n\tentries(): Generator<[T, T], undefined, unknown> {\n\t\treturn this.map.entries()\n\t}\n\tkeys(): Generator<T, undefined, unknown> {\n\t\treturn this.map.keys()\n\t}\n\tvalues(): Generator<T, undefined, unknown> {\n\t\treturn this.map.keys()\n\t}\n\t[Symbol.iterator](): Generator<T, undefined, unknown> {\n\t\treturn this.map.keys()\n\t}\n\t[Symbol.toStringTag]: string = 'AtomSet'\n}\n","let _isDev = false\ntry {\n\t_isDev = process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test'\n} catch (_e) {\n\t/* noop */\n}\ntry {\n\t_isDev =\n\t\t_isDev ||\n\t\t(import.meta as any).env.DEV ||\n\t\t(import.meta as any).env.TEST ||\n\t\t(import.meta as any).env.MODE === 'development' ||\n\t\t(import.meta as any).env.MODE === 'test'\n} catch (_e) {\n\t/* noop */\n}\n\nexport function isDev() {\n\treturn _isDev\n}\n","import { STRUCTURED_CLONE_OBJECT_PROTOTYPE } from '@ibodr/utils'\nimport { isDev } from './isDev'\n\n/**\n * Freeze an object when in development mode. Copied from\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\n *\n * @example\n *\n * ```ts\n * const frozen = devFreeze({ a: 1 })\n * ```\n *\n * @param object - The object to freeze.\n * @returns The frozen object when in development mode, or else the object when in other modes.\n * @public\n */\nexport function devFreeze<T>(object: T): T {\n\tif (!isDev()) return object\n\n\tconst proto = Object.getPrototypeOf(object)\n\tif (\n\t\tproto &&\n\t\t!(\n\t\t\tArray.isArray(object) ||\n\t\t\tproto === Object.prototype ||\n\t\t\tproto === null ||\n\t\t\tproto === STRUCTURED_CLONE_OBJECT_PROTOTYPE\n\t\t)\n\t) {\n\t\tconsole.error('cannot include non-js data in a record', object)\n\t\tthrow new Error('cannot include non-js data in a record')\n\t}\n\n\tif (Object.isFrozen(object)) {\n\t\treturn object\n\t}\n\n\t// Retrieve the property names defined on object\n\tconst propNames = Object.getOwnPropertyNames(object)\n\n\t// Recursively freeze properties before freezing self\n\tfor (const name of propNames) {\n\t\tconst value = (object as any)[name]\n\n\t\tif (value && typeof value === 'object') {\n\t\t\tdevFreeze(value)\n\t\t}\n\t}\n\n\treturn Object.freeze(object)\n}\n","import { CollectionDiff } from './Store'\n\n/**\n * A utility class for incrementally building a set while tracking changes. This class allows\n * you to add and remove items from a set while maintaining a diff of what was added and\n * removed from the original set. It's optimized for cases where you need to track changes\n * to a set over time and get both the final result and the change delta.\n *\n * @example\n * ```ts\n * const originalSet = new Set(['a', 'b', 'c'])\n * const constructor = new IncrementalSetConstructor(originalSet)\n *\n * constructor.add('d') // Add new item\n * constructor.remove('b') // Remove existing item\n * constructor.add('a') // Re-add removed item (no-op since already present)\n *\n * const result = constructor.get()\n * // result.value contains Set(['a', 'c', 'd'])\n * // result.diff contains { added: Set(['d']), removed: Set(['b']) }\n * ```\n *\n * @internal\n */\nexport class IncrementalSetConstructor<T> {\n\t/**\n\t * The next value of the set.\n\t *\n\t * @internal\n\t */\n\tprivate nextValue?: Set<T>\n\n\t/**\n\t * The diff of the set.\n\t *\n\t * @internal\n\t */\n\tprivate diff?: CollectionDiff<T>\n\n\tconstructor(\n\t\t/**\n\t\t * The previous value of the set.\n\t\t *\n\t\t * @internal\n\t\t * @readonly\n\t\t */\n\t\tprivate readonly previousValue: Set<T>\n\t) {}\n\n\t/**\n\t * Gets the result of the incremental set construction if any changes were made.\n\t * Returns undefined if no additions or removals occurred.\n\t *\n\t * @returns An object containing the final set value and the diff of changes,\n\t * or undefined if no changes were made\n\t *\n\t * @example\n\t * ```ts\n\t * const constructor = new IncrementalSetConstructor(new Set(['a', 'b']))\n\t * constructor.add('c')\n\t *\n\t * const result = constructor.get()\n\t * // result = {\n\t * // value: Set(['a', 'b', 'c']),\n\t * // diff: { added: Set(['c']) }\n\t * // }\n\t * ```\n\t *\n\t * @public\n\t */\n\tpublic get() {\n\t\tconst numRemoved = this.diff?.removed?.size ?? 0\n\t\tconst numAdded = this.diff?.added?.size ?? 0\n\t\tif (numRemoved === 0 && numAdded === 0) {\n\t\t\treturn undefined\n\t\t}\n\t\treturn { value: this.nextValue!, diff: this.diff! }\n\t}\n\n\t/**\n\t * Add an item to the set.\n\t *\n\t * @param item - The item to add.\n\t * @param wasAlreadyPresent - Whether the item was already present in the set.\n\t * @internal\n\t */\n\tprivate _add(item: T, wasAlreadyPresent: boolean) {\n\t\tthis.nextValue ??= new Set(this.previousValue)\n\t\tthis.nextValue.add(item)\n\n\t\tthis.diff ??= {}\n\t\tif (wasAlreadyPresent) {\n\t\t\tthis.diff.removed?.delete(item)\n\t\t} else {\n\t\t\tthis.diff.added ??= new Set()\n\t\t\tthis.diff.added.add(item)\n\t\t}\n\t}\n\n\t/**\n\t * Adds an item to the set. If the item was already present in the original set\n\t * and was previously removed during this construction, it will be restored.\n\t * If the item is already present and wasn't removed, this is a no-op.\n\t *\n\t * @param item - The item to add to the set\n\t *\n\t * @example\n\t * ```ts\n\t * const constructor = new IncrementalSetConstructor(new Set(['a', 'b']))\n\t * constructor.add('c') // Adds new item\n\t * constructor.add('a') // No-op, already present\n\t * constructor.remove('b')\n\t * constructor.add('b') // Restores previously removed item\n\t * ```\n\t *\n\t * @public\n\t */\n\tadd(item: T) {\n\t\tconst wasAlreadyPresent = this.previousValue.has(item)\n\t\tif (wasAlreadyPresent) {\n\t\t\tconst wasRemoved = this.diff?.removed?.has(item)\n\t\t\t// if it wasn't removed during the lifetime of this set constructor, there's no need to add it again\n\t\t\tif (!wasRemoved) return\n\t\t\treturn this._add(item, wasAlreadyPresent)\n\t\t}\n\t\tconst isCurrentlyPresent = this.nextValue?.has(item)\n\t\t// if it's already there, no need to add it again\n\t\tif (isCurrentlyPresent) return\n\t\t// otherwise add it\n\t\tthis._add(item, wasAlreadyPresent)\n\t}\n\n\t/**\n\t * Remove an item from the set.\n\t *\n\t * @param item - The item to remove.\n\t * @param wasAlreadyPresent - Whether the item was already present in the set.\n\t * @internal\n\t */\n\tprivate _remove(item: T, wasAlreadyPresent: boolean) {\n\t\tthis.nextValue ??= new Set(this.previousValue)\n\t\tthis.nextValue.delete(item)\n\n\t\tthis.diff ??= {}\n\t\tif (wasAlreadyPresent) {\n\t\t\t// it was in the original set, so we need to add it to the removed diff\n\t\t\tthis.diff.removed ??= new Set()\n\t\t\tthis.diff.removed.add(item)\n\t\t} else {\n\t\t\t// if it was added during the lifetime of this set constructor, we need to remove it from the added diff\n\t\t\tthis.diff.added?.delete(item)\n\t\t}\n\t}\n\n\t/**\n\t * Removes an item from the set. If the item wasn't present in the original set\n\t * and was added during this construction, it will be removed from the added diff.\n\t * If the item is not present at all, this is a no-op.\n\t *\n\t * @param item - The item to remove from the set\n\t *\n\t * @example\n\t * ```ts\n\t * const constructor = new IncrementalSetConstructor(new Set(['a', 'b']))\n\t * constructor.remove('a') // Removes existing item\n\t * constructor.remove('c') // No-op, not present\n\t * constructor.add('d')\n\t * constructor.remove('d') // Removes recently added item\n\t * ```\n\t *\n\t * @public\n\t */\n\tremove(item: T) {\n\t\tconst wasAlreadyPresent = this.previousValue.has(item)\n\t\tif (!wasAlreadyPresent) {\n\t\t\tconst wasAdded = this.diff?.added?.has(item)\n\t\t\t// if it wasn't added during the lifetime of this set constructor, there's no need to remove it\n\t\t\tif (!wasAdded) return\n\t\t\treturn this._remove(item, wasAlreadyPresent)\n\t\t}\n\t\tconst hasAlreadyBeenRemoved = this.diff?.removed?.has(item)\n\t\t// if it's already removed, no need to remove it again\n\t\tif (hasAlreadyBeenRemoved) return\n\t\t// otherwise remove it\n\t\tthis._remove(item, wasAlreadyPresent)\n\t}\n}\n","import { assert, objectMapEntries } from '@ibodr/utils'\nimport { UnknownRecord } from './BaseRecord'\nimport { SerializedStore } from './Store'\nimport { SerializedSchema } from './StoreSchema'\n\nfunction squashDependsOn(sequence: Array<Migration | StandaloneDependsOn>): Migration[] {\n\tconst result: Migration[] = []\n\tfor (let i = sequence.length - 1; i >= 0; i--) {\n\t\tconst elem = sequence[i]\n\t\tif (!('id' in elem)) {\n\t\t\tconst dependsOn = elem.dependsOn\n\t\t\tconst prev = result[0]\n\t\t\tif (prev) {\n\t\t\t\tresult[0] = {\n\t\t\t\t\t...prev,\n\t\t\t\t\tdependsOn: dependsOn.concat(prev.dependsOn ?? []),\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tresult.unshift(elem)\n\t\t}\n\t}\n\treturn result\n}\n\n/**\n * Creates a migration sequence that defines how to transform data as your schema evolves.\n *\n * A migration sequence contains a series of migrations that are applied in order to transform\n * data from older versions to newer versions. Each migration is identified by a unique ID\n * and can operate at either the record level (transforming individual records) or store level\n * (transforming the entire store structure).\n *\n * See the [migration guide](https://tldraw.dev/docs/persistence#Migrations) for more info on how to use this API.\n * @param options - Configuration for the migration sequence\n * - sequenceId - Unique identifier for this migration sequence (e.g., 'com.myapp.book')\n * - sequence - Array of migrations or dependency declarations to include in the sequence\n * - retroactive - Whether migrations should apply to snapshots created before this sequence was added (defaults to true)\n * @returns A validated migration sequence that can be included in a store schema\n * @example\n * ```ts\n * const bookMigrations = createMigrationSequence({\n * sequenceId: 'com.myapp.book',\n * sequence: [\n * {\n * id: 'com.myapp.book/1',\n * scope: 'record',\n * up: (record) => ({ ...record, newField: 'default' })\n * }\n * ]\n * })\n * ```\n * @public\n */\nexport function createMigrationSequence({\n\tsequence,\n\tsequenceId,\n\tretroactive = true,\n}: {\n\tsequenceId: string\n\tretroactive?: boolean\n\tsequence: Array<Migration | StandaloneDependsOn>\n}): MigrationSequence {\n\tconst migrations: MigrationSequence = {\n\t\tsequenceId,\n\t\tretroactive,\n\t\tsequence: squashDependsOn(sequence),\n\t}\n\tvalidateMigrations(migrations)\n\treturn migrations\n}\n\n/**\n * Creates a named set of migration IDs from version numbers and a sequence ID.\n *\n * This utility function helps generate properly formatted migration IDs that follow\n * the required `sequenceId/version` pattern. It takes a sequence ID and a record\n * of named versions, returning migration IDs that can be used in migration definitions.\n *\n * See the [migration guide](https://tldraw.dev/docs/persistence#Migrations) for more info on how to use this API.\n * @param sequenceId - The sequence identifier (e.g., 'com.myapp.book')\n * @param versions - Record mapping version names to numbers\n * @returns Record mapping version names to properly formatted migration IDs\n * @example\n * ```ts\n * const migrationIds = createMigrationIds('com.myapp.book', {\n * addGenre: 1,\n * addPublisher: 2,\n * removeOldField: 3\n * })\n * // Result: {\n * // addGenre: 'com.myapp.book/1',\n * // addPublisher: 'com.myapp.book/2',\n * // removeOldField: 'com.myapp.book/3'\n * // }\n * ```\n * @public\n */\nexport function createMigrationIds<\n\tconst ID extends string,\n\tconst Versions extends Record<string, number>,\n>(sequenceId: ID, versions: Versions): { [K in keyof Versions]: `${ID}/${Versions[K]}` } {\n\treturn Object.fromEntries(\n\t\tobjectMapEntries(versions).map(([key, version]) => [key, `${sequenceId}/${version}`] as const)\n\t) as any\n}\n\n/**\n * Creates a migration sequence specifically for record-level migrations.\n *\n * This is a convenience function that creates a migration sequence where all migrations\n * operate at the record scope and are automatically filtered to apply only to records\n * of a specific type. Each migration in the sequence will be enhanced with the record\n * scope and appropriate filtering logic.\n * @param opts - Configuration for the record migration sequence\n * - recordType - The record type name these migrations should apply to\n * - filter - Optional additional filter function to determine which records to migrate\n * - retroactive - Whether migrations should apply to snapshots created before this sequence was added\n * - sequenceId - Unique identifier for this migration sequence\n * - sequence - Array of record migration definitions (scope will be added automatically)\n * @returns A migration sequence configured for record-level operations\n * @internal\n */\nexport function createRecordMigrationSequence(opts: {\n\trecordType: string\n\tfilter?(record: UnknownRecord): boolean\n\tretroactive?: boolean\n\tsequenceId: string\n\tsequence: Omit<Extract<Migration, { scope: 'record' }>, 'scope'>[]\n}): MigrationSequence {\n\tconst sequenceId = opts.sequenceId\n\treturn createMigrationSequence({\n\t\tsequenceId,\n\t\tretroactive: opts.retroactive ?? true,\n\t\tsequence: opts.sequence.map((m) =>\n\t\t\t'id' in m\n\t\t\t\t? {\n\t\t\t\t\t\t...m,\n\t\t\t\t\t\tscope: 'record',\n\t\t\t\t\t\tfilter: (r: UnknownRecord) =>\n\t\t\t\t\t\t\tr.typeName === opts.recordType &&\n\t\t\t\t\t\t\t(m.filter?.(r) ?? true) &&\n\t\t\t\t\t\t\t(opts.filter?.(r) ?? true),\n\t\t\t\t\t}\n\t\t\t\t: m\n\t\t),\n\t})\n}\n\n/**\n * Legacy migration interface for backward compatibility.\n *\n * This interface represents the old migration format that included both `up` and `down`\n * transformation functions. While still supported, new code should use the `Migration`\n * type which provides more flexibility and better integration with the current system.\n * @public\n */\nexport interface LegacyMigration<Before = any, After = any> {\n\t// eslint-disable-next-line tldraw/method-signature-style\n\tup: (oldState: Before) => After\n\t// eslint-disable-next-line tldraw/method-signature-style\n\tdown: (newState: After) => Before\n}\n\n/**\n * Unique identifier for a migration in the format `sequenceId/version`.\n *\n * Migration IDs follow a specific pattern where the sequence ID identifies the migration\n * sequence and the version number indicates the order within that sequence. For example:\n * 'com.myapp.book/1', 'com.myapp.book/2', etc.\n * @public\n */\nexport type MigrationId = `${string}/${number}`\n\n/**\n * Declares dependencies for migrations without being a migration itself.\n *\n * This interface allows you to specify that future migrations in a sequence depend on\n * migrations from other sequences, without defining an actual migration transformation.\n * It's used to establish cross-sequence dependencies in the migration graph.\n * @public\n */\nexport interface StandaloneDependsOn {\n\treadonly dependsOn: readonly MigrationId[]\n}\n\n/**\n * Defines a single migration that transforms data from one schema version to another.\n *\n * A migration can operate at two different scopes:\n * - `record`: Transforms individual records, with optional filtering to target specific records\n * - `store`: Transforms the entire serialized store structure\n *\n * Each migration has a unique ID and can declare dependencies on other migrations that must\n * be applied first. The `up` function performs the forward transformation, while the optional\n * `down` function can reverse the migration if needed.\n * @public\n */\nexport type Migration = {\n\treadonly id: MigrationId\n\treadonly dependsOn?: readonly MigrationId[] | undefined\n} & (\n\t| {\n\t\t\treadonly scope: 'record'\n\t\t\t// eslint-disable-next-line tldraw/method-signature-style\n\t\t\treadonly filter?: (record: UnknownRecord) => boolean\n\t\t\t// eslint-disable-next-line tldraw/method-signature-style\n\t\t\treadonly up: (oldState: UnknownRecord) => void | UnknownRecord\n\t\t\t// eslint-disable-next-line tldraw/method-signature-style\n\t\t\treadonly down?: (newState: UnknownRecord) => void | UnknownRecord\n\t }\n\t| {\n\t\t\treadonly scope: 'store'\n\t\t\t// eslint-disable-next-line tldraw/method-signature-style\n\t\t\treadonly up: (\n\t\t\t\toldState: SerializedStore<UnknownRecord>\n\t\t\t) => void | SerializedStore<UnknownRecord>\n\t\t\t// eslint-disable-next-line tldraw/method-signature-style\n\t\t\treadonly down?: (\n\t\t\t\tnewState: SerializedStore<UnknownRecord>\n\t\t\t) => void | SerializedStore<UnknownRecord>\n\t }\n\t| {\n\t\t\treadonly scope: 'storage'\n\t\t\t// eslint-disable-next-line tldraw/method-signature-style\n\t\t\treadonly up: (storage: SynchronousRecordStorage<UnknownRecord>) => void\n\t\t\treadonly down?: never\n\t }\n)\n\n/**\n * Abstraction over the store that can be used to perform migrations.\n * @public\n */\nexport interface SynchronousRecordStorage<R extends UnknownRecord> {\n\tget(id: string): R | undefined\n\tset(id: string, record: R): void\n\tdelete(id: string): void\n\tkeys(): Iterable<string>\n\tvalues(): Iterable<R>\n\tentries(): Iterable<[string, R]>\n}\n\n/**\n * Abstraction over the storage that can be used to perform migrations.\n * @public\n */\nexport interface SynchronousStorage<R extends UnknownRecord> extends SynchronousRecordStorage<R> {\n\tgetSchema(): SerializedSchema\n\tsetSchema(schema: SerializedSchema): void\n}\n\n/**\n * Base interface for legacy migration information.\n *\n * Contains the basic structure used by the legacy migration system, including version\n * range information and the migration functions indexed by version number. This is\n * maintained for backward compatibility with older migration definitions.\n * @public\n */\nexport interface LegacyBaseMigrationsInfo {\n\tfirstVersion: number\n\tcurrentVersion: number\n\tmigrators: { [version: number]: LegacyMigration }\n}\n\n/**\n * Legacy migration configuration with support for sub-type migrations.\n *\n * This interface extends the base legacy migration info to support migrations that\n * vary based on a sub-type key within records. This allows different migration paths\n * for different variants of the same record type, which was useful in older migration\n * systems but is now handled more elegantly by the current Migration system.\n * @public\n */\nexport interface LegacyMigrations extends LegacyBaseMigrationsInfo {\n\tsubTypeKey?: string\n\tsubTypeMigrations?: Record<string, LegacyBaseMigrationsInfo>\n}\n\n/**\n * A complete sequence of migrations that can be applied to transform data.\n *\n * A migration sequence represents a series of ordered migrations that belong together,\n * typically for a specific part of your schema. The sequence includes metadata about\n * whether it should be applied retroactively to existing data and contains the actual\n * migration definitions in execution order.\n * @public\n */\nexport interface MigrationSequence {\n\tsequenceId: string\n\t/**\n\t * retroactive should be true if the migrations should be applied to snapshots that were created before\n\t * this migration sequence was added to the schema.\n\t *\n\t * In general:\n\t *\n\t * - retroactive should be true when app developers create their own new migration sequences.\n\t * - retroactive should be false when library developers ship a migration sequence. When you install a library for the first time, any migrations that were added in the library before that point should generally _not_ be applied to your existing data.\n\t */\n\tretroactive: boolean\n\tsequence: Migration[]\n}\n\n/**\n * Sorts migrations using a distance-minimizing topological sort.\n *\n * This function respects two types of dependencies:\n * 1. Implicit sequence dependencies (foo/1 must come before foo/2)\n * 2. Explicit dependencies via `dependsOn` property\n *\n * The algorithm minimizes the total distance between migrations and their explicit\n * dependencies in the final ordering, while maintaining topological correctness.\n * This means when migration A depends on migration B, A will be scheduled as close\n * as possible to B (while respecting all constraints).\n *\n * Implementation uses Kahn's algorithm with priority scoring:\n * - Builds dependency graph and calculates in-degrees\n * - Uses priority queue that prioritizes migrations which unblock explicit dependencies\n * - Processes migrations in urgency order while maintaining topological constraints\n * - Detects cycles by ensuring all migrations are processed\n *\n * @param migrations - Array of migrations to sort\n * @returns Sorted array of migrations in execution order\n * @throws Assertion error if circular dependencies are detected\n * @example\n * ```ts\n * const sorted = sortMigrations([\n * { id: 'app/2', scope: 'record', up: (r) => r },\n * { id: 'app/1', scope: 'record', up: (r) => r },\n * { id: 'lib/1', scope: 'record', up: (r) => r, dependsOn: ['app/1'] }\n * ])\n * // Result: [app/1, app/2, lib/1] (respects both sequence and explicit deps)\n * ```\n * @public\n */\nexport function sortMigrations(migrations: Migration[]): Migration[] {\n\tif (migrations.length === 0) return []\n\n\t// Build dependency graph and calculate in-degrees\n\tconst byId = new Map(migrations.map((m) => [m.id, m]))\n\tconst dependents = new Map<MigrationId, Set<MigrationId>>() // who depends on this\n\tconst inDegree = new Map<MigrationId, number>()\n\tconst explicitDeps = new Map<MigrationId, Set<MigrationId>>() // explicit dependsOn relationships\n\n\t// Initialize\n\tfor (const m of migrations) {\n\t\tinDegree.set(m.id, 0)\n\t\tdependents.set(m.id, new Set())\n\t\texplicitDeps.set(m.id, new Set())\n\t}\n\n\t// Add implicit sequence dependencies and explicit dependencies\n\tfor (const m of migrations) {\n\t\tconst { version, sequenceId } = parseMigrationId(m.id)\n\n\t\t// Implicit dependency on previous in sequence\n\t\tconst prevId = `${sequenceId}/${version - 1}` as MigrationId\n\t\tif (byId.has(prevId)) {\n\t\t\tdependents.get(prevId)!.add(m.id)\n\t\t\tinDegree.set(m.id, inDegree.get(m.id)! + 1)\n\t\t}\n\n\t\t// Explicit dependencies\n\t\tif (m.dependsOn) {\n\t\t\tfor (const depId of m.dependsOn) {\n\t\t\t\tif (byId.has(depId)) {\n\t\t\t\t\tdependents.get(depId)!.add(m.id)\n\t\t\t\t\texplicitDeps.get(m.id)!.add(depId)\n\t\t\t\t\tinDegree.set(m.id, inDegree.get(m.id)! + 1)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Priority queue: migrations ready to process (in-degree 0)\n\tconst ready = migrations.filter((m) => inDegree.get(m.id) === 0)\n\tconst result: Migration[] = []\n\tconst processed = new Set<MigrationId>()\n\n\twhile (ready.length > 0) {\n\t\t// Calculate urgency scores for ready migrations and pick the best one\n\t\tlet bestCandidate: Migration | undefined\n\t\tlet bestCandidateScore = -Infinity\n\n\t\tfor (const m of ready) {\n\t\t\tlet urgencyScore = 0\n\n\t\t\tfor (const depId of dependents.get(m.id) || []) {\n\t\t\t\tif (!processed.has(depId)) {\n\t\t\t\t\t// Priority 1: Count all unprocessed dependents (to break ties)\n\t\t\t\t\turgencyScore += 1\n\n\t\t\t\t\t// Priority 2: If this migration is explicitly depended on by others, boost priority\n\t\t\t\t\tif (explicitDeps.get(depId)!.has(m.id)) {\n\t\t\t\t\t\turgencyScore += 100\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\turgencyScore > bestCandidateScore ||\n\t\t\t\t// Tiebreaker: prefer lower sequence/version\n\t\t\t\t(urgencyScore === bestCandidateScore && m.id.localeCompare(bestCandidate?.id ?? '') < 0)\n\t\t\t) {\n\t\t\t\tbestCandidate = m\n\t\t\t\tbestCandidateScore = urgencyScore\n\t\t\t}\n\t\t}\n\n\t\tconst nextMigration = bestCandidate!\n\t\tready.splice(ready.indexOf(nextMigration), 1)\n\n\t\t// Cycle detection - if we have processed everything and still have items left, there's a cycle\n\t\t// This is handled by Kahn's algorithm naturally - if we finish with items unprocessed, there's a cycle\n\n\t\t// Process this migration\n\t\tresult.push(nextMigration)\n\t\tprocessed.add(nextMigration.id)\n\n\t\t// Update in-degrees and add newly ready migrations\n\t\tfor (const depId of dependents.get(nextMigration.id) || []) {\n\t\t\tif (!processed.has(depId)) {\n\t\t\t\tinDegree.set(depId, inDegree.get(depId)! - 1)\n\t\t\t\tif (inDegree.get(depId) === 0) {\n\t\t\t\t\tready.push(byId.get(depId)!)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for cycles - if we didn't process all migrations, there's a cycle\n\tif (result.length !== migrations.length) {\n\t\tconst unprocessed = migrations.filter((m) => !processed.has(m.id))\n\t\tassert(false, `Circular dependency in migrations: ${unprocessed[0].id}`)\n\t}\n\n\treturn result\n}\n\n/**\n * Parses a migration ID to extract the sequence ID and version number.\n *\n * Migration IDs follow the format `sequenceId/version`, and this function splits\n * them into their component parts. This is used internally for sorting migrations\n * and understanding their relationships.\n * @param id - The migration ID to parse\n * @returns Object containing the sequence ID and numeric version\n * @example\n * ```ts\n * const { sequenceId, version } = parseMigrationId('com.myapp.book/5')\n * // sequenceId: 'com.myapp.book', version: 5\n * ```\n * @internal\n */\nexport function parseMigrationId(id: MigrationId): { sequenceId: string; version: number } {\n\tconst [sequenceId, version] = id.split('/')\n\treturn { sequenceId, version: parseInt(version) }\n}\n\nfunction validateMigrationId(id: string, expectedSequenceId?: string) {\n\tif (expectedSequenceId) {\n\t\tassert(\n\t\t\tid.startsWith(expectedSequenceId + '/'),\n\t\t\t`Every migration in sequence '${expectedSequenceId}' must have an id starting with '${expectedSequenceId}/'. Got invalid id: '${id}'`\n\t\t)\n\t}\n\n\tassert(id.match(/^(.*?)\\/(0|[1-9]\\d*)$/), `Invalid migration id: '${id}'`)\n}\n\n/**\n * Validates that a migration sequence is correctly structured.\n *\n * Performs several validation checks to ensure the migration sequence is valid:\n * - Sequence ID doesn't contain invalid characters\n * - All migration IDs belong to the expected sequence\n * - Migration versions start at 1 and increment by 1\n * - Migration IDs follow the correct format\n * @param migrations - The migration sequence to validate\n * @throws Assertion error if any validation checks fail\n * @example\n * ```ts\n * const sequence = createMigrationSequence({\n * sequenceId: 'com.myapp.book',\n * sequence: [{ id: 'com.myapp.book/1', scope: 'record', up: (r) => r }]\n * })\n * validateMigrations(sequence) // Passes validation\n * ```\n * @public\n */\nexport function validateMigrations(migrations: MigrationSequence) {\n\tassert(\n\t\t!migrations.sequenceId.includes('/'),\n\t\t`sequenceId cannot contain a '/', got ${migrations.sequenceId}`\n\t)\n\tassert(migrations.sequenceId.length, 'sequenceId must be a non-empty string')\n\n\tif (migrations.sequence.length === 0) {\n\t\treturn\n\t}\n\n\tvalidateMigrationId(migrations.sequence[0].id, migrations.sequenceId)\n\tlet n = parseMigrationId(migrations.sequence[0].id).version\n\tassert(\n\t\tn === 1,\n\t\t`Expected the first migrationId to be '${migrations.sequenceId}/1' but got '${migrations.sequence[0].id}'`\n\t)\n\tfor (let i = 1; i < migrations.sequence.length; i++) {\n\t\tconst id = migrations.sequence[i].id\n\t\tvalidateMigrationId(id, migrations.sequenceId)\n\t\tconst m = parseMigrationId(id).version\n\t\tassert(\n\t\t\tm === n + 1,\n\t\t\t`Migration id numbers must increase in increments of 1, expected ${migrations.sequenceId}/${n + 1} but got '${migrations.sequence[i].id}'`\n\t\t)\n\t\tn = m\n\t}\n}\n\n/**\n * Result type returned by migration operations.\n *\n * Migration operations can either succeed and return the transformed value,\n * or fail with a specific reason. This discriminated union type allows for\n * safe handling of both success and error cases when applying migrations.\n * @public\n */\nexport type MigrationResult<T> =\n\t| { type: 'success'; value: T }\n\t| { type: 'error'; reason: MigrationFailureReason }\n\n/** @public */\nexport const MigrationFailureReason = {\n\tIncompatibleSubtype: 'incompatible-subtype',\n\tUnknownType: 'unknown-type',\n\tTargetVersionTooNew: 'target-version-too-new',\n\tTargetVersionTooOld: 'target-version-too-old',\n\tMigrationError: 'migration-error',\n\tUnrecognizedSubtype: 'unrecognized-subtype',\n} as const\n\n/** @public */\nexport type MigrationFailureReason =\n\t(typeof MigrationFailureReason)[keyof typeof MigrationFailureReason]\n\n// This is the magic part for backward compat:\n/** @public */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport declare namespace MigrationFailureReason {\n\texport type IncompatibleSubtype = typeof MigrationFailureReason.IncompatibleSubtype\n\texport type UnknownType = typeof MigrationFailureReason.UnknownType\n\texport type TargetVersionTooNew = typeof MigrationFailureReason.TargetVersionTooNew\n\texport type TargetVersionTooOld = typeof MigrationFailureReason.TargetVersionTooOld\n\texport type MigrationError = typeof MigrationFailureReason.MigrationError\n\texport type UnrecognizedSubtype = typeof MigrationFailureReason.UnrecognizedSubtype\n}\n","import { objectMapEntries } from '@ibodr/utils'\nimport { IdOf, UnknownRecord } from './BaseRecord'\n\n/**\n * A diff describing the changes to records, containing collections of records that were added,\n * updated, or removed. This is the fundamental data structure used throughout the store system\n * to track and communicate changes.\n *\n * @example\n * ```ts\n * const diff: RecordsDiff<Book> = {\n * added: {\n * 'book:1': { id: 'book:1', typeName: 'book', title: 'New Book' }\n * },\n * updated: {\n * 'book:2': [\n * { id: 'book:2', typeName: 'book', title: 'Old Title' }, // from\n * { id: 'book:2', typeName: 'book', title: 'New Title' } // to\n * ]\n * },\n * removed: {\n * 'book:3': { id: 'book:3', typeName: 'book', title: 'Deleted Book' }\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface RecordsDiff<R extends UnknownRecord> {\n\t/** Records that were created, keyed by their ID */\n\tadded: Record<IdOf<R>, R>\n\t/** Records that were modified, keyed by their ID. Each entry contains [from, to] tuple */\n\tupdated: Record<IdOf<R>, [from: R, to: R]>\n\t/** Records that were deleted, keyed by their ID */\n\tremoved: Record<IdOf<R>, R>\n}\n\n/**\n * Creates an empty RecordsDiff with no added, updated, or removed records.\n * This is useful as a starting point when building diffs programmatically.\n *\n * @returns An empty RecordsDiff with all collections initialized to empty objects\n * @example\n * ```ts\n * const emptyDiff = createEmptyRecordsDiff<Book>()\n * // Result: { added: {}, updated: {}, removed: {} }\n * ```\n *\n * @internal\n */\nexport function createEmptyRecordsDiff<R extends UnknownRecord>(): RecordsDiff<R> {\n\treturn { added: {}, updated: {}, removed: {} } as RecordsDiff<R>\n}\n\n/**\n * Creates the inverse of a RecordsDiff, effectively reversing all changes.\n * Added records become removed, removed records become added, and updated records\n * have their from/to values swapped. This is useful for implementing undo operations.\n *\n * @param diff - The diff to reverse\n * @returns A new RecordsDiff that represents the inverse of the input diff\n * @example\n * ```ts\n * const originalDiff: RecordsDiff<Book> = {\n * added: { 'book:1': newBook },\n * updated: { 'book:2': [oldBook, updatedBook] },\n * removed: { 'book:3': deletedBook }\n * }\n *\n * const reversedDiff = reverseRecordsDiff(originalDiff)\n * // Result: {\n * // added: { 'book:3': deletedBook },\n * // updated: { 'book:2': [updatedBook, oldBook] },\n * // removed: { 'book:1': newBook }\n * // }\n * ```\n *\n * @public\n */\nexport function reverseRecordsDiff(diff: RecordsDiff<any>) {\n\tconst result: RecordsDiff<any> = { added: diff.removed, removed: diff.added, updated: {} }\n\tfor (const [from, to] of Object.values(diff.updated)) {\n\t\tresult.updated[from.id] = [to, from]\n\t}\n\treturn result\n}\n\n/**\n * Checks whether a RecordsDiff contains any changes. A diff is considered empty\n * if it has no added, updated, or removed records.\n *\n * @param diff - The diff to check\n * @returns True if the diff contains no changes, false otherwise\n * @example\n * ```ts\n * const emptyDiff = createEmptyRecordsDiff<Book>()\n * console.log(isRecordsDiffEmpty(emptyDiff)) // true\n *\n * const nonEmptyDiff: RecordsDiff<Book> = {\n * added: { 'book:1': someBook },\n * updated: {},\n * removed: {}\n * }\n * console.log(isRecordsDiffEmpty(nonEmptyDiff)) // false\n * ```\n *\n * @public\n */\nexport function isRecordsDiffEmpty<T extends UnknownRecord>(diff: RecordsDiff<T>) {\n\treturn (\n\t\tObject.keys(diff.added).length === 0 &&\n\t\tObject.keys(diff.updated).length === 0 &&\n\t\tObject.keys(diff.removed).length === 0\n\t)\n}\n\n/**\n * Combines multiple RecordsDiff objects into a single consolidated diff.\n * This function intelligently merges changes, handling cases where the same record\n * is modified multiple times across different diffs. For example, if a record is\n * added in one diff and then updated in another, the result will show it as added\n * with the final state.\n *\n * @param diffs - An array of diffs to combine into a single diff\n * @param options - Configuration options for the squashing operation\n * - mutateFirstDiff - If true, modifies the first diff in place instead of creating a new one\n * @returns A single diff that represents the cumulative effect of all input diffs\n * @example\n * ```ts\n * const diff1: RecordsDiff<Book> = {\n * added: { 'book:1': { id: 'book:1', title: 'New Book' } },\n * updated: {},\n * removed: {}\n * }\n *\n * const diff2: RecordsDiff<Book> = {\n * added: {},\n * updated: { 'book:1': [{ id: 'book:1', title: 'New Book' }, { id: 'book:1', title: 'Updated Title' }] },\n * removed: {}\n * }\n *\n * const squashed = squashRecordDiffs([diff1, diff2])\n * // Result: {\n * // added: { 'book:1': { id: 'book:1', title: 'Updated Title' } },\n * // updated: {},\n * // removed: {}\n * // }\n * ```\n *\n * @public\n */\nexport function squashRecordDiffs<T extends UnknownRecord>(\n\tdiffs: RecordsDiff<T>[],\n\toptions?: {\n\t\tmutateFirstDiff?: boolean\n\t}\n): RecordsDiff<T> {\n\tconst result = options?.mutateFirstDiff\n\t\t? diffs[0]\n\t\t: ({ added: {}, removed: {}, updated: {} } as RecordsDiff<T>)\n\n\tsquashRecordDiffsMutable(result, options?.mutateFirstDiff ? diffs.slice(1) : diffs)\n\treturn result\n}\n\n/**\n * Applies an array of diffs to a target diff by mutating the target in-place.\n * This is the core implementation used by squashRecordDiffs. It handles complex\n * scenarios where records move between added/updated/removed states across multiple diffs.\n *\n * The function processes each diff sequentially, applying the following logic:\n * - Added records: If the record was previously removed, convert to an update; otherwise add it\n * - Updated records: Chain updates together, preserving the original 'from' state\n * - Removed records: If the record was added in this sequence, cancel both operations\n *\n * @param target - The diff to modify in-place (will be mutated)\n * @param diffs - Array of diffs to apply to the target\n * @example\n * ```ts\n * const targetDiff: RecordsDiff<Book> = {\n * added: {},\n * updated: {},\n * removed: { 'book:1': oldBook }\n * }\n *\n * const newDiffs = [{\n * added: { 'book:1': newBook },\n * updated: {},\n * removed: {}\n * }]\n *\n * squashRecordDiffsMutable(targetDiff, newDiffs)\n * // targetDiff is now: {\n * // added: {},\n * // updated: { 'book:1': [oldBook, newBook] },\n * // removed: {}\n * // }\n * ```\n *\n * @internal\n */\nexport function squashRecordDiffsMutable<T extends UnknownRecord>(\n\ttarget: RecordsDiff<T>,\n\tdiffs: RecordsDiff<T>[]\n): void {\n\tfor (const diff of diffs) {\n\t\tfor (const [id, value] of objectMapEntries(diff.added)) {\n\t\t\tif (target.removed[id]) {\n\t\t\t\tconst original = target.removed[id]\n\t\t\t\tdelete target.removed[id]\n\t\t\t\tif (original !== value) {\n\t\t\t\t\ttarget.updated[id] = [original, value]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttarget.added[id] = value\n\t\t\t}\n\t\t}\n\n\t\tfor (const [id, [_from, to]] of objectMapEntries(diff.updated)) {\n\t\t\tif (target.added[id]) {\n\t\t\t\ttarget.added[id] = to\n\t\t\t\tdelete target.updated[id]\n\t\t\t\tdelete target.removed[id]\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (target.updated[id]) {\n\t\t\t\ttarget.updated[id] = [target.updated[id][0], to]\n\t\t\t\tdelete target.removed[id]\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttarget.updated[id] = diff.updated[id]\n\t\t\tdelete target.removed[id]\n\t\t}\n\n\t\tfor (const [id, value] of objectMapEntries(diff.removed)) {\n\t\t\t// the same record was added in this diff sequence, just drop it\n\t\t\tif (target.added[id]) {\n\t\t\t\tdelete target.added[id]\n\t\t\t} else if (target.updated[id]) {\n\t\t\t\ttarget.removed[id] = target.updated[id][0]\n\t\t\t\tdelete target.updated[id]\n\t\t\t} else {\n\t\t\t\ttarget.removed[id] = value\n\t\t\t}\n\t\t}\n\t}\n}\n","import { Expand, objectMapEntries, structuredClone, uniqueId } from '@ibodr/utils'\nimport { IdOf, UnknownRecord } from './BaseRecord'\nimport { StoreValidator } from './Store'\n\n/**\n * Utility type that extracts the record type from a RecordType instance.\n *\n * @example\n * ```ts\n * const Book = createRecordType<BookRecord>('book', { scope: 'document' })\n * type BookFromType = RecordTypeRecord<typeof Book> // BookRecord\n * ```\n *\n * @public\n */\nexport type RecordTypeRecord<R extends RecordType<any, any>> = ReturnType<R['create']>\n\n/**\n * Defines the scope of the record\n *\n * session: The record belongs to a single instance of the store. It should not be synced, and any persistence logic should 'de-instance-ize' the record before persisting it, and apply the reverse when rehydrating.\n * document: The record is persisted and synced. It is available to all store instances.\n * presence: The record belongs to a single instance of the store. It may be synced to other instances, but other instances should not make changes to it. It should not be persisted.\n *\n * @public\n * */\nexport type RecordScope = 'session' | 'document' | 'presence'\n\n/**\n * A record type is a type that can be stored in a record store. It is created with\n * `createRecordType`.\n *\n * @public\n */\nexport class RecordType<\n\tR extends UnknownRecord,\n\tRequiredProperties extends keyof Omit<R, 'id' | 'typeName'>,\n> {\n\t/**\n\t * Factory function that creates default properties for new records.\n\t * @public\n\t */\n\treadonly createDefaultProperties: () => Exclude<Omit<R, 'id' | 'typeName'>, RequiredProperties>\n\n\t/**\n\t * Validator function used to validate records of this type.\n\t * @public\n\t */\n\treadonly validator: StoreValidator<R>\n\n\t/**\n\t * Optional configuration specifying which record properties are ephemeral.\n\t * Ephemeral properties are not included in snapshots or synchronization.\n\t * @public\n\t */\n\treadonly ephemeralKeys?: { readonly [K in Exclude<keyof R, 'id' | 'typeName'>]: boolean }\n\n\t/**\n\t * Set of property names that are marked as ephemeral for efficient lookup.\n\t * @public\n\t */\n\treadonly ephemeralKeySet: ReadonlySet<string>\n\n\t/**\n\t * The scope that determines how records of this type are persisted and synchronized.\n\t * @public\n\t */\n\treadonly scope: RecordScope\n\n\t/**\n\t * Creates a new RecordType instance.\n\t *\n\t * typeName - The unique type name for records created by this RecordType\n\t * config - Configuration object for the RecordType\n\t * - createDefaultProperties - Function that returns default properties for new records\n\t * - validator - Optional validator function for record validation\n\t * - scope - Optional scope determining persistence behavior (defaults to 'document')\n\t * - ephemeralKeys - Optional mapping of property names to ephemeral status\n\t * @public\n\t */\n\tconstructor(\n\t\t/**\n\t\t * The unique type associated with this record.\n\t\t *\n\t\t * @public\n\t\t * @readonly\n\t\t */\n\t\tpublic readonly typeName: R['typeName'],\n\t\tconfig: {\n\t\t\t// eslint-disable-next-line tldraw/method-signature-style\n\t\t\treadonly createDefaultProperties: () => Exclude<\n\t\t\t\tOmit<R, 'id' | 'typeName'>,\n\t\t\t\tRequiredProperties\n\t\t\t>\n\t\t\treadonly validator?: StoreValidator<R>\n\t\t\treadonly scope?: RecordScope\n\t\t\treadonly ephemeralKeys?: { readonly [K in Exclude<keyof R, 'id' | 'typeName'>]: boolean }\n\t\t}\n\t) {\n\t\tthis.createDefaultProperties = config.createDefaultProperties\n\t\tthis.validator = config.validator ?? { validate: (r: unknown) => r as R }\n\t\tthis.scope = config.scope ?? 'document'\n\t\tthis.ephemeralKeys = config.ephemeralKeys\n\n\t\tconst ephemeralKeySet = new Set<string>()\n\t\tif (config.ephemeralKeys) {\n\t\t\tfor (const [key, isEphemeral] of objectMapEntries(config.ephemeralKeys)) {\n\t\t\t\tif (isEphemeral) ephemeralKeySet.add(key as string)\n\t\t\t}\n\t\t}\n\t\tthis.ephemeralKeySet = ephemeralKeySet\n\t}\n\n\t/**\n\t * Creates a new record of this type with the given properties.\n\t *\n\t * Properties are merged with default properties from the RecordType configuration.\n\t * If no id is provided, a unique id will be generated automatically.\n\t *\n\t * @example\n\t * ```ts\n\t * const book = Book.create({\n\t * title: 'The Great Gatsby',\n\t * author: 'F. Scott Fitzgerald'\n\t * })\n\t * // Result: { id: 'book:abc123', typeName: 'book', title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', inStock: true }\n\t * ```\n\t *\n\t * @param properties - The properties for the new record, including both required and optional fields\n\t * @returns The newly created record with generated id and typeName\n\t * @public\n\t */\n\tcreate(\n\t\tproperties: Expand<Pick<R, RequiredProperties> & Omit<Partial<R>, RequiredProperties>>\n\t): R {\n\t\tconst result = {\n\t\t\t...this.createDefaultProperties(),\n\t\t\tid: 'id' in properties ? properties.id : this.createId(),\n\t\t} as any\n\n\t\tfor (const [k, v] of Object.entries(properties)) {\n\t\t\tif (v !== undefined) {\n\t\t\t\tresult[k] = v\n\t\t\t}\n\t\t}\n\n\t\tresult.typeName = this.typeName\n\n\t\treturn result as R\n\t}\n\n\t/**\n\t * Creates a deep copy of an existing record with a new unique id.\n\t *\n\t * This method performs a deep clone of all properties while generating a fresh id,\n\t * making it useful for duplicating records without id conflicts.\n\t *\n\t * @example\n\t * ```ts\n\t * const originalBook = Book.create({ title: '1984', author: 'George Orwell' })\n\t * const duplicatedBook = Book.clone(originalBook)\n\t * // duplicatedBook has same properties but different id\n\t * ```\n\t *\n\t * @param record - The record to clone\n\t * @returns A new record with the same properties but a different id\n\t * @public\n\t */\n\tclone(record: R): R {\n\t\treturn { ...structuredClone(record), id: this.createId() }\n\t}\n\n\t/**\n\t * Create a new ID for this record type.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * const id = recordType.createId()\n\t * ```\n\t *\n\t * @returns The new ID.\n\t * @public\n\t */\n\tcreateId(customUniquePart?: string): IdOf<R> {\n\t\treturn (this.typeName + ':' + (customUniquePart ?? uniqueId())) as IdOf<R>\n\t}\n\n\t/**\n\t * Extracts the unique identifier part from a full record id.\n\t *\n\t * Record ids have the format `typeName:uniquePart`. This method returns just the unique part.\n\t *\n\t * @example\n\t * ```ts\n\t * const bookId = Book.createId() // 'book:abc123'\n\t * const uniquePart = Book.parseId(bookId) // 'abc123'\n\t * ```\n\t *\n\t * @param id - The full record id to parse\n\t * @returns The unique identifier portion after the colon\n\t * @throws Error if the id is not valid for this record type\n\t * @public\n\t */\n\tparseId(id: IdOf<R>): string {\n\t\tif (!this.isId(id)) {\n\t\t\tthrow new Error(`ID \"${id}\" is not a valid ID for type \"${this.typeName}\"`)\n\t\t}\n\n\t\treturn id.slice(this.typeName.length + 1)\n\t}\n\n\t/**\n\t * Type guard that checks whether a record belongs to this RecordType.\n\t *\n\t * This method performs a runtime check by comparing the record's typeName\n\t * against this RecordType's typeName.\n\t *\n\t * @example\n\t * ```ts\n\t * if (Book.isInstance(someRecord)) {\n\t * // someRecord is now typed as a book record\n\t * console.log(someRecord.title)\n\t * }\n\t * ```\n\t *\n\t * @param record - The record to check, may be undefined\n\t * @returns True if the record is an instance of this record type\n\t * @public\n\t */\n\tisInstance(record?: UnknownRecord): record is R {\n\t\treturn record?.typeName === this.typeName\n\t}\n\n\t/**\n\t * Type guard that checks whether an id string belongs to this RecordType.\n\t *\n\t * Validates that the id starts with this RecordType's typeName followed by a colon.\n\t * This is more efficient than parsing the full id when you only need to verify the type.\n\t *\n\t * @example\n\t * ```ts\n\t * if (Book.isId(someId)) {\n\t * // someId is now typed as IdOf<BookRecord>\n\t * const book = store.get(someId)\n\t * }\n\t * ```\n\t *\n\t * @param id - The id string to check, may be undefined\n\t * @returns True if the id belongs to this record type\n\t * @public\n\t */\n\tisId(id?: string): id is IdOf<R> {\n\t\tif (!id) return false\n\t\tfor (let i = 0; i < this.typeName.length; i++) {\n\t\t\tif (id[i] !== this.typeName[i]) return false\n\t\t}\n\n\t\treturn id[this.typeName.length] === ':'\n\t}\n\n\t/**\n\t * Create a new RecordType that has the same type name as this RecordType and includes the given\n\t * default properties.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * const authorType = createRecordType('author', () => ({ living: true }))\n\t * const deadAuthorType = authorType.withDefaultProperties({ living: false })\n\t * ```\n\t *\n\t * @param createDefaultProperties - A function that returns the default properties of the new RecordType.\n\t * @returns The new RecordType.\n\t */\n\twithDefaultProperties<DefaultProps extends Omit<Partial<R>, 'typeName' | 'id'>>(\n\t\tcreateDefaultProperties: () => DefaultProps\n\t): RecordType<R, Exclude<RequiredProperties, keyof DefaultProps>> {\n\t\treturn new RecordType<R, Exclude<RequiredProperties, keyof DefaultProps>>(this.typeName, {\n\t\t\tcreateDefaultProperties: createDefaultProperties as any,\n\t\t\tvalidator: this.validator,\n\t\t\tscope: this.scope,\n\t\t\tephemeralKeys: this.ephemeralKeys,\n\t\t})\n\t}\n\n\t/**\n\t * Validates a record against this RecordType's validator and returns it with proper typing.\n\t *\n\t * This method runs the configured validator function and throws an error if validation fails.\n\t * If a previous version of the record is provided, it may use optimized validation.\n\t *\n\t * @example\n\t * ```ts\n\t * try {\n\t * const validBook = Book.validate(untrustedData)\n\t * // validBook is now properly typed and validated\n\t * } catch (error) {\n\t * console.log('Validation failed:', error.message)\n\t * }\n\t * ```\n\t *\n\t * @param record - The unknown record data to validate\n\t * @param recordBefore - Optional previous version for optimized validation\n\t * @returns The validated and properly typed record\n\t * @throws Error if validation fails\n\t * @public\n\t */\n\tvalidate(record: unknown, recordBefore?: R): R {\n\t\tif (recordBefore && this.validator.validateUsingKnownGoodVersion) {\n\t\t\treturn this.validator.validateUsingKnownGoodVersion(recordBefore, record)\n\t\t}\n\t\treturn this.validator.validate(record)\n\t}\n}\n\n/**\n * Creates a new RecordType with the specified configuration.\n *\n * This factory function creates a RecordType that can be used to create, validate, and manage\n * records of a specific type within a store. The resulting RecordType can be extended with\n * default properties using the withDefaultProperties method.\n *\n * @example\n * ```ts\n * interface BookRecord extends BaseRecord<'book', RecordId<BookRecord>> {\n * title: string\n * author: string\n * inStock: boolean\n * }\n *\n * const Book = createRecordType<BookRecord>('book', {\n * scope: 'document',\n * validator: bookValidator\n * })\n * ```\n *\n * @param typeName - The unique type name for this record type\n * @param config - Configuration object containing validator, scope, and ephemeral keys\n * @returns A new RecordType instance for creating and managing records\n * @public\n */\nexport function createRecordType<R extends UnknownRecord>(\n\ttypeName: R['typeName'],\n\tconfig: {\n\t\tvalidator?: StoreValidator<R>\n\t\tscope: RecordScope\n\t\tephemeralKeys?: { readonly [K in Exclude<keyof R, 'id' | 'typeName'>]: boolean }\n\t}\n): RecordType<R, keyof Omit<R, 'id' | 'typeName'>> {\n\treturn new RecordType<R, keyof Omit<R, 'id' | 'typeName'>>(typeName, {\n\t\tcreateDefaultProperties: () => ({}) as any,\n\t\tvalidator: config.validator,\n\t\tscope: config.scope,\n\t\tephemeralKeys: config.ephemeralKeys,\n\t})\n}\n\n/**\n * Assert whether an id correspond to a record type.\n *\n * @example\n *\n * ```ts\n * assertIdType(myId, \"shape\")\n * ```\n *\n * @param id - The id to check.\n * @param type - The type of the record.\n * @public\n */\nexport function assertIdType<R extends UnknownRecord>(\n\tid: string | undefined,\n\ttype: RecordType<R, any>\n): asserts id is IdOf<R> {\n\tif (!id || !type.isId(id)) {\n\t\tthrow new Error(`string ${JSON.stringify(id)} is not a valid ${type.typeName} id`)\n\t}\n}\n","import { CollectionDiff } from './Store'\n\n/**\n * Combine multiple sets into a single set containing only the common elements of all sets.\n * Returns the intersection of all provided sets - elements that exist in every set.\n * If no sets are provided, returns an empty set.\n *\n * @param sets - The sets to intersect. Can be an empty array.\n * @returns A new set containing only elements that exist in all input sets\n *\n * @example\n * ```ts\n * const set1 = new Set([1, 2, 3])\n * const set2 = new Set([2, 3, 4])\n * const set3 = new Set([3, 4, 5])\n *\n * const intersection = intersectSets([set1, set2, set3])\n * console.log(intersection) // Set {3}\n *\n * // Empty array returns empty set\n * const empty = intersectSets([])\n * console.log(empty) // Set {}\n * ```\n *\n * @public\n */\nexport function intersectSets<T>(sets: Set<T>[]) {\n\tif (sets.length === 0) return new Set<T>()\n\tconst first = sets[0]\n\tconst rest = sets.slice(1)\n\tconst result = new Set<T>()\n\n\tfor (const val of first) {\n\t\tif (rest.every((set) => set.has(val))) {\n\t\t\tresult.add(val)\n\t\t}\n\t}\n\n\treturn result\n}\n\n/**\n * Calculates a diff between two sets, identifying which elements were added or removed.\n * Returns undefined if the sets are identical (no changes detected).\n *\n * @param prev - The previous set to compare from\n * @param next - The next set to compare to\n * @returns A CollectionDiff object with `added` and/or `removed` sets, or undefined if no changes\n *\n * @example\n * ```ts\n * const prev = new Set(['a', 'b', 'c'])\n * const next = new Set(['b', 'c', 'd'])\n *\n * const diff = diffSets(prev, next)\n * console.log(diff)\n * // {\n * // added: Set {'d'},\n * // removed: Set {'a'}\n * // }\n *\n * // No changes returns undefined\n * const same = diffSets(prev, prev)\n * console.log(same) // undefined\n * ```\n *\n * @public\n */\nexport function diffSets<T>(prev: Set<T>, next: Set<T>): CollectionDiff<T> | undefined {\n\tconst result: CollectionDiff<T> = {}\n\n\tfor (const val of next) {\n\t\tif (!prev.has(val)) {\n\t\t\tresult.added ??= new Set()\n\t\t\tresult.added.add(val)\n\t\t}\n\t}\n\n\tfor (const val of prev) {\n\t\tif (!next.has(val)) {\n\t\t\tresult.removed ??= new Set()\n\t\t\tresult.removed.add(val)\n\t\t}\n\t}\n\n\treturn result.added || result.removed ? result : undefined\n}\n","import { IdOf, UnknownRecord } from './BaseRecord'\nimport { intersectSets } from './setUtils'\nimport { StoreQueries } from './StoreQueries'\n\n/**\n * Defines matching criteria for query values. Supports equality, inequality, and greater-than comparisons.\n *\n * @example\n * ```ts\n * // Exact match\n * const exactMatch: QueryValueMatcher<string> = { eq: 'Science Fiction' }\n *\n * // Not equal to\n * const notMatch: QueryValueMatcher<string> = { neq: 'Romance' }\n *\n * // Greater than (numeric values only)\n * const greaterThan: QueryValueMatcher<number> = { gt: 2020 }\n * ```\n *\n * @public\n */\nexport type QueryValueMatcher<T> = { eq: T } | { neq: T } | { gt: number }\n\n/**\n * Query expression for filtering records by their property values. Maps record property names\n * to matching criteria.\n *\n * @example\n * ```ts\n * // Query for books published after 2020 that are in stock\n * const bookQuery: QueryExpression<Book> = {\n * publishedYear: { gt: 2020 },\n * inStock: { eq: true }\n * }\n *\n * // Query for books not by a specific author\n * const notByAuthor: QueryExpression<Book> = {\n * authorId: { neq: 'author:tolkien' }\n * }\n *\n * // Query with nested properties\n * const nestedQuery: QueryExpression<Book> = {\n * metadata: { sessionId: { eq: 'session:alpha' } }\n * }\n * ```\n *\n * @public\n */\n/** @public */\nexport type QueryExpression<R extends object> = {\n\t[k in keyof R & string]?: R[k] extends string | number | boolean | null | undefined\n\t\t? QueryValueMatcher<R[k]>\n\t\t: R[k] extends object\n\t\t\t? QueryExpression<R[k]>\n\t\t\t: QueryValueMatcher<R[k]>\n}\n\nfunction isQueryValueMatcher(value: unknown): value is QueryValueMatcher<unknown> {\n\tif (typeof value !== 'object' || value === null) return false\n\treturn 'eq' in value || 'neq' in value || 'gt' in value\n}\n\nfunction extractMatcherPaths(\n\tquery: QueryExpression<any>,\n\tprefix: string = ''\n): Array<{ path: string; matcher: QueryValueMatcher<any> }> {\n\tconst paths: Array<{ path: string; matcher: QueryValueMatcher<any> }> = []\n\n\tfor (const [key, value] of Object.entries(query)) {\n\t\tconst currentPath = prefix ? `${prefix}\\\\${key}` : key\n\n\t\tif (isQueryValueMatcher(value)) {\n\t\t\t// It's a direct matcher\n\t\t\tpaths.push({ path: currentPath, matcher: value })\n\t\t} else if (typeof value === 'object' && value !== null) {\n\t\t\t// It's a nested query - recurse into it\n\t\t\tpaths.push(...extractMatcherPaths(value as QueryExpression<any>, currentPath))\n\t\t}\n\t}\n\n\treturn paths\n}\n\nexport function objectMatchesQuery<T extends object>(query: QueryExpression<T>, object: T) {\n\tfor (const [key, matcher] of Object.entries(query)) {\n\t\tconst value = object[key as keyof T]\n\n\t\t// if you add matching logic here, make sure you also update executeQuery,\n\t\t// where initial data is pulled out of the indexes, since that requires different\n\t\t// matching logic\n\t\tif (isQueryValueMatcher(matcher)) {\n\t\t\tif ('eq' in matcher && value !== matcher.eq) return false\n\t\t\tif ('neq' in matcher && value === matcher.neq) return false\n\t\t\tif ('gt' in matcher && (typeof value !== 'number' || value <= matcher.gt)) return false\n\t\t\tcontinue\n\t\t}\n\n\t\t// It's a nested query\n\t\tif (typeof value !== 'object' || value === null) return false\n\t\tif (!objectMatchesQuery(matcher as QueryExpression<any>, value as any)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n/**\n * Executes a query against the store using reactive indexes to efficiently find matching record IDs.\n * Uses the store's internal indexes for optimal performance, especially for equality matches.\n *\n * @param store - The store queries interface providing access to reactive indexes\n * @param typeName - The type name of records to query (e.g., 'book', 'author')\n * @param query - Query expression defining the matching criteria\n * @returns A Set containing the IDs of all records that match the query criteria\n *\n * @example\n * ```ts\n * // Find IDs of all books published after 2020 that are in stock\n * const bookIds = executeQuery(store, 'book', {\n * publishedYear: { gt: 2020 },\n * inStock: { eq: true }\n * })\n *\n * // Find IDs of books not by a specific author\n * const otherBookIds = executeQuery(store, 'book', {\n * authorId: { neq: 'author:tolkien' }\n * })\n *\n * // Query with nested properties\n * const nestedQueryIds = executeQuery(store, 'book', {\n * metadata: { sessionId: { eq: 'session:alpha' } }\n * })\n * ```\n *\n * @public\n */\nexport function executeQuery<R extends UnknownRecord, TypeName extends R['typeName']>(\n\tstore: StoreQueries<R>,\n\ttypeName: TypeName,\n\tquery: QueryExpression<Extract<R, { typeName: TypeName }>>\n): Set<IdOf<Extract<R, { typeName: TypeName }>>> {\n\ttype S = Extract<R, { typeName: TypeName }>\n\n\t// Extract all paths with matchers (flattens nested queries)\n\tconst matcherPaths = extractMatcherPaths(query)\n\n\t// Build a set of matching IDs for each path\n\tconst matchIds = Object.fromEntries(matcherPaths.map(({ path }) => [path, new Set<IdOf<S>>()]))\n\n\t// For each path, use the index to find matching IDs\n\tfor (const { path, matcher } of matcherPaths) {\n\t\tconst index = store.index(typeName, path as any)\n\n\t\tif ('eq' in matcher) {\n\t\t\tconst ids = index.get().get(matcher.eq)\n\t\t\tif (ids) {\n\t\t\t\tfor (const id of ids) {\n\t\t\t\t\tmatchIds[path].add(id)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if ('neq' in matcher) {\n\t\t\tfor (const [value, ids] of index.get()) {\n\t\t\t\tif (value !== matcher.neq) {\n\t\t\t\t\tfor (const id of ids) {\n\t\t\t\t\t\tmatchIds[path].add(id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if ('gt' in matcher) {\n\t\t\tfor (const [value, ids] of index.get()) {\n\t\t\t\tif (typeof value === 'number' && value > matcher.gt) {\n\t\t\t\t\tfor (const id of ids) {\n\t\t\t\t\t\tmatchIds[path].add(id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Short-circuit if this set is empty - intersection will be empty\n\t\tif (matchIds[path].size === 0) {\n\t\t\treturn new Set()\n\t\t}\n\t}\n\n\t// Intersect all the match sets\n\treturn intersectSets(Object.values(matchIds)) as Set<IdOf<S>>\n}\n","import {\n\tAtom,\n\tcomputed,\n\tComputed,\n\tEMPTY_ARRAY,\n\tisUninitialized,\n\tRESET_VALUE,\n\twithDiff,\n} from '@ibodr/state'\nimport { areArraysShallowEqual, isEqual, objectMapValues } from '@ibodr/utils'\nimport { AtomMap } from './AtomMap'\nimport { IdOf, UnknownRecord } from './BaseRecord'\nimport { executeQuery, objectMatchesQuery, QueryExpression } from './executeQuery'\nimport { IncrementalSetConstructor } from './IncrementalSetConstructor'\nimport { RecordsDiff } from './RecordsDiff'\nimport { diffSets } from './setUtils'\nimport { CollectionDiff } from './Store'\n\n/**\n * A type representing the diff of changes to a reactive store index.\n * Maps property values to the collection differences for record IDs that have that property value.\n *\n * @example\n * ```ts\n * // For an index on book titles, the diff might look like:\n * const titleIndexDiff: RSIndexDiff<Book, 'title'> = new Map([\n * ['The Lathe of Heaven', { added: new Set(['book:1']), removed: new Set() }],\n * ['Animal Farm', { added: new Set(), removed: new Set(['book:2']) }]\n * ])\n * ```\n *\n * @public\n */\nexport type RSIndexDiff<R extends UnknownRecord> = Map<any, CollectionDiff<IdOf<R>>>\n\n/**\n * A type representing a reactive store index as a map from property values to sets of record IDs.\n * This is used to efficiently look up records by a specific property value.\n *\n * @example\n * ```ts\n * // Index mapping book titles to the IDs of books with that title\n * const titleIndex: RSIndexMap<Book, 'title'> = new Map([\n * ['The Lathe of Heaven', new Set(['book:1'])],\n * ['Animal Farm', new Set(['book:2', 'book:3'])]\n * ])\n * ```\n *\n * @public\n */\nexport type RSIndexMap<R extends UnknownRecord> = Map<any, Set<IdOf<R>>>\n\n/**\n * A reactive computed index that provides efficient lookups of records by property values.\n * Returns a computed value containing an RSIndexMap with diffs for change tracking.\n *\n * @example\n * ```ts\n * // Create an index on book authors\n * const authorIndex: RSIndex<Book, 'authorId'> = store.query.index('book', 'authorId')\n *\n * // Get all books by a specific author\n * const leguinBooks = authorIndex.get().get('author:leguin')\n * ```\n *\n * @public\n */\nexport type RSIndex<R extends UnknownRecord> = Computed<RSIndexMap<R>, RSIndexDiff<R>>\n\n/**\n * A class that provides reactive querying capabilities for a record store.\n * Offers methods to create indexes, filter records, and perform efficient lookups with automatic cache management.\n * All queries are reactive and will automatically update when the underlying store data changes.\n *\n * @example\n * ```ts\n * // Create a store with books\n * const store = new Store({ schema: StoreSchema.create({ book: Book, author: Author }) })\n *\n * // Get reactive queries for books\n * const booksByAuthor = store.query.index('book', 'authorId')\n * const inStockBooks = store.query.records('book', () => ({ inStock: { eq: true } }))\n * ```\n *\n * @public\n */\nexport class StoreQueries<R extends UnknownRecord> {\n\t/**\n\t * Creates a new StoreQueries instance.\n\t *\n\t * recordMap - The atom map containing all records in the store\n\t * history - The atom tracking the store's change history with diffs\n\t *\n\t * @internal\n\t */\n\tconstructor(\n\t\tprivate readonly recordMap: AtomMap<IdOf<R>, R>,\n\t\tprivate readonly history: Atom<number, RecordsDiff<R>>\n\t) {}\n\n\t/**\n\t * A cache of derivations (indexes).\n\t *\n\t * @internal\n\t */\n\tprivate indexCache = new Map<string, RSIndex<R>>()\n\n\t/**\n\t * A cache of derivations (filtered histories).\n\t *\n\t * @internal\n\t */\n\tprivate historyCache = new Map<string, Computed<number, RecordsDiff<R>>>()\n\n\t/**\n\t * @internal\n\t */\n\tpublic getAllIdsForType<TypeName extends R['typeName']>(\n\t\ttypeName: TypeName\n\t): Set<IdOf<Extract<R, { typeName: TypeName }>>> {\n\t\ttype S = Extract<R, { typeName: TypeName }>\n\t\tconst ids = new Set<IdOf<S>>()\n\t\tfor (const record of this.recordMap.values()) {\n\t\t\tif (record.typeName === typeName) {\n\t\t\t\tids.add(record.id as IdOf<S>)\n\t\t\t}\n\t\t}\n\t\treturn ids\n\t}\n\n\t/**\n\t * @internal\n\t */\n\tpublic getRecordById<TypeName extends R['typeName']>(\n\t\ttypeName: TypeName,\n\t\tid: IdOf<Extract<R, { typeName: TypeName }>>\n\t): Extract<R, { typeName: TypeName }> | undefined {\n\t\tconst record = this.recordMap.get(id as IdOf<R>)\n\t\tif (record && record.typeName === typeName) {\n\t\t\treturn record as Extract<R, { typeName: TypeName }>\n\t\t}\n\t\treturn undefined\n\t}\n\n\t/**\n\t * Helper to extract nested property value using pre-split path parts.\n\t * @internal\n\t */\n\tprivate getNestedValue(obj: any, pathParts: string[]): any {\n\t\tlet current = obj\n\t\tfor (const part of pathParts) {\n\t\t\tif (current == null || typeof current !== 'object') return undefined\n\t\t\tcurrent = current[part]\n\t\t}\n\t\treturn current\n\t}\n\n\t/**\n\t * Creates a reactive computed that tracks the change history for records of a specific type.\n\t * The returned computed provides incremental diffs showing what records of the given type\n\t * have been added, updated, or removed.\n\t *\n\t * @param typeName - The type name to filter the history by\n\t * @returns A computed value containing the current epoch and diffs of changes for the specified type\n\t *\n\t * @example\n\t * ```ts\n\t * // Track changes to book records only\n\t * const bookHistory = store.query.filterHistory('book')\n\t *\n\t * // React to book changes\n\t * react('book-changes', () => {\n\t * const currentEpoch = bookHistory.get()\n\t * console.log('Books updated at epoch:', currentEpoch)\n\t * })\n\t * ```\n\t *\n\t * @public\n\t */\n\tpublic filterHistory<TypeName extends R['typeName']>(\n\t\ttypeName: TypeName\n\t): Computed<number, RecordsDiff<Extract<R, { typeName: TypeName }>>> {\n\t\ttype S = Extract<R, { typeName: TypeName }>\n\n\t\tif (this.historyCache.has(typeName)) {\n\t\t\treturn this.historyCache.get(typeName) as any\n\t\t}\n\n\t\tconst filtered = computed<number, RecordsDiff<S>>(\n\t\t\t'filterHistory:' + typeName,\n\t\t\t(lastValue, lastComputedEpoch) => {\n\t\t\t\tif (isUninitialized(lastValue)) {\n\t\t\t\t\treturn this.history.get()\n\t\t\t\t}\n\n\t\t\t\tconst diff = this.history.getDiffSince(lastComputedEpoch)\n\t\t\t\tif (diff === RESET_VALUE) return this.history.get()\n\n\t\t\t\tconst res = { added: {}, removed: {}, updated: {} } as RecordsDiff<S>\n\t\t\t\tlet numAdded = 0\n\t\t\t\tlet numRemoved = 0\n\t\t\t\tlet numUpdated = 0\n\n\t\t\t\tfor (const changes of diff) {\n\t\t\t\t\tfor (const added of objectMapValues(changes.added)) {\n\t\t\t\t\t\tif (added.typeName === typeName) {\n\t\t\t\t\t\t\tif (res.removed[added.id as IdOf<S>]) {\n\t\t\t\t\t\t\t\tconst original = res.removed[added.id as IdOf<S>]\n\t\t\t\t\t\t\t\tdelete res.removed[added.id as IdOf<S>]\n\t\t\t\t\t\t\t\tnumRemoved--\n\t\t\t\t\t\t\t\tif (original !== added) {\n\t\t\t\t\t\t\t\t\tres.updated[added.id as IdOf<S>] = [original, added as S]\n\t\t\t\t\t\t\t\t\tnumUpdated++\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tres.added[added.id as IdOf<S>] = added as S\n\t\t\t\t\t\t\t\tnumAdded++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const [from, to] of objectMapValues(changes.updated)) {\n\t\t\t\t\t\tif (to.typeName === typeName) {\n\t\t\t\t\t\t\tif (res.added[to.id as IdOf<S>]) {\n\t\t\t\t\t\t\t\tres.added[to.id as IdOf<S>] = to as S\n\t\t\t\t\t\t\t} else if (res.updated[to.id as IdOf<S>]) {\n\t\t\t\t\t\t\t\tres.updated[to.id as IdOf<S>] = [res.updated[to.id as IdOf<S>][0], to as S]\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tres.updated[to.id as IdOf<S>] = [from as S, to as S]\n\t\t\t\t\t\t\t\tnumUpdated++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const removed of objectMapValues(changes.removed)) {\n\t\t\t\t\t\tif (removed.typeName === typeName) {\n\t\t\t\t\t\t\tif (res.added[removed.id as IdOf<S>]) {\n\t\t\t\t\t\t\t\t// was added during this diff sequence, so just undo the add\n\t\t\t\t\t\t\t\tdelete res.added[removed.id as IdOf<S>]\n\t\t\t\t\t\t\t\tnumAdded--\n\t\t\t\t\t\t\t} else if (res.updated[removed.id as IdOf<S>]) {\n\t\t\t\t\t\t\t\t// remove oldest version\n\t\t\t\t\t\t\t\tres.removed[removed.id as IdOf<S>] = res.updated[removed.id as IdOf<S>][0]\n\t\t\t\t\t\t\t\tdelete res.updated[removed.id as IdOf<S>]\n\t\t\t\t\t\t\t\tnumUpdated--\n\t\t\t\t\t\t\t\tnumRemoved++\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tres.removed[removed.id as IdOf<S>] = removed as S\n\t\t\t\t\t\t\t\tnumRemoved++\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\n\t\t\t\tif (numAdded || numRemoved || numUpdated) {\n\t\t\t\t\treturn withDiff(this.history.get(), res)\n\t\t\t\t} else {\n\t\t\t\t\treturn lastValue\n\t\t\t\t}\n\t\t\t},\n\t\t\t{ historyLength: 100 }\n\t\t)\n\n\t\tthis.historyCache.set(typeName, filtered)\n\n\t\treturn filtered\n\t}\n\n\t/**\n\t * Creates a reactive index that maps property values to sets of record IDs for efficient lookups.\n\t * The index automatically updates when records are added, updated, or removed, and results are cached\n\t * for performance.\n\t *\n\t * Supports nested property paths using backslash separator (e.g., 'metadata\\\\sessionId').\n\t *\n\t * @param typeName - The type name of records to index\n\t * @param path - The property name or backslash-delimited path to index by\n\t * @returns A reactive computed containing the index map with change diffs\n\t *\n\t * @example\n\t * ```ts\n\t * // Create an index of books by author ID\n\t * const booksByAuthor = store.query.index('book', 'authorId')\n\t *\n\t * // Get all books by a specific author\n\t * const authorBooks = booksByAuthor.get().get('author:leguin')\n\t * console.log(authorBooks) // Set<RecordId<Book>>\n\t *\n\t * // Index by nested property using backslash separator\n\t * const booksBySession = store.query.index('book', 'metadata\\\\sessionId')\n\t * const sessionBooks = booksBySession.get().get('session:alpha')\n\t * ```\n\t *\n\t * @public\n\t */\n\tpublic index<TypeName extends R['typeName']>(\n\t\ttypeName: TypeName,\n\t\tpath: string\n\t): RSIndex<Extract<R, { typeName: TypeName }>> {\n\t\tconst cacheKey = typeName + ':' + path\n\n\t\tif (this.indexCache.has(cacheKey)) {\n\t\t\treturn this.indexCache.get(cacheKey) as any\n\t\t}\n\n\t\tconst index = this.__uncached_createIndex(typeName, path)\n\n\t\tthis.indexCache.set(cacheKey, index as any)\n\n\t\treturn index\n\t}\n\n\t/**\n\t * Creates a new index without checking the cache. This method performs the actual work\n\t * of building the reactive index computation that tracks property values to record ID sets.\n\t *\n\t * Supports nested property paths using backslash separator.\n\t *\n\t * @param typeName - The type name of records to index\n\t * @param path - The property name or backslash-delimited path to index by\n\t * @returns A reactive computed containing the index map with change diffs\n\t *\n\t * @internal\n\t */\n\t__uncached_createIndex<TypeName extends R['typeName']>(\n\t\ttypeName: TypeName,\n\t\tpath: string\n\t): RSIndex<Extract<R, { typeName: TypeName }>> {\n\t\ttype S = Extract<R, { typeName: TypeName }>\n\n\t\tconst typeHistory = this.filterHistory(typeName)\n\n\t\t// Create closure for efficient property value extraction\n\t\tconst pathParts = path.split('\\\\')\n\t\tconst getPropertyValue =\n\t\t\tpathParts.length > 1\n\t\t\t\t? (obj: S) => this.getNestedValue(obj, pathParts)\n\t\t\t\t: (obj: S) => obj[path as keyof S]\n\n\t\tconst fromScratch = () => {\n\t\t\t// deref typeHistory early so that the first time the incremental version runs\n\t\t\t// it gets a diff to work with instead of having to bail to this from-scratch version\n\t\t\ttypeHistory.get()\n\t\t\tconst res = new Map<any, Set<IdOf<S>>>()\n\t\t\tfor (const record of this.recordMap.values()) {\n\t\t\t\tif (record.typeName === typeName) {\n\t\t\t\t\tconst value = getPropertyValue(record as S)\n\t\t\t\t\tif (value !== undefined) {\n\t\t\t\t\t\tif (!res.has(value)) {\n\t\t\t\t\t\t\tres.set(value, new Set())\n\t\t\t\t\t\t}\n\t\t\t\t\t\tres.get(value)!.add(record.id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn res\n\t\t}\n\n\t\treturn computed<RSIndexMap<S>, RSIndexDiff<S>>(\n\t\t\t'index:' + typeName + ':' + path,\n\t\t\t(prevValue, lastComputedEpoch) => {\n\t\t\t\tif (isUninitialized(prevValue)) return fromScratch()\n\n\t\t\t\tconst history = typeHistory.getDiffSince(lastComputedEpoch)\n\t\t\t\tif (history === RESET_VALUE) {\n\t\t\t\t\treturn fromScratch()\n\t\t\t\t}\n\n\t\t\t\tconst setConstructors = new Map<any, IncrementalSetConstructor<IdOf<S>>>()\n\n\t\t\t\tconst add = (value: any, id: IdOf<S>) => {\n\t\t\t\t\tlet setConstructor = setConstructors.get(value)\n\t\t\t\t\tif (!setConstructor)\n\t\t\t\t\t\tsetConstructor = new IncrementalSetConstructor<IdOf<S>>(\n\t\t\t\t\t\t\tprevValue.get(value) ?? new Set()\n\t\t\t\t\t\t)\n\t\t\t\t\tsetConstructor.add(id)\n\t\t\t\t\tsetConstructors.set(value, setConstructor)\n\t\t\t\t}\n\n\t\t\t\tconst remove = (value: any, id: IdOf<S>) => {\n\t\t\t\t\tlet set = setConstructors.get(value)\n\t\t\t\t\tif (!set) set = new IncrementalSetConstructor<IdOf<S>>(prevValue.get(value) ?? new Set())\n\t\t\t\t\tset.remove(id)\n\t\t\t\t\tsetConstructors.set(value, set)\n\t\t\t\t}\n\n\t\t\t\tfor (const changes of history) {\n\t\t\t\t\tfor (const record of objectMapValues(changes.added)) {\n\t\t\t\t\t\tif (record.typeName === typeName) {\n\t\t\t\t\t\t\tconst value = getPropertyValue(record as S)\n\t\t\t\t\t\t\tif (value !== undefined) {\n\t\t\t\t\t\t\t\tadd(value, record.id)\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\tfor (const [from, to] of objectMapValues(changes.updated)) {\n\t\t\t\t\t\tif (to.typeName === typeName) {\n\t\t\t\t\t\t\tconst prev = getPropertyValue(from as S)\n\t\t\t\t\t\t\tconst next = getPropertyValue(to as S)\n\t\t\t\t\t\t\tif (prev !== next) {\n\t\t\t\t\t\t\t\tif (prev !== undefined) {\n\t\t\t\t\t\t\t\t\tremove(prev, to.id)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (next !== undefined) {\n\t\t\t\t\t\t\t\t\tadd(next, to.id)\n\t\t\t\t\t\t\t\t}\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\tfor (const record of objectMapValues(changes.removed)) {\n\t\t\t\t\t\tif (record.typeName === typeName) {\n\t\t\t\t\t\t\tconst value = getPropertyValue(record as S)\n\t\t\t\t\t\t\tif (value !== undefined) {\n\t\t\t\t\t\t\t\tremove(value, record.id)\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\n\t\t\t\tlet nextValue: undefined | RSIndexMap<S> = undefined\n\t\t\t\tlet nextDiff: undefined | RSIndexDiff<S> = undefined\n\n\t\t\t\tfor (const [value, setConstructor] of setConstructors) {\n\t\t\t\t\tconst result = setConstructor.get()\n\t\t\t\t\tif (!result) continue\n\t\t\t\t\tif (!nextValue) nextValue = new Map(prevValue)\n\t\t\t\t\tif (!nextDiff) nextDiff = new Map()\n\t\t\t\t\tif (result.value.size === 0) {\n\t\t\t\t\t\tnextValue.delete(value)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnextValue.set(value, result.value)\n\t\t\t\t\t}\n\t\t\t\t\tnextDiff.set(value, result.diff)\n\t\t\t\t}\n\n\t\t\t\tif (nextValue && nextDiff) {\n\t\t\t\t\treturn withDiff(nextValue, nextDiff)\n\t\t\t\t}\n\n\t\t\t\treturn prevValue\n\t\t\t},\n\t\t\t{ historyLength: 100 }\n\t\t)\n\t}\n\n\t/**\n\t * Creates a reactive query that returns the first record matching the given query criteria.\n\t * Returns undefined if no matching record is found. The query automatically updates\n\t * when records change.\n\t *\n\t * @param typeName - The type name of records to query\n\t * @param queryCreator - Function that returns the query expression object to match against\n\t * @param name - Optional name for the query computation (used for debugging)\n\t * @returns A computed value containing the first matching record or undefined\n\t *\n\t * @example\n\t * ```ts\n\t * // Find the first book with a specific title\n\t * const bookLatheOfHeaven = store.query.record('book', () => ({ title: { eq: 'The Lathe of Heaven' } }))\n\t * console.log(bookLatheOfHeaven.get()?.title) // 'The Lathe of Heaven' or undefined\n\t *\n\t * // Find any book in stock\n\t * const anyInStockBook = store.query.record('book', () => ({ inStock: { eq: true } }))\n\t * ```\n\t *\n\t * @public\n\t */\n\trecord<TypeName extends R['typeName']>(\n\t\ttypeName: TypeName,\n\t\tqueryCreator: () => QueryExpression<Extract<R, { typeName: TypeName }>> = () => ({}),\n\t\tname = 'record:' + typeName + (queryCreator ? ':' + queryCreator.toString() : '')\n\t): Computed<Extract<R, { typeName: TypeName }> | undefined> {\n\t\ttype S = Extract<R, { typeName: TypeName }>\n\t\tconst ids = this.ids(typeName, queryCreator, name)\n\n\t\treturn computed<S | undefined>(name, () => {\n\t\t\tfor (const id of ids.get()) {\n\t\t\t\treturn this.recordMap.get(id) as S | undefined\n\t\t\t}\n\t\t\treturn undefined\n\t\t})\n\t}\n\n\t/**\n\t * Creates a reactive query that returns an array of all records matching the given query criteria.\n\t * The array automatically updates when records are added, updated, or removed.\n\t *\n\t * @param typeName - The type name of records to query\n\t * @param queryCreator - Function that returns the query expression object to match against\n\t * @param name - Optional name for the query computation (used for debugging)\n\t * @returns A computed value containing an array of all matching records\n\t *\n\t * @example\n\t * ```ts\n\t * // Get all books in stock\n\t * const inStockBooks = store.query.records('book', () => ({ inStock: { eq: true } }))\n\t * console.log(inStockBooks.get()) // Book[]\n\t *\n\t * // Get all books by a specific author\n\t * const leguinBooks = store.query.records('book', () => ({ authorId: { eq: 'author:leguin' } }))\n\t *\n\t * // Get all books (no filter)\n\t * const allBooks = store.query.records('book')\n\t * ```\n\t *\n\t * @public\n\t */\n\trecords<TypeName extends R['typeName']>(\n\t\ttypeName: TypeName,\n\t\tqueryCreator: () => QueryExpression<Extract<R, { typeName: TypeName }>> = () => ({}),\n\t\tname = 'records:' + typeName + (queryCreator ? ':' + queryCreator.toString() : '')\n\t): Computed<Array<Extract<R, { typeName: TypeName }>>> {\n\t\ttype S = Extract<R, { typeName: TypeName }>\n\t\tconst ids = this.ids(typeName, queryCreator, 'ids:' + name)\n\n\t\treturn computed<S[]>(\n\t\t\tname,\n\t\t\t() => {\n\t\t\t\treturn Array.from(ids.get(), (id) => this.recordMap.get(id) as S)\n\t\t\t},\n\t\t\t{\n\t\t\t\tisEqual: areArraysShallowEqual,\n\t\t\t}\n\t\t)\n\t}\n\n\t/**\n\t * Creates a reactive query that returns a set of record IDs matching the given query criteria.\n\t * This is more efficient than `records()` when you only need the IDs and not the full record objects.\n\t * The set automatically updates with collection diffs when records change.\n\t *\n\t * @param typeName - The type name of records to query\n\t * @param queryCreator - Function that returns the query expression object to match against\n\t * @param name - Optional name for the query computation (used for debugging)\n\t * @returns A computed value containing a set of matching record IDs with collection diffs\n\t *\n\t * @example\n\t * ```ts\n\t * // Get IDs of all books in stock\n\t * const inStockBookIds = store.query.ids('book', () => ({ inStock: { eq: true } }))\n\t * console.log(inStockBookIds.get()) // Set<RecordId<Book>>\n\t *\n\t * // Get all book IDs (no filter)\n\t * const allBookIds = store.query.ids('book')\n\t *\n\t * // Use with other queries for efficient lookups\n\t * const authorBookIds = store.query.ids('book', () => ({ authorId: { eq: 'author:leguin' } }))\n\t * ```\n\t *\n\t * @public\n\t */\n\tids<TypeName extends R['typeName']>(\n\t\ttypeName: TypeName,\n\t\tqueryCreator: () => QueryExpression<Extract<R, { typeName: TypeName }>> = () => ({}),\n\t\tname = 'ids:' + typeName + (queryCreator ? ':' + queryCreator.toString() : '')\n\t): Computed<\n\t\tSet<IdOf<Extract<R, { typeName: TypeName }>>>,\n\t\tCollectionDiff<IdOf<Extract<R, { typeName: TypeName }>>>\n\t> {\n\t\ttype S = Extract<R, { typeName: TypeName }>\n\n\t\tconst typeHistory = this.filterHistory(typeName)\n\n\t\tconst fromScratch = () => {\n\t\t\t// deref type history early to allow first incremental update to use diffs\n\t\t\ttypeHistory.get()\n\t\t\tconst query: QueryExpression<S> = queryCreator()\n\t\t\tif (Object.keys(query).length === 0) {\n\t\t\t\treturn this.getAllIdsForType(typeName)\n\t\t\t}\n\n\t\t\treturn executeQuery(this, typeName, query)\n\t\t}\n\n\t\tconst fromScratchWithDiff = (prevValue: Set<IdOf<S>>) => {\n\t\t\tconst nextValue = fromScratch()\n\t\t\tconst diff = diffSets(prevValue, nextValue)\n\t\t\tif (diff) {\n\t\t\t\treturn withDiff(nextValue, diff)\n\t\t\t} else {\n\t\t\t\treturn prevValue\n\t\t\t}\n\t\t}\n\t\tconst cachedQuery = computed('ids_query:' + name, queryCreator, {\n\t\t\tisEqual,\n\t\t})\n\n\t\treturn computed(\n\t\t\t'query:' + name,\n\t\t\t(prevValue, lastComputedEpoch) => {\n\t\t\t\tconst query = cachedQuery.get()\n\t\t\t\tif (isUninitialized(prevValue)) {\n\t\t\t\t\treturn fromScratch()\n\t\t\t\t}\n\n\t\t\t\t// if the query changed since last time this ran then we need to start again\n\t\t\t\tif (lastComputedEpoch < cachedQuery.lastChangedEpoch) {\n\t\t\t\t\treturn fromScratchWithDiff(prevValue)\n\t\t\t\t}\n\n\t\t\t\t// otherwise iterate over the changes from the store and apply them to the previous value if needed\n\t\t\t\tconst history = typeHistory.getDiffSince(lastComputedEpoch)\n\t\t\t\tif (history === RESET_VALUE) {\n\t\t\t\t\treturn fromScratchWithDiff(prevValue)\n\t\t\t\t}\n\n\t\t\t\tconst setConstructor = new IncrementalSetConstructor<IdOf<S>>(\n\t\t\t\t\tprevValue\n\t\t\t\t) as IncrementalSetConstructor<IdOf<S>>\n\n\t\t\t\tfor (const changes of history) {\n\t\t\t\t\tfor (const added of objectMapValues(changes.added)) {\n\t\t\t\t\t\tif (added.typeName === typeName && objectMatchesQuery(query, added)) {\n\t\t\t\t\t\t\tsetConstructor.add(added.id)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor (const [_, updated] of objectMapValues(changes.updated)) {\n\t\t\t\t\t\tif (updated.typeName === typeName) {\n\t\t\t\t\t\t\tif (objectMatchesQuery(query, updated)) {\n\t\t\t\t\t\t\t\tsetConstructor.add(updated.id)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsetConstructor.remove(updated.id)\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\tfor (const removed of objectMapValues(changes.removed)) {\n\t\t\t\t\t\tif (removed.typeName === typeName) {\n\t\t\t\t\t\t\tsetConstructor.remove(removed.id)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst result = setConstructor.get()\n\t\t\t\tif (!result) {\n\t\t\t\t\treturn prevValue\n\t\t\t\t}\n\n\t\t\t\treturn withDiff(result.value, result.diff)\n\t\t\t},\n\t\t\t{ historyLength: 50 }\n\t\t)\n\t}\n\n\t/**\n\t * Executes a one-time query against the current store state and returns matching records.\n\t * This is a non-reactive query that returns results immediately without creating a computed value.\n\t * Use this when you need a snapshot of data at a specific point in time.\n\t *\n\t * @param typeName - The type name of records to query\n\t * @param query - The query expression object to match against\n\t * @returns An array of records that match the query at the current moment\n\t *\n\t * @example\n\t * ```ts\n\t * // Get current in-stock books (non-reactive)\n\t * const currentInStockBooks = store.query.exec('book', { inStock: { eq: true } })\n\t * console.log(currentInStockBooks) // Book[]\n\t *\n\t * // Unlike records(), this won't update when the data changes\n\t * const staticBookList = store.query.exec('book', { authorId: { eq: 'author:leguin' } })\n\t * ```\n\t *\n\t * @public\n\t */\n\texec<TypeName extends R['typeName']>(\n\t\ttypeName: TypeName,\n\t\tquery: QueryExpression<Extract<R, { typeName: TypeName }>>\n\t): Array<Extract<R, { typeName: TypeName }>> {\n\t\tconst ids = executeQuery(this, typeName, query)\n\t\tif (ids.size === 0) {\n\t\t\treturn EMPTY_ARRAY\n\t\t}\n\t\treturn Array.from(ids, (id) => this.recordMap.get(id) as Extract<R, { typeName: TypeName }>)\n\t}\n}\n","import { UnknownRecord } from './BaseRecord'\nimport { Store } from './Store'\n\n/**\n * Handler function called before a record is created in the store.\n * The handler receives the record to be created and can return a modified version.\n * Use this to validate, transform, or modify records before they are added to the store.\n *\n * @param record - The record about to be created\n * @param source - Whether the change originated from 'user' interaction or 'remote' synchronization\n * @returns The record to actually create (may be modified)\n *\n * @example\n * ```ts\n * const handler: StoreBeforeCreateHandler<MyRecord> = (record, source) => {\n * // Ensure all user-created records have a timestamp\n * if (source === 'user' && !record.createdAt) {\n * return { ...record, createdAt: Date.now() }\n * }\n * return record\n * }\n * ```\n *\n * @public\n */\nexport type StoreBeforeCreateHandler<R extends UnknownRecord> = (\n\trecord: R,\n\tsource: 'remote' | 'user'\n) => R\n/**\n * Handler function called after a record has been successfully created in the store.\n * Use this for side effects that should happen after record creation, such as updating\n * related records or triggering notifications.\n *\n * @param record - The record that was created\n * @param source - Whether the change originated from 'user' interaction or 'remote' synchronization\n *\n * @example\n * ```ts\n * const handler: StoreAfterCreateHandler<BookRecord> = (book, source) => {\n * if (source === 'user') {\n * console.log(`New book added: ${book.title}`)\n * updateAuthorBookCount(book.authorId)\n * }\n * }\n * ```\n *\n * @public\n */\nexport type StoreAfterCreateHandler<R extends UnknownRecord> = (\n\trecord: R,\n\tsource: 'remote' | 'user'\n) => void\n/**\n * Handler function called before a record is updated in the store.\n * The handler receives the current and new versions of the record and can return\n * a modified version or the original to prevent the change.\n *\n * @param prev - The current version of the record in the store\n * @param next - The proposed new version of the record\n * @param source - Whether the change originated from 'user' interaction or 'remote' synchronization\n * @returns The record version to actually store (may be modified or the original to block change)\n *\n * @example\n * ```ts\n * const handler: StoreBeforeChangeHandler<ShapeRecord> = (prev, next, source) => {\n * // Prevent shapes from being moved outside the canvas bounds\n * if (next.x < 0 || next.y < 0) {\n * return prev // Block the change\n * }\n * return next\n * }\n * ```\n *\n * @public\n */\nexport type StoreBeforeChangeHandler<R extends UnknownRecord> = (\n\tprev: R,\n\tnext: R,\n\tsource: 'remote' | 'user'\n) => R\n/**\n * Handler function called after a record has been successfully updated in the store.\n * Use this for side effects that should happen after record changes, such as\n * updating related records or maintaining consistency constraints.\n *\n * @param prev - The previous version of the record\n * @param next - The new version of the record that was stored\n * @param source - Whether the change originated from 'user' interaction or 'remote' synchronization\n *\n * @example\n * ```ts\n * const handler: StoreAfterChangeHandler<ShapeRecord> = (prev, next, source) => {\n * // Update connected arrows when a shape moves\n * if (prev.x !== next.x || prev.y !== next.y) {\n * updateConnectedArrows(next.id)\n * }\n * }\n * ```\n *\n * @public\n */\nexport type StoreAfterChangeHandler<R extends UnknownRecord> = (\n\tprev: R,\n\tnext: R,\n\tsource: 'remote' | 'user'\n) => void\n/**\n * Handler function called before a record is deleted from the store.\n * The handler can return `false` to prevent the deletion from occurring.\n *\n * @param record - The record about to be deleted\n * @param source - Whether the change originated from 'user' interaction or 'remote' synchronization\n * @returns `false` to prevent deletion, `void` or any other value to allow it\n *\n * @example\n * ```ts\n * const handler: StoreBeforeDeleteHandler<BookRecord> = (book, source) => {\n * // Prevent deletion of books that are currently checked out\n * if (book.isCheckedOut) {\n * console.warn('Cannot delete checked out book')\n * return false\n * }\n * // Allow deletion for other books\n * }\n * ```\n *\n * @public\n */\nexport type StoreBeforeDeleteHandler<R extends UnknownRecord> = (\n\trecord: R,\n\tsource: 'remote' | 'user'\n) => void | false\n/**\n * Handler function called after a record has been successfully deleted from the store.\n * Use this for cleanup operations and maintaining referential integrity.\n *\n * @param record - The record that was deleted\n * @param source - Whether the change originated from 'user' interaction or 'remote' synchronization\n *\n * @example\n * ```ts\n * const handler: StoreAfterDeleteHandler<ShapeRecord> = (shape, source) => {\n * // Clean up arrows that were connected to this shape\n * const connectedArrows = findArrowsConnectedTo(shape.id)\n * store.remove(connectedArrows.map(arrow => arrow.id))\n * }\n * ```\n *\n * @public\n */\nexport type StoreAfterDeleteHandler<R extends UnknownRecord> = (\n\trecord: R,\n\tsource: 'remote' | 'user'\n) => void\n\n/**\n * Handler function called when a store operation (atomic transaction) completes.\n * This is useful for performing actions after a batch of changes has been applied,\n * such as triggering saves or sending notifications.\n *\n * @param source - Whether the operation originated from 'user' interaction or 'remote' synchronization\n *\n * @example\n * ```ts\n * const handler: StoreOperationCompleteHandler = (source) => {\n * if (source === 'user') {\n * // Auto-save after user operations complete\n * saveStoreSnapshot()\n * }\n * }\n * ```\n *\n * @public\n */\nexport type StoreOperationCompleteHandler = (source: 'remote' | 'user') => void\n\n/**\n * The side effect manager (aka a \"correct state enforcer\") is responsible\n * for making sure that the store's state is always correct and consistent. This includes\n * things like: deleting a shape if its parent is deleted; unbinding\n * arrows when their binding target is deleted; maintaining referential integrity; etc.\n *\n * Side effects are organized into lifecycle hooks that run before and after\n * record operations (create, change, delete), allowing you to validate data,\n * transform records, and maintain business rules.\n *\n * @example\n * ```ts\n * const sideEffects = new StoreSideEffects(store)\n *\n * // Ensure arrows are deleted when their target shape is deleted\n * sideEffects.registerAfterDeleteHandler('shape', (shape) => {\n * const arrows = store.query.records('arrow', () => ({\n * toId: { eq: shape.id }\n * })).get()\n * store.remove(arrows.map(arrow => arrow.id))\n * })\n * ```\n *\n * @public\n */\nexport class StoreSideEffects<R extends UnknownRecord> {\n\t/**\n\t * Creates a new side effects manager for the given store.\n\t *\n\t * store - The store instance to manage side effects for\n\t */\n\tconstructor(private readonly store: Store<R>) {}\n\n\tprivate _beforeCreateHandlers: { [K in string]?: StoreBeforeCreateHandler<any>[] } = {}\n\tprivate _afterCreateHandlers: { [K in string]?: StoreAfterCreateHandler<any>[] } = {}\n\tprivate _beforeChangeHandlers: { [K in string]?: StoreBeforeChangeHandler<any>[] } = {}\n\tprivate _afterChangeHandlers: { [K in string]?: StoreAfterChangeHandler<any>[] } = {}\n\tprivate _beforeDeleteHandlers: { [K in string]?: StoreBeforeDeleteHandler<any>[] } = {}\n\tprivate _afterDeleteHandlers: { [K in string]?: StoreAfterDeleteHandler<any>[] } = {}\n\tprivate _operationCompleteHandlers: StoreOperationCompleteHandler[] = []\n\n\tprivate _isEnabled = true\n\t/**\n\t * Checks whether side effects are currently enabled.\n\t * When disabled, all side effect handlers are bypassed.\n\t *\n\t * @returns `true` if side effects are enabled, `false` otherwise\n\t * @internal\n\t */\n\tisEnabled() {\n\t\treturn this._isEnabled\n\t}\n\t/**\n\t * Enables or disables side effects processing.\n\t * When disabled, no side effect handlers will be called.\n\t *\n\t * @param enabled - Whether to enable or disable side effects\n\t * @internal\n\t */\n\tsetIsEnabled(enabled: boolean) {\n\t\tthis._isEnabled = enabled\n\t}\n\n\t/**\n\t * Processes all registered 'before create' handlers for a record.\n\t * Handlers are called in registration order and can transform the record.\n\t *\n\t * @param record - The record about to be created\n\t * @param source - Whether the change originated from 'user' or 'remote'\n\t * @returns The potentially modified record to actually create\n\t * @internal\n\t */\n\thandleBeforeCreate(record: R, source: 'remote' | 'user') {\n\t\tif (!this._isEnabled) return record\n\n\t\tconst handlers = this._beforeCreateHandlers[record.typeName] as StoreBeforeCreateHandler<R>[]\n\t\tif (handlers) {\n\t\t\tlet r = record\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tr = handler(r, source)\n\t\t\t}\n\t\t\treturn r\n\t\t}\n\n\t\treturn record\n\t}\n\n\t/**\n\t * Processes all registered 'after create' handlers for a record.\n\t * Handlers are called in registration order after the record is created.\n\t *\n\t * @param record - The record that was created\n\t * @param source - Whether the change originated from 'user' or 'remote'\n\t * @internal\n\t */\n\thandleAfterCreate(record: R, source: 'remote' | 'user') {\n\t\tif (!this._isEnabled) return\n\n\t\tconst handlers = this._afterCreateHandlers[record.typeName] as StoreAfterCreateHandler<R>[]\n\t\tif (handlers) {\n\t\t\tfor (const handler of handlers) {\n\t\t\t\thandler(record, source)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Processes all registered 'before change' handlers for a record.\n\t * Handlers are called in registration order and can modify or block the change.\n\t *\n\t * @param prev - The current version of the record\n\t * @param next - The proposed new version of the record\n\t * @param source - Whether the change originated from 'user' or 'remote'\n\t * @returns The potentially modified record to actually store\n\t * @internal\n\t */\n\thandleBeforeChange(prev: R, next: R, source: 'remote' | 'user') {\n\t\tif (!this._isEnabled) return next\n\n\t\tconst handlers = this._beforeChangeHandlers[next.typeName] as StoreBeforeChangeHandler<R>[]\n\t\tif (handlers) {\n\t\t\tlet r = next\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tr = handler(prev, r, source)\n\t\t\t}\n\t\t\treturn r\n\t\t}\n\n\t\treturn next\n\t}\n\n\t/**\n\t * Processes all registered 'after change' handlers for a record.\n\t * Handlers are called in registration order after the record is updated.\n\t *\n\t * @param prev - The previous version of the record\n\t * @param next - The new version of the record that was stored\n\t * @param source - Whether the change originated from 'user' or 'remote'\n\t * @internal\n\t */\n\thandleAfterChange(prev: R, next: R, source: 'remote' | 'user') {\n\t\tif (!this._isEnabled) return\n\n\t\tconst handlers = this._afterChangeHandlers[next.typeName] as StoreAfterChangeHandler<R>[]\n\t\tif (handlers) {\n\t\t\tfor (const handler of handlers) {\n\t\t\t\thandler(prev, next, source)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Processes all registered 'before delete' handlers for a record.\n\t * If any handler returns `false`, the deletion is prevented.\n\t *\n\t * @param record - The record about to be deleted\n\t * @param source - Whether the change originated from 'user' or 'remote'\n\t * @returns `true` to allow deletion, `false` to prevent it\n\t * @internal\n\t */\n\thandleBeforeDelete(record: R, source: 'remote' | 'user') {\n\t\tif (!this._isEnabled) return true\n\n\t\tconst handlers = this._beforeDeleteHandlers[record.typeName] as StoreBeforeDeleteHandler<R>[]\n\t\tif (handlers) {\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tif (handler(record, source) === false) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t/**\n\t * Processes all registered 'after delete' handlers for a record.\n\t * Handlers are called in registration order after the record is deleted.\n\t *\n\t * @param record - The record that was deleted\n\t * @param source - Whether the change originated from 'user' or 'remote'\n\t * @internal\n\t */\n\thandleAfterDelete(record: R, source: 'remote' | 'user') {\n\t\tif (!this._isEnabled) return\n\n\t\tconst handlers = this._afterDeleteHandlers[record.typeName] as StoreAfterDeleteHandler<R>[]\n\t\tif (handlers) {\n\t\t\tfor (const handler of handlers) {\n\t\t\t\thandler(record, source)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Processes all registered operation complete handlers.\n\t * Called after an atomic store operation finishes.\n\t *\n\t * @param source - Whether the operation originated from 'user' or 'remote'\n\t * @internal\n\t */\n\thandleOperationComplete(source: 'remote' | 'user') {\n\t\tif (!this._isEnabled) return\n\n\t\tfor (const handler of this._operationCompleteHandlers) {\n\t\t\thandler(source)\n\t\t}\n\t}\n\n\t/**\n\t * Internal helper for registering multiple side effect handlers at once and keeping them organized.\n\t * This provides a convenient way to register handlers for multiple record types and lifecycle events\n\t * in a single call, returning a single cleanup function.\n\t *\n\t * @param handlersByType - An object mapping record type names to their respective handlers\n\t * @returns A function that removes all registered handlers when called\n\t *\n\t * @example\n\t * ```ts\n\t * const cleanup = sideEffects.register({\n\t * shape: {\n\t * afterDelete: (shape) => console.log('Shape deleted:', shape.id),\n\t * beforeChange: (prev, next) => ({ ...next, lastModified: Date.now() })\n\t * },\n\t * arrow: {\n\t * afterCreate: (arrow) => updateConnectedShapes(arrow)\n\t * }\n\t * })\n\t *\n\t * // Later, remove all handlers\n\t * cleanup()\n\t * ```\n\t *\n\t * @internal\n\t */\n\tregister(handlersByType: {\n\t\t[T in R as T['typeName']]?: {\n\t\t\tbeforeCreate?: StoreBeforeCreateHandler<T>\n\t\t\tafterCreate?: StoreAfterCreateHandler<T>\n\t\t\tbeforeChange?: StoreBeforeChangeHandler<T>\n\t\t\tafterChange?: StoreAfterChangeHandler<T>\n\t\t\tbeforeDelete?: StoreBeforeDeleteHandler<T>\n\t\t\tafterDelete?: StoreAfterDeleteHandler<T>\n\t\t}\n\t}) {\n\t\tconst disposes: (() => void)[] = []\n\t\tfor (const [type, handlers] of Object.entries(handlersByType) as any) {\n\t\t\tif (handlers?.beforeCreate) {\n\t\t\t\tdisposes.push(this.registerBeforeCreateHandler(type, handlers.beforeCreate))\n\t\t\t}\n\t\t\tif (handlers?.afterCreate) {\n\t\t\t\tdisposes.push(this.registerAfterCreateHandler(type, handlers.afterCreate))\n\t\t\t}\n\t\t\tif (handlers?.beforeChange) {\n\t\t\t\tdisposes.push(this.registerBeforeChangeHandler(type, handlers.beforeChange))\n\t\t\t}\n\t\t\tif (handlers?.afterChange) {\n\t\t\t\tdisposes.push(this.registerAfterChangeHandler(type, handlers.afterChange))\n\t\t\t}\n\t\t\tif (handlers?.beforeDelete) {\n\t\t\t\tdisposes.push(this.registerBeforeDeleteHandler(type, handlers.beforeDelete))\n\t\t\t}\n\t\t\tif (handlers?.afterDelete) {\n\t\t\t\tdisposes.push(this.registerAfterDeleteHandler(type, handlers.afterDelete))\n\t\t\t}\n\t\t}\n\t\treturn () => {\n\t\t\tfor (const dispose of disposes) dispose()\n\t\t}\n\t}\n\n\t/**\n\t * Register a handler to be called before a record of a certain type is created. Return a\n\t * modified record from the handler to change the record that will be created.\n\t *\n\t * Use this handle only to modify the creation of the record itself. If you want to trigger a\n\t * side-effect on a different record (for example, moving one shape when another is created),\n\t * use {@link StoreSideEffects.registerAfterCreateHandler} instead.\n\t *\n\t * @example\n\t * ```ts\n\t * editor.sideEffects.registerBeforeCreateHandler('shape', (shape, source) => {\n\t * // only modify shapes created by the user\n\t * if (source !== 'user') return shape\n\t *\n\t * //by default, arrow shapes have no label. Let's make sure they always have a label.\n\t * if (shape.type === 'arrow') {\n\t * return {...shape, props: {...shape.props, text: 'an arrow'}}\n\t * }\n\t *\n\t * // other shapes get returned unmodified\n\t * return shape\n\t * })\n\t * ```\n\t *\n\t * @param typeName - The type of record to listen for\n\t * @param handler - The handler to call\n\t *\n\t * @returns A callback that removes the handler.\n\t */\n\tregisterBeforeCreateHandler<T extends R['typeName']>(\n\t\ttypeName: T,\n\t\thandler: StoreBeforeCreateHandler<R & { typeName: T }>\n\t) {\n\t\tconst handlers = this._beforeCreateHandlers[typeName] as StoreBeforeCreateHandler<any>[]\n\t\tif (!handlers) this._beforeCreateHandlers[typeName] = []\n\t\tthis._beforeCreateHandlers[typeName]!.push(handler)\n\t\treturn () => remove(this._beforeCreateHandlers[typeName]!, handler)\n\t}\n\n\t/**\n\t * Register a handler to be called after a record is created. This is useful for side-effects\n\t * that would update _other_ records. If you want to modify the record being created use\n\t * {@link StoreSideEffects.registerBeforeCreateHandler} instead.\n\t *\n\t * @example\n\t * ```ts\n\t * editor.sideEffects.registerAfterCreateHandler('page', (page, source) => {\n\t * // Automatically create a shape when a page is created\n\t * editor.createShape({\n\t * id: createShapeId(),\n\t * type: 'text',\n\t * props: { richText: toRichText(page.name) },\n\t * })\n\t * })\n\t * ```\n\t *\n\t * @param typeName - The type of record to listen for\n\t * @param handler - The handler to call\n\t *\n\t * @returns A callback that removes the handler.\n\t */\n\tregisterAfterCreateHandler<T extends R['typeName']>(\n\t\ttypeName: T,\n\t\thandler: StoreAfterCreateHandler<R & { typeName: T }>\n\t) {\n\t\tconst handlers = this._afterCreateHandlers[typeName] as StoreAfterCreateHandler<any>[]\n\t\tif (!handlers) this._afterCreateHandlers[typeName] = []\n\t\tthis._afterCreateHandlers[typeName]!.push(handler)\n\t\treturn () => remove(this._afterCreateHandlers[typeName]!, handler)\n\t}\n\n\t/**\n\t * Register a handler to be called before a record is changed. The handler is given the old and\n\t * new record - you can return a modified record to apply a different update, or the old record\n\t * to block the update entirely.\n\t *\n\t * Use this handler only for intercepting updates to the record itself. If you want to update\n\t * other records in response to a change, use\n\t * {@link StoreSideEffects.registerAfterChangeHandler} instead.\n\t *\n\t * @example\n\t * ```ts\n\t * editor.sideEffects.registerBeforeChangeHandler('shape', (prev, next, source) => {\n\t * if (next.isLocked && !prev.isLocked) {\n\t * // prevent shapes from ever being locked:\n\t * return prev\n\t * }\n\t * // other types of change are allowed\n\t * return next\n\t * })\n\t * ```\n\t *\n\t * @param typeName - The type of record to listen for\n\t * @param handler - The handler to call\n\t *\n\t * @returns A callback that removes the handler.\n\t */\n\tregisterBeforeChangeHandler<T extends R['typeName']>(\n\t\ttypeName: T,\n\t\thandler: StoreBeforeChangeHandler<R & { typeName: T }>\n\t) {\n\t\tconst handlers = this._beforeChangeHandlers[typeName] as StoreBeforeChangeHandler<any>[]\n\t\tif (!handlers) this._beforeChangeHandlers[typeName] = []\n\t\tthis._beforeChangeHandlers[typeName]!.push(handler)\n\t\treturn () => remove(this._beforeChangeHandlers[typeName]!, handler)\n\t}\n\n\t/**\n\t * Register a handler to be called after a record is changed. This is useful for side-effects\n\t * that would update _other_ records - if you want to modify the record being changed, use\n\t * {@link StoreSideEffects.registerBeforeChangeHandler} instead.\n\t *\n\t * @example\n\t * ```ts\n\t * editor.sideEffects.registerAfterChangeHandler('shape', (prev, next, source) => {\n\t * if (next.props.color === 'red') {\n\t * // there can only be one red shape at a time:\n\t * const otherRedShapes = editor.getCurrentPageShapes().filter(s => s.props.color === 'red' && s.id !== next.id)\n\t * editor.updateShapes(otherRedShapes.map(s => ({...s, props: {...s.props, color: 'blue'}})))\n\t * }\n\t * })\n\t * ```\n\t *\n\t * @param typeName - The type of record to listen for\n\t * @param handler - The handler to call\n\t *\n\t * @returns A callback that removes the handler.\n\t */\n\tregisterAfterChangeHandler<T extends R['typeName']>(\n\t\ttypeName: T,\n\t\thandler: StoreAfterChangeHandler<R & { typeName: T }>\n\t) {\n\t\tconst handlers = this._afterChangeHandlers[typeName] as StoreAfterChangeHandler<any>[]\n\t\tif (!handlers) this._afterChangeHandlers[typeName] = []\n\t\tthis._afterChangeHandlers[typeName]!.push(handler as StoreAfterChangeHandler<any>)\n\t\treturn () => remove(this._afterChangeHandlers[typeName]!, handler)\n\t}\n\n\t/**\n\t * Register a handler to be called before a record is deleted. The handler can return `false` to\n\t * prevent the deletion.\n\t *\n\t * Use this handler only for intercepting deletions of the record itself. If you want to do\n\t * something to other records in response to a deletion, use\n\t * {@link StoreSideEffects.registerAfterDeleteHandler} instead.\n\t *\n\t * @example\n\t * ```ts\n\t * editor.sideEffects.registerBeforeDeleteHandler('shape', (shape, source) => {\n\t * if (shape.props.color === 'red') {\n\t * // prevent red shapes from being deleted\n\t * \t return false\n\t * }\n\t * })\n\t * ```\n\t *\n\t * @param typeName - The type of record to listen for\n\t * @param handler - The handler to call\n\t *\n\t * @returns A callback that removes the handler.\n\t */\n\tregisterBeforeDeleteHandler<T extends R['typeName']>(\n\t\ttypeName: T,\n\t\thandler: StoreBeforeDeleteHandler<R & { typeName: T }>\n\t) {\n\t\tconst handlers = this._beforeDeleteHandlers[typeName] as StoreBeforeDeleteHandler<any>[]\n\t\tif (!handlers) this._beforeDeleteHandlers[typeName] = []\n\t\tthis._beforeDeleteHandlers[typeName]!.push(handler as StoreBeforeDeleteHandler<any>)\n\t\treturn () => remove(this._beforeDeleteHandlers[typeName]!, handler)\n\t}\n\n\t/**\n\t * Register a handler to be called after a record is deleted. This is useful for side-effects\n\t * that would update _other_ records - if you want to block the deletion of the record itself,\n\t * use {@link StoreSideEffects.registerBeforeDeleteHandler} instead.\n\t *\n\t * @example\n\t * ```ts\n\t * editor.sideEffects.registerAfterDeleteHandler('shape', (shape, source) => {\n\t * // if the last shape in a frame is deleted, delete the frame too:\n\t * const parentFrame = editor.getShape(shape.parentId)\n\t * if (!parentFrame || parentFrame.type !== 'frame') return\n\t *\n\t * const siblings = editor.getSortedChildIdsForParent(parentFrame)\n\t * if (siblings.length === 0) {\n\t * editor.deleteShape(parentFrame.id)\n\t * }\n\t * })\n\t * ```\n\t *\n\t * @param typeName - The type of record to listen for\n\t * @param handler - The handler to call\n\t *\n\t * @returns A callback that removes the handler.\n\t */\n\tregisterAfterDeleteHandler<T extends R['typeName']>(\n\t\ttypeName: T,\n\t\thandler: StoreAfterDeleteHandler<R & { typeName: T }>\n\t) {\n\t\tconst handlers = this._afterDeleteHandlers[typeName] as StoreAfterDeleteHandler<any>[]\n\t\tif (!handlers) this._afterDeleteHandlers[typeName] = []\n\t\tthis._afterDeleteHandlers[typeName]!.push(handler as StoreAfterDeleteHandler<any>)\n\t\treturn () => remove(this._afterDeleteHandlers[typeName]!, handler)\n\t}\n\n\t/**\n\t * Register a handler to be called when a store completes an atomic operation.\n\t *\n\t * @example\n\t * ```ts\n\t * let count = 0\n\t *\n\t * editor.sideEffects.registerOperationCompleteHandler(() => count++)\n\t *\n\t * editor.selectAll()\n\t * expect(count).toBe(1)\n\t *\n\t * editor.store.atomic(() => {\n\t *\teditor.selectNone()\n\t * \teditor.selectAll()\n\t * })\n\t *\n\t * expect(count).toBe(2)\n\t * ```\n\t *\n\t * @param handler - The handler to call\n\t *\n\t * @returns A callback that removes the handler.\n\t *\n\t * @public\n\t */\n\tregisterOperationCompleteHandler(handler: StoreOperationCompleteHandler) {\n\t\tthis._operationCompleteHandlers.push(handler)\n\t\treturn () => remove(this._operationCompleteHandlers, handler)\n\t}\n}\n\nfunction remove(array: any[], item: any) {\n\tconst index = array.indexOf(item)\n\tif (index >= 0) {\n\t\tarray.splice(index, 1)\n\t}\n}\n","import { Atom, Reactor, Signal, atom, computed, reactor, transact } from '@ibodr/state'\nimport {\n\tWeakCache,\n\tassert,\n\tfilterEntries,\n\tgetOwnProperty,\n\tisEqual,\n\tobjectMapEntries,\n\tobjectMapKeys,\n\tobjectMapValues,\n\tthrottleToNextFrame,\n\tuniqueId,\n} from '@ibodr/utils'\nimport { AtomMap } from './AtomMap'\nimport { IdOf, RecordId, UnknownRecord } from './BaseRecord'\nimport { devFreeze } from './devFreeze'\nimport { RecordsDiff, squashRecordDiffs } from './RecordsDiff'\nimport { RecordScope } from './RecordType'\nimport { StoreQueries } from './StoreQueries'\nimport { SerializedSchema, StoreSchema } from './StoreSchema'\nimport { StoreSideEffects } from './StoreSideEffects'\n\n/**\n * Extracts the record type from a record ID type.\n *\n * @example\n * ```ts\n * type BookId = RecordId<Book>\n * type BookType = RecordFromId<BookId> // Book\n * ```\n *\n * @public\n */\nexport type RecordFromId<K extends RecordId<UnknownRecord>> =\n\tK extends RecordId<infer R> ? R : never\n\n/**\n * A diff describing the changes to a collection.\n *\n * @example\n * ```ts\n * const diff: CollectionDiff<string> = {\n * added: new Set(['newItem']),\n * removed: new Set(['oldItem'])\n * }\n * ```\n *\n * @public\n */\nexport interface CollectionDiff<T> {\n\t/** Items that were added to the collection */\n\tadded?: Set<T>\n\t/** Items that were removed from the collection */\n\tremoved?: Set<T>\n}\n\n/**\n * The source of a change to the store.\n * - `'user'` - Changes originating from local user actions\n * - `'remote'` - Changes originating from remote synchronization\n *\n * @public\n */\nexport type ChangeSource = 'user' | 'remote'\n\n/**\n * Filters for store listeners to control which changes trigger the listener.\n *\n * @example\n * ```ts\n * const filters: StoreListenerFilters = {\n * source: 'user', // Only listen to user changes\n * scope: 'document' // Only listen to document-scoped records\n * }\n * ```\n *\n * @public\n */\nexport interface StoreListenerFilters {\n\t/** Filter by the source of changes */\n\tsource: ChangeSource | 'all'\n\t/** Filter by the scope of records */\n\tscope: RecordScope | 'all'\n}\n\n/**\n * An entry containing changes that originated either by user actions or remote changes.\n * History entries are used to track and replay changes to the store.\n *\n * @example\n * ```ts\n * const entry: HistoryEntry<Book> = {\n * changes: {\n * added: { 'book:123': bookRecord },\n * updated: {},\n * removed: {}\n * },\n * source: 'user'\n * }\n * ```\n *\n * @public\n */\nexport interface HistoryEntry<R extends UnknownRecord = UnknownRecord> {\n\t/** The changes that occurred in this history entry */\n\tchanges: RecordsDiff<R>\n\t/** The source of these changes */\n\tsource: ChangeSource\n}\n\n/**\n * A function that will be called when the history changes.\n *\n * @example\n * ```ts\n * const listener: StoreListener<Book> = (entry) => {\n * console.log('Changes:', entry.changes)\n * console.log('Source:', entry.source)\n * }\n *\n * store.listen(listener)\n * ```\n *\n * @param entry - The history entry containing the changes\n *\n * @public\n */\nexport type StoreListener<R extends UnknownRecord> = (entry: HistoryEntry<R>) => void\n\n/**\n * A computed cache that stores derived data for records.\n * The cache automatically updates when underlying records change and cleans up when records are deleted.\n *\n * @example\n * ```ts\n * const expensiveCache = store.createComputedCache(\n * 'expensive',\n * (book: Book) => performExpensiveCalculation(book)\n * )\n *\n * const result = expensiveCache.get(bookId)\n * ```\n *\n * @public\n */\nexport interface ComputedCache<Data, R extends UnknownRecord> {\n\t/**\n\t * Get the cached data for a record by its ID.\n\t *\n\t * @param id - The ID of the record\n\t * @returns The cached data or undefined if the record doesn't exist\n\t */\n\tget(id: IdOf<R>): Data | undefined\n}\n\n/**\n * Options for creating a computed cache.\n *\n * @example\n * ```ts\n * const options: CreateComputedCacheOpts<string[], Book> = {\n * areRecordsEqual: (a, b) => a.title === b.title,\n * areResultsEqual: (a, b) => JSON.stringify(a) === JSON.stringify(b)\n * }\n * ```\n *\n * @public\n */\nexport interface CreateComputedCacheOpts<Data, R extends UnknownRecord> {\n\t/** Custom equality function for comparing records */\n\tareRecordsEqual?(a: R, b: R): boolean\n\t/** Custom equality function for comparing results */\n\tareResultsEqual?(a: Data, b: Data): boolean\n}\n\n/**\n * A serialized snapshot of the record store's values.\n * This is a plain JavaScript object that can be saved to storage or transmitted over the network.\n *\n * @example\n * ```ts\n * const serialized: SerializedStore<Book> = {\n * 'book:123': { id: 'book:123', typeName: 'book', title: 'The Lathe of Heaven' },\n * 'book:456': { id: 'book:456', typeName: 'book', title: 'The Left Hand of Darkness' }\n * }\n * ```\n *\n * @public\n */\nexport type SerializedStore<R extends UnknownRecord> = Record<IdOf<R>, R>\n\n/**\n * A snapshot of the store including both data and schema information.\n * This enables proper migration when loading data from different schema versions.\n *\n * @example\n * ```ts\n * const snapshot = store.getStoreSnapshot()\n * // Later...\n * store.loadStoreSnapshot(snapshot)\n * ```\n *\n * @public\n */\nexport interface StoreSnapshot<R extends UnknownRecord> {\n\t/** The serialized store data */\n\tstore: SerializedStore<R>\n\t/** The serialized schema information */\n\tschema: SerializedSchema\n}\n\n/**\n * A validator for store records that ensures data integrity.\n * Validators are called when records are created or updated.\n *\n * @example\n * ```ts\n * const bookValidator: StoreValidator<Book> = {\n * validate(record: unknown): Book {\n * // Validate and return the record\n * if (typeof record !== 'object' || !record.title) {\n * throw new Error('Invalid book')\n * }\n * return record as Book\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface StoreValidator<R extends UnknownRecord> {\n\t/**\n\t * Validate a record.\n\t *\n\t * @param record - The record to validate\n\t * @returns The validated record\n\t * @throws When validation fails\n\t */\n\tvalidate(record: unknown): R\n\t/**\n\t * Validate a record using a known good version for reference.\n\t *\n\t * @param knownGoodVersion - A known valid version of the record\n\t * @param record - The record to validate\n\t * @returns The validated record\n\t */\n\tvalidateUsingKnownGoodVersion?(knownGoodVersion: R, record: unknown): R\n}\n\n/**\n * A map of validators for each record type in the store.\n *\n * @example\n * ```ts\n * const validators: StoreValidators<Book | Author> = {\n * book: bookValidator,\n * author: authorValidator\n * }\n * ```\n *\n * @public\n */\nexport type StoreValidators<R extends UnknownRecord> = {\n\t[K in R['typeName']]: StoreValidator<Extract<R, { typeName: K }>>\n}\n\n/**\n * Information about an error that occurred in the store.\n *\n * @example\n * ```ts\n * const error: StoreError = {\n * error: new Error('Validation failed'),\n * phase: 'updateRecord',\n * recordBefore: oldRecord,\n * recordAfter: newRecord,\n * isExistingValidationIssue: false\n * }\n * ```\n *\n * @public\n */\nexport interface StoreError {\n\t/** The error that occurred */\n\terror: Error\n\t/** The phase during which the error occurred */\n\tphase: 'initialize' | 'createRecord' | 'updateRecord' | 'tests'\n\t/** The record state before the operation (if applicable) */\n\trecordBefore?: unknown\n\t/** The record state after the operation */\n\trecordAfter: unknown\n\t/** Whether this is an existing validation issue */\n\tisExistingValidationIssue: boolean\n}\n\n/**\n * Extract the record type from a Store type.\n * Used internally for type inference.\n *\n * @internal\n */\nexport type StoreRecord<S extends Store<any>> = S extends Store<infer R> ? R : never\n\n/**\n * A reactive store that manages collections of typed records.\n *\n * The Store is the central container for your application's data, providing:\n * - Reactive state management with automatic updates\n * - Type-safe record operations\n * - History tracking and change notifications\n * - Schema validation and migrations\n * - Side effects and business logic hooks\n * - Efficient querying and indexing\n *\n * @example\n * ```ts\n * // Create a store with schema\n * const schema = StoreSchema.create({\n * book: Book,\n * author: Author\n * })\n *\n * const store = new Store({\n * schema,\n * props: {}\n * })\n *\n * // Add records\n * const book = Book.create({ title: 'The Lathe of Heaven', author: 'Le Guin' })\n * store.put([book])\n *\n * // Listen to changes\n * store.listen((entry) => {\n * console.log('Changes:', entry.changes)\n * })\n * ```\n *\n * @public\n */\nexport class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {\n\t/**\n\t * The unique identifier of the store instance.\n\t *\n\t * @public\n\t */\n\tpublic readonly id: string\n\t/**\n\t * An AtomMap containing the stores records.\n\t *\n\t * @internal\n\t * @readonly\n\t */\n\tprivate readonly records: AtomMap<IdOf<R>, R>\n\n\t/**\n\t * An atom containing the store's history.\n\t *\n\t * @public\n\t * @readonly\n\t */\n\treadonly history: Atom<number, RecordsDiff<R>> = atom('history', 0, {\n\t\thistoryLength: 1000,\n\t})\n\n\t/**\n\t * Reactive queries and indexes for efficiently accessing store data.\n\t * Provides methods for filtering, indexing, and subscribing to subsets of records.\n\t *\n\t * @example\n\t * ```ts\n\t * // Create an index by a property\n\t * const booksByAuthor = store.query.index('book', 'author')\n\t *\n\t * // Get records matching criteria\n\t * const inStockBooks = store.query.records('book', () => ({\n\t * inStock: { eq: true }\n\t * }))\n\t * ```\n\t *\n\t * @public\n\t * @readonly\n\t */\n\treadonly query: StoreQueries<R>\n\n\t/**\n\t * A set containing listeners that have been added to this store.\n\t *\n\t * @internal\n\t */\n\tprivate listeners = new Set<{ onHistory: StoreListener<R>; filters: StoreListenerFilters }>()\n\n\t/**\n\t * An array of history entries that have not yet been flushed.\n\t *\n\t * @internal\n\t */\n\tprivate historyAccumulator = new HistoryAccumulator<R>()\n\n\t/**\n\t * A reactor that responds to changes to the history by squashing the accumulated history and\n\t * notifying listeners of the changes.\n\t *\n\t * @internal\n\t */\n\tprivate historyReactor: Reactor\n\n\t/**\n\t * Function to dispose of any in-flight timeouts.\n\t *\n\t * @internal\n\t */\n\tprivate cancelHistoryReactor(): void {\n\t\t/* noop */\n\t}\n\n\t/**\n\t * The schema that defines the structure and validation rules for records in this store.\n\t *\n\t * @public\n\t */\n\treadonly schema: StoreSchema<R, Props>\n\n\t/**\n\t * Custom properties associated with this store instance.\n\t *\n\t * @public\n\t */\n\treadonly props: Props\n\n\t/**\n\t * A mapping of record scopes to the set of record type names that belong to each scope.\n\t * Used to filter records by their persistence and synchronization behavior.\n\t *\n\t * @public\n\t */\n\tpublic readonly scopedTypes: { readonly [K in RecordScope]: ReadonlySet<R['typeName']> }\n\n\t/**\n\t * Side effects manager that handles lifecycle events for record operations.\n\t * Allows registration of callbacks for create, update, delete, and validation events.\n\t *\n\t * @example\n\t * ```ts\n\t * store.sideEffects.registerAfterCreateHandler('book', (book) => {\n\t * console.log('Book created:', book.title)\n\t * })\n\t * ```\n\t *\n\t * @public\n\t */\n\tpublic readonly sideEffects = new StoreSideEffects<R>(this)\n\n\t/**\n\t * Creates a new Store instance.\n\t *\n\t * @example\n\t * ```ts\n\t * const store = new Store({\n\t * schema: StoreSchema.create({ book: Book }),\n\t * props: { appName: 'MyLibrary' },\n\t * initialData: savedData\n\t * })\n\t * ```\n\t *\n\t * @param config - Configuration object for the store\n\t */\n\tconstructor(config: {\n\t\t/** Optional unique identifier for the store */\n\t\tid?: string\n\t\t/** The store's initial data to populate on creation */\n\t\tinitialData?: SerializedStore<R>\n\t\t/** The schema defining record types, validation, and migrations */\n\t\tschema: StoreSchema<R, Props>\n\t\t/** Custom properties for the store instance */\n\t\tprops: Props\n\t}) {\n\t\tconst { initialData, schema, id } = config\n\n\t\tthis.id = id ?? uniqueId()\n\t\tthis.schema = schema\n\t\tthis.props = config.props\n\n\t\tif (initialData) {\n\t\t\tthis.records = new AtomMap(\n\t\t\t\t'store',\n\t\t\t\tobjectMapEntries(initialData).map(([id, record]) => [\n\t\t\t\t\tid,\n\t\t\t\t\tdevFreeze(this.schema.validateRecord(this, record, 'initialize', null)),\n\t\t\t\t])\n\t\t\t)\n\t\t} else {\n\t\t\tthis.records = new AtomMap('store')\n\t\t}\n\n\t\tthis.query = new StoreQueries<R>(this.records, this.history)\n\n\t\tthis.historyReactor = reactor(\n\t\t\t'Store.historyReactor',\n\t\t\t() => {\n\t\t\t\t// deref to make sure we're subscribed regardless of whether we need to propagate\n\t\t\t\tthis.history.get()\n\t\t\t\t// If we have accumulated history, flush it and update listeners\n\t\t\t\tthis._flushHistory()\n\t\t\t},\n\t\t\t{ scheduleEffect: (cb) => (this.cancelHistoryReactor = throttleToNextFrame(cb)) }\n\t\t)\n\t\tthis.scopedTypes = {\n\t\t\tdocument: new Set(\n\t\t\t\tobjectMapValues(this.schema.types)\n\t\t\t\t\t.filter((t) => t.scope === 'document')\n\t\t\t\t\t.map((t) => t.typeName)\n\t\t\t),\n\t\t\tsession: new Set(\n\t\t\t\tobjectMapValues(this.schema.types)\n\t\t\t\t\t.filter((t) => t.scope === 'session')\n\t\t\t\t\t.map((t) => t.typeName)\n\t\t\t),\n\t\t\tpresence: new Set(\n\t\t\t\tobjectMapValues(this.schema.types)\n\t\t\t\t\t.filter((t) => t.scope === 'presence')\n\t\t\t\t\t.map((t) => t.typeName)\n\t\t\t),\n\t\t}\n\t}\n\n\tpublic _flushHistory() {\n\t\t// If we have accumulated history, flush it and update listeners\n\t\tif (this.historyAccumulator.hasChanges()) {\n\t\t\tconst entries = this.historyAccumulator.flush()\n\t\t\tfor (const { changes, source } of entries) {\n\t\t\t\tlet instanceChanges = null as null | RecordsDiff<R>\n\t\t\t\tlet documentChanges = null as null | RecordsDiff<R>\n\t\t\t\tlet presenceChanges = null as null | RecordsDiff<R>\n\t\t\t\tfor (const { onHistory, filters } of this.listeners) {\n\t\t\t\t\tif (filters.source !== 'all' && filters.source !== source) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif (filters.scope !== 'all') {\n\t\t\t\t\t\tif (filters.scope === 'document') {\n\t\t\t\t\t\t\tdocumentChanges ??= this.filterChangesByScope(changes, 'document')\n\t\t\t\t\t\t\tif (!documentChanges) continue\n\t\t\t\t\t\t\tonHistory({ changes: documentChanges, source })\n\t\t\t\t\t\t} else if (filters.scope === 'session') {\n\t\t\t\t\t\t\tinstanceChanges ??= this.filterChangesByScope(changes, 'session')\n\t\t\t\t\t\t\tif (!instanceChanges) continue\n\t\t\t\t\t\t\tonHistory({ changes: instanceChanges, source })\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpresenceChanges ??= this.filterChangesByScope(changes, 'presence')\n\t\t\t\t\t\t\tif (!presenceChanges) continue\n\t\t\t\t\t\t\tonHistory({ changes: presenceChanges, source })\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tonHistory({ changes, source })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdispose() {\n\t\tthis.cancelHistoryReactor()\n\t}\n\n\t/**\n\t * Filters out non-document changes from a diff. Returns null if there are no changes left.\n\t * @param change - the records diff\n\t * @param scope - the records scope\n\t * @returns\n\t */\n\tfilterChangesByScope(change: RecordsDiff<R>, scope: RecordScope) {\n\t\tconst result = {\n\t\t\tadded: filterEntries(change.added, (_, r) => this.scopedTypes[scope].has(r.typeName)),\n\t\t\tupdated: filterEntries(change.updated, (_, r) => this.scopedTypes[scope].has(r[1].typeName)),\n\t\t\tremoved: filterEntries(change.removed, (_, r) => this.scopedTypes[scope].has(r.typeName)),\n\t\t}\n\t\tif (\n\t\t\tObject.keys(result.added).length === 0 &&\n\t\t\tObject.keys(result.updated).length === 0 &&\n\t\t\tObject.keys(result.removed).length === 0\n\t\t) {\n\t\t\treturn null\n\t\t}\n\t\treturn result\n\t}\n\n\t/**\n\t * Update the history with a diff of changes.\n\t *\n\t * @param changes - The changes to add to the history.\n\t */\n\tprivate updateHistory(changes: RecordsDiff<R>): void {\n\t\tthis.historyAccumulator.add({\n\t\t\tchanges,\n\t\t\tsource: this.isMergingRemoteChanges ? 'remote' : 'user',\n\t\t})\n\t\tif (this.listeners.size === 0) {\n\t\t\tthis.historyAccumulator.clear()\n\t\t}\n\t\tthis.history.set(this.history.get() + 1, changes)\n\t}\n\n\tvalidate(phase: 'initialize' | 'createRecord' | 'updateRecord' | 'tests') {\n\t\tthis.allRecords().forEach((record) => this.schema.validateRecord(this, record, phase, null))\n\t}\n\n\t/**\n\t * Add or update records in the store. If a record with the same ID already exists, it will be updated.\n\t * Otherwise, a new record will be created.\n\t *\n\t * @example\n\t * ```ts\n\t * // Add new records\n\t * const book = Book.create({ title: 'Lathe Of Heaven', author: 'Le Guin' })\n\t * store.put([book])\n\t *\n\t * // Update existing record\n\t * store.put([{ ...book, title: 'The Lathe of Heaven' }])\n\t * ```\n\t *\n\t * @param records - The records to add or update\n\t * @param phaseOverride - Override the validation phase (used internally)\n\t * @public\n\t */\n\tput(records: R[], phaseOverride?: 'initialize'): void {\n\t\tthis.atomic(() => {\n\t\t\tconst updates: Record<IdOf<UnknownRecord>, [from: R, to: R]> = {}\n\t\t\tconst additions: Record<IdOf<UnknownRecord>, R> = {}\n\n\t\t\t// Iterate through all records, creating, updating or removing as needed\n\t\t\tlet record: R\n\n\t\t\t// There's a chance that, despite having records, all of the values are\n\t\t\t// identical to what they were before; and so we'd end up with an \"empty\"\n\t\t\t// history entry. Let's keep track of whether we've actually made any\n\t\t\t// changes (e.g. additions, deletions, or updates that produce a new value).\n\t\t\tlet didChange = false\n\n\t\t\tconst source = this.isMergingRemoteChanges ? 'remote' : 'user'\n\n\t\t\tfor (let i = 0, n = records.length; i < n; i++) {\n\t\t\t\trecord = records[i]\n\n\t\t\t\tconst initialValue = this.records.__unsafe__getWithoutCapture(record.id)\n\t\t\t\t// If we already have an atom for this record, update its value.\n\t\t\t\tif (initialValue) {\n\t\t\t\t\t// If we have a beforeUpdate callback, run it against the initial and next records\n\t\t\t\t\trecord = this.sideEffects.handleBeforeChange(initialValue, record, source)\n\n\t\t\t\t\t// Validate the record\n\t\t\t\t\tconst validated = this.schema.validateRecord(\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\trecord,\n\t\t\t\t\t\tphaseOverride ?? 'updateRecord',\n\t\t\t\t\t\tinitialValue\n\t\t\t\t\t)\n\n\t\t\t\t\tif (validated === initialValue) continue\n\n\t\t\t\t\trecord = devFreeze(record)\n\t\t\t\t\tthis.records.set(record.id, record)\n\n\t\t\t\t\tdidChange = true\n\t\t\t\t\tupdates[record.id] = [initialValue, record]\n\t\t\t\t\tthis.addDiffForAfterEvent(initialValue, record)\n\t\t\t\t} else {\n\t\t\t\t\trecord = this.sideEffects.handleBeforeCreate(record, source)\n\n\t\t\t\t\tdidChange = true\n\n\t\t\t\t\t// If we don't have an atom, create one.\n\n\t\t\t\t\t// Validate the record\n\t\t\t\t\trecord = this.schema.validateRecord(\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\trecord as R,\n\t\t\t\t\t\tphaseOverride ?? 'createRecord',\n\t\t\t\t\t\tnull\n\t\t\t\t\t)\n\n\t\t\t\t\t// freeze it\n\t\t\t\t\trecord = devFreeze(record)\n\n\t\t\t\t\t// Mark the change as a new addition.\n\t\t\t\t\tadditions[record.id] = record\n\t\t\t\t\tthis.addDiffForAfterEvent(null, record)\n\n\t\t\t\t\tthis.records.set(record.id, record)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we did change, update the history\n\t\t\tif (!didChange) return\n\t\t\tthis.updateHistory({\n\t\t\t\tadded: additions,\n\t\t\t\tupdated: updates,\n\t\t\t\tremoved: {} as Record<IdOf<R>, R>,\n\t\t\t})\n\t\t})\n\t}\n\n\t/**\n\t * Remove records from the store by their IDs.\n\t *\n\t * @example\n\t * ```ts\n\t * // Remove a single record\n\t * store.remove([book.id])\n\t *\n\t * // Remove multiple records\n\t * store.remove([book1.id, book2.id, book3.id])\n\t * ```\n\t *\n\t * @param ids - The IDs of the records to remove\n\t * @public\n\t */\n\tremove(ids: IdOf<R>[]): void {\n\t\tthis.atomic(() => {\n\t\t\tconst toDelete = new Set<IdOf<R>>(ids)\n\t\t\tconst source = this.isMergingRemoteChanges ? 'remote' : 'user'\n\n\t\t\tif (this.sideEffects.isEnabled()) {\n\t\t\t\tfor (const id of ids) {\n\t\t\t\t\tconst record = this.records.__unsafe__getWithoutCapture(id)\n\t\t\t\t\tif (!record) continue\n\n\t\t\t\t\tif (this.sideEffects.handleBeforeDelete(record, source) === false) {\n\t\t\t\t\t\ttoDelete.delete(id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst actuallyDeleted = this.records.deleteMany(toDelete)\n\t\t\tif (actuallyDeleted.length === 0) return\n\n\t\t\tconst removed = {} as RecordsDiff<R>['removed']\n\t\t\tfor (const [id, record] of actuallyDeleted) {\n\t\t\t\tremoved[id] = record\n\t\t\t\tthis.addDiffForAfterEvent(record, null)\n\t\t\t}\n\n\t\t\t// Update the history with the removed records.\n\t\t\tthis.updateHistory({ added: {}, updated: {}, removed } as RecordsDiff<R>)\n\t\t})\n\t}\n\n\t/**\n\t * Get a record by its ID. This creates a reactive subscription to the record.\n\t *\n\t * @example\n\t * ```ts\n\t * const book = store.get(bookId)\n\t * if (book) {\n\t * console.log(book.title)\n\t * }\n\t * ```\n\t *\n\t * @param id - The ID of the record to get\n\t * @returns The record if it exists, undefined otherwise\n\t * @public\n\t */\n\tget<K extends IdOf<R>>(id: K): RecordFromId<K> | undefined {\n\t\treturn this.records.get(id) as RecordFromId<K> | undefined\n\t}\n\n\t/**\n\t * Get a record by its ID without creating a reactive subscription.\n\t * Use this when you need to access a record but don't want reactive updates.\n\t *\n\t * @example\n\t * ```ts\n\t * // Won't trigger reactive updates when this record changes\n\t * const book = store.unsafeGetWithoutCapture(bookId)\n\t * ```\n\t *\n\t * @param id - The ID of the record to get\n\t * @returns The record if it exists, undefined otherwise\n\t * @public\n\t */\n\tunsafeGetWithoutCapture<K extends IdOf<R>>(id: K): RecordFromId<K> | undefined {\n\t\treturn this.records.__unsafe__getWithoutCapture(id) as RecordFromId<K> | undefined\n\t}\n\n\t/**\n\t * Serialize the store's records to a plain JavaScript object.\n\t * Only includes records matching the specified scope.\n\t *\n\t * @example\n\t * ```ts\n\t * // Serialize only document records (default)\n\t * const documentData = store.serialize('document')\n\t *\n\t * // Serialize all records\n\t * const allData = store.serialize('all')\n\t * ```\n\t *\n\t * @param scope - The scope of records to serialize. Defaults to 'document'\n\t * @returns The serialized store data\n\t * @public\n\t */\n\tserialize(scope: RecordScope | 'all' = 'document'): SerializedStore<R> {\n\t\tconst result = {} as SerializedStore<R>\n\t\tfor (const [id, record] of this.records) {\n\t\t\tif (scope === 'all' || this.scopedTypes[scope].has(record.typeName)) {\n\t\t\t\tresult[id as IdOf<R>] = record\n\t\t\t}\n\t\t}\n\t\treturn result\n\t}\n\n\t/**\n\t * Get a serialized snapshot of the store and its schema.\n\t * This includes both the data and schema information needed for proper migration.\n\t *\n\t * @example\n\t * ```ts\n\t * const snapshot = store.getStoreSnapshot()\n\t * localStorage.setItem('myApp', JSON.stringify(snapshot))\n\t *\n\t * // Later...\n\t * const saved = JSON.parse(localStorage.getItem('myApp'))\n\t * store.loadStoreSnapshot(saved)\n\t * ```\n\t *\n\t * @param scope - The scope of records to serialize. Defaults to 'document'\n\t * @returns A snapshot containing both store data and schema information\n\t * @public\n\t */\n\tgetStoreSnapshot(scope: RecordScope | 'all' = 'document'): StoreSnapshot<R> {\n\t\treturn {\n\t\t\tstore: this.serialize(scope),\n\t\t\tschema: this.schema.serialize(),\n\t\t}\n\t}\n\n\t/**\n\t * Migrate a serialized snapshot to the current schema version.\n\t * This applies any necessary migrations to bring old data up to date.\n\t *\n\t * @example\n\t * ```ts\n\t * const oldSnapshot = JSON.parse(localStorage.getItem('myApp'))\n\t * const migratedSnapshot = store.migrateSnapshot(oldSnapshot)\n\t * ```\n\t *\n\t * @param snapshot - The snapshot to migrate\n\t * @returns The migrated snapshot with current schema version\n\t * @throws Error if migration fails\n\t * @public\n\t */\n\tmigrateSnapshot(snapshot: StoreSnapshot<R>): StoreSnapshot<R> {\n\t\tconst migrationResult = this.schema.migrateStoreSnapshot(snapshot)\n\n\t\tif (migrationResult.type === 'error') {\n\t\t\tthrow new Error(`Failed to migrate snapshot: ${migrationResult.reason}`)\n\t\t}\n\n\t\treturn {\n\t\t\tstore: migrationResult.value,\n\t\t\tschema: this.schema.serialize(),\n\t\t}\n\t}\n\n\t/**\n\t * Load a serialized snapshot into the store, replacing all current data.\n\t * The snapshot will be automatically migrated to the current schema version if needed.\n\t *\n\t * @example\n\t * ```ts\n\t * const snapshot = JSON.parse(localStorage.getItem('myApp'))\n\t * store.loadStoreSnapshot(snapshot)\n\t * ```\n\t *\n\t * @param snapshot - The snapshot to load\n\t * @throws Error if migration fails or snapshot is invalid\n\t * @public\n\t */\n\tloadStoreSnapshot(snapshot: StoreSnapshot<R>): void {\n\t\tconst migrationResult = this.schema.migrateStoreSnapshot(snapshot)\n\n\t\tif (migrationResult.type === 'error') {\n\t\t\tthrow new Error(`Failed to migrate snapshot: ${migrationResult.reason}`)\n\t\t}\n\n\t\tconst prevSideEffectsEnabled = this.sideEffects.isEnabled()\n\t\ttry {\n\t\t\tthis.sideEffects.setIsEnabled(false)\n\t\t\tthis.atomic(() => {\n\t\t\t\tthis.clear()\n\t\t\t\tthis.put(Object.values(migrationResult.value))\n\t\t\t\tthis.ensureStoreIsUsable()\n\t\t\t})\n\t\t} finally {\n\t\t\tthis.sideEffects.setIsEnabled(prevSideEffectsEnabled)\n\t\t}\n\t}\n\n\t/**\n\t * Get an array of all records in the store.\n\t *\n\t * @example\n\t * ```ts\n\t * const allRecords = store.allRecords()\n\t * const books = allRecords.filter(r => r.typeName === 'book')\n\t * ```\n\t *\n\t * @returns An array containing all records in the store\n\t * @public\n\t */\n\tallRecords(): R[] {\n\t\treturn Array.from(this.records.values())\n\t}\n\n\t/**\n\t * Remove all records from the store.\n\t *\n\t * @example\n\t * ```ts\n\t * store.clear()\n\t * console.log(store.allRecords().length) // 0\n\t * ```\n\t *\n\t * @public\n\t */\n\tclear(): void {\n\t\tthis.remove(Array.from(this.records.keys()))\n\t}\n\n\t/**\n\t * Update a single record using an updater function. To update multiple records at once,\n\t * use the `update` method of the `TypedStore` class.\n\t *\n\t * @example\n\t * ```ts\n\t * store.update(book.id, (book) => ({\n\t * ...book,\n\t * title: 'Updated Title'\n\t * }))\n\t * ```\n\t *\n\t * @param id - The ID of the record to update\n\t * @param updater - A function that receives the current record and returns the updated record\n\t * @public\n\t */\n\tupdate<K extends IdOf<R>>(id: K, updater: (record: RecordFromId<K>) => RecordFromId<K>) {\n\t\tconst existing = this.unsafeGetWithoutCapture(id)\n\t\tif (!existing) {\n\t\t\tconsole.error(`Record ${id} not found. This is probably an error`)\n\t\t\treturn\n\t\t}\n\n\t\tthis.put([updater(existing) as any])\n\t}\n\n\t/**\n\t * Check whether a record with the given ID exists in the store.\n\t *\n\t * @example\n\t * ```ts\n\t * if (store.has(bookId)) {\n\t * console.log('Book exists!')\n\t * }\n\t * ```\n\t *\n\t * @param id - The ID of the record to check\n\t * @returns True if the record exists, false otherwise\n\t * @public\n\t */\n\thas<K extends IdOf<R>>(id: K): boolean {\n\t\treturn this.records.has(id)\n\t}\n\n\t/**\n\t * Add a listener that will be called when the store changes.\n\t * Returns a function to remove the listener.\n\t *\n\t * @example\n\t * ```ts\n\t * const removeListener = store.listen((entry) => {\n\t * console.log('Changes:', entry.changes)\n\t * console.log('Source:', entry.source)\n\t * })\n\t *\n\t * // Listen only to user changes to document records\n\t * const removeDocumentListener = store.listen(\n\t * (entry) => console.log('Document changed:', entry),\n\t * { source: 'user', scope: 'document' }\n\t * )\n\t *\n\t * // Later, remove the listener\n\t * removeListener()\n\t * ```\n\t *\n\t * @param onHistory - The listener function to call when changes occur\n\t * @param filters - Optional filters to control when the listener is called\n\t * @returns A function that removes the listener when called\n\t * @public\n\t */\n\tlisten(onHistory: StoreListener<R>, filters?: Partial<StoreListenerFilters>) {\n\t\t// flush history so that this listener's history starts from exactly now\n\t\tthis._flushHistory()\n\n\t\tconst listener = {\n\t\t\tonHistory,\n\t\t\tfilters: {\n\t\t\t\tsource: filters?.source ?? 'all',\n\t\t\t\tscope: filters?.scope ?? 'all',\n\t\t\t},\n\t\t}\n\n\t\tif (!this.historyReactor.scheduler.isActivelyListening) {\n\t\t\tthis.historyReactor.start()\n\t\t\tthis.historyReactor.scheduler.execute()\n\t\t}\n\n\t\tthis.listeners.add(listener)\n\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener)\n\n\t\t\tif (this.listeners.size === 0) {\n\t\t\t\tthis.historyReactor.stop()\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate isMergingRemoteChanges = false\n\n\t/**\n\t * Merge changes from a remote source. Changes made within the provided function\n\t * will be marked with source 'remote' instead of 'user'.\n\t *\n\t * @example\n\t * ```ts\n\t * // Changes from sync/collaboration\n\t * store.mergeRemoteChanges(() => {\n\t * store.put(remoteRecords)\n\t * store.remove(deletedIds)\n\t * })\n\t * ```\n\t *\n\t * @param fn - A function that applies the remote changes\n\t * @public\n\t */\n\tmergeRemoteChanges(fn: () => void) {\n\t\tif (this.isMergingRemoteChanges) {\n\t\t\treturn fn()\n\t\t}\n\n\t\tif (this._isInAtomicOp) {\n\t\t\tthrow new Error('Cannot merge remote changes while in atomic operation')\n\t\t}\n\n\t\ttry {\n\t\t\tthis.atomic(fn, true, true)\n\t\t} finally {\n\t\t\tthis.ensureStoreIsUsable()\n\t\t}\n\t}\n\n\t/**\n\t * Run `fn` and return a {@link RecordsDiff} of the changes that occurred as a result.\n\t */\n\textractingChanges(fn: () => void): RecordsDiff<R> {\n\t\tconst changes: Array<RecordsDiff<R>> = []\n\t\tconst dispose = this.historyAccumulator.addInterceptor((entry) => changes.push(entry.changes))\n\t\ttry {\n\t\t\ttransact(fn)\n\t\t\treturn squashRecordDiffs(changes)\n\t\t} finally {\n\t\t\tdispose()\n\t\t}\n\t}\n\n\tapplyDiff(\n\t\tdiff: RecordsDiff<R>,\n\t\t{\n\t\t\trunCallbacks = true,\n\t\t\tignoreEphemeralKeys = false,\n\t\t}: { runCallbacks?: boolean; ignoreEphemeralKeys?: boolean } = {}\n\t) {\n\t\tthis.atomic(() => {\n\t\t\tconst toPut = objectMapValues(diff.added)\n\n\t\t\tfor (const [_from, to] of objectMapValues(diff.updated)) {\n\t\t\t\tconst type = this.schema.getType(to.typeName)\n\t\t\t\tif (ignoreEphemeralKeys && type.ephemeralKeySet.size) {\n\t\t\t\t\tconst existing = this.get(to.id)\n\t\t\t\t\tif (!existing) {\n\t\t\t\t\t\ttoPut.push(to)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tlet changed: R | null = null\n\t\t\t\t\tfor (const [key, value] of Object.entries(to)) {\n\t\t\t\t\t\tif (type.ephemeralKeySet.has(key) || Object.is(value, getOwnProperty(existing, key))) {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!changed) changed = { ...existing } as R\n\t\t\t\t\t\t;(changed as any)[key] = value\n\t\t\t\t\t}\n\t\t\t\t\tif (changed) toPut.push(changed)\n\t\t\t\t} else {\n\t\t\t\t\ttoPut.push(to)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst toRemove = objectMapKeys(diff.removed)\n\t\t\tif (toPut.length) {\n\t\t\t\tthis.put(toPut)\n\t\t\t}\n\t\t\tif (toRemove.length) {\n\t\t\t\tthis.remove(toRemove)\n\t\t\t}\n\t\t}, runCallbacks)\n\t}\n\n\t/**\n\t * Create a cache based on values in the store. Pass in a function that takes and ID and a\n\t * signal for the underlying record. Return a signal (usually a computed) for the cached value.\n\t * For simple derivations, use {@link Store.createComputedCache}. This function is useful if you\n\t * need more precise control over intermediate values.\n\t */\n\tcreateCache<Result, Record extends R = R>(\n\t\tcreate: (id: IdOf<Record>, recordSignal: Signal<R>) => Signal<Result>\n\t) {\n\t\tconst cache = new WeakCache<Atom<any>, Signal<Result>>()\n\t\treturn {\n\t\t\tget: (id: IdOf<Record>) => {\n\t\t\t\tconst atom = this.records.getAtom(id)\n\t\t\t\tif (!atom) return undefined\n\t\t\t\treturn cache.get(atom, () => create(id, atom as Signal<R>)).get()\n\t\t\t},\n\t\t}\n\t}\n\n\t/**\n\t * Create a computed cache.\n\t *\n\t * @param name - The name of the derivation cache.\n\t * @param derive - A function used to derive the value of the cache.\n\t * @param opts - Options for the computed cache.\n\t * @public\n\t */\n\tcreateComputedCache<Result, Record extends R = R>(\n\t\tname: string,\n\t\tderive: (record: Record) => Result | undefined,\n\t\topts?: CreateComputedCacheOpts<Result, Record>\n\t): ComputedCache<Result, Record> {\n\t\treturn this.createCache((id, record) => {\n\t\t\tconst recordSignal = opts?.areRecordsEqual\n\t\t\t\t? computed(`${name}:${id}:isEqual`, () => record.get(), { isEqual: opts.areRecordsEqual })\n\t\t\t\t: record\n\n\t\t\treturn computed<Result | undefined>(\n\t\t\t\tname + ':' + id,\n\t\t\t\t() => {\n\t\t\t\t\treturn derive(recordSignal.get() as Record)\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tisEqual: opts?.areResultsEqual,\n\t\t\t\t}\n\t\t\t)\n\t\t})\n\t}\n\n\tprivate _integrityChecker?: () => void | undefined\n\n\t/** @internal */\n\tensureStoreIsUsable() {\n\t\tthis.atomic(() => {\n\t\t\tthis._integrityChecker ??= this.schema.createIntegrityChecker(this)\n\t\t\tthis._integrityChecker?.()\n\t\t})\n\t}\n\n\tprivate _isPossiblyCorrupted = false\n\t/** @internal */\n\tmarkAsPossiblyCorrupted() {\n\t\tthis._isPossiblyCorrupted = true\n\t}\n\t/** @internal */\n\tisPossiblyCorrupted() {\n\t\treturn this._isPossiblyCorrupted\n\t}\n\n\tprivate pendingAfterEvents: Map<IdOf<R>, { before: R | null; after: R | null }> | null = null\n\tprivate addDiffForAfterEvent(before: R | null, after: R | null) {\n\t\tassert(this.pendingAfterEvents, 'must be in event operation')\n\t\tif (before === after) return\n\t\tif (before && after) assert(before.id === after.id)\n\t\tif (!before && !after) return\n\t\tconst id = (before || after)!.id\n\t\tconst existing = this.pendingAfterEvents.get(id)\n\t\tif (existing) {\n\t\t\texisting.after = after\n\t\t} else {\n\t\t\tthis.pendingAfterEvents.set(id, { before, after })\n\t\t}\n\t}\n\tprivate flushAtomicCallbacks(isMergingRemoteChanges: boolean) {\n\t\tlet updateDepth = 0\n\t\tlet source: ChangeSource = isMergingRemoteChanges ? 'remote' : 'user'\n\t\twhile (this.pendingAfterEvents) {\n\t\t\tconst events = this.pendingAfterEvents\n\t\t\tthis.pendingAfterEvents = null\n\n\t\t\tif (!this.sideEffects.isEnabled()) continue\n\n\t\t\tupdateDepth++\n\t\t\tif (updateDepth > 100) {\n\t\t\t\tthrow new Error('Maximum store update depth exceeded, bailing out')\n\t\t\t}\n\n\t\t\tfor (const { before, after } of events.values()) {\n\t\t\t\tif (before && after && before !== after && !isEqual(before, after)) {\n\t\t\t\t\tthis.sideEffects.handleAfterChange(before, after, source)\n\t\t\t\t} else if (before && !after) {\n\t\t\t\t\tthis.sideEffects.handleAfterDelete(before, source)\n\t\t\t\t} else if (!before && after) {\n\t\t\t\t\tthis.sideEffects.handleAfterCreate(after, source)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!this.pendingAfterEvents) {\n\t\t\t\tthis.sideEffects.handleOperationComplete(source)\n\t\t\t} else {\n\t\t\t\t// if the side effects triggered by a remote operation resulted in more effects,\n\t\t\t\t// those extra effects should not be marked as originating remotely.\n\t\t\t\tsource = 'user'\n\t\t\t}\n\t\t}\n\t}\n\tprivate _isInAtomicOp = false\n\t/** @internal */\n\tatomic<T>(fn: () => T, runCallbacks = true, isMergingRemoteChanges = false): T {\n\t\treturn transact(() => {\n\t\t\tif (this._isInAtomicOp) {\n\t\t\t\tif (!this.pendingAfterEvents) this.pendingAfterEvents = new Map()\n\t\t\t\tconst prevSideEffectsEnabled = this.sideEffects.isEnabled()\n\t\t\t\tassert(!isMergingRemoteChanges, 'cannot call mergeRemoteChanges while in atomic operation')\n\t\t\t\ttry {\n\t\t\t\t\t// if we are in an atomic context with side effects ON allow switching before* callbacks OFF.\n\t\t\t\t\t// but don't allow switching them ON if they had been marked OFF before.\n\t\t\t\t\tif (prevSideEffectsEnabled && !runCallbacks) {\n\t\t\t\t\t\tthis.sideEffects.setIsEnabled(false)\n\t\t\t\t\t}\n\t\t\t\t\treturn fn()\n\t\t\t\t} finally {\n\t\t\t\t\tthis.sideEffects.setIsEnabled(prevSideEffectsEnabled)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.pendingAfterEvents = new Map()\n\t\t\tconst prevSideEffectsEnabled = this.sideEffects.isEnabled()\n\t\t\tthis.sideEffects.setIsEnabled(runCallbacks ?? prevSideEffectsEnabled)\n\t\t\tthis._isInAtomicOp = true\n\n\t\t\tif (isMergingRemoteChanges) {\n\t\t\t\tthis.isMergingRemoteChanges = true\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst result = fn()\n\t\t\t\tthis.isMergingRemoteChanges = false\n\n\t\t\t\tthis.flushAtomicCallbacks(isMergingRemoteChanges)\n\n\t\t\t\treturn result\n\t\t\t} finally {\n\t\t\t\tthis.pendingAfterEvents = null\n\t\t\t\tthis.sideEffects.setIsEnabled(prevSideEffectsEnabled)\n\t\t\t\tthis._isInAtomicOp = false\n\t\t\t\tthis.isMergingRemoteChanges = false\n\t\t\t}\n\t\t})\n\t}\n\n\t/** @internal */\n\taddHistoryInterceptor(fn: (entry: HistoryEntry<R>, source: ChangeSource) => void) {\n\t\treturn this.historyAccumulator.addInterceptor((entry) =>\n\t\t\tfn(entry, this.isMergingRemoteChanges ? 'remote' : 'user')\n\t\t)\n\t}\n}\n\n/**\n * Collect and squash history entries by their adjacent sources.\n * Adjacent entries from the same source are combined into a single entry.\n *\n * For example: [user, user, remote, remote, user] becomes [user, remote, user]\n *\n * @example\n * ```ts\n * const entries = [\n * { source: 'user', changes: userChanges1 },\n * { source: 'user', changes: userChanges2 },\n * { source: 'remote', changes: remoteChanges }\n * ]\n *\n * const squashed = squashHistoryEntries(entries)\n * // Results in 2 entries: combined user changes + remote changes\n * ```\n *\n * @param entries - The array of history entries to squash\n * @returns An array of squashed history entries\n * @public\n */\nfunction squashHistoryEntries<T extends UnknownRecord>(\n\tentries: HistoryEntry<T>[]\n): HistoryEntry<T>[] {\n\tif (entries.length === 0) return []\n\n\tconst chunked: HistoryEntry<T>[][] = []\n\tlet chunk: HistoryEntry<T>[] = [entries[0]]\n\tlet entry: HistoryEntry<T>\n\n\tfor (let i = 1, n = entries.length; i < n; i++) {\n\t\tentry = entries[i]\n\t\tif (chunk[0].source !== entry.source) {\n\t\t\tchunked.push(chunk)\n\t\t\tchunk = []\n\t\t}\n\t\tchunk.push(entry)\n\t}\n\t// Push the last chunk\n\tchunked.push(chunk)\n\n\treturn devFreeze(\n\t\tchunked.map((chunk) => ({\n\t\t\tsource: chunk[0].source,\n\t\t\tchanges: squashRecordDiffs(chunk.map((e) => e.changes)),\n\t\t}))\n\t)\n}\n\n/**\n * Internal class that accumulates history entries before they are flushed to listeners.\n * Handles batching and squashing of adjacent entries from the same source.\n *\n * @internal\n */\nclass HistoryAccumulator<T extends UnknownRecord> {\n\tprivate _history: HistoryEntry<T>[] = []\n\n\tprivate _interceptors: Set<(entry: HistoryEntry<T>) => void> = new Set()\n\n\t/**\n\t * Add an interceptor that will be called for each history entry.\n\t * Returns a function to remove the interceptor.\n\t */\n\taddInterceptor(fn: (entry: HistoryEntry<T>) => void) {\n\t\tthis._interceptors.add(fn)\n\t\treturn () => {\n\t\t\tthis._interceptors.delete(fn)\n\t\t}\n\t}\n\n\t/**\n\t * Add a history entry to the accumulator.\n\t * Calls all registered interceptors with the entry.\n\t */\n\tadd(entry: HistoryEntry<T>) {\n\t\tthis._history.push(entry)\n\t\tfor (const interceptor of this._interceptors) {\n\t\t\tinterceptor(entry)\n\t\t}\n\t}\n\n\t/**\n\t * Flush all accumulated history entries, squashing adjacent entries from the same source.\n\t * Clears the internal history buffer.\n\t */\n\tflush() {\n\t\tconst history = squashHistoryEntries(this._history)\n\t\tthis._history = []\n\t\treturn history\n\t}\n\n\t/**\n\t * Clear all accumulated history entries without flushing.\n\t */\n\tclear() {\n\t\tthis._history = []\n\t}\n\n\t/**\n\t * Check if there are any accumulated history entries.\n\t */\n\thasChanges() {\n\t\treturn this._history.length > 0\n\t}\n}\n\n/**\n * A store or an object containing a store.\n * This type is used for APIs that can accept either a store directly or an object with a store property.\n *\n * @example\n * ```ts\n * function useStore(storeOrObject: StoreObject<MyRecord>) {\n * const store = storeOrObject instanceof Store ? storeOrObject : storeOrObject.store\n * return store\n * }\n * ```\n *\n * @public\n */\nexport type StoreObject<R extends UnknownRecord> = Store<R> | { store: Store<R> }\n/**\n * Extract the record type from a StoreObject.\n *\n * @example\n * ```ts\n * type MyStoreObject = { store: Store<Book | Author> }\n * type Records = StoreObjectRecordType<MyStoreObject> // Book | Author\n * ```\n *\n * @public\n */\nexport type StoreObjectRecordType<Context extends StoreObject<any>> =\n\tContext extends Store<infer R> ? R : Context extends { store: Store<infer R> } ? R : never\n\n/**\n * Create a computed cache that works with any StoreObject (store or object containing a store).\n * This is a standalone version of Store.createComputedCache that can work with multiple store instances.\n *\n * @example\n * ```ts\n * const expensiveCache = createComputedCache(\n * 'expensiveData',\n * (context: { store: Store<Book> }, book: Book) => {\n * return performExpensiveCalculation(book)\n * }\n * )\n *\n * // Use with different store instances\n * const result1 = expensiveCache.get(storeObject1, bookId)\n * const result2 = expensiveCache.get(storeObject2, bookId)\n * ```\n *\n * @param name - A unique name for the cache (used for debugging)\n * @param derive - Function that derives a value from the context and record\n * @param opts - Optional configuration for equality checks\n * @returns A cache that can be used with multiple store instances\n * @public\n */\nexport function createComputedCache<\n\tContext extends StoreObject<any>,\n\tResult,\n\tRecord extends StoreObjectRecordType<Context> = StoreObjectRecordType<Context>,\n>(\n\tname: string,\n\tderive: (context: Context, record: Record) => Result | undefined,\n\topts?: CreateComputedCacheOpts<Result, Record>\n) {\n\tconst cache = new WeakCache<Context, ComputedCache<Result, Record>>()\n\treturn {\n\t\tget(context: Context, id: IdOf<Record>) {\n\t\t\tconst computedCache = cache.get(context, () => {\n\t\t\t\tconst store = (context instanceof Store ? context : context.store) as Store<Record>\n\t\t\t\treturn store.createComputedCache(name, (record) => derive(context, record), opts)\n\t\t\t})\n\t\t\treturn computedCache.get(id)\n\t\t},\n\t}\n}\n","import {\n\tassert,\n\texhaustiveSwitchError,\n\tgetOwnProperty,\n\tisEqual,\n\tobjectMapEntries,\n\tResult,\n\tstructuredClone,\n} from '@ibodr/utils'\nimport { UnknownRecord } from './BaseRecord'\nimport { devFreeze } from './devFreeze'\nimport {\n\tMigration,\n\tMigrationFailureReason,\n\tMigrationId,\n\tMigrationResult,\n\tMigrationSequence,\n\tparseMigrationId,\n\tsortMigrations,\n\tSynchronousStorage,\n\tvalidateMigrations,\n} from './migrate'\nimport { RecordType } from './RecordType'\nimport { SerializedStore, Store, StoreSnapshot } from './Store'\n\n/**\n * Version 1 format for serialized store schema information.\n *\n * This is the legacy format used before schema version 2. Version 1 schemas\n * separate store-level versioning from record-level versioning, and support\n * subtypes for complex record types like shapes.\n *\n * @example\n * ```ts\n * const schemaV1: SerializedSchemaV1 = {\n * schemaVersion: 1,\n * storeVersion: 2,\n * recordVersions: {\n * book: { version: 3 },\n * shape: {\n * version: 2,\n * subTypeVersions: { rectangle: 1, circle: 2 },\n * subTypeKey: 'type'\n * }\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface SerializedSchemaV1 {\n\t/** Schema version is the version for this type you're looking at right now */\n\tschemaVersion: 1\n\t/**\n\t * Store version is the version for the structure of the store. e.g. higher level structure like\n\t * removing or renaming a record type.\n\t */\n\tstoreVersion: number\n\t/** Record versions are the versions for each record type. e.g. adding a new field to a record */\n\trecordVersions: Record<\n\t\tstring,\n\t\t| {\n\t\t\t\tversion: number\n\t\t }\n\t\t| {\n\t\t\t\t// subtypes are used for migrating shape and asset props\n\t\t\t\tversion: number\n\t\t\t\tsubTypeVersions: Record<string, number>\n\t\t\t\tsubTypeKey: string\n\t\t }\n\t>\n}\n\n/**\n * Version 2 format for serialized store schema information.\n *\n * This is the current format that uses a unified sequence-based approach\n * for tracking versions across all migration sequences. Each sequence ID\n * maps to the latest version number for that sequence.\n *\n * @example\n * ```ts\n * const schemaV2: SerializedSchemaV2 = {\n * schemaVersion: 2,\n * sequences: {\n * 'com.draw.store': 3,\n * 'com.draw.book': 2,\n * 'com.draw.shape': 4,\n * 'com.draw.shape.rectangle': 1\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface SerializedSchemaV2 {\n\tschemaVersion: 2\n\tsequences: {\n\t\t[sequenceId: string]: number\n\t}\n}\n\n/**\n * Union type representing all supported serialized schema formats.\n *\n * This type allows the store to handle both legacy (V1) and current (V2)\n * schema formats during deserialization and migration.\n *\n * @example\n * ```ts\n * function handleSchema(schema: SerializedSchema) {\n * if (schema.schemaVersion === 1) {\n * // Handle V1 format\n * console.log('Store version:', schema.storeVersion)\n * } else {\n * // Handle V2 format\n * console.log('Sequences:', schema.sequences)\n * }\n * }\n * ```\n *\n * @public\n */\nexport type SerializedSchema = SerializedSchemaV1 | SerializedSchemaV2\n\n/**\n * Upgrades a serialized schema from version 1 to version 2 format.\n *\n * Version 1 schemas use separate `storeVersion` and `recordVersions` fields,\n * while version 2 schemas use a unified `sequences` object with sequence IDs.\n *\n * @param schema - The serialized schema to upgrade\n * @returns A Result containing the upgraded schema or an error message\n *\n * @example\n * ```ts\n * const v1Schema = {\n * schemaVersion: 1,\n * storeVersion: 1,\n * recordVersions: {\n * book: { version: 2 },\n * author: { version: 1, subTypeVersions: { fiction: 1 }, subTypeKey: 'genre' }\n * }\n * }\n *\n * const result = upgradeSchema(v1Schema)\n * if (result.ok) {\n * console.log(result.value.sequences)\n * // { 'com.draw.store': 1, 'com.draw.book': 2, 'com.draw.author': 1, 'com.draw.author.fiction': 1 }\n * }\n * ```\n *\n * @public\n */\nexport function upgradeSchema(schema: SerializedSchema): Result<SerializedSchemaV2, string> {\n\tif (schema.schemaVersion > 2 || schema.schemaVersion < 1) return Result.err('Bad schema version')\n\tif (schema.schemaVersion === 2) return Result.ok(schema as SerializedSchemaV2)\n\tconst result: SerializedSchemaV2 = {\n\t\tschemaVersion: 2,\n\t\tsequences: {\n\t\t\t'com.draw.store': schema.storeVersion,\n\t\t},\n\t}\n\n\tfor (const [typeName, recordVersion] of Object.entries(schema.recordVersions)) {\n\t\tresult.sequences[`com.draw.${typeName}`] = recordVersion.version\n\t\tif ('subTypeKey' in recordVersion) {\n\t\t\tfor (const [subType, version] of Object.entries(recordVersion.subTypeVersions)) {\n\t\t\t\tresult.sequences[`com.draw.${typeName}.${subType}`] = version\n\t\t\t}\n\t\t}\n\t}\n\treturn Result.ok(result)\n}\n\n/**\n * Information about a record validation failure that occurred in the store.\n *\n * This interface provides context about validation errors, including the failed\n * record, the store state, and the operation phase where the failure occurred.\n * It's used by validation failure handlers to implement recovery strategies.\n *\n * @example\n * ```ts\n * const schema = StoreSchema.create(\n * { book: Book },\n * {\n * onValidationFailure: (failure: StoreValidationFailure<Book>) => {\n * console.error(`Validation failed during ${failure.phase}:`, failure.error)\n * console.log('Failed record:', failure.record)\n * console.log('Previous record:', failure.recordBefore)\n *\n * // Return a corrected version of the record\n * return { ...failure.record, title: failure.record.title || 'Untitled' }\n * }\n * }\n * )\n * ```\n *\n * @public\n */\nexport interface StoreValidationFailure<R extends UnknownRecord> {\n\terror: unknown\n\tstore: Store<R>\n\trecord: R\n\tphase: 'initialize' | 'createRecord' | 'updateRecord' | 'tests'\n\trecordBefore: R | null\n}\n\n/**\n * Configuration options for creating a StoreSchema.\n *\n * These options control migration behavior, validation error handling,\n * and integrity checking for the store schema.\n *\n * @example\n * ```ts\n * const options: StoreSchemaOptions<MyRecord, MyProps> = {\n * migrations: [bookMigrations, authorMigrations],\n * onValidationFailure: (failure) => {\n * // Log the error and return a corrected record\n * console.error('Validation failed:', failure.error)\n * return sanitizeRecord(failure.record)\n * },\n * createIntegrityChecker: (store) => {\n * // Set up integrity checking logic\n * return setupIntegrityChecks(store)\n * }\n * }\n * ```\n *\n * @public\n */\nexport interface StoreSchemaOptions<R extends UnknownRecord, P> {\n\tmigrations?: MigrationSequence[]\n\t/** @public */\n\tonValidationFailure?(data: StoreValidationFailure<R>): R\n\t/** @internal */\n\tcreateIntegrityChecker?(store: Store<R, P>): void\n}\n\n/**\n * Manages the schema definition, validation, and migration system for a Store.\n *\n * StoreSchema coordinates record types, handles data migrations between schema\n * versions, validates records, and provides the foundational structure for\n * reactive stores. It acts as the central authority for data consistency\n * and evolution within the store system.\n *\n * @example\n * ```ts\n * // Define record types\n * const Book = createRecordType<Book>('book', { scope: 'document' })\n * const Author = createRecordType<Author>('author', { scope: 'document' })\n *\n * // Create schema with migrations\n * const schema = StoreSchema.create(\n * { book: Book, author: Author },\n * {\n * migrations: [bookMigrations, authorMigrations],\n * onValidationFailure: (failure) => {\n * console.warn('Validation failed, using default:', failure.error)\n * return failure.record // or return a corrected version\n * }\n * }\n * )\n *\n * // Use with store\n * const store = new Store({ schema })\n * ```\n *\n * @public\n */\nexport class StoreSchema<R extends UnknownRecord, P = unknown> {\n\t/**\n\t * Creates a new StoreSchema with the given record types and options.\n\t *\n\t * This static factory method is the recommended way to create a StoreSchema.\n\t * It ensures type safety while providing a clean API for schema definition.\n\t *\n\t * @param types - Object mapping type names to their RecordType definitions\n\t * @param options - Optional configuration for migrations, validation, and integrity checking\n\t * @returns A new StoreSchema instance\n\t *\n\t * @example\n\t * ```ts\n\t * const Book = createRecordType<Book>('book', { scope: 'document' })\n\t * const Author = createRecordType<Author>('author', { scope: 'document' })\n\t *\n\t * const schema = StoreSchema.create(\n\t * {\n\t * book: Book,\n\t * author: Author\n\t * },\n\t * {\n\t * migrations: [bookMigrations],\n\t * onValidationFailure: (failure) => failure.record\n\t * }\n\t * )\n\t * ```\n\t *\n\t * @public\n\t */\n\tstatic create<R extends UnknownRecord, P = unknown>(\n\t\t// HACK: making this param work with RecordType is an enormous pain\n\t\t// let's just settle for making sure each typeName has a corresponding RecordType\n\t\t// and accept that this function won't be able to infer the record type from it's arguments\n\t\ttypes: { [TypeName in R['typeName']]: { createId: any } },\n\t\toptions?: StoreSchemaOptions<R, P>\n\t): StoreSchema<R, P> {\n\t\treturn new StoreSchema<R, P>(types as any, options ?? {})\n\t}\n\n\treadonly migrations: Record<string, MigrationSequence> = {}\n\treadonly sortedMigrations: readonly Migration[]\n\tprivate readonly migrationCache = new WeakMap<SerializedSchema, Result<Migration[], string>>()\n\n\tprivate constructor(\n\t\tpublic readonly types: {\n\t\t\t[Record in R as Record['typeName']]: RecordType<R, any>\n\t\t},\n\t\tprivate readonly options: StoreSchemaOptions<R, P>\n\t) {\n\t\tfor (const m of options.migrations ?? []) {\n\t\t\tassert(!this.migrations[m.sequenceId], `Duplicate migration sequenceId ${m.sequenceId}`)\n\t\t\tvalidateMigrations(m)\n\t\t\tthis.migrations[m.sequenceId] = m\n\t\t}\n\t\tconst allMigrations = Object.values(this.migrations).flatMap((m) => m.sequence)\n\t\tthis.sortedMigrations = sortMigrations(allMigrations)\n\n\t\tfor (const migration of this.sortedMigrations) {\n\t\t\tif (!migration.dependsOn?.length) continue\n\t\t\tfor (const dep of migration.dependsOn) {\n\t\t\t\tconst depMigration = allMigrations.find((m) => m.id === dep)\n\t\t\t\tassert(depMigration, `Migration '${migration.id}' depends on missing migration '${dep}'`)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Validates a record using its corresponding RecordType validator.\n\t *\n\t * This method ensures that records conform to their type definitions before\n\t * being stored. If validation fails and an onValidationFailure handler is\n\t * provided, it will be called to potentially recover from the error.\n\t *\n\t * @param store - The store instance where validation is occurring\n\t * @param record - The record to validate\n\t * @param phase - The lifecycle phase where validation is happening\n\t * @param recordBefore - The previous version of the record (for updates)\n\t * @returns The validated record, potentially modified by validation failure handler\n\t *\n\t * @example\n\t * ```ts\n\t * try {\n\t * const validatedBook = schema.validateRecord(\n\t * store,\n\t * { id: 'book:1', typeName: 'book', title: '', author: 'Jane Doe' },\n\t * 'createRecord',\n\t * null\n\t * )\n\t * } catch (error) {\n\t * console.error('Record validation failed:', error)\n\t * }\n\t * ```\n\t *\n\t * @public\n\t */\n\tvalidateRecord(\n\t\tstore: Store<R>,\n\t\trecord: R,\n\t\tphase: 'initialize' | 'createRecord' | 'updateRecord' | 'tests',\n\t\trecordBefore: R | null\n\t): R {\n\t\ttry {\n\t\t\tconst recordType = getOwnProperty(this.types, record.typeName)\n\t\t\tif (!recordType) {\n\t\t\t\tthrow new Error(`Missing definition for record type ${record.typeName}`)\n\t\t\t}\n\t\t\treturn recordType.validate(record, recordBefore ?? undefined)\n\t\t} catch (error: unknown) {\n\t\t\tif (this.options.onValidationFailure) {\n\t\t\t\treturn this.options.onValidationFailure({\n\t\t\t\t\tstore,\n\t\t\t\t\trecord,\n\t\t\t\t\tphase,\n\t\t\t\t\trecordBefore,\n\t\t\t\t\terror,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tthrow error\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Gets all migrations that need to be applied to upgrade from a persisted schema\n\t * to the current schema version.\n\t *\n\t * This method compares the persisted schema with the current schema and determines\n\t * which migrations need to be applied to bring the data up to date. It handles\n\t * both regular migrations and retroactive migrations, and caches results for\n\t * performance.\n\t *\n\t * @param persistedSchema - The schema version that was previously persisted\n\t * @returns A Result containing the list of migrations to apply, or an error message\n\t *\n\t * @example\n\t * ```ts\n\t * const persistedSchema = {\n\t * schemaVersion: 2,\n\t * sequences: { 'com.draw.book': 1, 'com.draw.author': 0 }\n\t * }\n\t *\n\t * const migrationsResult = schema.getMigrationsSince(persistedSchema)\n\t * if (migrationsResult.ok) {\n\t * console.log('Migrations to apply:', migrationsResult.value.length)\n\t * // Apply each migration to bring data up to date\n\t * }\n\t * ```\n\t *\n\t * @public\n\t */\n\tpublic getMigrationsSince(persistedSchema: SerializedSchema): Result<Migration[], string> {\n\t\t// Check cache first\n\t\tconst cached = this.migrationCache.get(persistedSchema)\n\t\tif (cached) {\n\t\t\treturn cached\n\t\t}\n\n\t\tconst upgradeResult = upgradeSchema(persistedSchema)\n\t\tif (!upgradeResult.ok) {\n\t\t\t// Cache the error result\n\t\t\tthis.migrationCache.set(persistedSchema, upgradeResult)\n\t\t\treturn upgradeResult\n\t\t}\n\t\tconst schema = upgradeResult.value\n\t\tconst sequenceIdsToInclude = new Set(\n\t\t\t// start with any shared sequences\n\t\t\tObject.keys(schema.sequences).filter((sequenceId) => this.migrations[sequenceId])\n\t\t)\n\n\t\t// also include any sequences that are not in the persisted schema but are marked as postHoc\n\t\tfor (const sequenceId in this.migrations) {\n\t\t\tif (schema.sequences[sequenceId] === undefined && this.migrations[sequenceId].retroactive) {\n\t\t\t\tsequenceIdsToInclude.add(sequenceId)\n\t\t\t}\n\t\t}\n\n\t\tif (sequenceIdsToInclude.size === 0) {\n\t\t\tconst result = Result.ok([])\n\t\t\t// Cache the empty result\n\t\t\tthis.migrationCache.set(persistedSchema, result)\n\t\t\treturn result\n\t\t}\n\n\t\tconst allMigrationsToInclude = new Set<MigrationId>()\n\t\tfor (const sequenceId of sequenceIdsToInclude) {\n\t\t\tconst theirVersion = schema.sequences[sequenceId]\n\t\t\tif (\n\t\t\t\t(typeof theirVersion !== 'number' && this.migrations[sequenceId].retroactive) ||\n\t\t\t\ttheirVersion === 0\n\t\t\t) {\n\t\t\t\tfor (const migration of this.migrations[sequenceId].sequence) {\n\t\t\t\t\tallMigrationsToInclude.add(migration.id)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst theirVersionId = `${sequenceId}/${theirVersion}`\n\t\t\tconst idx = this.migrations[sequenceId].sequence.findIndex((m) => m.id === theirVersionId)\n\t\t\t// todo: better error handling\n\t\t\tif (idx === -1) {\n\t\t\t\tconst result = Result.err('Incompatible schema?')\n\t\t\t\t// Cache the error result\n\t\t\t\tthis.migrationCache.set(persistedSchema, result)\n\t\t\t\treturn result\n\t\t\t}\n\t\t\tfor (const migration of this.migrations[sequenceId].sequence.slice(idx + 1)) {\n\t\t\t\tallMigrationsToInclude.add(migration.id)\n\t\t\t}\n\t\t}\n\n\t\t// collect any migrations\n\t\tconst result = Result.ok(\n\t\t\tthis.sortedMigrations.filter(({ id }) => allMigrationsToInclude.has(id))\n\t\t)\n\t\t// Cache the result\n\t\tthis.migrationCache.set(persistedSchema, result)\n\t\treturn result\n\t}\n\n\t/**\n\t * Migrates a single persisted record to match the current schema version.\n\t *\n\t * This method applies the necessary migrations to transform a record from an\n\t * older (or newer) schema version to the current version. It supports both\n\t * forward ('up') and backward ('down') migrations.\n\t *\n\t * @param record - The record to migrate\n\t * @param persistedSchema - The schema version the record was persisted with\n\t * @param direction - Direction to migrate ('up' for newer, 'down' for older)\n\t * @returns A MigrationResult containing the migrated record or an error\n\t *\n\t * @example\n\t * ```ts\n\t * const oldRecord = { id: 'book:1', typeName: 'book', title: 'Old Title', publishDate: '2020-01-01' }\n\t * const oldSchema = { schemaVersion: 2, sequences: { 'com.draw.book': 1 } }\n\t *\n\t * const result = schema.migratePersistedRecord(oldRecord, oldSchema, 'up')\n\t * if (result.type === 'success') {\n\t * console.log('Migrated record:', result.value)\n\t * // Record now has publishedYear instead of publishDate\n\t * } else {\n\t * console.error('Migration failed:', result.reason)\n\t * }\n\t * ```\n\t *\n\t * @public\n\t */\n\tmigratePersistedRecord(\n\t\trecord: R,\n\t\tpersistedSchema: SerializedSchema,\n\t\tdirection: 'up' | 'down' = 'up'\n\t): MigrationResult<R> {\n\t\tconst migrations = this.getMigrationsSince(persistedSchema)\n\t\tif (!migrations.ok) {\n\t\t\t// TODO: better error\n\t\t\tconsole.error('Error migrating record', migrations.error)\n\t\t\treturn { type: 'error', reason: MigrationFailureReason.MigrationError }\n\t\t}\n\t\tlet migrationsToApply = migrations.value\n\t\tif (migrationsToApply.length === 0) {\n\t\t\treturn { type: 'success', value: record }\n\t\t}\n\n\t\tif (!migrationsToApply.every((m) => m.scope === 'record')) {\n\t\t\treturn {\n\t\t\t\ttype: 'error',\n\t\t\t\treason:\n\t\t\t\t\tdirection === 'down'\n\t\t\t\t\t\t? MigrationFailureReason.TargetVersionTooOld\n\t\t\t\t\t\t: MigrationFailureReason.TargetVersionTooNew,\n\t\t\t}\n\t\t}\n\n\t\tif (direction === 'down') {\n\t\t\tif (!migrationsToApply.every((m) => m.scope === 'record' && m.down)) {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'error',\n\t\t\t\t\treason: MigrationFailureReason.TargetVersionTooOld,\n\t\t\t\t}\n\t\t\t}\n\t\t\tmigrationsToApply = migrationsToApply.slice().reverse()\n\t\t}\n\n\t\trecord = structuredClone(record)\n\t\ttry {\n\t\t\tfor (const migration of migrationsToApply) {\n\t\t\t\tif (migration.scope === 'store') throw new Error(/* won't happen, just for TS */)\n\t\t\t\tif (migration.scope === 'storage') throw new Error(/* won't happen, just for TS */)\n\t\t\t\tconst shouldApply = migration.filter ? migration.filter(record) : true\n\t\t\t\tif (!shouldApply) continue\n\t\t\t\tconst result = migration[direction]!(record)\n\t\t\t\tif (result) {\n\t\t\t\t\trecord = structuredClone(result) as any\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconsole.error('Error migrating record', e)\n\t\t\treturn { type: 'error', reason: MigrationFailureReason.MigrationError }\n\t\t}\n\n\t\treturn { type: 'success', value: record }\n\t}\n\n\tmigrateStorage(storage: SynchronousStorage<R>) {\n\t\tconst schema = storage.getSchema()\n\t\tassert(schema, 'Schema is missing.')\n\n\t\tconst migrations = this.getMigrationsSince(schema)\n\t\tif (!migrations.ok) {\n\t\t\tconsole.error('Error migrating store', migrations.error)\n\t\t\tthrow new Error(migrations.error)\n\t\t}\n\t\tconst migrationsToApply = migrations.value\n\t\tif (migrationsToApply.length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tstorage.setSchema(this.serialize())\n\n\t\tfor (const migration of migrationsToApply) {\n\t\t\tif (migration.scope === 'record') {\n\t\t\t\t// Collect updates during iteration, then apply them after.\n\t\t\t\t// This avoids issues with live iterators (e.g., SQLite) where updating\n\t\t\t\t// records during iteration can cause them to be visited multiple times.\n\t\t\t\tconst updates: [string, R][] = []\n\t\t\t\tfor (const [id, state] of storage.entries()) {\n\t\t\t\t\tconst shouldApply = migration.filter ? migration.filter(state) : true\n\t\t\t\t\tif (!shouldApply) continue\n\t\t\t\t\tconst record = structuredClone(state)\n\t\t\t\t\tconst result = migration.up!(record as any) ?? record\n\t\t\t\t\tif (!isEqual(result, state)) {\n\t\t\t\t\t\tupdates.push([id, result as R])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const [id, record] of updates) {\n\t\t\t\t\tstorage.set(id, record)\n\t\t\t\t}\n\t\t\t} else if (migration.scope === 'store') {\n\t\t\t\t// legacy\n\t\t\t\tconst prevStore = Object.fromEntries(storage.entries())\n\t\t\t\tlet nextStore = structuredClone(prevStore)\n\t\t\t\tnextStore = (migration.up!(nextStore) as any) ?? nextStore\n\t\t\t\tfor (const [id, state] of Object.entries(nextStore)) {\n\t\t\t\t\tif (!state) continue // these will be deleted in the next loop\n\t\t\t\t\tif (!isEqual(state, prevStore[id])) {\n\t\t\t\t\t\tstorage.set(id, state)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const id of Object.keys(prevStore)) {\n\t\t\t\t\tif (!nextStore[id]) {\n\t\t\t\t\t\tstorage.delete(id)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (migration.scope === 'storage') {\n\t\t\t\tmigration.up!(storage)\n\t\t\t} else {\n\t\t\t\texhaustiveSwitchError(migration)\n\t\t\t}\n\t\t}\n\t\t// Clean up by filtering out any non-document records.\n\t\t// This is mainly legacy support for extremely early days tldraw.\n\t\tfor (const [id, state] of storage.entries()) {\n\t\t\tif (this.getType(state.typeName).scope !== 'document') {\n\t\t\t\tstorage.delete(id)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Migrates an entire store snapshot to match the current schema version.\n\t *\n\t * This method applies all necessary migrations to bring a persisted store\n\t * snapshot up to the current schema version. It handles both record-level\n\t * and store-level migrations, and can optionally mutate the input store\n\t * for performance.\n\t *\n\t * @param snapshot - The store snapshot containing data and schema information\n\t * @param opts - Options controlling migration behavior\n\t * - mutateInputStore - Whether to modify the input store directly (default: false)\n\t * @returns A MigrationResult containing the migrated store or an error\n\t *\n\t * @example\n\t * ```ts\n\t * const snapshot = {\n\t * schema: { schemaVersion: 2, sequences: { 'com.draw.book': 1 } },\n\t * store: {\n\t * 'book:1': { id: 'book:1', typeName: 'book', title: 'Old Book', publishDate: '2020-01-01' }\n\t * }\n\t * }\n\t *\n\t * const result = schema.migrateStoreSnapshot(snapshot)\n\t * if (result.type === 'success') {\n\t * console.log('Migrated store:', result.value)\n\t * // All records are now at current schema version\n\t * }\n\t * ```\n\t *\n\t * @public\n\t */\n\tmigrateStoreSnapshot(\n\t\tsnapshot: StoreSnapshot<R>,\n\t\topts?: { mutateInputStore?: boolean }\n\t): MigrationResult<SerializedStore<R>> {\n\t\tconst migrations = this.getMigrationsSince(snapshot.schema)\n\t\tif (!migrations.ok) {\n\t\t\t// TODO: better error\n\t\t\tconsole.error('Error migrating store', migrations.error)\n\t\t\treturn { type: 'error', reason: MigrationFailureReason.MigrationError }\n\t\t}\n\t\tconst migrationsToApply = migrations.value\n\t\tif (migrationsToApply.length === 0) {\n\t\t\treturn { type: 'success', value: snapshot.store }\n\t\t}\n\t\tconst store = Object.assign(\n\t\t\tnew Map<string, R>(objectMapEntries(snapshot.store).map(devFreeze)),\n\t\t\t{\n\t\t\t\tgetSchema: () => snapshot.schema,\n\t\t\t\tsetSchema: (_: SerializedSchema) => {},\n\t\t\t}\n\t\t)\n\t\ttry {\n\t\t\tthis.migrateStorage(store)\n\t\t\tif (opts?.mutateInputStore) {\n\t\t\t\tfor (const [id, record] of store.entries()) {\n\t\t\t\t\tsnapshot.store[id as keyof typeof snapshot.store] = record\n\t\t\t\t}\n\t\t\t\tfor (const id of Object.keys(snapshot.store)) {\n\t\t\t\t\tif (!store.has(id)) {\n\t\t\t\t\t\tdelete snapshot.store[id as keyof typeof snapshot.store]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { type: 'success', value: snapshot.store }\n\t\t\t} else {\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'success',\n\t\t\t\t\tvalue: Object.fromEntries(store.entries()) as SerializedStore<R>,\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconsole.error('Error migrating store', e)\n\t\t\treturn { type: 'error', reason: MigrationFailureReason.MigrationError }\n\t\t}\n\t}\n\n\t/**\n\t * Creates an integrity checker function for the given store.\n\t *\n\t * This method calls the createIntegrityChecker option if provided, allowing\n\t * custom integrity checking logic to be set up for the store. The integrity\n\t * checker is used to validate store consistency and catch data corruption.\n\t *\n\t * @param store - The store instance to create an integrity checker for\n\t * @returns An integrity checker function, or undefined if none is configured\n\t *\n\t * @internal\n\t */\n\tcreateIntegrityChecker(store: Store<R, P>): (() => void) | undefined {\n\t\treturn this.options.createIntegrityChecker?.(store) ?? undefined\n\t}\n\n\t/**\n\t * Serializes the current schema to a SerializedSchemaV2 format.\n\t *\n\t * This method creates a serialized representation of the current schema,\n\t * capturing the latest version number for each migration sequence.\n\t * The result can be persisted and later used to determine what migrations\n\t * need to be applied when loading data.\n\t *\n\t * @returns A SerializedSchemaV2 object representing the current schema state\n\t *\n\t * @example\n\t * ```ts\n\t * const serialized = schema.serialize()\n\t * console.log(serialized)\n\t * // {\n\t * // schemaVersion: 2,\n\t * // sequences: {\n\t * // 'com.draw.book': 3,\n\t * // 'com.draw.author': 2\n\t * // }\n\t * // }\n\t *\n\t * // Store this with your data for future migrations\n\t * localStorage.setItem('schema', JSON.stringify(serialized))\n\t * ```\n\t *\n\t * @public\n\t */\n\tserialize(): SerializedSchemaV2 {\n\t\treturn {\n\t\t\tschemaVersion: 2,\n\t\t\tsequences: Object.fromEntries(\n\t\t\t\tObject.values(this.migrations).map(({ sequenceId, sequence }) => [\n\t\t\t\t\tsequenceId,\n\t\t\t\t\tsequence.length ? parseMigrationId(sequence.at(-1)!.id).version : 0,\n\t\t\t\t])\n\t\t\t),\n\t\t}\n\t}\n\n\t/**\n\t * Serializes a schema representing the earliest possible version.\n\t *\n\t * This method creates a serialized schema where all migration sequences\n\t * are set to version 0, representing the state before any migrations\n\t * have been applied. This is used in specific legacy scenarios.\n\t *\n\t * @returns A SerializedSchema with all sequences set to version 0\n\t *\n\t * @deprecated This is only here for legacy reasons, don't use it unless you have david's blessing!\n\t * @internal\n\t */\n\tserializeEarliestVersion(): SerializedSchema {\n\t\treturn {\n\t\t\tschemaVersion: 2,\n\t\t\tsequences: Object.fromEntries(\n\t\t\t\tObject.values(this.migrations).map(({ sequenceId }) => [sequenceId, 0])\n\t\t\t),\n\t\t}\n\t}\n\n\t/**\n\t * Gets the RecordType definition for a given type name.\n\t *\n\t * This method retrieves the RecordType associated with the specified\n\t * type name, which contains the record's validation, creation, and\n\t * other behavioral logic.\n\t *\n\t * @param typeName - The name of the record type to retrieve\n\t * @returns The RecordType definition for the specified type\n\t *\n\t * @throws Will throw an error if the record type does not exist\n\t *\n\t * @internal\n\t */\n\tgetType(typeName: string) {\n\t\tconst type = getOwnProperty(this.types, typeName)\n\t\tassert(type, 'record type does not exists')\n\t\treturn type\n\t}\n}\n","import { registerDrawLibraryVersion } from '@ibodr/utils'\nexport { AtomMap } from './lib/AtomMap'\nexport { AtomSet } from './lib/AtomSet'\nexport type { BaseRecord, IdOf, RecordId, UnknownRecord } from './lib/BaseRecord'\nexport { devFreeze } from './lib/devFreeze'\nexport { type QueryExpression, type QueryValueMatcher } from './lib/executeQuery'\nexport { IncrementalSetConstructor } from './lib/IncrementalSetConstructor'\nexport {\n\tcreateMigrationIds,\n\tcreateMigrationSequence,\n\tcreateRecordMigrationSequence,\n\tMigrationFailureReason,\n\tparseMigrationId,\n\ttype LegacyBaseMigrationsInfo,\n\ttype LegacyMigration,\n\ttype LegacyMigrations,\n\ttype Migration,\n\ttype MigrationId,\n\ttype MigrationResult,\n\ttype MigrationSequence,\n\ttype StandaloneDependsOn,\n\ttype SynchronousRecordStorage,\n\ttype SynchronousStorage,\n} from './lib/migrate'\nexport {\n\tcreateEmptyRecordsDiff,\n\tisRecordsDiffEmpty,\n\treverseRecordsDiff,\n\tsquashRecordDiffs,\n\tsquashRecordDiffsMutable,\n\ttype RecordsDiff,\n} from './lib/RecordsDiff'\nexport { assertIdType, createRecordType, RecordType, type RecordScope } from './lib/RecordType'\nexport {\n\tcreateComputedCache,\n\tStore,\n\ttype ChangeSource,\n\ttype CollectionDiff,\n\ttype ComputedCache,\n\ttype CreateComputedCacheOpts,\n\ttype HistoryEntry,\n\ttype RecordFromId,\n\ttype SerializedStore,\n\ttype StoreError,\n\ttype StoreListener,\n\ttype StoreListenerFilters,\n\ttype StoreObject,\n\ttype StoreObjectRecordType,\n\ttype StoreRecord,\n\ttype StoreSnapshot,\n\ttype StoreValidator,\n\ttype StoreValidators,\n} from './lib/Store'\nexport { StoreQueries, type RSIndex, type RSIndexDiff, type RSIndexMap } from './lib/StoreQueries'\nexport { StoreSchema, type StoreValidationFailure } from './lib/StoreSchema'\nexport type {\n\tSerializedSchema,\n\tSerializedSchemaV1,\n\tSerializedSchemaV2,\n\tStoreSchemaOptions,\n} from './lib/StoreSchema'\nexport {\n\tStoreSideEffects,\n\ttype StoreAfterChangeHandler,\n\ttype StoreAfterCreateHandler,\n\ttype StoreAfterDeleteHandler,\n\ttype StoreBeforeChangeHandler,\n\ttype StoreBeforeCreateHandler,\n\ttype StoreBeforeDeleteHandler,\n\ttype StoreOperationCompleteHandler,\n} from './lib/StoreSideEffects'\n\nregisterDrawLibraryVersion(\n\t(globalThis as any).DRAW_LIBRARY_NAME,\n\t(globalThis as any).DRAW_LIBRARY_VERSION,\n\t(globalThis as any).DRAW_LIBRARY_MODULES\n)\n"]}
|