@tldraw/store 4.3.0-next.f13438eb7775 → 4.3.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.
Files changed (43) hide show
  1. package/dist-cjs/index.d.ts +49 -1
  2. package/dist-cjs/index.js +3 -1
  3. package/dist-cjs/index.js.map +2 -2
  4. package/dist-cjs/lib/AtomSet.js +68 -0
  5. package/dist-cjs/lib/AtomSet.js.map +7 -0
  6. package/dist-cjs/lib/ImmutableMap.js +25 -23
  7. package/dist-cjs/lib/ImmutableMap.js.map +2 -2
  8. package/dist-cjs/lib/StoreSchema.js +84 -24
  9. package/dist-cjs/lib/StoreSchema.js.map +2 -2
  10. package/dist-cjs/lib/StoreSideEffects.js +1 -1
  11. package/dist-cjs/lib/StoreSideEffects.js.map +1 -1
  12. package/dist-cjs/lib/devFreeze.js +5 -3
  13. package/dist-cjs/lib/devFreeze.js.map +2 -2
  14. package/dist-cjs/lib/isDev.js +37 -0
  15. package/dist-cjs/lib/isDev.js.map +7 -0
  16. package/dist-cjs/lib/migrate.js.map +2 -2
  17. package/dist-esm/index.d.mts +49 -1
  18. package/dist-esm/index.mjs +3 -1
  19. package/dist-esm/index.mjs.map +2 -2
  20. package/dist-esm/lib/AtomSet.mjs +48 -0
  21. package/dist-esm/lib/AtomSet.mjs.map +7 -0
  22. package/dist-esm/lib/ImmutableMap.mjs +25 -23
  23. package/dist-esm/lib/ImmutableMap.mjs.map +2 -2
  24. package/dist-esm/lib/StoreSchema.mjs +87 -25
  25. package/dist-esm/lib/StoreSchema.mjs.map +2 -2
  26. package/dist-esm/lib/StoreSideEffects.mjs +1 -1
  27. package/dist-esm/lib/StoreSideEffects.mjs.map +1 -1
  28. package/dist-esm/lib/devFreeze.mjs +5 -3
  29. package/dist-esm/lib/devFreeze.mjs.map +2 -2
  30. package/dist-esm/lib/isDev.mjs +16 -0
  31. package/dist-esm/lib/isDev.mjs.map +7 -0
  32. package/dist-esm/lib/migrate.mjs.map +2 -2
  33. package/package.json +4 -4
  34. package/src/index.ts +3 -0
  35. package/src/lib/AtomSet.ts +52 -0
  36. package/src/lib/ImmutableMap.ts +25 -33
  37. package/src/lib/StoreSchema.ts +97 -30
  38. package/src/lib/StoreSideEffects.ts +1 -1
  39. package/src/lib/devFreeze.test.ts +6 -2
  40. package/src/lib/devFreeze.ts +7 -3
  41. package/src/lib/isDev.ts +20 -0
  42. package/src/lib/migrate.ts +29 -0
  43. package/src/lib/test/recordStore.test.ts +182 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/ImmutableMap.ts"],
4
- "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 */\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 v.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(v) : hashString(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 (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {\n\t\t\tSTRING_HASH_CACHE_SIZE = 0\n\t\t\tstringHashCache = {}\n\t\t}\n\t\tSTRING_HASH_CACHE_SIZE++\n\t\tstringHashCache[string] = hashed\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\nconst STRING_HASH_CACHE_MIN_STRLEN = 16\nconst STRING_HASH_CACHE_MAX_SIZE = 255\nlet STRING_HASH_CACHE_SIZE = 0\nlet stringHashCache: Record<string, number> = {}\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\n// http://jsperf.com/copy-array-inline\nfunction arrCopy<I>(arr: Array<I>, offset?: number): Array<I> {\n\toffset = offset || 0\n\tconst len = Math.max(0, arr.length - offset)\n\tconst newArr: Array<I> = new Array(len)\n\tfor (let ii = 0; ii < len; ii++) {\n\t\t// We may want to guard for undefined values with `if (arr[ii + offset] !== undefined`, but ths should not happen by design\n\t\tnewArr[ii] = arr[ii + offset]\n\t}\n\treturn newArr\n}\n\nconst is = Object.is\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 (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 (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\t// eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here\n\t\t;(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\t// eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here\n\t\t\t\tidx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()!)\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 (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 (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\t// eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here\n\t\t;(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\t// eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here\n\t\t\t\tidx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()!)\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 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 = 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\t// eslint-disable-next-line @typescript-eslint/no-unused-expressions -- TODO enable eslint here\n\titeratorResult\n\t\t? (iteratorResult.value = value)\n\t\t: (iteratorResult = {\n\t\t\t\tvalue: value,\n\t\t\t\tdone: false,\n\t\t\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;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WAAW,MAAM,MAAM,QAAQ;AAClC,UAAM,GAAG,IAAI;AACb,WAAO;AAAA,EACR;AACA,QAAM,WAAW,IAAI,MAAS,MAAM;AACpC,MAAI,QAAQ;AACZ,WAAS,KAAK,GAAG,KAAK,QAAQ,MAAM;AACnC,QAAI,OAAO,KAAK;AACf,eAAS,EAAE,IAAI;AACf,cAAQ;AAAA,IACT,OAAO;AACN,eAAS,EAAE,IAAI,MAAM,KAAK,KAAK;AAAA,IAChC;AAAA,EACD;AACA,SAAO;AACR;AAEA,SAAS,UAAa,OAAY,KAAa,SAAkB;AAChE,QAAM,SAAS,MAAM,SAAS;AAC9B,MAAI,WAAW,QAAQ,QAAQ;AAC9B,UAAM,IAAI;AACV,WAAO;AAAA,EACR;AACA,QAAM,WAAW,IAAI,MAAM,MAAM;AACjC,MAAI,QAAQ;AACZ,WAAS,KAAK,GAAG,KAAK,QAAQ,MAAM;AACnC,QAAI,OAAO,KAAK;AACf,cAAQ;AAAA,IACT;AACA,aAAS,EAAE,IAAI,MAAM,KAAK,KAAK;AAAA,EAChC;AACA,SAAO;AACR;AAEA,MAAM,qBAAqB,OAAO;AAClC,MAAM,0BAA0B,OAAO;AACvC,MAAM,0BAA0B,OAAO;",
4
+ "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 */\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 v.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(v) : hashString(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 (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {\n\t\t\tSTRING_HASH_CACHE_SIZE = 0\n\t\t\tstringHashCache = {}\n\t\t}\n\t\tSTRING_HASH_CACHE_SIZE++\n\t\tstringHashCache[string] = hashed\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\nconst STRING_HASH_CACHE_MIN_STRLEN = 16\nconst STRING_HASH_CACHE_MAX_SIZE = 255\nlet STRING_HASH_CACHE_SIZE = 0\nlet stringHashCache: Record<string, number> = {}\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\t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AAI,MAAS,MAAM;AACpC,MAAI,QAAQ;AACZ,WAAS,KAAK,GAAG,KAAK,QAAQ,MAAM;AACnC,QAAI,OAAO,KAAK;AACf,eAAS,EAAE,IAAI;AACf,cAAQ;AAAA,IACT,OAAO;AACN,eAAS,EAAE,IAAI,MAAM,KAAK,KAAK;AAAA,IAChC;AAAA,EACD;AACA,SAAO;AACR;AAEA,SAAS,UAAa,OAAY,KAAa,SAAkB;AAChE,QAAM,SAAS,MAAM,SAAS;AAC9B,MAAI,WAAW,QAAQ,QAAQ;AAC9B,UAAM,IAAI;AACV,WAAO;AAAA,EACR;AACA,QAAM,WAAW,IAAI,MAAM,MAAM;AACjC,MAAI,QAAQ;AACZ,WAAS,KAAK,GAAG,KAAK,QAAQ,MAAM;AACnC,QAAI,OAAO,KAAK;AACf,cAAQ;AAAA,IACT;AACA,aAAS,EAAE,IAAI,MAAM,KAAK,KAAK;AAAA,EAChC;AACA,SAAO;AACR;AAEA,MAAM,qBAAqB,OAAO;AAClC,MAAM,0BAA0B,OAAO;AACvC,MAAM,0BAA0B,OAAO;",
6
6
  "names": ["hash", "nextHash"]
7
7
  }
@@ -1,10 +1,13 @@
1
1
  import {
2
- Result,
3
2
  assert,
4
3
  exhaustiveSwitchError,
5
4
  getOwnProperty,
5
+ isEqual,
6
+ objectMapEntries,
7
+ Result,
6
8
  structuredClone
7
9
  } from "@tldraw/utils";
10
+ import { devFreeze } from "./devFreeze.mjs";
8
11
  import {
9
12
  MigrationFailureReason,
10
13
  parseMigrationId,
@@ -251,14 +254,14 @@ class StoreSchema {
251
254
  if (migrationsToApply.length === 0) {
252
255
  return { type: "success", value: record };
253
256
  }
254
- if (migrationsToApply.some((m) => m.scope === "store")) {
257
+ if (!migrationsToApply.every((m) => m.scope === "record")) {
255
258
  return {
256
259
  type: "error",
257
260
  reason: direction === "down" ? MigrationFailureReason.TargetVersionTooOld : MigrationFailureReason.TargetVersionTooNew
258
261
  };
259
262
  }
260
263
  if (direction === "down") {
261
- if (!migrationsToApply.every((m) => m.down)) {
264
+ if (!migrationsToApply.every((m) => m.scope === "record" && m.down)) {
262
265
  return {
263
266
  type: "error",
264
267
  reason: MigrationFailureReason.TargetVersionTooOld
@@ -272,6 +275,9 @@ class StoreSchema {
272
275
  if (migration.scope === "store") throw new Error(
273
276
  /* won't happen, just for TS */
274
277
  );
278
+ if (migration.scope === "storage") throw new Error(
279
+ /* won't happen, just for TS */
280
+ );
275
281
  const shouldApply = migration.filter ? migration.filter(record) : true;
276
282
  if (!shouldApply) continue;
277
283
  const result = migration[direction](record);
@@ -285,6 +291,61 @@ class StoreSchema {
285
291
  }
286
292
  return { type: "success", value: record };
287
293
  }
294
+ migrateStorage(storage) {
295
+ const schema = storage.getSchema();
296
+ assert(schema, "Schema is missing.");
297
+ const migrations = this.getMigrationsSince(schema);
298
+ if (!migrations.ok) {
299
+ console.error("Error migrating store", migrations.error);
300
+ throw new Error(migrations.error);
301
+ }
302
+ const migrationsToApply = migrations.value;
303
+ if (migrationsToApply.length === 0) {
304
+ return;
305
+ }
306
+ storage.setSchema(this.serialize());
307
+ for (const migration of migrationsToApply) {
308
+ if (migration.scope === "record") {
309
+ const updates = [];
310
+ for (const [id, state] of storage.entries()) {
311
+ const shouldApply = migration.filter ? migration.filter(state) : true;
312
+ if (!shouldApply) continue;
313
+ const record = structuredClone(state);
314
+ const result = migration.up(record) ?? record;
315
+ if (!isEqual(result, state)) {
316
+ updates.push([id, result]);
317
+ }
318
+ }
319
+ for (const [id, record] of updates) {
320
+ storage.set(id, record);
321
+ }
322
+ } else if (migration.scope === "store") {
323
+ const prevStore = Object.fromEntries(storage.entries());
324
+ let nextStore = structuredClone(prevStore);
325
+ nextStore = migration.up(nextStore) ?? nextStore;
326
+ for (const [id, state] of Object.entries(nextStore)) {
327
+ if (!state) continue;
328
+ if (!isEqual(state, prevStore[id])) {
329
+ storage.set(id, state);
330
+ }
331
+ }
332
+ for (const id of Object.keys(prevStore)) {
333
+ if (!nextStore[id]) {
334
+ storage.delete(id);
335
+ }
336
+ }
337
+ } else if (migration.scope === "storage") {
338
+ migration.up(storage);
339
+ } else {
340
+ exhaustiveSwitchError(migration);
341
+ }
342
+ }
343
+ for (const [id, state] of storage.entries()) {
344
+ if (this.getType(state.typeName).scope !== "document") {
345
+ storage.delete(id);
346
+ }
347
+ }
348
+ }
288
349
  /**
289
350
  * Migrates an entire store snapshot to match the current schema version.
290
351
  *
@@ -317,7 +378,6 @@ class StoreSchema {
317
378
  * @public
318
379
  */
319
380
  migrateStoreSnapshot(snapshot, opts) {
320
- let { store } = snapshot;
321
381
  const migrations = this.getMigrationsSince(snapshot.schema);
322
382
  if (!migrations.ok) {
323
383
  console.error("Error migrating store", migrations.error);
@@ -325,36 +385,38 @@ class StoreSchema {
325
385
  }
326
386
  const migrationsToApply = migrations.value;
327
387
  if (migrationsToApply.length === 0) {
328
- return { type: "success", value: store };
329
- }
330
- if (!opts?.mutateInputStore) {
331
- store = structuredClone(store);
388
+ return { type: "success", value: snapshot.store };
332
389
  }
390
+ const store = Object.assign(
391
+ new Map(objectMapEntries(snapshot.store).map(devFreeze)),
392
+ {
393
+ getSchema: () => snapshot.schema,
394
+ setSchema: (_) => {
395
+ }
396
+ }
397
+ );
333
398
  try {
334
- for (const migration of migrationsToApply) {
335
- if (migration.scope === "record") {
336
- for (const [id, record] of Object.entries(store)) {
337
- const shouldApply = migration.filter ? migration.filter(record) : true;
338
- if (!shouldApply) continue;
339
- const result = migration.up(record);
340
- if (result) {
341
- store[id] = result;
342
- }
343
- }
344
- } else if (migration.scope === "store") {
345
- const result = migration.up(store);
346
- if (result) {
347
- store = result;
399
+ this.migrateStorage(store);
400
+ if (opts?.mutateInputStore) {
401
+ for (const [id, record] of store.entries()) {
402
+ snapshot.store[id] = record;
403
+ }
404
+ for (const id of Object.keys(snapshot.store)) {
405
+ if (!store.has(id)) {
406
+ delete snapshot.store[id];
348
407
  }
349
- } else {
350
- exhaustiveSwitchError(migration);
351
408
  }
409
+ return { type: "success", value: snapshot.store };
410
+ } else {
411
+ return {
412
+ type: "success",
413
+ value: Object.fromEntries(store.entries())
414
+ };
352
415
  }
353
416
  } catch (e) {
354
417
  console.error("Error migrating store", e);
355
418
  return { type: "error", reason: MigrationFailureReason.MigrationError };
356
419
  }
357
- return { type: "success", value: store };
358
420
  }
359
421
  /**
360
422
  * Creates an integrity checker function for the given store.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/StoreSchema.ts"],
4
- "sourcesContent": ["import {\n\tResult,\n\tassert,\n\texhaustiveSwitchError,\n\tgetOwnProperty,\n\tstructuredClone,\n} from '@tldraw/utils'\nimport { UnknownRecord } from './BaseRecord'\nimport { RecordType } from './RecordType'\nimport { SerializedStore, Store, StoreSnapshot } from './Store'\nimport {\n\tMigration,\n\tMigrationFailureReason,\n\tMigrationId,\n\tMigrationResult,\n\tMigrationSequence,\n\tparseMigrationId,\n\tsortMigrations,\n\tvalidateMigrations,\n} from './migrate'\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.tldraw.store': 3,\n * 'com.tldraw.book': 2,\n * 'com.tldraw.shape': 4,\n * 'com.tldraw.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.tldraw.store': 1, 'com.tldraw.book': 2, 'com.tldraw.author': 1, 'com.tldraw.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.tldraw.store': schema.storeVersion,\n\t\t},\n\t}\n\n\tfor (const [typeName, recordVersion] of Object.entries(schema.recordVersions)) {\n\t\tresult.sequences[`com.tldraw.${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.tldraw.${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.tldraw.book': 1, 'com.tldraw.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.tldraw.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.some((m) => m.scope === 'store')) {\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.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\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\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.tldraw.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\tlet { store } = snapshot\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: store }\n\t\t}\n\n\t\tif (!opts?.mutateInputStore) {\n\t\t\tstore = structuredClone(store)\n\t\t}\n\n\t\ttry {\n\t\t\tfor (const migration of migrationsToApply) {\n\t\t\t\tif (migration.scope === 'record') {\n\t\t\t\t\tfor (const [id, record] of Object.entries(store)) {\n\t\t\t\t\t\tconst shouldApply = migration.filter ? migration.filter(record as UnknownRecord) : true\n\t\t\t\t\t\tif (!shouldApply) continue\n\t\t\t\t\t\tconst result = migration.up!(record as any)\n\t\t\t\t\t\tif (result) {\n\t\t\t\t\t\t\tstore[id as keyof typeof store] = result as any\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (migration.scope === 'store') {\n\t\t\t\t\tconst result = migration.up!(store)\n\t\t\t\t\tif (result) {\n\t\t\t\t\t\tstore = result as any\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\texhaustiveSwitchError(migration)\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\n\t\treturn { type: 'success', value: store }\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.tldraw.book': 3,\n\t * // 'com.tldraw.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"],
5
- "mappings": "AAAA;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAIP;AAAA,EAEC;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAmIA,SAAS,cAAc,QAA8D;AAC3F,MAAI,OAAO,gBAAgB,KAAK,OAAO,gBAAgB,EAAG,QAAO,OAAO,IAAI,oBAAoB;AAChG,MAAI,OAAO,kBAAkB,EAAG,QAAO,OAAO,GAAG,MAA4B;AAC7E,QAAM,SAA6B;AAAA,IAClC,eAAe;AAAA,IACf,WAAW;AAAA,MACV,oBAAoB,OAAO;AAAA,IAC5B;AAAA,EACD;AAEA,aAAW,CAAC,UAAU,aAAa,KAAK,OAAO,QAAQ,OAAO,cAAc,GAAG;AAC9E,WAAO,UAAU,cAAc,QAAQ,EAAE,IAAI,cAAc;AAC3D,QAAI,gBAAgB,eAAe;AAClC,iBAAW,CAAC,SAAS,OAAO,KAAK,OAAO,QAAQ,cAAc,eAAe,GAAG;AAC/E,eAAO,UAAU,cAAc,QAAQ,IAAI,OAAO,EAAE,IAAI;AAAA,MACzD;AAAA,IACD;AAAA,EACD;AACA,SAAO,OAAO,GA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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8BA,YAAgC;AAC/B,WAAO;AAAA,MACN,eAAe;AAAA,MACf,WAAW,OAAO;AAAA,QACjB,OAAO,OAAO,KAAK,UAAU,EAAE,IAAI,CAAC,EAAE,YAAY,SAAS,MAAM;AAAA,UAChE;AAAA,UACA,SAAS,SAAS,iBAAiB,SAAS,GAAG,EAAE,EAAG,EAAE,EAAE,UAAU;AAAA,QACnE,CAAC;AAAA,MACF;AAAA,IACD;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,2BAA6C;AAC5C,WAAO;AAAA,MACN,eAAe;AAAA,MACf,WAAW,OAAO;AAAA,QACjB,OAAO,OAAO,KAAK,UAAU,EAAE,IAAI,CAAC,EAAE,WAAW,MAAM,CAAC,YAAY,CAAC,CAAC;AAAA,MACvE;AAAA,IACD;AAAA,EACD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBA,QAAQ,UAAkB;AACzB,UAAM,OAAO,eAAe,KAAK,OAAO,QAAQ;AAChD,WAAO,MAAM,6BAA6B;AAC1C,WAAO;AAAA,EACR;AACD;",
4
+ "sourcesContent": ["import {\n\tassert,\n\texhaustiveSwitchError,\n\tgetOwnProperty,\n\tisEqual,\n\tobjectMapEntries,\n\tResult,\n\tstructuredClone,\n} from '@tldraw/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.tldraw.store': 3,\n * 'com.tldraw.book': 2,\n * 'com.tldraw.shape': 4,\n * 'com.tldraw.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.tldraw.store': 1, 'com.tldraw.book': 2, 'com.tldraw.author': 1, 'com.tldraw.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.tldraw.store': schema.storeVersion,\n\t\t},\n\t}\n\n\tfor (const [typeName, recordVersion] of Object.entries(schema.recordVersions)) {\n\t\tresult.sequences[`com.tldraw.${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.tldraw.${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.tldraw.book': 1, 'com.tldraw.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.tldraw.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.tldraw.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.tldraw.book': 3,\n\t * // 'com.tldraw.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"],
5
+ "mappings": "AAAA;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAEP,SAAS,iBAAiB;AAC1B;AAAA,EAEC;AAAA,EAIA;AAAA,EACA;AAAA,EAEA;AAAA,OACM;AAqIA,SAAS,cAAc,QAA8D;AAC3F,MAAI,OAAO,gBAAgB,KAAK,OAAO,gBAAgB,EAAG,QAAO,OAAO,IAAI,oBAAoB;AAChG,MAAI,OAAO,kBAAkB,EAAG,QAAO,OAAO,GAAG,MAA4B;AAC7E,QAAM,SAA6B;AAAA,IAClC,eAAe;AAAA,IACf,WAAW;AAAA,MACV,oBAAoB,OAAO;AAAA,IAC5B;AAAA,EACD;AAEA,aAAW,CAAC,UAAU,aAAa,KAAK,OAAO,QAAQ,OAAO,cAAc,GAAG;AAC9E,WAAO,UAAU,cAAc,QAAQ,EAAE,IAAI,cAAc;AAC3D,QAAI,gBAAgB,eAAe;AAClC,iBAAW,CAAC,SAAS,OAAO,KAAK,OAAO,QAAQ,cAAc,eAAe,GAAG;AAC/E,eAAO,UAAU,cAAc,QAAQ,IAAI,OAAO,EAAE,IAAI;AAAA,MACzD;AAAA,IACD;AAAA,EACD;AACA,SAAO,OAAO,GAAG,MAAM;AACxB;AAoGO,MAAM,YAAkD;AAAA,EA4CtD,YACS,OAGC,SAChB;AAJe;AAGC;AAEjB,eAAW,KAA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gBA,QAAQ,UAAkB;AACzB,UAAM,OAAO,eAAe,KAAK,OAAO,QAAQ;AAChD,WAAO,MAAM,6BAA6B;AAC1C,WAAO;AAAA,EACR;AACD;",
6
6
  "names": ["result"]
7
7
  }
@@ -260,7 +260,7 @@ class StoreSideEffects {
260
260
  * ```ts
261
261
  * editor.sideEffects.registerAfterCreateHandler('page', (page, source) => {
262
262
  * // Automatically create a shape when a page is created
263
- * editor.createShape<TLTextShape>({
263
+ * editor.createShape({
264
264
  * id: createShapeId(),
265
265
  * type: 'text',
266
266
  * props: { richText: toRichText(page.name) },