@mocanvas/store 4.1.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/MIGRATION.md CHANGED
@@ -253,6 +253,40 @@ during the zero-rename step. Under pnpm's strict `node_modules` that means
253
253
  adding `@mocanvas/mocanvas` to your own dependencies alongside
254
254
  `@mocanvas/compat`.
255
255
 
256
+ **If your own CSS reads tldraw's custom properties, add a second line:**
257
+
258
+ ```ts
259
+ import "@mocanvas/compat/compat.css"
260
+ ```
261
+
262
+ This is the half of the compat layer that nothing checks for you. The package
263
+ alias covers the symbols TypeScript sees; it cannot cover the `--tl-*` names in
264
+ your stylesheets. Without it a migration goes green — build, types, tests — and
265
+ the damage shows up only to the eye, because a `var()` that resolves to nothing
266
+ does not fail, it deletes the declaration it sits in (and inside `calc()`, the
267
+ whole property). One consumer found it as a cursor whose white outline had
268
+ quietly stopped being drawn.
269
+
270
+ `compat.css` maps tldraw's tokens onto mocanvas's and gives **every** one a
271
+ literal fallback, so a token with no counterpart cannot take a rule down with
272
+ it. Two groups are worth knowing about:
273
+
274
+ | tldraw token | What you get |
275
+ | --- | --- |
276
+ | `--tl-zoom`, `--tl-scale` | Real values. mocanvas now stamps `--mocanvas-zoom` and `--mocanvas-scale` on the canvas container and restamps them on zoom, so `calc()` rules that hold a constant on-screen size keep working. |
277
+ | `--tl-color-overlay`, `--tl-color-background-overlay`, `--tl-color-warn` | A static fallback. mocanvas has no equivalent, so these do not follow your theme — set them yourself if they matter. |
278
+
279
+ Everything else maps onto a themed mocanvas variable and follows a theme swap
280
+ or a flip to dark. The stylesheet is scoped to `.mocanvas` rather than `:root`,
281
+ so a page that still renders a real tldraw editor somewhere keeps its own
282
+ values.
283
+
284
+ **Next.js**: an app coming from tldraw almost certainly lists it in
285
+ `serverExternalPackages`. Next matches that by package name, so leaving
286
+ `@mocanvas/mocanvas` in the list turns `…/mocanvas.css` into a request Node has
287
+ to resolve — and Node has no loader for `.css`. Take mocanvas out of the list
288
+ entirely; there is nothing in it that needs to be external.
289
+
256
290
  ### Step 2 — drop the prefixes
257
291
 
258
292
  Once the app builds and runs against `@mocanvas/compat`, rename `TLFoo` →
package/dist/index.d.ts CHANGED
@@ -120,17 +120,24 @@ type IndexKey = string & {
120
120
  };
121
121
  /** The conventional first key. */
122
122
  declare const ZERO_INDEX_KEY: IndexKey;
123
- /** Generate a key strictly between `below` and `above`; either may be omitted. Throws when `below >= above`. */
123
+ /**
124
+ * Generate a key strictly between `below` and `above`; either may be omitted.
125
+ * Throws when `below >= above`.
126
+ *
127
+ * Jittered — see the note above {@link JITTER_DIGITS}. Two calls with the same
128
+ * arguments return *different* keys, both in the same gap, which is what lets
129
+ * two clients insert at one position without one of them being merged away.
130
+ */
124
131
  declare function getIndexBetween(below?: IndexKey | undefined, above?: IndexKey | undefined): IndexKey;
125
- /** Generate a key strictly above `below` (or a first key when omitted). */
132
+ /** Generate a key strictly above `below` (or a first key when omitted). Jittered. */
126
133
  declare function getIndexAbove(below?: IndexKey | undefined): IndexKey;
127
- /** Generate a key strictly below `above` (or a first key when omitted). */
134
+ /** Generate a key strictly below `above` (or a first key when omitted). Jittered. */
128
135
  declare function getIndexBelow(above?: IndexKey | undefined): IndexKey;
129
- /** Generate `n` sorted keys strictly between `below` and `above`. */
136
+ /** Generate `n` sorted keys strictly between `below` and `above`. Jittered. */
130
137
  declare function getIndicesBetween(below: IndexKey | undefined, above: IndexKey | undefined, n: number): IndexKey[];
131
- /** Generate `n` sorted keys strictly above `below`. */
138
+ /** Generate `n` sorted keys strictly above `below`. Jittered. */
132
139
  declare function getIndicesAbove(below: IndexKey | undefined, n: number): IndexKey[];
133
- /** Generate `n` sorted keys strictly below `above`. */
140
+ /** Generate `n` sorted keys strictly below `above`. Jittered. */
134
141
  declare function getIndicesBelow(above: IndexKey | undefined, n: number): IndexKey[];
135
142
  /**
136
143
  * Generate `n` sorted keys, the first of which is `start` (default `a0`).
package/dist/index.js CHANGED
@@ -108,25 +108,47 @@ function assertOrdered(below, above) {
108
108
  throw new Error(`Index keys out of order: ${JSON.stringify(below)} must be below ${JSON.stringify(above)}`);
109
109
  }
110
110
  }
111
+ var JITTER_DIGITS = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
112
+ var JITTER_LENGTH = 6;
113
+ function randomJitterChar(maxExclusive) {
114
+ const pool = maxExclusive === void 0 ? JITTER_DIGITS : [...JITTER_DIGITS].filter((c) => c < maxExclusive).join("");
115
+ if (pool.length === 0) return "";
116
+ return pool[Math.floor(Math.random() * pool.length)];
117
+ }
118
+ function withJitter(key, above) {
119
+ const bounded = above !== void 0 && above.startsWith(key);
120
+ const first = randomJitterChar(bounded ? above[key.length] : void 0);
121
+ if (first === "") return key;
122
+ let out = key + first;
123
+ for (let i = 1; i < JITTER_LENGTH; i++) out += randomJitterChar();
124
+ return out;
125
+ }
111
126
  function getIndexBetween(below, above) {
112
127
  assertOrdered(below, above);
113
- return generateKeyBetween(below ?? null, above ?? null);
128
+ return withJitter(generateKeyBetween(below ?? null, above ?? null), above);
114
129
  }
115
130
  function getIndexAbove(below) {
116
- return generateKeyBetween(below ?? null, null);
131
+ return withJitter(generateKeyBetween(below ?? null, null), void 0);
117
132
  }
118
133
  function getIndexBelow(above) {
119
- return generateKeyBetween(null, above ?? null);
134
+ return withJitter(generateKeyBetween(null, above ?? null), above);
135
+ }
136
+ function withJitterEach(keys, above) {
137
+ const out = [];
138
+ for (let i = 0; i < keys.length; i++) {
139
+ out.push(withJitter(keys[i], i + 1 < keys.length ? keys[i + 1] : above));
140
+ }
141
+ return out;
120
142
  }
121
143
  function getIndicesBetween(below, above, n) {
122
144
  assertOrdered(below, above);
123
- return generateNKeysBetween(below ?? null, above ?? null, n);
145
+ return withJitterEach(generateNKeysBetween(below ?? null, above ?? null, n), above);
124
146
  }
125
147
  function getIndicesAbove(below, n) {
126
- return generateNKeysBetween(below ?? null, null, n);
148
+ return withJitterEach(generateNKeysBetween(below ?? null, null, n), void 0);
127
149
  }
128
150
  function getIndicesBelow(above, n) {
129
- return generateNKeysBetween(null, above ?? null, n);
151
+ return withJitterEach(generateNKeysBetween(null, above ?? null, n), above);
130
152
  }
131
153
  function getIndices(n, start = ZERO_INDEX_KEY) {
132
154
  if (n <= 0) return [];
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ids.ts","../src/indexKey.ts","../src/zkey.ts","../src/RecordsDiff.ts","../src/migrate.ts","../src/legacy.ts","../src/StoreSchema.ts","../src/query.ts","../src/Store.ts","../src/tldr.ts","../src/computedCache.ts","../src/devFreeze.ts","../src/storage.ts","../src/graphemes.ts"],"names":["BASE_62","isPlainObject"],"mappings":";;;;;;AAGO,IAAM,gBAAA,GAAmB;AAGzB,SAAS,QAAA,CAAS,OAAe,gBAAA,EAA0B;AAChE,EAAA,OAAO,OAAO,IAAI,CAAA;AACpB;AAyEO,IAAM,UAAA,GAAN,MAAM,WAAA,CAAuF;AAAA,EAOlG,WAAA,CACE,UACiB,MAAA,EAGjB;AAHiB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAIjB,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,QAAQ,MAAA,CAAO,KAAA;AACpB,IAAA,IAAA,CAAK,YAAY,MAAA,CAAO,SAAA;AACxB,IAAA,IAAA,CAAK,gBAAgB,MAAA,CAAO,aAAA;AAC5B,IAAA,MAAM,SAAA,uBAAgB,GAAA,EAAY;AAClC,IAAA,IAAI,OAAO,aAAA,EAAe;AACxB,MAAA,KAAA,MAAW,CAAC,KAAK,KAAK,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,aAAa,CAAA,EAAG;AAC/D,QAAA,IAAI,KAAA,EAAO,SAAA,CAAU,GAAA,CAAI,GAAG,CAAA;AAAA,MAC9B;AAAA,IACF;AACA,IAAA,IAAA,CAAK,eAAA,GAAkB,SAAA;AAAA,EACzB;AAAA,EA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AAG,CAAA,EAAG,CAAA,EAAA;AACvC,EAAA,OAAO,CAAA;AACT","file":"index.js","sourcesContent":["import { nanoid } from \"nanoid\"\n\n/** Length of the unique part of a generated record id. */\nexport const UNIQUE_ID_LENGTH = 21\n\n/** Generate a URL-safe unique id (21 chars by default). */\nexport function uniqueId(size: number = UNIQUE_ID_LENGTH): string {\n return nanoid(size)\n}\n\n/**\n * A branded string id. The brand carries the record type so that ids of\n * different record types cannot be mixed up at compile time.\n */\nexport type RecordId<R extends UnknownRecord> = string & { __type__: R }\n\n/** Every record has an id and a type name. */\nexport interface BaseRecord<TypeName extends string, Id extends RecordId<UnknownRecord>> {\n readonly id: Id\n readonly typeName: TypeName\n}\n\nexport type UnknownRecord = BaseRecord<string, RecordId<UnknownRecord>>\n\nexport type IdOf<R extends UnknownRecord> = R[\"id\"]\n\n/** Extract the record type an id refers to. */\nexport type RecordFromId<K extends RecordId<UnknownRecord>> = K extends RecordId<infer R> ? R : never\n\n/**\n * Where a record lives:\n * - `document`: persisted, shared between collaborators (shapes, pages, ...)\n * - `session`: persisted locally only (camera, current page, ...)\n * - `presence`: shared but never persisted (cursors, ...)\n */\nexport type RecordScope = \"document\" | \"session\" | \"presence\"\n\nexport interface StoreValidator<R extends UnknownRecord> {\n validate(record: unknown): R\n /**\n * Optional fast path: validate `newRecord` knowing that `knownGoodVersion`\n * is a valid record of the same type. Implementations may skip the parts\n * that did not change.\n *\n * Declared as a property that may be `undefined` rather than as an optional\n * method, so that a validator carrying an explicit `undefined` — which is\n * what a class with an optional constructor argument produces — still\n * satisfies this under `exactOptionalPropertyTypes`.\n */\n validateUsingKnownGoodVersion?: ((knownGoodVersion: R, newRecord: unknown) => R) | undefined\n}\n\n/** Keys of `R` that hold data (everything except `id` and `typeName`). */\nexport type RecordDataKeys<R extends UnknownRecord> = Exclude<keyof R, \"id\" | \"typeName\">\n\nexport type EphemeralKeys<R extends UnknownRecord> = { readonly [K in RecordDataKeys<R>]: boolean }\n\nexport interface RecordTypeConfig<R extends UnknownRecord> {\n readonly scope: RecordScope\n readonly validator?: StoreValidator<R> | undefined\n /**\n * Keys whose changes should not be considered \"real\" document changes,\n * e.g. transient UI flags. Used by `Store.applyDiff({ ignoreEphemeralKeys })`.\n */\n readonly ephemeralKeys?: EphemeralKeys<R> | undefined\n}\n\n/**\n * Properties the caller must pass to `create()`: the record's data keys minus\n * whatever `withDefaultProperties` provides. `id` is always optional.\n */\nexport type RecordCreateProps<R extends UnknownRecord, RequiredProps extends keyof R> = Pick<\n R,\n RequiredProps\n> &\n Partial<Omit<R, RequiredProps | \"typeName\">>\n\n/**\n * Describes one kind of record in the store: how to make ids, defaults,\n * validation, and where the record lives (its scope).\n */\nexport class RecordType<R extends UnknownRecord, RequiredProps extends keyof R = RecordDataKeys<R>> {\n readonly typeName: R[\"typeName\"]\n readonly scope: RecordScope\n readonly validator: StoreValidator<R> | undefined\n readonly ephemeralKeys: EphemeralKeys<R> | undefined\n readonly ephemeralKeySet: ReadonlySet<string>\n\n constructor(\n typeName: R[\"typeName\"],\n private readonly config: RecordTypeConfig<R> & {\n readonly createDefaultProperties: () => Partial<Omit<R, \"id\" | \"typeName\">>\n },\n ) {\n this.typeName = typeName\n this.scope = config.scope\n this.validator = config.validator\n this.ephemeralKeys = config.ephemeralKeys\n const ephemeral = new Set<string>()\n if (config.ephemeralKeys) {\n for (const [key, value] of Object.entries(config.ephemeralKeys)) {\n if (value) ephemeral.add(key)\n }\n }\n this.ephemeralKeySet = ephemeral\n }\n\n /** Create a new record with defaults applied. A fresh id is generated when none is given. */\n create(properties: RecordCreateProps<R, RequiredProps>): R {\n const result: Record<string, unknown> = {\n ...this.config.createDefaultProperties(),\n ...(properties as Record<string, unknown>),\n }\n if (result[\"id\"] === undefined) result[\"id\"] = this.createId()\n result[\"typeName\"] = this.typeName\n return result as R\n }\n\n /** Shallow-clone a record (props/meta are shared). */\n clone(record: R): R {\n return { ...record }\n }\n\n /** Make an id of this type: `${typeName}:${uniquePart}`. */\n createId(customUniquePart?: string): IdOf<R> {\n return `${this.typeName}:${customUniquePart ?? uniqueId()}` as IdOf<R>\n }\n\n /** Recover the unique part of an id of this type. */\n parseId(id: IdOf<R>): string {\n if (!this.isId(id)) {\n throw new Error(`Id ${JSON.stringify(id)} is not a ${this.typeName} id`)\n }\n return (id as string).slice(this.typeName.length + 1)\n }\n\n isId(id?: string): id is IdOf<R> {\n if (typeof id !== \"string\") return false\n if (id.length <= this.typeName.length + 1) return false\n if (id.charCodeAt(this.typeName.length) !== 58 /* ':' */) return false\n return id.startsWith(this.typeName)\n }\n\n isInstance(record?: unknown): record is R {\n return (\n typeof record === \"object\" &&\n record !== null &&\n (record as { typeName?: unknown }).typeName === this.typeName\n )\n }\n\n /**\n * Return a new RecordType whose `create()` fills in the given defaults, so\n * those properties become optional for callers.\n */\n withDefaultProperties<DefaultProps extends RecordDataKeys<R>>(\n createDefaultProperties: () => Pick<R, DefaultProps>,\n ): RecordType<R, Exclude<RequiredProps, DefaultProps>> {\n return new RecordType<R, Exclude<RequiredProps, DefaultProps>>(this.typeName, {\n scope: this.scope,\n validator: this.validator,\n ephemeralKeys: this.ephemeralKeys,\n createDefaultProperties: createDefaultProperties as () => Partial<Omit<R, \"id\" | \"typeName\">>,\n })\n }\n\n /** Run the validator (if any). Throws on invalid input. */\n validate(record: unknown, recordBefore?: R): R {\n if (!this.validator) return record as R\n if (recordBefore !== undefined && this.validator.validateUsingKnownGoodVersion) {\n return this.validator.validateUsingKnownGoodVersion(recordBefore, record)\n }\n return this.validator.validate(record)\n }\n}\n\n/**\n * Define a record type.\n *\n * ```ts\n * const Book = createRecordType<Book>('book', { scope: 'document' })\n * .withDefaultProperties(() => ({ inStock: true }))\n * const b = Book.create({ title: 'Dune' }) // -> { id: 'book:...', typeName: 'book', title, inStock }\n * ```\n */\nexport function createRecordType<R extends UnknownRecord>(\n typeName: R[\"typeName\"],\n config: RecordTypeConfig<R>,\n): RecordType<R, RecordDataKeys<R>> {\n return new RecordType<R, RecordDataKeys<R>>(typeName, {\n scope: config.scope,\n validator: config.validator,\n ephemeralKeys: config.ephemeralKeys,\n createDefaultProperties: () => ({}),\n })\n}\n\n/** Split any `${typeName}:${unique}` id into its parts. */\nexport function parseRecordId(id: string): { typeName: string; uniquePart: string } {\n const colon = id.indexOf(\":\")\n if (colon <= 0 || colon === id.length - 1) {\n throw new Error(`Malformed record id ${JSON.stringify(id)}`)\n }\n return { typeName: id.slice(0, colon), uniquePart: id.slice(colon + 1) }\n}\n\n/** Assert that `value` looks like a record: an object with string `id` and `typeName`. */\nexport function isRecordLike(value: unknown): value is UnknownRecord {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { id?: unknown }).id === \"string\" &&\n typeof (value as { typeName?: unknown }).typeName === \"string\"\n )\n}\n","import { generateKeyBetween, generateNKeysBetween } from \"fractional-indexing\"\n\n/**\n * A fractional index: an order key that sorts lexicographically (plain string\n * comparison) and between which new keys can always be generated.\n */\nexport type IndexKey = string & { __brand: \"indexKey\" }\n\n/** The conventional first key. */\nexport const ZERO_INDEX_KEY = \"a0\" as IndexKey\n\nfunction assertOrdered(below: IndexKey | undefined, above: IndexKey | undefined) {\n if (below !== undefined && above !== undefined && !(below < above)) {\n throw new Error(`Index keys out of order: ${JSON.stringify(below)} must be below ${JSON.stringify(above)}`)\n }\n}\n\n/** Generate a key strictly between `below` and `above`; either may be omitted. Throws when `below >= above`. */\nexport function getIndexBetween(below?: IndexKey | undefined, above?: IndexKey | undefined): IndexKey {\n assertOrdered(below, above)\n return generateKeyBetween(below ?? null, above ?? null) as IndexKey\n}\n\n/** Generate a key strictly above `below` (or a first key when omitted). */\nexport function getIndexAbove(below?: IndexKey | undefined): IndexKey {\n return generateKeyBetween(below ?? null, null) as IndexKey\n}\n\n/** Generate a key strictly below `above` (or a first key when omitted). */\nexport function getIndexBelow(above?: IndexKey | undefined): IndexKey {\n return generateKeyBetween(null, above ?? null) as IndexKey\n}\n\n/** Generate `n` sorted keys strictly between `below` and `above`. */\nexport function getIndicesBetween(\n below: IndexKey | undefined,\n above: IndexKey | undefined,\n n: number,\n): IndexKey[] {\n assertOrdered(below, above)\n return generateNKeysBetween(below ?? null, above ?? null, n) as IndexKey[]\n}\n\n/** Generate `n` sorted keys strictly above `below`. */\nexport function getIndicesAbove(below: IndexKey | undefined, n: number): IndexKey[] {\n return generateNKeysBetween(below ?? null, null, n) as IndexKey[]\n}\n\n/** Generate `n` sorted keys strictly below `above`. */\nexport function getIndicesBelow(above: IndexKey | undefined, n: number): IndexKey[] {\n return generateNKeysBetween(null, above ?? null, n) as IndexKey[]\n}\n\n/**\n * Generate `n` sorted keys, the first of which is `start` (default `a0`).\n * Useful when creating `n` items at once.\n */\nexport function getIndices(n: number, start: IndexKey = ZERO_INDEX_KEY): IndexKey[] {\n if (n <= 0) return []\n validateIndexKey(start)\n return [start, ...getIndicesAbove(start, n - 1)]\n}\n\n/** Return a sorted copy of `items` ordered by their `index` (stable). */\nexport function sortByIndex<T extends { index: IndexKey }>(items: readonly T[]): T[] {\n return items\n .map((item, i) => [item, i] as const)\n .sort(([a, ai], [b, bi]) => {\n if (a.index < b.index) return -1\n if (a.index > b.index) return 1\n return ai - bi\n })\n .map(([item]) => item)\n}\n\n/** Compare two keys: negative, zero, or positive. */\nexport function compareIndexKeys(a: IndexKey, b: IndexKey): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\nconst BASE_62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\nconst IS_DIGIT = new Uint8Array(128)\nfor (let i = 0; i < BASE_62.length; i++) IS_DIGIT[BASE_62.charCodeAt(i)] = 1\n\n/**\n * Length of the integer part (head marker included) encoded by a head\n * character, or -1 when the character is not a head marker.\n * `a`..`z` mark positive integer parts of length 2..27, `Z`..`A` negative ones.\n */\nfunction integerPartLength(head: number): number {\n if (head >= 97 && head <= 122) return head - 97 + 2 // a..z\n if (head >= 65 && head <= 90) return 90 - head + 2 // A..Z\n return -1\n}\n\n/**\n * Throws if `key` is not a well-formed fractional index key: a head marker,\n * enough base-62 integer digits for that head, then an optional fraction of\n * base-62 digits that does not end in `0`.\n * Narrows the type on success.\n */\nexport function validateIndexKey(key: string): asserts key is IndexKey {\n const fail = (why: string): never => {\n throw new Error(`Invalid index key ${JSON.stringify(key)}: ${why}`)\n }\n if (typeof key !== \"string\" || key.length === 0) fail(\"empty\")\n const intLen = integerPartLength(key.charCodeAt(0))\n if (intLen < 0) fail(\"bad head marker\")\n if (key.length < intLen) fail(`integer part needs ${intLen - 1} digits`)\n for (let i = 1; i < key.length; i++) {\n const c = key.charCodeAt(i)\n if (c > 127 || IS_DIGIT[c] !== 1) fail(`bad digit at ${i}`)\n }\n if (key.length > intLen && key.endsWith(\"0\")) fail(\"fraction ends in 0\")\n}\n\n/** Non-throwing variant of `validateIndexKey`. */\nexport function isIndexKey(key: unknown): key is IndexKey {\n if (typeof key !== \"string\") return false\n try {\n validateIndexKey(key)\n return true\n } catch {\n return false\n }\n}\n","import type { IndexKey } from \"./indexKey\"\n\n/**\n * Convert a fractional index key into a 64-bit unsigned sortable integer,\n * returned as two uint32 words `[lo, hi]` for transport into WASM memory.\n *\n * Key anatomy (fractional-indexing spec): the first character is a *head*\n * marker drawn from `A..Z` (negative integer parts, `Z` shortest) and `a..z`\n * (positive integer parts, `a` shortest). It encodes the length of the\n * integer part; the remaining characters are base-62 digits (integer digits\n * followed by fractional digits, no trailing `0` in the fraction).\n *\n * Because the head already sorts integer parts by length and sign, the\n * lexicographic order of two keys is: head rank first, then the digit string\n * compared as a zero-padded fixed-point fraction. We encode exactly that:\n *\n * zkey = headRank * 62^10 + Σ digit[i] * 62^(9 - i) for i in 0..9\n *\n * with headRank in 0..51 (`A`=0 … `Z`=25, `a`=26 … `z`=51). The maximum value\n * is 52 * 62^10 - 1 ≈ 4.36e18 < 2^64, so it fits in 64 bits. Ten base-62\n * digits after the head are significant; keys that agree on those ten digits\n * tie, which only happens for keys sharing a long common prefix.\n */\n\nconst BASE_62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\nconst HEADS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n/** Number of base-62 digits (after the head marker) that affect the zkey. */\nexport const ZKEY_SIGNIFICANT_DIGITS = 10\n\nconst DIGIT_VALUE = new Int8Array(128).fill(-1)\nfor (let i = 0; i < BASE_62.length; i++) DIGIT_VALUE[BASE_62.charCodeAt(i)] = i\n\nconst HEAD_RANK = new Int8Array(128).fill(-1)\nfor (let i = 0; i < HEADS.length; i++) HEAD_RANK[HEADS.charCodeAt(i)] = i\n\nconst B = 62n\nconst B10 = B ** BigInt(ZKEY_SIGNIFICANT_DIGITS)\nconst MASK_32 = 0xffff_ffffn\n\nexport type ZKey = readonly [lo: number, hi: number]\n\nexport function indexKeyToZKey(key: IndexKey): [lo: number, hi: number] {\n if (key.length === 0) throw new Error(\"Cannot convert an empty index key\")\n const headRank = HEAD_RANK[key.charCodeAt(0)] ?? -1\n if (headRank < 0) throw new Error(`Invalid index key head in ${JSON.stringify(key)}`)\n\n let fraction = 0n\n const n = Math.min(key.length - 1, ZKEY_SIGNIFICANT_DIGITS)\n for (let i = 0; i < n; i++) {\n const d = DIGIT_VALUE[key.charCodeAt(i + 1)] ?? -1\n if (d < 0) throw new Error(`Invalid index key digit in ${JSON.stringify(key)}`)\n fraction = fraction * B + BigInt(d)\n }\n // Pad remaining digit positions with zero so shorter keys sort first.\n for (let i = n; i < ZKEY_SIGNIFICANT_DIGITS; i++) fraction *= B\n\n const value = BigInt(headRank) * B10 + fraction\n const lo = Number(value & MASK_32)\n const hi = Number((value >> 32n) & MASK_32)\n return [lo, hi]\n}\n\n/** Recombine a zkey into a BigInt (mostly for tests and debugging). */\nexport function zKeyToBigInt([lo, hi]: ZKey): bigint {\n return (BigInt(hi) << 32n) | BigInt(lo)\n}\n\n/** Compare two zkeys as unsigned 64-bit integers. */\nexport function compareZKeys(a: ZKey, b: ZKey): number {\n if (a[1] !== b[1]) return a[1] < b[1] ? -1 : 1\n if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1\n return 0\n}\n","import type { IdOf, UnknownRecord } from \"./ids\"\n\n/** A set of changes to a store's records. */\nexport interface RecordsDiff<R extends UnknownRecord> {\n added: Record<IdOf<R>, R>\n updated: Record<IdOf<R>, [from: R, to: R]>\n removed: Record<IdOf<R>, R>\n}\n\nexport function createEmptyRecordsDiff<R extends UnknownRecord>(): RecordsDiff<R> {\n return { added: {}, updated: {}, removed: {} } as RecordsDiff<R>\n}\n\nexport function isRecordsDiffEmpty<R extends UnknownRecord>(diff: RecordsDiff<R>): boolean {\n for (const _ in diff.added) return false\n for (const _ in diff.updated) return false\n for (const _ in diff.removed) return false\n return true\n}\n\n/** Produce the diff that undoes `diff`. */\nexport function reverseRecordsDiff<R extends UnknownRecord>(diff: RecordsDiff<R>): RecordsDiff<R> {\n const result = createEmptyRecordsDiff<R>()\n for (const id in diff.added) {\n result.removed[id as IdOf<R>] = diff.added[id as IdOf<R>]!\n }\n for (const id in diff.removed) {\n result.added[id as IdOf<R>] = diff.removed[id as IdOf<R>]!\n }\n for (const id in diff.updated) {\n const [from, to] = diff.updated[id as IdOf<R>]!\n result.updated[id as IdOf<R>] = [to, from]\n }\n return result\n}\n\n/**\n * Record that `id` went from `before` to `after` in `target`, collapsing with\n * any change already recorded for the same id:\n *\n * added + updated -> added (latest)\n * added + removed -> (nothing)\n * updated + updated -> updated [original from, latest to]\n * updated + removed -> removed (original from)\n * removed + added -> updated [removed, added] (or nothing if identical)\n */\nexport function applyChangeToDiff<R extends UnknownRecord>(\n target: RecordsDiff<R>,\n id: IdOf<R>,\n before: R | undefined,\n after: R | undefined,\n): void {\n if (before === undefined && after === undefined) return\n\n if (id in target.added) {\n if (after === undefined) {\n delete target.added[id]\n } else {\n target.added[id] = after\n }\n return\n }\n\n if (id in target.updated) {\n const [from] = target.updated[id]!\n if (after === undefined) {\n delete target.updated[id]\n target.removed[id] = from\n } else if (from === after) {\n delete target.updated[id]\n } else {\n target.updated[id] = [from, after]\n }\n return\n }\n\n if (id in target.removed) {\n const original = target.removed[id]!\n if (after === undefined) return // removed twice: keep original\n delete target.removed[id]\n if (original !== after) target.updated[id] = [original, after]\n return\n }\n\n // No prior entry for this id.\n if (before === undefined) {\n if (after !== undefined) target.added[id] = after\n } else if (after === undefined) {\n target.removed[id] = before\n } else if (before !== after) {\n target.updated[id] = [before, after]\n }\n}\n\n/** Merge `diff` into `target` in place (see `applyChangeToDiff` for the rules). */\nexport function squashRecordDiffsMutable<R extends UnknownRecord>(\n target: RecordsDiff<R>,\n diff: RecordsDiff<R>,\n): void {\n for (const id in diff.added) {\n applyChangeToDiff(target, id as IdOf<R>, undefined, diff.added[id as IdOf<R>]!)\n }\n for (const id in diff.updated) {\n const [from, to] = diff.updated[id as IdOf<R>]!\n applyChangeToDiff(target, id as IdOf<R>, from, to)\n }\n for (const id in diff.removed) {\n applyChangeToDiff(target, id as IdOf<R>, diff.removed[id as IdOf<R>]!, undefined)\n }\n}\n\n/** Squash a sequence of diffs into one equivalent diff (does not mutate inputs). */\nexport function squashRecordDiffs<R extends UnknownRecord>(diffs: readonly RecordsDiff<R>[]): RecordsDiff<R> {\n const result = createEmptyRecordsDiff<R>()\n for (const diff of diffs) squashRecordDiffsMutable(result, diff)\n return result\n}\n\n/** Shallow-copy a diff (entries are shared). */\nexport function cloneRecordsDiff<R extends UnknownRecord>(diff: RecordsDiff<R>): RecordsDiff<R> {\n return {\n added: { ...diff.added },\n updated: { ...diff.updated },\n removed: { ...diff.removed },\n } as RecordsDiff<R>\n}\n","import type { IdOf, UnknownRecord } from \"./ids\"\nimport type { SerializedSchemaV1 } from \"./legacy\"\n\n/** Serialized records keyed by id. */\nexport type SerializedStore<R extends UnknownRecord> = Record<IdOf<R>, R>\n\n/**\n * Persisted description of a schema: for each migration sequence, how many\n * migrations had been applied when the data was saved.\n */\nexport interface SerializedSchemaV2 {\n schemaVersion: 2\n sequences: { [sequenceId: string]: number }\n}\n\n/**\n * A persisted schema, in either format mocanvas can read.\n *\n * Only {@link SerializedSchemaV2} is ever *written* — see\n * `StoreSchema.serialize`. The v1 arm is here so a document saved by an older,\n * pre-sequence writer is still loadable rather than being rejected as\n * \"unsupported schema version\".\n */\nexport type SerializedSchema = SerializedSchemaV1 | SerializedSchemaV2\n\nexport type MigrationId = `${string}/${number}`\n\nexport interface RecordMigration {\n readonly id: MigrationId\n readonly scope: \"record\"\n /** Only records for which this returns true are migrated. Defaults to all records. */\n readonly filter?: ((record: UnknownRecord) => boolean) | undefined\n /** Mutate the record in place, or return a replacement. */\n readonly up: (record: UnknownRecord) => void | UnknownRecord\n readonly down?: ((record: UnknownRecord) => void | UnknownRecord) | undefined\n}\n\nexport interface StoreMigration {\n readonly id: MigrationId\n readonly scope: \"store\"\n /** Mutate the store in place, or return a replacement. */\n readonly up: (store: SerializedStore<UnknownRecord>) => void | SerializedStore<UnknownRecord>\n readonly down?:\n | ((store: SerializedStore<UnknownRecord>) => void | SerializedStore<UnknownRecord>)\n | undefined\n}\n\nexport type Migration = RecordMigration | StoreMigration\n\nexport interface MigrationSequence {\n readonly sequenceId: string\n /**\n * When data is loaded that has never seen this sequence, should every\n * migration be applied (`true`, the default) or should the data be assumed\n * already up to date (`false`)? Use `false` for sequences added to a type\n * that already existed before the sequence did.\n */\n readonly retroactive: boolean\n readonly sequence: readonly Migration[]\n}\n\nexport type MigrationResult<T> = { type: \"success\"; value: T } | { type: \"error\"; reason: string }\n\n/**\n * Build the ids of a sequence's migrations from friendly names:\n *\n * ```ts\n * const Versions = createMigrationIds('com.example.shape.box', { AddColor: 1, AddSize: 2 })\n * // Versions.AddColor === 'com.example.shape.box/1'\n * ```\n */\nexport function createMigrationIds<const ID extends string, const Versions extends Record<string, number>>(\n sequenceId: ID,\n versions: Versions,\n): { readonly [K in keyof Versions]: `${ID}/${Versions[K]}` } {\n const result: Record<string, string> = {}\n for (const [name, version] of Object.entries(versions)) {\n result[name] = `${sequenceId}/${version}`\n }\n return result as { readonly [K in keyof Versions]: `${ID}/${Versions[K]}` }\n}\n\nexport function parseMigrationId(id: string): { sequenceId: string; version: number } {\n const slash = id.lastIndexOf(\"/\")\n if (slash <= 0) throw new Error(`Malformed migration id ${JSON.stringify(id)}`)\n const version = Number(id.slice(slash + 1))\n if (!Number.isInteger(version) || version < 1) {\n throw new Error(`Malformed migration id ${JSON.stringify(id)}: version must be a positive integer`)\n }\n return { sequenceId: id.slice(0, slash), version }\n}\n\n/**\n * Create a validated migration sequence. Migration ids must be\n * `${sequenceId}/1`, `${sequenceId}/2`, ... in order.\n */\nexport function createMigrationSequence(options: {\n sequenceId: string\n retroactive?: boolean | undefined\n sequence: readonly Migration[]\n}): MigrationSequence {\n const { sequenceId, retroactive = true, sequence } = options\n if (!sequenceId || sequenceId.includes(\"/\")) {\n throw new Error(`Invalid sequenceId ${JSON.stringify(sequenceId)}: must be non-empty and not contain \"/\"`)\n }\n sequence.forEach((migration, i) => {\n const id = migration.id\n const parsed = parseMigrationId(id)\n if (parsed.sequenceId !== sequenceId) {\n throw new Error(`Migration ${id} does not belong to sequence ${sequenceId}`)\n }\n if (parsed.version !== i + 1) {\n throw new Error(`Migration ${id} is out of order: expected version ${i + 1}`)\n }\n const scope: string = migration.scope\n if (scope !== \"record\" && scope !== \"store\") {\n throw new Error(`Migration ${id} has invalid scope ${JSON.stringify(scope)}`)\n }\n })\n return { sequenceId, retroactive, sequence: [...sequence] }\n}\n\n/**\n * Convenience for the common case: a sequence of record-scoped migrations\n * that all apply to one record type (optionally narrowed further by `filter`).\n */\nexport function createRecordMigrationSequence(options: {\n sequenceId: string\n recordType: string\n retroactive?: boolean | undefined\n filter?: ((record: UnknownRecord) => boolean) | undefined\n sequence: readonly Omit<RecordMigration, \"scope\" | \"filter\">[]\n}): MigrationSequence {\n const { recordType, filter } = options\n const combinedFilter = (record: UnknownRecord) =>\n record.typeName === recordType && (filter ? filter(record) : true)\n return createMigrationSequence({\n sequenceId: options.sequenceId,\n retroactive: options.retroactive,\n sequence: options.sequence.map(\n (m): RecordMigration => ({ id: m.id, scope: \"record\", filter: combinedFilter, up: m.up, down: m.down }),\n ),\n })\n}\n\n/** Apply one record migration to a single record, honoring its filter. */\nexport function applyRecordMigration(\n migration: RecordMigration,\n record: UnknownRecord,\n direction: \"up\" | \"down\",\n): UnknownRecord {\n if (migration.filter && !migration.filter(record)) return record\n const fn = direction === \"up\" ? migration.up : migration.down\n if (!fn) throw new Error(`Migration ${migration.id} has no ${direction} function`)\n const result = fn(record)\n return result === undefined ? record : result\n}\n\n/** Apply one migration (record- or store-scoped) to a whole store in place. */\nexport function applyMigrationToStore(\n migration: Migration,\n store: SerializedStore<UnknownRecord>,\n direction: \"up\" | \"down\",\n): SerializedStore<UnknownRecord> {\n if (migration.scope === \"store\") {\n const fn = direction === \"up\" ? migration.up : migration.down\n if (!fn) throw new Error(`Migration ${migration.id} has no ${direction} function`)\n const result = fn(store)\n return result === undefined ? store : result\n }\n for (const id in store) {\n const record = store[id as IdOf<UnknownRecord>]!\n const next = applyRecordMigration(migration, record, direction)\n if (next !== record) store[id as IdOf<UnknownRecord>] = next\n }\n return store\n}\n","/**\n * The pre-sequence migration format, and the reasons a migration can fail.\n *\n * Before migrations were named sequences, a schema declared one integer version\n * per record type plus one for the store, and a table of numbered up/down\n * functions between them. mocanvas never *writes* that format — {@link\n * SerializedSchemaV1} exists so a document saved by something that did can\n * still be recognised and loaded, and so a schema written against the old shape\n * can still be described.\n *\n * Nothing here changes what mocanvas persists. See `StoreSchema.serialize`,\n * which always produces the v2 shape.\n */\n\nimport type { UnknownRecord } from \"./ids\"\n\n/**\n * The persisted schema shape used before migration sequences: a version number\n * per record type, and one for the store as a whole.\n *\n * Read-only as far as mocanvas is concerned. A snapshot carrying one is treated\n * as knowing none of today's sequences, so every retroactive sequence runs from\n * the beginning — which is right, because none of them existed when the file\n * was written.\n */\nexport interface SerializedSchemaV1 {\n schemaVersion: 1\n storeVersion: number\n recordVersions: Record<\n string,\n { version: number } | { version: number; subTypeVersions: Record<string, number>; subTypeKey: string }\n >\n}\n\n/** Whether a persisted schema is in the pre-sequence format. */\nexport function isSerializedSchemaV1(schema: { schemaVersion: number }): schema is SerializedSchemaV1 {\n return schema.schemaVersion === 1\n}\n\n/** One numbered step of a {@link LegacyMigrations} table. */\nexport interface LegacyMigration<Before = any, After = any> {\n up: (oldState: Before) => After\n down: (newState: After) => Before\n}\n\n/** The version bounds every legacy migration table declares. */\nexport interface LegacyBaseMigrationsInfo {\n firstVersion: number\n currentVersion: number\n migrators: { [version: number]: LegacyMigration }\n}\n\n/**\n * A legacy migration table: the version range it covers, the numbered steps,\n * and optionally the sub-type split a record type used (a shape's `type`, say,\n * each with its own version line).\n */\nexport interface LegacyMigrations extends LegacyBaseMigrationsInfo {\n subTypeKey?: string\n subTypeMigrations?: Record<string, LegacyBaseMigrationsInfo>\n}\n\n/**\n * A dependency declared by a standalone migration sequence: it must run after\n * (or before) another sequence's numbered migration, even though neither owns\n * the other.\n *\n * Ordering between sequences is otherwise registration order, which is fine\n * until one sequence's `up` reads a field another sequence is still about to\n * add.\n */\nexport interface StandaloneDependsOn {\n dependsOn: readonly string[]\n}\n\n/**\n * Why loading a persisted snapshot failed.\n *\n * These are the cases worth telling apart in a UI: \"this file is from a newer\n * version of the app\" is a message a user can act on, and\n * \"migrationError\" is not.\n */\nexport const MigrationFailureReason = {\n /** The persisted schema names a sequence version higher than this schema knows. */\n TargetVersionTooNew: \"target-version-too-new\",\n /** The persisted data is older than the oldest migration that survives. */\n TargetVersionTooOld: \"target-version-too-old\",\n /** A record's type is not registered in this schema and cannot be migrated. */\n UnrecognizedType: \"unrecognized-type\",\n /** A migration function threw. */\n MigrationError: \"migration-error\",\n /** The persisted schema itself is malformed. */\n IncompatibleSubtype: \"incompatible-subtype\",\n /** The persisted schema version is not one this store understands. */\n UnknownSchemaVersion: \"unknown-schema-version\",\n} as const\n\n/** One of the {@link MigrationFailureReason} values. */\nexport type MigrationFailureReason = (typeof MigrationFailureReason)[keyof typeof MigrationFailureReason]\n","import { isRecordLike, type IdOf, type RecordScope, type RecordType, type UnknownRecord } from \"./ids\"\nimport {\n applyMigrationToStore,\n applyRecordMigration,\n type Migration,\n type MigrationResult,\n type MigrationSequence,\n type SerializedSchema,\n type SerializedSchemaV2,\n type SerializedStore,\n} from \"./migrate\"\nimport { isSerializedSchemaV1 } from \"./legacy\"\nimport type { Store } from \"./Store\"\n\nexport type StoreValidationPhase = \"initialize\" | \"createRecord\" | \"updateRecord\" | \"tests\"\n\nexport type RecordTypeMap<R extends UnknownRecord> = {\n readonly [TypeName in R[\"typeName\"]]: RecordType<Extract<R, { typeName: TypeName }>, any>\n}\n\nexport interface StoreValidationFailure<R extends UnknownRecord> {\n error: unknown\n store: Store<R, any>\n record: R\n phase: StoreValidationPhase\n recordBefore: R | null\n}\n\nexport interface StoreSchemaOptions<R extends UnknownRecord, Props> {\n readonly migrations?: readonly MigrationSequence[] | undefined\n /**\n * Called when a record fails validation. Return a repaired record to keep\n * going, or throw to abort the operation. When omitted the error is thrown.\n */\n readonly onValidationFailure?: ((data: StoreValidationFailure<R>) => R) | undefined\n /** Reserved for store-level integrity checks; unused by the schema itself. */\n readonly createIntegrityChecker?: ((store: Store<R, Props>) => void) | undefined\n}\n\nexport interface StoreSnapshot<R extends UnknownRecord> {\n store: SerializedStore<R>\n schema: SerializedSchema\n}\n\n/**\n * The set of record types a store holds plus the migrations that bring\n * persisted data up to date.\n */\nexport class StoreSchema<R extends UnknownRecord, Props = unknown> {\n static create<R extends UnknownRecord, Props = unknown>(\n types: RecordTypeMap<R>,\n options?: StoreSchemaOptions<R, Props>,\n ): StoreSchema<R, Props> {\n return new StoreSchema<R, Props>(types, options ?? {})\n }\n\n readonly migrations: Readonly<Record<string, MigrationSequence>>\n /** All migrations in application order (sequence registration order, then version). */\n readonly sortedMigrations: readonly Migration[]\n private readonly typeByName: ReadonlyMap<string, RecordType<R, any>>\n\n private constructor(\n readonly types: RecordTypeMap<R>,\n private readonly options: StoreSchemaOptions<R, Props>,\n ) {\n const byName = new Map<string, RecordType<R, any>>()\n for (const [name, type] of Object.entries(types) as [string, RecordType<R, any>][]) {\n if (type.typeName !== name) {\n throw new Error(`Record type registered under \"${name}\" has typeName \"${type.typeName}\"`)\n }\n byName.set(name, type)\n }\n this.typeByName = byName\n\n const migrations: Record<string, MigrationSequence> = {}\n const sorted: Migration[] = []\n const seenIds = new Set<string>()\n for (const sequence of options.migrations ?? []) {\n if (migrations[sequence.sequenceId]) {\n throw new Error(`Duplicate migration sequence \"${sequence.sequenceId}\"`)\n }\n migrations[sequence.sequenceId] = sequence\n for (const migration of sequence.sequence) {\n if (seenIds.has(migration.id)) throw new Error(`Duplicate migration id \"${migration.id}\"`)\n seenIds.add(migration.id)\n sorted.push(migration)\n }\n }\n this.migrations = migrations\n this.sortedMigrations = sorted\n }\n\n getType(typeName: string): RecordType<R, any> | undefined {\n return this.typeByName.get(typeName)\n }\n\n /** Scope of a record type; unknown types are treated as `document`. */\n getScope(typeName: string): RecordScope {\n return this.typeByName.get(typeName)?.scope ?? \"document\"\n }\n\n /**\n * Validate a record, delegating to its record type's validator.\n *\n * Two things are checked before the delegation. First, the value has to be a\n * record at all: an object with a string `id` and a string `typeName`.\n * Without that check a value carrying no `typeName` looks up `undefined` in\n * the type map, misses, and takes the unknown-type path below — which is how\n * `store.put([{ id: \"shape:bogus\", x: 0, y: 0 }])` used to be accepted.\n *\n * Second, a record whose `typeName` this schema does not know is passed\n * through untouched, so foreign data survives a load/save round-trip. That\n * is the escape hatch; it is not meant to cover malformed input, hence the\n * first check.\n */\n validateRecord(\n store: Store<R, any>,\n record: R,\n phase: StoreValidationPhase,\n recordBefore: R | undefined,\n ): R {\n if (!isRecordLike(record)) {\n return this.onFailure(\n new Error(\n `Expected a record with a string \\`id\\` and \\`typeName\\`, got ${describeRecord(record)}`,\n ),\n store,\n record,\n phase,\n recordBefore,\n )\n }\n const type = this.typeByName.get(record.typeName)\n if (!type) return record\n try {\n return type.validate(record, recordBefore)\n } catch (error) {\n return this.onFailure(error, store, record, phase, recordBefore)\n }\n }\n\n private onFailure(\n error: unknown,\n store: Store<R, any>,\n record: R,\n phase: StoreValidationPhase,\n recordBefore: R | undefined,\n ): R {\n if (this.options.onValidationFailure) {\n return this.options.onValidationFailure({\n error,\n store,\n record,\n phase,\n recordBefore: recordBefore ?? null,\n })\n }\n throw error\n }\n\n /** The current version of every sequence. Always the v2 shape — mocanvas never writes v1. */\n serialize(): SerializedSchemaV2 {\n const sequences: Record<string, number> = {}\n for (const sequence of Object.values(this.migrations)) {\n sequences[sequence.sequenceId] = sequence.sequence.length\n }\n return { schemaVersion: 2, sequences }\n }\n\n /** A schema at version 0 of every sequence (all migrations still pending). */\n serializeEarliestVersion(): SerializedSchemaV2 {\n const sequences: Record<string, number> = {}\n for (const sequence of Object.values(this.migrations)) sequences[sequence.sequenceId] = 0\n return { schemaVersion: 2, sequences }\n }\n\n /**\n * The migrations that must run to bring data saved under `persistedSchema`\n * up to this schema, in order. Sequences the persisted schema knows but we\n * do not are ignored with a warning.\n */\n getMigrationsSince(persistedSchema: SerializedSchema): MigrationResult<Migration[]> {\n // A pre-sequence schema records one version number per record type and\n // says nothing about which of today's sequences have run. There is no\n // sound mapping from that to sequence versions, and guessing would\n // re-apply migrations that had already been applied — so this is refused\n // rather than migrated. `SerializedSchemaV1` exists so such a file can be\n // *recognised* and reported, not silently corrupted.\n if (isSerializedSchemaV1(persistedSchema)) {\n return {\n type: \"error\",\n reason:\n \"Schema version 1 (per-record-type versions) predates migration sequences and cannot be migrated automatically\",\n }\n }\n if (persistedSchema.schemaVersion !== 2) {\n return {\n type: \"error\",\n reason: `Unsupported schema version ${String((persistedSchema as { schemaVersion: unknown }).schemaVersion)}`,\n }\n }\n return this.migrationsSince(persistedSchema.sequences ?? {})\n }\n\n private migrationsSince(persisted: { [sequenceId: string]: number }): MigrationResult<Migration[]> {\n for (const sequenceId of Object.keys(persisted)) {\n if (!this.migrations[sequenceId]) {\n console.warn(`[store] ignoring unknown migration sequence \"${sequenceId}\" in persisted schema`)\n }\n }\n\n const result: Migration[] = []\n for (const sequence of Object.values(this.migrations)) {\n const persistedVersion = persisted[sequence.sequenceId]\n let startAt: number\n if (persistedVersion === undefined) {\n if (!sequence.retroactive) continue\n startAt = 0\n } else {\n if (!Number.isInteger(persistedVersion) || persistedVersion < 0) {\n return { type: \"error\", reason: `Invalid version ${String(persistedVersion)} for sequence \"${sequence.sequenceId}\"` }\n }\n if (persistedVersion > sequence.sequence.length) {\n return {\n type: \"error\",\n reason: `Sequence \"${sequence.sequenceId}\" is at version ${persistedVersion} but this schema only knows ${sequence.sequence.length}: data comes from a newer version`,\n }\n }\n startAt = persistedVersion\n }\n for (let i = startAt; i < sequence.sequence.length; i++) result.push(sequence.sequence[i]!)\n }\n return { type: \"success\", value: result }\n }\n\n /**\n * Migrate a single record. Only record-scoped migrations can be applied;\n * encountering a store-scoped one is an error. `down` runs the migrations\n * in reverse (from this schema to `persistedSchema`).\n */\n migratePersistedRecord(\n record: UnknownRecord,\n persistedSchema: SerializedSchema,\n direction: \"up\" | \"down\" = \"up\",\n ): MigrationResult<UnknownRecord> {\n const migrations = this.getMigrationsSince(persistedSchema)\n if (migrations.type === \"error\") return migrations\n const ordered = direction === \"up\" ? migrations.value : [...migrations.value].reverse()\n let current: UnknownRecord = structuredClone(record)\n try {\n for (const migration of ordered) {\n if (migration.scope !== \"record\") {\n return { type: \"error\", reason: `Migration ${migration.id} is store-scoped and cannot be applied to a single record` }\n }\n if (direction === \"down\" && !migration.down) {\n return { type: \"error\", reason: `Migration ${migration.id} has no down migration` }\n }\n current = applyRecordMigration(migration, current, direction)\n }\n } catch (error) {\n return { type: \"error\", reason: `Migration failed: ${error instanceof Error ? error.message : String(error)}` }\n }\n return { type: \"success\", value: current }\n }\n\n /**\n * Bring a whole persisted store up to date. The input is not mutated.\n * Records of types this schema does not know are preserved as-is.\n */\n migrateStoreSnapshot(snapshot: StoreSnapshot<R>): MigrationResult<SerializedStore<R>> {\n const migrations = this.getMigrationsSince(snapshot.schema)\n if (migrations.type === \"error\") return migrations\n\n let store: SerializedStore<UnknownRecord> = structuredClone(snapshot.store)\n if (migrations.value.length === 0) return { type: \"success\", value: store as SerializedStore<R> }\n\n try {\n for (const migration of migrations.value) {\n store = applyMigrationToStore(migration, store, \"up\")\n }\n } catch (error) {\n return { type: \"error\", reason: `Migration failed: ${error instanceof Error ? error.message : String(error)}` }\n }\n\n // Migrations must not change a record's id or lose it.\n for (const id in store) {\n const record = store[id as IdOf<UnknownRecord>]\n if (!record || record.id !== id) {\n return { type: \"error\", reason: `Migration produced a record whose id does not match its key (${id})` }\n }\n }\n return { type: \"success\", value: store as SerializedStore<R> }\n }\n}\n\n/** How a non-record reads back in the failure message. */\nfunction describeRecord(value: unknown): string {\n if (value === null) return \"null\"\n if (typeof value !== \"object\") return typeof value\n if (Array.isArray(value)) return \"an array\"\n const { id, typeName } = value as { id?: unknown; typeName?: unknown }\n const parts: string[] = []\n parts.push(typeof id === \"string\" ? `id ${JSON.stringify(id)}` : `id ${id === undefined ? \"missing\" : typeof id}`)\n parts.push(\n typeof typeName === \"string\"\n ? `typeName ${JSON.stringify(typeName)}`\n : `typeName ${typeName === undefined ? \"missing\" : typeof typeName}`,\n )\n return `an object with ${parts.join(\" and \")}`\n}\n","/**\n * Declarative queries over the store, and the incremental indexes they run on.\n *\n * A query is a plain object — `{ type: { eq: \"geo\" }, parentId: { eq: pageId } }`\n * — rather than a predicate function, and that is the point: an object can be\n * inspected. The store picks one of the query's properties, maintains an index\n * from that property's value to the ids that hold it, and answers the query by\n * intersecting index buckets instead of scanning every record. A predicate can\n * only be run over everything.\n *\n * The index is itself a signal, and it carries diffs: a dependent that already\n * built a result can patch it from {@link RSIndexDiff} rather than rebuilding.\n */\n\nimport type { IdOf, UnknownRecord } from \"./ids\"\n\n/**\n * What changed in a set: the members added and the members removed.\n *\n * Either side may be absent, which means \"nothing on that side\" — a diff with\n * neither is a diff that says nothing happened.\n */\nexport interface CollectionDiff<T> {\n added?: Set<T>\n removed?: Set<T>\n}\n\n/**\n * How one property of a record is matched.\n *\n * SEMANTICS-ASSUMED: three comparisons — equality, inequality and a numeric\n * greater-than — are what an index can answer without scanning, which is the\n * whole reason queries are data rather than functions. `gt` is deliberately\n * numeric: the only ordered property records carry is a number.\n */\nexport type QueryValueMatcher<T> = { eq: T } | { neq: T } | { gt: number }\n\n/**\n * A query over the records of one type: property name to matcher, every entry\n * of which must hold (they are ANDed).\n *\n * ```ts\n * store.query.records(\"shape\", () => ({ type: { eq: \"geo\" }, isLocked: { eq: false } }))\n * ```\n */\nexport type QueryExpression<R extends object> = {\n [K in keyof R]?: QueryValueMatcher<R[K]>\n}\n\n/**\n * An index over one property of one record type: for each value that property\n * takes, the ids of the records that hold it.\n */\nexport type RSIndexMap<R extends UnknownRecord, Property extends keyof R & string = keyof R & string> = Map<\n R[Property],\n Set<IdOf<R>>\n>\n\n/** How an {@link RSIndexMap} changed: per property value, which ids joined and left. */\nexport type RSIndexDiff<R extends UnknownRecord, Property extends keyof R & string = keyof R & string> = Map<\n R[Property],\n CollectionDiff<IdOf<R>>\n>\n\n/**\n * A live index over one property, as a diff-carrying signal.\n *\n * Reading it gives the current {@link RSIndexMap}; asking it for the diffs\n * since a past epoch gives {@link RSIndexDiff}s that describe how to get from\n * the old map to the new one.\n */\nexport type RSIndex<R extends UnknownRecord, Property extends keyof R & string = keyof R & string> = import(\"./_signals\").Computed<\n RSIndexMap<R, Property>,\n RSIndexDiff<R, Property>\n>\n\n/** Whether `value` satisfies `matcher`. */\nexport function matchesQueryValue<T>(matcher: QueryValueMatcher<T>, value: T): boolean {\n if (\"eq\" in matcher) return Object.is(matcher.eq, value)\n if (\"neq\" in matcher) return !Object.is(matcher.neq, value)\n return typeof value === \"number\" && value > matcher.gt\n}\n\n/** Whether `record` satisfies every entry of `query`. An empty query matches everything. */\nexport function matchesQuery<R extends object>(query: QueryExpression<R>, record: R): boolean {\n for (const key of Object.keys(query) as (keyof R)[]) {\n const matcher = query[key]\n if (matcher === undefined) continue\n if (!matchesQueryValue(matcher, record[key])) return false\n }\n return true\n}\n\n/**\n * The property this query can be answered from an index on, or `undefined`\n * when none of it is indexable.\n *\n * Only an `eq` clause narrows to a single index bucket; `neq` and `gt` still\n * need every bucket looked at, so they are no better than a scan. The first\n * `eq` wins — the remaining clauses are checked against the records it yields.\n */\nexport function getIndexablePropertyOf<R extends object>(query: QueryExpression<R>): (keyof R & string) | undefined {\n for (const key of Object.keys(query) as (keyof R & string)[]) {\n const matcher = query[key]\n if (matcher && \"eq\" in matcher) return key\n }\n return undefined\n}\n\n/** Apply a {@link CollectionDiff} to a set, in place. */\nexport function applyCollectionDiff<T>(set: Set<T>, diff: CollectionDiff<T>): Set<T> {\n if (diff.removed) for (const value of diff.removed) set.delete(value)\n if (diff.added) for (const value of diff.added) set.add(value)\n return set\n}\n\n/** Whether a {@link CollectionDiff} describes no change at all. */\nexport function isCollectionDiffEmpty<T>(diff: CollectionDiff<T>): boolean {\n return (diff.added?.size ?? 0) === 0 && (diff.removed?.size ?? 0) === 0\n}\n","import {\n atom,\n computed,\n isUninitialized,\n RESET_VALUE,\n transact,\n unsafe__withoutCapture,\n withDiff,\n type Atom,\n type Computed,\n} from \"./_signals\"\nimport type { IdOf, RecordFromId, RecordScope, RecordType, StoreValidator, UnknownRecord } from \"./ids\"\nimport { parseRecordId, uniqueId } from \"./ids\"\nimport {\n getIndexablePropertyOf,\n matchesQuery,\n type CollectionDiff,\n type QueryExpression,\n type RSIndex,\n type RSIndexDiff,\n type RSIndexMap,\n} from \"./query\"\nimport type { SerializedSchema, SerializedStore } from \"./migrate\"\nimport {\n applyChangeToDiff,\n createEmptyRecordsDiff,\n isRecordsDiffEmpty,\n squashRecordDiffs,\n type RecordsDiff,\n} from \"./RecordsDiff\"\nimport type { StoreSchema, StoreSnapshot, StoreValidationPhase } from \"./StoreSchema\"\n\nexport type ChangeSource = \"user\" | \"remote\"\n\nexport interface HistoryEntry<R extends UnknownRecord> {\n changes: RecordsDiff<R>\n source: ChangeSource\n}\n\nexport type StoreListener<R extends UnknownRecord> = (entry: HistoryEntry<R>) => void\n\nexport interface StoreListenerFilters {\n source: ChangeSource | \"all\"\n scope: RecordScope | \"all\"\n}\n\nexport type RecordFromTypeName<R extends UnknownRecord, T extends string> = Extract<R, { typeName: T }>\n\nexport type StoreRecord<S extends Store<any, any>> = S extends Store<infer R, any> ? R : never\n\n/**\n * Anything that owns a store: a `Store` itself, or an object holding one (an\n * `Editor`). Written for the helpers that want to accept either without their\n * callers having to reach for `.store`.\n */\nexport type StoreObject<R extends UnknownRecord = UnknownRecord> = Store<R, any> | { store: Store<R, any> }\n\n/** The record union of whatever store a {@link StoreObject} carries. */\nexport type StoreObjectRecordType<Context extends StoreObject<any>> = Context extends Store<infer R, any>\n ? R\n : Context extends { store: Store<infer R, any> }\n ? R\n : never\n\n/** A validator per record type, as `StoreSchema` collects them from the record types. */\nexport type StoreValidators<R extends UnknownRecord> = {\n [TypeName in R[\"typeName\"]]: StoreValidator<Extract<R, { typeName: TypeName }>>\n}\n\n/**\n * A record that failed validation, with enough context to say what was being\n * done to it at the time.\n *\n * Thrown rather than returned: a store that keeps going after writing an\n * invalid record is a store whose next save produces a file nothing can load.\n */\nexport interface StoreError {\n error: Error\n phase: \"initialize\" | \"createRecord\" | \"updateRecord\" | \"tests\"\n recordBefore?: unknown\n recordAfter: unknown\n isExistingValidationIssue: boolean\n}\n\nexport interface StoreOptions<R extends UnknownRecord, Props> {\n schema: StoreSchema<R, Props>\n initialData?: SerializedStore<R> | undefined\n props: Props\n id?: string | undefined\n}\n\n/* ------------------------------------------------------------------------ */\n/* side effects */\n/* ------------------------------------------------------------------------ */\n\nexport type StoreBeforeCreateHandler<R extends UnknownRecord> = (record: R, source: ChangeSource) => R\nexport type StoreAfterCreateHandler<R extends UnknownRecord> = (record: R, source: ChangeSource) => void\nexport type StoreBeforeChangeHandler<R extends UnknownRecord> = (prev: R, next: R, source: ChangeSource) => R\nexport type StoreAfterChangeHandler<R extends UnknownRecord> = (prev: R, next: R, source: ChangeSource) => void\n/** Return `false` to veto the deletion. */\nexport type StoreBeforeDeleteHandler<R extends UnknownRecord> = (record: R, source: ChangeSource) => void | false\nexport type StoreAfterDeleteHandler<R extends UnknownRecord> = (record: R, source: ChangeSource) => void\nexport type StoreOperationCompleteHandler = (source: ChangeSource) => void\n\nexport interface StoreSideEffectHandlers<R extends UnknownRecord> {\n beforeCreate?: StoreBeforeCreateHandler<R> | undefined\n afterCreate?: StoreAfterCreateHandler<R> | undefined\n beforeChange?: StoreBeforeChangeHandler<R> | undefined\n afterChange?: StoreAfterChangeHandler<R> | undefined\n beforeDelete?: StoreBeforeDeleteHandler<R> | undefined\n afterDelete?: StoreAfterDeleteHandler<R> | undefined\n}\n\ninterface HandlerSets<R extends UnknownRecord> {\n beforeCreate: Set<StoreBeforeCreateHandler<R>>\n afterCreate: Set<StoreAfterCreateHandler<R>>\n beforeChange: Set<StoreBeforeChangeHandler<R>>\n afterChange: Set<StoreAfterChangeHandler<R>>\n beforeDelete: Set<StoreBeforeDeleteHandler<R>>\n afterDelete: Set<StoreAfterDeleteHandler<R>>\n}\n\n/**\n * Hooks that run around record writes. `before*` handlers may replace the\n * record being written (or veto a delete); `after*` handlers observe.\n * `operationComplete` handlers run once when the outermost operation ends,\n * before history listeners are notified.\n */\nexport class StoreSideEffects<R extends UnknownRecord> {\n private readonly byType = new Map<string, HandlerSets<R>>()\n private readonly operationComplete = new Set<StoreOperationCompleteHandler>()\n private enabled = true\n\n isEnabled(): boolean {\n return this.enabled\n }\n\n setIsEnabled(enabled: boolean): void {\n this.enabled = enabled\n }\n\n private sets(typeName: string): HandlerSets<R> {\n let sets = this.byType.get(typeName)\n if (!sets) {\n sets = {\n beforeCreate: new Set(),\n afterCreate: new Set(),\n beforeChange: new Set(),\n afterChange: new Set(),\n beforeDelete: new Set(),\n afterDelete: new Set(),\n }\n this.byType.set(typeName, sets)\n }\n return sets\n }\n\n private add<K extends keyof HandlerSets<R>>(\n typeName: string,\n kind: K,\n handler: HandlerSets<R>[K] extends Set<infer H> ? H : never,\n ): () => void {\n const set = this.sets(typeName)[kind] as Set<unknown>\n set.add(handler)\n return () => {\n set.delete(handler)\n }\n }\n\n /** Register several handlers for several types at once. Returns a disposer for all of them. */\n register(handlers: {\n [T in R[\"typeName\"]]?: StoreSideEffectHandlers<RecordFromTypeName<R, T>>\n }): () => void {\n const disposers: (() => void)[] = []\n for (const [typeName, h] of Object.entries(handlers) as [string, StoreSideEffectHandlers<any> | undefined][]) {\n if (!h) continue\n if (h.beforeCreate) disposers.push(this.add(typeName, \"beforeCreate\", h.beforeCreate))\n if (h.afterCreate) disposers.push(this.add(typeName, \"afterCreate\", h.afterCreate))\n if (h.beforeChange) disposers.push(this.add(typeName, \"beforeChange\", h.beforeChange))\n if (h.afterChange) disposers.push(this.add(typeName, \"afterChange\", h.afterChange))\n if (h.beforeDelete) disposers.push(this.add(typeName, \"beforeDelete\", h.beforeDelete))\n if (h.afterDelete) disposers.push(this.add(typeName, \"afterDelete\", h.afterDelete))\n }\n return () => disposers.forEach((d) => d())\n }\n\n registerBeforeCreateHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreBeforeCreateHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"beforeCreate\", handler as unknown as StoreBeforeCreateHandler<R>)\n }\n\n registerAfterCreateHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreAfterCreateHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"afterCreate\", handler as unknown as StoreAfterCreateHandler<R>)\n }\n\n registerBeforeChangeHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreBeforeChangeHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"beforeChange\", handler as unknown as StoreBeforeChangeHandler<R>)\n }\n\n registerAfterChangeHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreAfterChangeHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"afterChange\", handler as unknown as StoreAfterChangeHandler<R>)\n }\n\n registerBeforeDeleteHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreBeforeDeleteHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"beforeDelete\", handler as unknown as StoreBeforeDeleteHandler<R>)\n }\n\n registerAfterDeleteHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreAfterDeleteHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"afterDelete\", handler as unknown as StoreAfterDeleteHandler<R>)\n }\n\n registerOperationCompleteHandler(handler: StoreOperationCompleteHandler): () => void {\n this.operationComplete.add(handler)\n return () => {\n this.operationComplete.delete(handler)\n }\n }\n\n /** @internal */\n handleBeforeCreate(record: R, source: ChangeSource): R {\n const sets = this.byType.get(record.typeName)\n if (!sets) return record\n let result = record\n for (const handler of sets.beforeCreate) result = handler(result, source)\n return result\n }\n\n /** @internal */\n handleAfterCreate(record: R, source: ChangeSource): void {\n const sets = this.byType.get(record.typeName)\n if (!sets) return\n for (const handler of sets.afterCreate) handler(record, source)\n }\n\n /** @internal */\n handleBeforeChange(prev: R, next: R, source: ChangeSource): R {\n const sets = this.byType.get(next.typeName)\n if (!sets) return next\n let result = next\n for (const handler of sets.beforeChange) result = handler(prev, result, source)\n return result\n }\n\n /** @internal */\n handleAfterChange(prev: R, next: R, source: ChangeSource): void {\n const sets = this.byType.get(next.typeName)\n if (!sets) return\n for (const handler of sets.afterChange) handler(prev, next, source)\n }\n\n /** @internal Returns false when a handler vetoed the delete. */\n handleBeforeDelete(record: R, source: ChangeSource): boolean {\n const sets = this.byType.get(record.typeName)\n if (!sets) return true\n for (const handler of sets.beforeDelete) {\n if (handler(record, source) === false) return false\n }\n return true\n }\n\n /** @internal */\n handleAfterDelete(record: R, source: ChangeSource): void {\n const sets = this.byType.get(record.typeName)\n if (!sets) return\n for (const handler of sets.afterDelete) handler(record, source)\n }\n\n /** @internal */\n handleOperationComplete(source: ChangeSource): void {\n for (const handler of this.operationComplete) handler(source)\n }\n}\n\n/* ------------------------------------------------------------------------ */\n/* helpers */\n/* ------------------------------------------------------------------------ */\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\nfunction shallowEqualObjects(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n if (a === b) return true\n const aKeys = Object.keys(a)\n const bKeys = Object.keys(b)\n if (aKeys.length !== bKeys.length) return false\n for (const key of aKeys) {\n if (!(key in b) || a[key] !== b[key]) return false\n }\n return true\n}\n\n/**\n * Records are considered unchanged when every top-level value is identical,\n * with `props` and `meta` compared one level deeper. Cheap enough to run on\n * every `put`, and avoids no-op history entries.\n */\nexport function isRecordShallowEqual(a: UnknownRecord, b: UnknownRecord): boolean {\n if (a === b) return true\n const ao = a as unknown as Record<string, unknown>\n const bo = b as unknown as Record<string, unknown>\n const aKeys = Object.keys(ao)\n const bKeys = Object.keys(bo)\n if (aKeys.length !== bKeys.length) return false\n for (const key of aKeys) {\n if (!(key in bo)) return false\n const av = ao[key]\n const bv = bo[key]\n if (av === bv) continue\n if ((key === \"props\" || key === \"meta\") && isPlainObject(av) && isPlainObject(bv)) {\n if (!shallowEqualObjects(av, bv)) return false\n continue\n }\n return false\n }\n return true\n}\n\n/** Freeze a record and its `props` / `meta` bags (one level). */\nexport function freezeRecord<R extends UnknownRecord>(record: R): R {\n const r = record as unknown as Record<string, unknown>\n if (isPlainObject(r[\"props\"]) && !Object.isFrozen(r[\"props\"])) Object.freeze(r[\"props\"])\n if (isPlainObject(r[\"meta\"]) && !Object.isFrozen(r[\"meta\"])) Object.freeze(r[\"meta\"])\n return Object.freeze(record)\n}\n\ninterface TypeIndex<R extends UnknownRecord> {\n /** Mutated in place on every add/remove: O(1) per record. */\n readonly live: Set<IdOf<R>>\n /** Bumped whenever `live` changes; the reactive handle on membership. */\n readonly epoch: Atom<number>\n}\n\ninterface Listener<R extends UnknownRecord> {\n onHistory: StoreListener<R>\n filters: StoreListenerFilters\n}\n\n/* ------------------------------------------------------------------------ */\n/* queries */\n/* ------------------------------------------------------------------------ */\n\n/** Reactive views over the store's records, cached per type name. */\n/**\n * How the records of one type are narrowed: a predicate, or a declarative\n * {@link QueryExpression} the store can answer from an index.\n *\n * Prefer the query object. A predicate has to be run against every record of\n * the type; a query with an `eq` clause is answered from an index bucket.\n */\nexport type StoreQueryFilter<Rec extends UnknownRecord> =\n | ((record: Rec) => boolean)\n | QueryExpression<Rec>\n\nfunction toPredicate<Rec extends UnknownRecord>(filter: StoreQueryFilter<Rec>): (record: Rec) => boolean {\n return typeof filter === \"function\" ? filter : (record) => matchesQuery(filter, record)\n}\n\nexport class StoreQueries<R extends UnknownRecord> {\n private readonly idsCache = new Map<string, Computed<ReadonlySet<IdOf<R>>>>()\n private readonly recordsCache = new Map<string, Computed<R[]>>()\n private readonly indexCache = new Map<string, RSIndex<any, any>>()\n private readonly historyCache = new Map<string, Computed<number, RecordsDiff<R>>>()\n\n constructor(private readonly store: Store<R, any>) {}\n\n /**\n * The set of ids of every record of `typeName`, optionally narrowed by a\n * filter. Maintained incrementally.\n */\n ids<T extends R[\"typeName\"]>(\n typeName: T,\n filter?: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): Computed<ReadonlySet<IdOf<RecordFromTypeName<R, T>>>> {\n if (filter) {\n const records = this.records(typeName, filter)\n return computed(`store:${this.store.id}:ids:${typeName}:filtered`, () => {\n const set = new Set<IdOf<RecordFromTypeName<R, T>>>()\n for (const record of records.get()) set.add(record.id as IdOf<RecordFromTypeName<R, T>>)\n return set as ReadonlySet<IdOf<RecordFromTypeName<R, T>>>\n })\n }\n let c = this.idsCache.get(typeName)\n if (!c) {\n const index = this.store.getTypeIndex(typeName)\n c = computed(`store:${this.store.id}:ids:${typeName}`, () => {\n index.epoch.get()\n return new Set(index.live) as ReadonlySet<IdOf<R>>\n })\n this.idsCache.set(typeName, c)\n }\n return c as unknown as Computed<ReadonlySet<IdOf<RecordFromTypeName<R, T>>>>\n }\n\n /**\n * Every record of `typeName`, in insertion order, optionally narrowed by a\n * filter.\n *\n * A {@link QueryExpression} with an `eq` clause is answered from the index on\n * that property, so a page with ten thousand shapes does not have to be\n * walked to find the twelve on one frame.\n */\n records<T extends R[\"typeName\"]>(\n typeName: T,\n filter?: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): Computed<RecordFromTypeName<R, T>[]> {\n if (filter) return this.filteredRecords(typeName, filter)\n let c = this.recordsCache.get(typeName)\n if (!c) {\n const ids = this.ids(typeName)\n c = computed(`store:${this.store.id}:records:${typeName}`, () => {\n const result: R[] = []\n for (const id of ids.get()) {\n const record = this.store.get(id as IdOf<R>) as R | undefined\n if (record !== undefined) result.push(record)\n }\n return result\n })\n this.recordsCache.set(typeName, c)\n }\n return c as unknown as Computed<RecordFromTypeName<R, T>[]>\n }\n\n private filteredRecords<T extends R[\"typeName\"]>(\n typeName: T,\n filter: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): Computed<RecordFromTypeName<R, T>[]> {\n type Rec = RecordFromTypeName<R, T>\n const predicate = toPredicate<Rec>(filter)\n const indexedProperty = typeof filter === \"function\" ? undefined : getIndexablePropertyOf(filter)\n\n if (indexedProperty !== undefined) {\n const clause = (filter as QueryExpression<Rec>)[indexedProperty as keyof Rec]\n const wanted = clause && \"eq\" in clause ? clause.eq : undefined\n const index = this.index(typeName, indexedProperty as keyof Rec & string)\n return computed(`store:${this.store.id}:records:${typeName}:${String(indexedProperty)}`, () => {\n const bucket = index.get().get(wanted as Rec[keyof Rec & string])\n if (!bucket) return []\n const result: Rec[] = []\n for (const id of bucket) {\n const record = this.store.get(id as IdOf<R>) as Rec | undefined\n if (record !== undefined && predicate(record)) result.push(record)\n }\n return result\n })\n }\n\n const all = this.records(typeName)\n return computed(`store:${this.store.id}:records:${typeName}:filtered`, () => all.get().filter(predicate))\n }\n\n /** The first record of `typeName` matching `filter` (or the first record, when omitted). */\n record<T extends R[\"typeName\"]>(\n typeName: T,\n filter?: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): Computed<RecordFromTypeName<R, T> | undefined> {\n const records = filter ? this.filteredRecords(typeName, filter) : this.records(typeName)\n return computed(`store:${this.store.id}:record:${typeName}`, () => records.get()[0])\n }\n\n /** Non-reactive filter over the records of `typeName`. */\n exec<T extends R[\"typeName\"]>(\n typeName: T,\n filter: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): RecordFromTypeName<R, T>[] {\n return unsafe__withoutCapture(() => this.filteredRecords(typeName, filter).get())\n }\n\n /**\n * A live index from the values of one property to the ids of the records\n * holding them.\n *\n * The index is cached per type and property, and it carries diffs: a\n * dependent that already built something from it can ask\n * `index.getDiffSince(epoch)` and patch, instead of walking the whole map\n * again. That is what makes \"every shape whose parentId is this frame\" cheap\n * enough to recompute on every pointer move.\n */\n index<T extends R[\"typeName\"], Property extends keyof RecordFromTypeName<R, T> & string>(\n typeName: T,\n property: Property,\n ): RSIndex<RecordFromTypeName<R, T>, Property> {\n type Rec = RecordFromTypeName<R, T>\n const key = `${typeName}:${property}`\n const cached = this.indexCache.get(key)\n if (cached) return cached as RSIndex<Rec, Property>\n\n const history = this.filterHistory(typeName)\n\n const index = computed<RSIndexMap<Rec, Property>, RSIndexDiff<Rec, Property>>(\n `store:${this.store.id}:index:${key}`,\n (previous, lastComputedEpoch) => {\n if (isUninitialized(previous)) {\n history.get()\n return this.buildIndex<T, Property>(typeName, property)\n }\n\n const diffs = history.getDiffSince(lastComputedEpoch)\n if (diffs === RESET_VALUE) return this.buildIndex<T, Property>(typeName, property)\n\n const nextMap: RSIndexMap<Rec, Property> = new Map(previous)\n const indexDiff: RSIndexDiff<Rec, Property> = new Map()\n let changed = false\n\n const remove = (value: Rec[Property], id: IdOf<Rec>) => {\n const bucket = nextMap.get(value)\n if (!bucket?.has(id)) return\n const next = new Set(bucket)\n next.delete(id)\n if (next.size === 0) nextMap.delete(value)\n else nextMap.set(value, next)\n const entry = indexDiff.get(value) ?? {}\n ;(entry.removed ??= new Set()).add(id)\n indexDiff.set(value, entry)\n changed = true\n }\n const add = (value: Rec[Property], id: IdOf<Rec>) => {\n const bucket = nextMap.get(value)\n if (bucket?.has(id)) return\n nextMap.set(value, new Set(bucket).add(id))\n const entry = indexDiff.get(value) ?? {}\n ;(entry.added ??= new Set()).add(id)\n indexDiff.set(value, entry)\n changed = true\n }\n\n for (const diff of diffs) {\n for (const id in diff.added) {\n const record = diff.added[id as IdOf<R>] as Rec | undefined\n if (record?.typeName === typeName) add(record[property], record.id as IdOf<Rec>)\n }\n for (const id in diff.updated) {\n const [before, after] = diff.updated[id as IdOf<R>] as [Rec, Rec]\n if (after.typeName !== typeName) continue\n if (Object.is(before[property], after[property])) continue\n remove(before[property], before.id as IdOf<Rec>)\n add(after[property], after.id as IdOf<Rec>)\n }\n for (const id in diff.removed) {\n const record = diff.removed[id as IdOf<R>] as Rec | undefined\n if (record?.typeName === typeName) remove(record[property], record.id as IdOf<Rec>)\n }\n }\n\n if (!changed) return previous\n return withDiff(nextMap, indexDiff)\n },\n { historyLength: 128 },\n )\n\n this.indexCache.set(key, index as RSIndex<any, any>)\n return index as RSIndex<Rec, Property>\n }\n\n private buildIndex<T extends R[\"typeName\"], Property extends keyof RecordFromTypeName<R, T> & string>(\n typeName: T,\n property: Property,\n ): RSIndexMap<RecordFromTypeName<R, T>, Property> {\n type Rec = RecordFromTypeName<R, T>\n const map: RSIndexMap<Rec, Property> = new Map()\n for (const record of this.records(typeName).get()) {\n const value = record[property]\n const bucket = map.get(value)\n if (bucket) bucket.add(record.id as IdOf<Rec>)\n else map.set(value, new Set([record.id as IdOf<Rec>]))\n }\n return map\n }\n\n /**\n * The store's history, narrowed to one record type.\n *\n * Its *value* is only a counter — what it is for is the diffs it carries.\n * `filterHistory(\"shape\").getDiffSince(epoch)` is every change to shapes\n * since `epoch`, with changes to other record types dropped, which is how a\n * derived collection stays incremental without re-reading the store.\n */\n filterHistory<T extends R[\"typeName\"]>(typeName: T): Computed<number, RecordsDiff<RecordFromTypeName<R, T>>> {\n const cached = this.historyCache.get(typeName)\n if (cached) return cached as unknown as Computed<number, RecordsDiff<RecordFromTypeName<R, T>>>\n\n const filtered = computed<number, RecordsDiff<R>>(\n `store:${this.store.id}:history:${typeName}`,\n (previous, lastComputedEpoch) => {\n const epoch = this.store.history.get()\n if (isUninitialized(previous)) return epoch\n\n const diffs = this.store.history.getDiffSince(lastComputedEpoch)\n if (diffs === RESET_VALUE) return epoch\n\n const merged = createEmptyRecordsDiff<R>()\n let any = false\n for (const diff of diffs) {\n for (const id in diff.added) {\n const record = diff.added[id as IdOf<R>]!\n if (record.typeName !== typeName) continue\n merged.added[id as IdOf<R>] = record\n any = true\n }\n for (const id in diff.updated) {\n const pair = diff.updated[id as IdOf<R>]!\n if (pair[1].typeName !== typeName) continue\n merged.updated[id as IdOf<R>] = pair\n any = true\n }\n for (const id in diff.removed) {\n const record = diff.removed[id as IdOf<R>]!\n if (record.typeName !== typeName) continue\n merged.removed[id as IdOf<R>] = record\n any = true\n }\n }\n // Nothing of this type changed: keep the old value so dependents are\n // not woken at all.\n if (!any) return previous\n return withDiff(epoch, merged)\n },\n { historyLength: 128 },\n )\n\n this.historyCache.set(typeName, filtered)\n return filtered as unknown as Computed<number, RecordsDiff<RecordFromTypeName<R, T>>>\n }\n}\n\n/* ------------------------------------------------------------------------ */\n/* store */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A reactive, transactional collection of records.\n *\n * - one atom per record, so consumers subscribe to exactly what they read\n * - per-type id sets maintained incrementally\n * - writes are batched; listeners receive one squashed diff per outermost operation\n * - records are frozen on write\n */\nexport class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {\n readonly id: string\n readonly schema: StoreSchema<R, Props>\n readonly props: Props\n readonly scopedTypes: { readonly [S in RecordScope]: ReadonlySet<string> }\n readonly sideEffects = new StoreSideEffects<R>()\n readonly query: StoreQueries<R>\n /**\n * Bumped once per completed operation that changed something.\n *\n * The counter itself carries no information; the diffs do. The atom keeps a\n * bounded history of the squashed {@link RecordsDiff} of each operation, so a\n * derived collection can ask `history.getDiffSince(epoch)` and patch itself\n * instead of rebuilding. `store.query.filterHistory(typeName)` is the same\n * thing narrowed to one record type.\n */\n readonly history: Atom<number, RecordsDiff<R>>\n\n private readonly records = new Map<IdOf<R>, Atom<R | undefined>>()\n private readonly typeIndexes = new Map<string, TypeIndex<R>>()\n private readonly listeners = new Set<Listener<R>>()\n private pendingEntries: HistoryEntry<R>[] = []\n private readonly extractStack: RecordsDiff<R>[] = []\n private depth = 0\n private source: ChangeSource = \"user\"\n private runCallbacks = true\n private inOperationComplete = false\n private disposed = false\n /**\n * The diff of the operation currently being committed, handed to the history\n * atom's `computeDiff` as it is written. The atom only sees two counter\n * values, so the diff has to be staged here for the one write that follows.\n */\n private pendingHistoryDiff: RecordsDiff<R> | null = null\n\n constructor(options: StoreOptions<R, Props>) {\n this.id = options.id ?? uniqueId()\n this.schema = options.schema\n this.props = options.props\n this.history = atom<number, RecordsDiff<R>>(`store:${this.id}:history`, 0, {\n // 128 operations is deep enough that a dependent which rendered a frame\n // ago can still patch, and shallow enough that the buffer costs nothing.\n historyLength: 128,\n computeDiff: () => this.pendingHistoryDiff ?? RESET_VALUE,\n })\n this.query = new StoreQueries(this)\n\n const scoped = { document: new Set<string>(), session: new Set<string>(), presence: new Set<string>() }\n for (const type of Object.values(this.schema.types) as RecordType<R, any>[]) {\n scoped[type.scope].add(type.typeName)\n }\n this.scopedTypes = scoped\n\n if (options.initialData) {\n const records = Object.values(options.initialData) as R[]\n this.atomic(() => this.put(records, \"initialize\"), { runCallbacks: false })\n }\n }\n\n /* ---- reading ---------------------------------------------------------- */\n\n /** @internal */\n getTypeIndex(typeName: string): TypeIndex<R> {\n let index = this.typeIndexes.get(typeName)\n if (!index) {\n index = { live: new Set(), epoch: atom(`store:${this.id}:index:${typeName}`, 0) }\n this.typeIndexes.set(typeName, index)\n }\n return index\n }\n\n /** Get a record (reactive: subscribes to the record, or to its type's membership when absent). */\n get<K extends IdOf<R>>(id: K): RecordFromId<K> | undefined {\n const a = this.records.get(id)\n if (a) return a.get() as RecordFromId<K> | undefined\n // Not present: depend on membership of this id's type so creation is observed.\n this.getTypeIndex(typeNameOfId(id)).epoch.get()\n return undefined\n }\n\n /** Get a record without registering a reactive dependency. */\n unsafeGetWithoutCapture<K extends IdOf<R>>(id: K): RecordFromId<K> | undefined {\n const a = this.records.get(id)\n return a ? (unsafe__withoutCapture(() => a.get()) as RecordFromId<K> | undefined) : undefined\n }\n\n has<K extends IdOf<R>>(id: K): boolean {\n return this.get(id) !== undefined\n }\n\n /** All records (reactive over every record and every type's membership). */\n allRecords(): R[] {\n for (const index of this.typeIndexes.values()) index.epoch.get()\n const result: R[] = []\n for (const a of this.records.values()) {\n const record = a.get()\n if (record !== undefined) result.push(record)\n }\n return result\n }\n\n /** Scope of a record type; unknown types are `document`. */\n getScope(typeName: string): RecordScope {\n return this.schema.getScope(typeName)\n }\n\n /* ---- writing ---------------------------------------------------------- */\n\n /**\n * Insert or update records. Records are validated, passed through `before*`\n * side effects, frozen, and written. `after*` side effects run once every\n * record in the call has been written.\n */\n put(records: readonly R[], phaseOverride?: StoreValidationPhase): void {\n this.atomic(() => {\n const source = this.source\n const callbacks = this.runCallbacks && this.sideEffects.isEnabled()\n const created: R[] = []\n const changed: [R, R][] = []\n\n for (const record of records) {\n const id = record.id\n const existing = this.records.get(id)\n const before = existing?.get()\n\n if (before !== undefined) {\n if (before === record) continue\n let next = this.schema.validateRecord(this, record, phaseOverride ?? \"updateRecord\", before)\n if (callbacks) next = this.sideEffects.handleBeforeChange(before, next, source)\n if (next === before || isRecordShallowEqual(before, next)) continue\n if (next.id !== id) {\n throw new Error(`Cannot change the id of a record (${id} -> ${next.id})`)\n }\n freezeRecord(next)\n if (before.typeName !== next.typeName) {\n this.removeFromIndex(before.typeName, id)\n this.addToIndex(next.typeName, id)\n }\n existing!.set(next)\n this.recordChange(id, before, next)\n changed.push([before, next])\n } else {\n let next = this.schema.validateRecord(this, record, phaseOverride ?? \"createRecord\", undefined)\n if (callbacks) next = this.sideEffects.handleBeforeCreate(next, source)\n if (next.id !== id) {\n throw new Error(`Cannot change the id of a record (${id} -> ${next.id})`)\n }\n freezeRecord(next)\n const a = existing ?? atom<R | undefined>(`store:${this.id}:record:${id}`, undefined)\n a.set(next)\n this.records.set(id, a)\n this.addToIndex(next.typeName, id)\n this.recordChange(id, undefined, next)\n created.push(next)\n }\n }\n\n if (callbacks) {\n for (const record of created) this.sideEffects.handleAfterCreate(record, source)\n for (const [prev, next] of changed) this.sideEffects.handleAfterChange(prev, next, source)\n }\n })\n }\n\n /** Remove records by id. Missing ids are ignored. `beforeDelete` handlers may veto. */\n remove(ids: readonly IdOf<R>[]): void {\n this.atomic(() => {\n const source = this.source\n const callbacks = this.runCallbacks && this.sideEffects.isEnabled()\n const toRemove: R[] = []\n\n for (const id of ids) {\n const a = this.records.get(id)\n if (!a) continue\n const record = a.get()\n if (record === undefined) continue\n if (callbacks && !this.sideEffects.handleBeforeDelete(record, source)) continue\n toRemove.push(record)\n }\n\n const removed: R[] = []\n for (const record of toRemove) {\n const a = this.records.get(record.id)\n if (!a) continue // a handler already removed it\n const current = a.get()\n if (current === undefined) continue\n a.set(undefined)\n this.records.delete(record.id)\n this.removeFromIndex(current.typeName, record.id)\n this.recordChange(record.id, current, undefined)\n removed.push(current)\n }\n\n if (callbacks) {\n for (const record of removed) this.sideEffects.handleAfterDelete(record, source)\n }\n })\n }\n\n /** Remove every record. */\n clear(): void {\n this.remove(Array.from(this.records.keys()))\n }\n\n /**\n * Update one record with a function. No-op when the record does not exist.\n */\n update<K extends IdOf<R>>(id: K, updater: (record: RecordFromId<K>) => RecordFromId<K>): void {\n const current = this.unsafeGetWithoutCapture(id)\n if (current === undefined) return\n this.put([updater(current) as unknown as R])\n }\n\n /* ---- transactions ----------------------------------------------------- */\n\n /**\n * Run `fn` as one operation: side effects' `operationComplete` handlers run\n * once at the end, and listeners get a single squashed history entry.\n */\n atomic<T>(fn: () => T, options?: { source?: ChangeSource | undefined; runCallbacks?: boolean | undefined }): T {\n const prevSource = this.source\n const prevRunCallbacks = this.runCallbacks\n if (options?.source !== undefined) this.source = options.source\n if (options?.runCallbacks !== undefined) this.runCallbacks = options.runCallbacks\n const source = this.source\n const runCallbacks = this.runCallbacks\n this.depth++\n try {\n return transact(() => unsafe__withoutCapture(fn))\n } finally {\n this.depth--\n if (this.depth === 0) {\n try {\n this.completeOperation(source, runCallbacks)\n } finally {\n this.source = prevSource\n this.runCallbacks = prevRunCallbacks\n }\n } else {\n this.source = prevSource\n this.runCallbacks = prevRunCallbacks\n }\n }\n }\n\n /** Changes made inside `fn` are reported to listeners with source `remote`. */\n mergeRemoteChanges(fn: () => void): void {\n this.atomic(fn, { source: \"remote\" })\n }\n\n /** Run `fn` and return the squashed diff of everything it changed. Listeners are still notified. */\n extractingChanges(fn: () => void): RecordsDiff<R> {\n const diff = createEmptyRecordsDiff<R>()\n this.extractStack.push(diff)\n try {\n this.atomic(fn)\n } finally {\n this.extractStack.pop()\n }\n return diff\n }\n\n /**\n * Apply a diff (e.g. from `extractingChanges` or `reverseRecordsDiff`).\n * With `ignoreEphemeralKeys`, ephemeral keys of updated records keep their\n * current store values instead of the diff's.\n */\n applyDiff(\n diff: RecordsDiff<R>,\n options?: { runCallbacks?: boolean | undefined; ignoreEphemeralKeys?: boolean | undefined },\n ): void {\n const runCallbacks = options?.runCallbacks ?? true\n const ignoreEphemeralKeys = options?.ignoreEphemeralKeys ?? false\n this.atomic(\n () => {\n const toPut: R[] = []\n for (const id in diff.added) toPut.push(diff.added[id as IdOf<R>]!)\n for (const id in diff.updated) {\n let [, to] = diff.updated[id as IdOf<R>]!\n if (ignoreEphemeralKeys) {\n const current = this.unsafeGetWithoutCapture(id as IdOf<R>)\n const type = this.schema.getType(to.typeName)\n if (current !== undefined && type && type.ephemeralKeySet.size > 0) {\n const merged: Record<string, unknown> = { ...(to as unknown as Record<string, unknown>) }\n const cur = current as unknown as Record<string, unknown>\n for (const key of type.ephemeralKeySet) {\n if (key in cur) merged[key] = cur[key]\n else delete merged[key]\n }\n to = merged as unknown as R\n }\n }\n toPut.push(to)\n }\n this.put(toPut)\n const toRemove = Object.keys(diff.removed) as IdOf<R>[]\n if (toRemove.length > 0) this.remove(toRemove)\n },\n { runCallbacks },\n )\n }\n\n /* ---- listening -------------------------------------------------------- */\n\n /**\n * Subscribe to history entries. Called after each outermost operation with\n * the squashed changes, filtered by source and record scope.\n */\n listen(onHistory: StoreListener<R>, filters?: Partial<StoreListenerFilters>): () => void {\n const listener: Listener<R> = {\n onHistory,\n filters: { source: filters?.source ?? \"all\", scope: filters?.scope ?? \"all\" },\n }\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n /* ---- persistence ------------------------------------------------------ */\n\n /** Plain-object snapshot of the records in `scope` (default `document`). */\n serialize(scope: RecordScope | \"all\" = \"document\"): SerializedStore<R> {\n const result = {} as SerializedStore<R>\n unsafe__withoutCapture(() => {\n for (const [id, a] of this.records) {\n const record = a.get()\n if (record === undefined) continue\n if (scope === \"all\" || this.getScope(record.typeName) === scope) result[id] = record\n }\n })\n return result\n }\n\n getStoreSnapshot(scope: RecordScope | \"all\" = \"document\"): StoreSnapshot<R> {\n return { store: this.serialize(scope), schema: this.schema.serialize() }\n }\n\n /**\n * Bring a snapshot saved by an older document up to this store's schema,\n * without loading it.\n *\n * Every migration sequence the schema knows is run — including the ones\n * `createStore` derives from the shape and binding utils, so a board saved\n * before a prop existed is backfilled here rather than failing validation on\n * load. The input is not mutated: the result is a new snapshot carrying this\n * schema's serialized version, ready for {@link Store.loadStoreSnapshot} (or\n * for a caller that wants to inspect the migrated records first).\n *\n * A snapshot that cannot be migrated — an unknown schema version, a sequence\n * from a NEWER build than this one, a migration that throws — raises rather\n * than returning half-migrated data, so a caller can fail closed on it.\n */\n migrateSnapshot(snapshot: StoreSnapshot<R>): StoreSnapshot<R> {\n const migrated = this.schema.migrateStoreSnapshot(snapshot)\n if (migrated.type === \"error\") {\n throw new Error(`Failed to migrate snapshot: ${migrated.reason}`)\n }\n return { store: migrated.value, schema: this.schema.serialize() }\n }\n\n /**\n * Replace the store's contents with a snapshot (migrating it first).\n * Existing records in `document` scope and in every scope present in the\n * snapshot are removed unless the snapshot contains them; other scopes are\n * left alone. Side effects do not run; listeners are notified.\n */\n loadStoreSnapshot(snapshot: StoreSnapshot<R>): void {\n const migrated = this.schema.migrateStoreSnapshot(snapshot)\n if (migrated.type === \"error\") {\n throw new Error(`Failed to migrate snapshot: ${migrated.reason}`)\n }\n const incoming = migrated.value\n const records = Object.values(incoming) as R[]\n this.atomic(\n () => {\n const scopes = new Set<RecordScope>([\"document\"])\n for (const record of records) scopes.add(this.getScope(record.typeName))\n const toRemove: IdOf<R>[] = []\n for (const [id, a] of this.records) {\n const record = a.get()\n if (record === undefined) continue\n if (scopes.has(this.getScope(record.typeName)) && !(id in incoming)) toRemove.push(id)\n }\n this.remove(toRemove)\n this.put(records, \"initialize\")\n },\n { runCallbacks: false },\n )\n }\n\n /* ---- derived caches --------------------------------------------------- */\n\n /**\n * A per-record derived value, recomputed only when that record changes.\n * Entries are dropped automatically when records are removed.\n */\n createComputedCache<T, K extends IdOf<R> = IdOf<R>>(\n name: string,\n derive: (record: RecordFromId<K>) => T,\n options?: { isEqual?: ((a: T, b: T) => boolean) | undefined },\n ): { get(id: K): T | undefined } {\n const cache = new WeakMap<Atom<R | undefined>, Computed<T | undefined>>()\n return {\n get: (id: K) => {\n const a = this.records.get(id)\n if (!a) {\n this.getTypeIndex(typeNameOfId(id)).epoch.get()\n return undefined\n }\n let c = cache.get(a)\n if (!c) {\n c = computed(\n `${name}:${id}`,\n () => {\n const record = a.get()\n return record === undefined ? undefined : derive(record as unknown as RecordFromId<K>)\n },\n options?.isEqual\n ? { isEqual: (x, y) => (x === undefined || y === undefined ? x === y : options.isEqual!(x, y)) }\n : undefined,\n )\n cache.set(a, c)\n }\n return c.get()\n },\n }\n }\n\n /* ---- lifecycle -------------------------------------------------------- */\n\n isDisposed(): boolean {\n return this.disposed\n }\n\n dispose(): void {\n this.disposed = true\n this.listeners.clear()\n }\n\n /* ---- internals -------------------------------------------------------- */\n\n private addToIndex(typeName: string, id: IdOf<R>) {\n const index = this.getTypeIndex(typeName)\n if (index.live.has(id)) return\n index.live.add(id)\n index.epoch.update((n) => n + 1)\n }\n\n private removeFromIndex(typeName: string, id: IdOf<R>) {\n const index = this.typeIndexes.get(typeName)\n if (!index || !index.live.delete(id)) return\n index.epoch.update((n) => n + 1)\n }\n\n private recordChange(id: IdOf<R>, before: R | undefined, after: R | undefined) {\n const last = this.pendingEntries[this.pendingEntries.length - 1]\n let entry: HistoryEntry<R>\n if (last && last.source === this.source) {\n entry = last\n } else {\n entry = { changes: createEmptyRecordsDiff<R>(), source: this.source }\n this.pendingEntries.push(entry)\n }\n applyChangeToDiff(entry.changes, id, before, after)\n for (const diff of this.extractStack) applyChangeToDiff(diff, id, before, after)\n }\n\n private completeOperation(source: ChangeSource, runCallbacks: boolean) {\n if (!this.pendingEntries.some((e) => !isRecordsDiffEmpty(e.changes))) {\n this.pendingEntries = []\n return\n }\n if (runCallbacks && this.sideEffects.isEnabled() && !this.inOperationComplete) {\n this.inOperationComplete = true\n const prevSource = this.source\n this.source = source\n this.depth++\n try {\n transact(() => unsafe__withoutCapture(() => this.sideEffects.handleOperationComplete(source)))\n } finally {\n this.depth--\n this.source = prevSource\n this.inOperationComplete = false\n }\n }\n this.pendingHistoryDiff = this.squashPendingEntries()\n try {\n this.history.update((n) => n + 1)\n } finally {\n this.pendingHistoryDiff = null\n }\n this.flushHistory()\n }\n\n /** One diff describing everything the operation just committed changed. */\n private squashPendingEntries(): RecordsDiff<R> {\n const diffs = this.pendingEntries.map((entry) => entry.changes).filter((diff) => !isRecordsDiffEmpty(diff))\n if (diffs.length === 1) return diffs[0]!\n return squashRecordDiffs(diffs)\n }\n\n private flushHistory() {\n const entries = this.pendingEntries\n this.pendingEntries = []\n if (this.listeners.size === 0) return\n for (const entry of entries) {\n if (isRecordsDiffEmpty(entry.changes)) continue\n for (const listener of Array.from(this.listeners)) {\n if (listener.filters.source !== \"all\" && listener.filters.source !== entry.source) continue\n const changes =\n listener.filters.scope === \"all\" ? entry.changes : this.filterDiffByScope(entry.changes, listener.filters.scope)\n if (isRecordsDiffEmpty(changes)) continue\n listener.onHistory({ changes, source: entry.source })\n }\n }\n }\n\n private filterDiffByScope(diff: RecordsDiff<R>, scope: RecordScope): RecordsDiff<R> {\n const result = createEmptyRecordsDiff<R>()\n for (const id in diff.added) {\n const record = diff.added[id as IdOf<R>]!\n if (this.getScope(record.typeName) === scope) result.added[id as IdOf<R>] = record\n }\n for (const id in diff.updated) {\n const pair = diff.updated[id as IdOf<R>]!\n if (this.getScope(pair[1].typeName) === scope) result.updated[id as IdOf<R>] = pair\n }\n for (const id in diff.removed) {\n const record = diff.removed[id as IdOf<R>]!\n if (this.getScope(record.typeName) === scope) result.removed[id as IdOf<R>] = record\n }\n return result\n }\n}\n\nfunction typeNameOfId(id: string): string {\n const colon = id.indexOf(\":\")\n return colon > 0 ? id.slice(0, colon) : parseRecordId(id).typeName\n}\n","import { isRecordLike, type IdOf, type UnknownRecord } from \"./ids\"\nimport type { SerializedSchema, SerializedStore } from \"./migrate\"\n\n/**\n * `.tldr` file envelope. Schema-agnostic: this module does not know or care\n * what record types the file holds.\n */\nexport const TLDR_FILE_FORMAT_VERSION = 1\n\nexport interface TldrFile {\n tldrawFileFormatVersion: number\n schema: SerializedSchema\n records: UnknownRecord[]\n}\n\nexport type TldrFileParseError = \"notATldrFile\" | \"v1File\" | \"invalidRecords\" | \"futureVersion\"\n\nexport type ParseTldrFileResult =\n | { ok: true; schema: SerializedSchema; records: UnknownRecord[] }\n | { ok: false; error: TldrFileParseError; cause?: unknown }\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction isSerializedSchema(value: unknown): value is SerializedSchema {\n return isPlainObject(value) && typeof value[\"schemaVersion\"] === \"number\"\n}\n\n/**\n * Parse a `.tldr` file. Accepts either the JSON text or the already-parsed\n * value. Never throws.\n */\nexport function parseTldrFile(json: unknown): ParseTldrFileResult {\n let data: unknown = json\n if (typeof json === \"string\") {\n try {\n data = JSON.parse(json)\n } catch (cause) {\n return { ok: false, error: \"notATldrFile\", cause }\n }\n }\n\n if (!isPlainObject(data)) return { ok: false, error: \"notATldrFile\" }\n\n if (!(\"tldrawFileFormatVersion\" in data)) {\n // The legacy (pre-envelope) format stored a whole document object.\n const legacyDocument = data[\"document\"]\n if (isPlainObject(legacyDocument) && (\"pages\" in legacyDocument || \"version\" in legacyDocument)) {\n return { ok: false, error: \"v1File\" }\n }\n return { ok: false, error: \"notATldrFile\" }\n }\n\n const version = data[\"tldrawFileFormatVersion\"]\n if (typeof version !== \"number\" || !Number.isInteger(version) || version < 1) {\n return { ok: false, error: \"notATldrFile\" }\n }\n if (version > TLDR_FILE_FORMAT_VERSION) return { ok: false, error: \"futureVersion\" }\n\n if (!isSerializedSchema(data[\"schema\"])) return { ok: false, error: \"notATldrFile\" }\n\n const records = data[\"records\"]\n if (!Array.isArray(records)) return { ok: false, error: \"invalidRecords\" }\n const seen = new Set<string>()\n for (const record of records) {\n if (!isRecordLike(record)) return { ok: false, error: \"invalidRecords\" }\n if (seen.has(record.id)) return { ok: false, error: \"invalidRecords\" }\n seen.add(record.id)\n }\n\n return { ok: true, schema: data[\"schema\"], records: records as UnknownRecord[] }\n}\n\n/**\n * JSON.stringify with object keys sorted recursively so that identical data\n * always produces identical text. Arrays keep their order.\n */\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeysDeep)\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(value).sort()) {\n const v = value[key]\n if (v !== undefined) out[key] = sortKeysDeep(v)\n }\n return out\n }\n return value\n}\n\n/**\n * Serialize records and their schema into the `.tldr` envelope\n * (pretty-printed, stable key order). Records are written in the given order.\n */\nexport function serializeTldrFile(schema: SerializedSchema, records: readonly UnknownRecord[]): string {\n const envelope = {\n tldrawFileFormatVersion: TLDR_FILE_FORMAT_VERSION,\n schema: sortKeysDeep(schema),\n records: records.map(sortKeysDeep),\n }\n return JSON.stringify(envelope, null, 2)\n}\n\n/** Convert a parsed file into a `{ store, schema }` snapshot. */\nexport function tldrFileToStoreSnapshot(file: { schema: SerializedSchema; records: readonly UnknownRecord[] }): {\n store: SerializedStore<UnknownRecord>\n schema: SerializedSchema\n} {\n const store = {} as SerializedStore<UnknownRecord>\n for (const record of file.records) store[record.id as IdOf<UnknownRecord>] = record\n return { store, schema: file.schema }\n}\n\n/** Convert a `{ store, schema }` snapshot into `.tldr` text. Records are ordered by id. */\nexport function storeSnapshotToTldrFile(snapshot: {\n store: SerializedStore<UnknownRecord>\n schema: SerializedSchema\n}): string {\n const records = Object.values(snapshot.store).sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n return serializeTldrFile(snapshot.schema, records)\n}\n","/**\n * Standalone per-record memos.\n *\n * `Store.createComputedCache` already memoizes a value per record, but it is a\n * method: the cache belongs to one store instance, and the derivation cannot see\n * anything else. A shape util or binding util usually needs the opposite shape —\n * one cache declared once at module scope, derived from a record *and* the editor\n * that owns it, and shared by every store that editor drives.\n *\n * `createComputedCache` is that form. The context is passed in at `get` time and\n * the underlying per-record cache is created lazily, once per context.\n */\nimport type { IdOf, RecordId, UnknownRecord } from \"./ids\"\nimport { Store } from \"./Store\"\n\n/**\n * A context a computed cache can read a store from: a store itself, or anything\n * holding one (an `Editor`).\n */\nexport type ComputedCacheContext = Store<any, any> | { readonly store: Store<any, any> }\n\n/** The handle returned by {@link createComputedCache}. */\nexport interface ComputedCache<Context, R extends UnknownRecord, Result> {\n /** The derived value for `id`, or `undefined` if no such record exists. */\n get(context: Context, id: IdOf<R>): Result | undefined\n}\n\n/** Options for {@link createComputedCache}. */\nexport interface CreateComputedCacheOptions<Result> {\n /**\n * Treat two derived values as the same, so dependents are not woken when the\n * derivation recomputes to an equivalent result.\n */\n isEqual?: ((a: Result, b: Result) => boolean) | undefined\n}\n\nfunction storeOf(context: unknown): Store<any, any> {\n if (context instanceof Store) return context\n const store = (context as { store?: unknown } | null | undefined)?.store\n if (store instanceof Store) return store\n throw new Error(\"createComputedCache: context is neither a Store nor an object holding one\")\n}\n\n/**\n * Declare a per-record memo, keyed by record id, recomputed only when that\n * record changes.\n *\n * ```ts\n * const bindingsCache = createComputedCache(\"connection bindings\", (editor: Editor, shape: TLShape) =>\n * editor.getBindingsFromShape(shape.id, \"connection\"),\n * )\n * bindingsCache.get(editor, shapeId)\n * ```\n *\n * SEMANTICS-ASSUMED: `Context` is unconstrained rather than bound to\n * {@link ComputedCacheContext}. The consumer annotates the derivation's own\n * parameter (`(editor: Editor, shape: TLShape) => …`) and that is what `get`\n * must accept; constraining the type parameter as well would force every caller\n * to prove `Editor` is structurally a store holder at each call site for no\n * added safety. The store is resolved at `get` time instead, and a context that\n * carries none throws immediately rather than silently returning `undefined`.\n */\nexport function createComputedCache<Context, R extends UnknownRecord, Result>(\n name: string,\n derive: (context: Context, record: R) => Result,\n options?: CreateComputedCacheOpts<Result, R>,\n): ComputedCache<Context, R, Result> {\n // Keyed on the context object, so an editor that is torn down takes its\n // caches with it and a second editor does not read the first one's values.\n const perContext = new WeakMap<object, { get(id: RecordId<UnknownRecord>): Result | undefined }>()\n\n return {\n get(context: Context, id: IdOf<R>): Result | undefined {\n const key = context as unknown as object\n if (key === null || (typeof key !== \"object\" && typeof key !== \"function\")) {\n throw new Error(\"createComputedCache: context must be an object\")\n }\n let cache = perContext.get(key)\n if (!cache) {\n // `areRecordsEqual` gates the derivation itself: when the incoming\n // record is equivalent to the one the last result came from, the\n // previous result is handed back untouched.\n const areRecordsEqual = options?.areRecordsEqual\n // Memoized per record id, not per cache: one shared \"last record\" would\n // compare a shape against whichever unrelated shape was derived before it.\n const previous = new Map<string, { record: R; result: Result }>()\n const derivation = areRecordsEqual\n ? (record: UnknownRecord): Result => {\n const next = record as R\n const last = previous.get(record.id)\n if (last && areRecordsEqual(last.record, next)) return last.result\n const result = derive(context, next)\n previous.set(record.id, { record: next, result })\n return result\n }\n : (record: UnknownRecord): Result => derive(context, record as R)\n\n cache = storeOf(context).createComputedCache<Result>(\n name,\n derivation,\n options?.isEqual ? { isEqual: options.isEqual } : undefined,\n )\n perContext.set(key, cache)\n }\n return cache.get(id as unknown as RecordId<UnknownRecord>)\n },\n }\n}\n\n/**\n * Options for {@link createComputedCache}, including the record-level equality\n * that decides when a derivation is worth re-running at all.\n */\nexport type CreateComputedCacheOpts<Result, R extends UnknownRecord = UnknownRecord> =\n CreateComputedCacheOptions<Result> & {\n /**\n * Treat two versions of the *record* as the same, so the derivation is not\n * re-run when only parts it does not read have changed.\n *\n * `isEqual` compares results and can only save the dependents work;\n * `areRecordsEqual` compares inputs and saves the derivation itself. Use it\n * when the derivation is expensive and reads only a couple of fields —\n * geometry from `props`, say, which should not be rebuilt because the shape\n * moved.\n */\n areRecordsEqual?: ((a: R, b: R) => boolean) | undefined\n }\n","/**\n * Two small guards the store leans on: a development-only deep freeze, and an\n * id assertion that narrows.\n */\n\nimport type { IdOf, RecordType, UnknownRecord } from \"./ids\"\n\n/** Whether the bundle is a development build. Frozen at module load. */\nconst IS_DEV =\n typeof process !== \"undefined\" && typeof process.env === \"object\" && process.env[\"NODE_ENV\"] !== \"production\"\n\n/**\n * Deep-freeze `object` in development builds, and hand it straight back in\n * production.\n *\n * Records in the store are shared by reference with every consumer that read\n * them, so mutating one in place skips the whole change pipeline: no diff, no\n * side effects, no listeners, and an undo that silently does nothing. Freezing\n * turns that from a bug someone finds a week later into a `TypeError` on the\n * line that did it. The check is skipped in production because freezing every\n * record on every write is not free.\n *\n * Already-frozen objects are left alone, so re-freezing a record that came out\n * of the store costs one property read.\n */\nexport function devFreeze<T>(object: T): T {\n if (!IS_DEV) return object\n return deepFreeze(object)\n}\n\nfunction deepFreeze<T>(object: T): T {\n if (object === null || typeof object !== \"object\") return object\n if (Object.isFrozen(object)) return object\n Object.freeze(object)\n // `Object.freeze` is shallow; a record's `props` and `meta` are the parts\n // most likely to be mutated in place, and they are one level down.\n for (const value of Object.values(object as Record<string, unknown>)) deepFreeze(value)\n if (Array.isArray(object)) for (const value of object) deepFreeze(value)\n return object\n}\n\n/**\n * Assert that `id` belongs to `type`, narrowing it to that type's id.\n *\n * Record ids are branded strings, so the compiler already stops most mix-ups —\n * but ids that arrive from outside the program (a URL, a saved file, a sync\n * message) are plain strings that someone has to vouch for. This is the place\n * to do that vouching: it throws with the offending id rather than letting a\n * `page:` id be looked up as a shape and quietly returning `undefined`.\n *\n * ```ts\n * assertIdType(idFromUrl, PageRecordType)\n * editor.setCurrentPage(idFromUrl) // now typed as TLPageId\n * ```\n */\nexport function assertIdType<R extends UnknownRecord>(\n id: string | undefined,\n type: RecordType<R, any>,\n): asserts id is IdOf<R> {\n if (!type.isId(id)) {\n throw new Error(`Expected ${type.typeName} id, got ${JSON.stringify(id)}`)\n }\n}\n","/**\n * The synchronous storage contract a store can be backed by.\n *\n * Deliberately synchronous and deliberately tiny: it is the shape an embedded\n * key-value store (a SQLite table, a `Map`, an in-process test double) already\n * has, so a host can hand one over without writing an adapter. Anything\n * asynchronous — a network, IndexedDB — belongs behind a snapshot load and save\n * rather than behind this.\n */\n\nimport type { IdOf, UnknownRecord } from \"./ids\"\nimport type { SerializedSchema } from \"./migrate\"\n\n/**\n * Somewhere records can be read from and written to, one at a time, without\n * awaiting.\n *\n * Implementations must be consistent within a call: `getAll` reflects every\n * `set` and `delete` that has already returned.\n */\nexport interface SynchronousRecordStorage<R extends UnknownRecord = UnknownRecord> {\n /** The record stored under `id`, or `undefined`. */\n get(id: IdOf<R>): R | undefined\n /** Every stored record. Order is not significant. */\n getAll(): R[]\n /** Store `record` under its own id, replacing anything already there. */\n set(record: R): void\n /** Remove the record stored under `id`. Removing an absent id is not an error. */\n delete(id: IdOf<R>): void\n /** Remove every record. */\n clear(): void\n}\n\n/**\n * Record storage that also remembers the schema its records were written\n * against, so they can be migrated when they are read back.\n *\n * Storing records without their schema is the one mistake that cannot be\n * recovered from later: there is no way to tell which migrations have already\n * run, and re-running them corrupts the data.\n */\nexport interface SynchronousStorage<R extends UnknownRecord = UnknownRecord> extends SynchronousRecordStorage<R> {\n /** The schema the stored records were written against, or `undefined` when empty. */\n getSchema(): SerializedSchema | undefined\n /** Record the schema the stored records are written against. */\n setSchema(schema: SerializedSchema): void\n}\n\n/**\n * A {@link SynchronousStorage} backed by a plain `Map`.\n *\n * Useful in tests and as the reference implementation of the contract — the\n * shortest correct answer to \"what does a storage have to do?\".\n */\nexport function createInMemoryStorage<R extends UnknownRecord = UnknownRecord>(): SynchronousStorage<R> {\n const records = new Map<IdOf<R>, R>()\n let schema: SerializedSchema | undefined\n\n return {\n get: (id) => records.get(id),\n getAll: () => [...records.values()],\n set: (record) => {\n records.set(record.id as IdOf<R>, record)\n },\n delete: (id) => {\n records.delete(id)\n },\n clear: () => records.clear(),\n getSchema: () => schema,\n setSchema: (next) => {\n schema = next\n },\n }\n}\n","/**\n * Grapheme cluster iteration.\n *\n * \"One character\" as a person sees it is a grapheme cluster, not a UTF-16 code\n * unit and not a code point: `👩‍👩‍👧` is one, `é` written as `e` + a combining\n * accent is one, and a flag emoji is one. Anything that measures, truncates or\n * steps through text a character at a time has to walk clusters or it will cut a\n * family emoji in half.\n */\n\n/** Lazily created, because constructing a `Segmenter` is not free. */\nlet segmenter: Intl.Segmenter | undefined\nlet segmenterChecked = false\n\nfunction getSegmenter(): Intl.Segmenter | undefined {\n if (!segmenterChecked) {\n segmenterChecked = true\n try {\n // `Intl.Segmenter` is missing on older Safari and on some minimal Node builds.\n if (typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\") {\n segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" })\n }\n } catch {\n segmenter = undefined\n }\n }\n return segmenter\n}\n\n/**\n * Iterate the grapheme clusters of `str`.\n *\n * Uses `Intl.Segmenter` where it exists and falls back to code-point iteration\n * otherwise — which keeps surrogate pairs intact (so a plain emoji survives) but\n * cannot join a ZWJ sequence or a combining mark to its base.\n *\n * ```ts\n * [...iterateGraphemes(\"a👍🏽b\")] // [\"a\", \"👍🏽\", \"b\"]\n * ```\n */\nexport function* iterateGraphemes(str: string): Generator<string, void, undefined> {\n const seg = getSegmenter()\n if (seg) {\n for (const { segment } of seg.segment(str)) yield segment\n return\n }\n // SEMANTICS-ASSUMED: the fallback splits on code points. It is the closest\n // approximation available without shipping a Unicode break table, and it is\n // never worse than the `for (const c of str)` a caller would otherwise write.\n for (const codePoint of str) yield codePoint\n}\n\n/** The grapheme clusters of `str`, as an array. */\nexport function getGraphemes(str: string): string[] {\n return [...iterateGraphemes(str)]\n}\n\n/** How many grapheme clusters `str` has — its length as a reader would count it. */\nexport function getGraphemeLength(str: string): number {\n let n = 0\n for (const _ of iterateGraphemes(str)) n++\n return n\n}\n"]}
1
+ {"version":3,"sources":["../src/ids.ts","../src/indexKey.ts","../src/zkey.ts","../src/RecordsDiff.ts","../src/migrate.ts","../src/legacy.ts","../src/StoreSchema.ts","../src/query.ts","../src/Store.ts","../src/tldr.ts","../src/computedCache.ts","../src/devFreeze.ts","../src/storage.ts","../src/graphemes.ts"],"names":["BASE_62","isPlainObject"],"mappings":";;;;;;AAGO,IAAM,gBAAA,GAAmB;AAGzB,SAAS,QAAA,CAAS,OAAe,gBAAA,EAA0B;AAChE,EAAA,OAAO,OAAO,IAAI,CAAA;AACpB;AAyEO,IAAM,UAAA,GAAN,MAAM,WAAA,CAAuF;AAAA,EAOlG,WAAA,CACE,UACiB,MAAA,EAGjB;AAHiB,IAAA,IAAA,CAAA,MAAA,GAA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GAAY,IAAI,IAAA,CAAK,SAAA,CAAU,QAAW,EAAE,WAAA,EAAa,YAAY,CAAA;AAAA,MACvE;AAAA,IACF,CAAA,CAAA,MAAQ;AACN,MAAA,SAAA,GAAY,MAAA;AAAA,IACd;AAAA,EACF;AACA,EAAA,OAAO,SAAA;AACT;AAaO,UAAU,iBAAiB,GAAA,EAAiD;AACjF,EAAA,MAAM,MAAM,YAAA,EAAa;AACzB,EAAA,IAAI,GAAA,EAAK;AACP,IAAA,KAAA,MAAW,EAAE,OAAA,EAAQ,IAAK,IAAI,OAAA,CAAQ,GAAG,GAAG,MAAM,OAAA;AAClD,IAAA;AAAA,EACF;AAIA,EAAA,KAAA,MAAW,SAAA,IAAa,KAAK,MAAM,SAAA;AACrC;AAGO,SAAS,aAAa,GAAA,EAAuB;AAClD,EAAA,OAAO,CAAC,GAAG,gBAAA,CAAiB,GAAG,CAAC,CAAA;AAClC;AAGO,SAAS,kBAAkB,GAAA,EAAqB;AACrD,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,KAAA,MAAW,CAAA,IAAK,gBAAA,CAAiB,GAAG,CAAA,EAAG,CAAA,EAAA;AACvC,EAAA,OAAO,CAAA;AACT","file":"index.js","sourcesContent":["import { nanoid } from \"nanoid\"\n\n/** Length of the unique part of a generated record id. */\nexport const UNIQUE_ID_LENGTH = 21\n\n/** Generate a URL-safe unique id (21 chars by default). */\nexport function uniqueId(size: number = UNIQUE_ID_LENGTH): string {\n return nanoid(size)\n}\n\n/**\n * A branded string id. The brand carries the record type so that ids of\n * different record types cannot be mixed up at compile time.\n */\nexport type RecordId<R extends UnknownRecord> = string & { __type__: R }\n\n/** Every record has an id and a type name. */\nexport interface BaseRecord<TypeName extends string, Id extends RecordId<UnknownRecord>> {\n readonly id: Id\n readonly typeName: TypeName\n}\n\nexport type UnknownRecord = BaseRecord<string, RecordId<UnknownRecord>>\n\nexport type IdOf<R extends UnknownRecord> = R[\"id\"]\n\n/** Extract the record type an id refers to. */\nexport type RecordFromId<K extends RecordId<UnknownRecord>> = K extends RecordId<infer R> ? R : never\n\n/**\n * Where a record lives:\n * - `document`: persisted, shared between collaborators (shapes, pages, ...)\n * - `session`: persisted locally only (camera, current page, ...)\n * - `presence`: shared but never persisted (cursors, ...)\n */\nexport type RecordScope = \"document\" | \"session\" | \"presence\"\n\nexport interface StoreValidator<R extends UnknownRecord> {\n validate(record: unknown): R\n /**\n * Optional fast path: validate `newRecord` knowing that `knownGoodVersion`\n * is a valid record of the same type. Implementations may skip the parts\n * that did not change.\n *\n * Declared as a property that may be `undefined` rather than as an optional\n * method, so that a validator carrying an explicit `undefined` — which is\n * what a class with an optional constructor argument produces — still\n * satisfies this under `exactOptionalPropertyTypes`.\n */\n validateUsingKnownGoodVersion?: ((knownGoodVersion: R, newRecord: unknown) => R) | undefined\n}\n\n/** Keys of `R` that hold data (everything except `id` and `typeName`). */\nexport type RecordDataKeys<R extends UnknownRecord> = Exclude<keyof R, \"id\" | \"typeName\">\n\nexport type EphemeralKeys<R extends UnknownRecord> = { readonly [K in RecordDataKeys<R>]: boolean }\n\nexport interface RecordTypeConfig<R extends UnknownRecord> {\n readonly scope: RecordScope\n readonly validator?: StoreValidator<R> | undefined\n /**\n * Keys whose changes should not be considered \"real\" document changes,\n * e.g. transient UI flags. Used by `Store.applyDiff({ ignoreEphemeralKeys })`.\n */\n readonly ephemeralKeys?: EphemeralKeys<R> | undefined\n}\n\n/**\n * Properties the caller must pass to `create()`: the record's data keys minus\n * whatever `withDefaultProperties` provides. `id` is always optional.\n */\nexport type RecordCreateProps<R extends UnknownRecord, RequiredProps extends keyof R> = Pick<\n R,\n RequiredProps\n> &\n Partial<Omit<R, RequiredProps | \"typeName\">>\n\n/**\n * Describes one kind of record in the store: how to make ids, defaults,\n * validation, and where the record lives (its scope).\n */\nexport class RecordType<R extends UnknownRecord, RequiredProps extends keyof R = RecordDataKeys<R>> {\n readonly typeName: R[\"typeName\"]\n readonly scope: RecordScope\n readonly validator: StoreValidator<R> | undefined\n readonly ephemeralKeys: EphemeralKeys<R> | undefined\n readonly ephemeralKeySet: ReadonlySet<string>\n\n constructor(\n typeName: R[\"typeName\"],\n private readonly config: RecordTypeConfig<R> & {\n readonly createDefaultProperties: () => Partial<Omit<R, \"id\" | \"typeName\">>\n },\n ) {\n this.typeName = typeName\n this.scope = config.scope\n this.validator = config.validator\n this.ephemeralKeys = config.ephemeralKeys\n const ephemeral = new Set<string>()\n if (config.ephemeralKeys) {\n for (const [key, value] of Object.entries(config.ephemeralKeys)) {\n if (value) ephemeral.add(key)\n }\n }\n this.ephemeralKeySet = ephemeral\n }\n\n /** Create a new record with defaults applied. A fresh id is generated when none is given. */\n create(properties: RecordCreateProps<R, RequiredProps>): R {\n const result: Record<string, unknown> = {\n ...this.config.createDefaultProperties(),\n ...(properties as Record<string, unknown>),\n }\n if (result[\"id\"] === undefined) result[\"id\"] = this.createId()\n result[\"typeName\"] = this.typeName\n return result as R\n }\n\n /** Shallow-clone a record (props/meta are shared). */\n clone(record: R): R {\n return { ...record }\n }\n\n /** Make an id of this type: `${typeName}:${uniquePart}`. */\n createId(customUniquePart?: string): IdOf<R> {\n return `${this.typeName}:${customUniquePart ?? uniqueId()}` as IdOf<R>\n }\n\n /** Recover the unique part of an id of this type. */\n parseId(id: IdOf<R>): string {\n if (!this.isId(id)) {\n throw new Error(`Id ${JSON.stringify(id)} is not a ${this.typeName} id`)\n }\n return (id as string).slice(this.typeName.length + 1)\n }\n\n isId(id?: string): id is IdOf<R> {\n if (typeof id !== \"string\") return false\n if (id.length <= this.typeName.length + 1) return false\n if (id.charCodeAt(this.typeName.length) !== 58 /* ':' */) return false\n return id.startsWith(this.typeName)\n }\n\n isInstance(record?: unknown): record is R {\n return (\n typeof record === \"object\" &&\n record !== null &&\n (record as { typeName?: unknown }).typeName === this.typeName\n )\n }\n\n /**\n * Return a new RecordType whose `create()` fills in the given defaults, so\n * those properties become optional for callers.\n */\n withDefaultProperties<DefaultProps extends RecordDataKeys<R>>(\n createDefaultProperties: () => Pick<R, DefaultProps>,\n ): RecordType<R, Exclude<RequiredProps, DefaultProps>> {\n return new RecordType<R, Exclude<RequiredProps, DefaultProps>>(this.typeName, {\n scope: this.scope,\n validator: this.validator,\n ephemeralKeys: this.ephemeralKeys,\n createDefaultProperties: createDefaultProperties as () => Partial<Omit<R, \"id\" | \"typeName\">>,\n })\n }\n\n /** Run the validator (if any). Throws on invalid input. */\n validate(record: unknown, recordBefore?: R): R {\n if (!this.validator) return record as R\n if (recordBefore !== undefined && this.validator.validateUsingKnownGoodVersion) {\n return this.validator.validateUsingKnownGoodVersion(recordBefore, record)\n }\n return this.validator.validate(record)\n }\n}\n\n/**\n * Define a record type.\n *\n * ```ts\n * const Book = createRecordType<Book>('book', { scope: 'document' })\n * .withDefaultProperties(() => ({ inStock: true }))\n * const b = Book.create({ title: 'Dune' }) // -> { id: 'book:...', typeName: 'book', title, inStock }\n * ```\n */\nexport function createRecordType<R extends UnknownRecord>(\n typeName: R[\"typeName\"],\n config: RecordTypeConfig<R>,\n): RecordType<R, RecordDataKeys<R>> {\n return new RecordType<R, RecordDataKeys<R>>(typeName, {\n scope: config.scope,\n validator: config.validator,\n ephemeralKeys: config.ephemeralKeys,\n createDefaultProperties: () => ({}),\n })\n}\n\n/** Split any `${typeName}:${unique}` id into its parts. */\nexport function parseRecordId(id: string): { typeName: string; uniquePart: string } {\n const colon = id.indexOf(\":\")\n if (colon <= 0 || colon === id.length - 1) {\n throw new Error(`Malformed record id ${JSON.stringify(id)}`)\n }\n return { typeName: id.slice(0, colon), uniquePart: id.slice(colon + 1) }\n}\n\n/** Assert that `value` looks like a record: an object with string `id` and `typeName`. */\nexport function isRecordLike(value: unknown): value is UnknownRecord {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { id?: unknown }).id === \"string\" &&\n typeof (value as { typeName?: unknown }).typeName === \"string\"\n )\n}\n","import { generateKeyBetween, generateNKeysBetween } from \"fractional-indexing\"\n\n/**\n * A fractional index: an order key that sorts lexicographically (plain string\n * comparison) and between which new keys can always be generated.\n */\nexport type IndexKey = string & { __brand: \"indexKey\" }\n\n/** The conventional first key. */\nexport const ZERO_INDEX_KEY = \"a0\" as IndexKey\n\nfunction assertOrdered(below: IndexKey | undefined, above: IndexKey | undefined) {\n if (below !== undefined && above !== undefined && !(below < above)) {\n throw new Error(`Index keys out of order: ${JSON.stringify(below)} must be below ${JSON.stringify(above)}`)\n }\n}\n\n/* ---- jitter -------------------------------------------------------------\n *\n * Plain fractional indexing is a pure function of its two neighbours, so two\n * clients inserting in the same gap generate the *same* key — not rarely, but\n * every single time. A record's `index` is one register to a last-writer-wins\n * merge, so the two shapes end up claiming one position and the merge keeps\n * one of them. Appending a few random digits makes the keys differ while\n * staying in the same gap, which is what makes concurrent insertion safe.\n *\n * The alphabet deliberately omits \"0\": a key may not end in the smallest digit\n * (`fractional-indexing` rejects it), and excluding it outright is cheaper than\n * checking the last character and costs a negligible amount of entropy —\n * 61^6 is about 5.1e10 per gap.\n * ------------------------------------------------------------------------- */\n\nconst JITTER_DIGITS = \"123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\nconst JITTER_LENGTH = 6\n\nfunction randomJitterChar(maxExclusive?: string): string {\n // When `key` is a prefix of `above`, the first jittered character has to be\n // strictly below the character `above` continues with, or the jittered key\n // would sort past it. Anything after that first character is then free.\n const pool = maxExclusive === undefined ? JITTER_DIGITS : [...JITTER_DIGITS].filter((c) => c < maxExclusive).join(\"\")\n if (pool.length === 0) return \"\"\n return pool[Math.floor(Math.random() * pool.length)]!\n}\n\n/**\n * `key` with random digits appended, still strictly between its neighbours.\n *\n * Returns `key` unchanged when there is no room — `above` continues with the\n * smallest digit, so no suffix fits underneath it. That is the one case where\n * two clients can still collide, and it is vanishingly rarer than the every-time\n * collision it replaces.\n */\nfunction withJitter(key: string, above: string | undefined): IndexKey {\n // `key` already sorts below `above`. If they differ *inside* `key` then any\n // suffix keeps that difference, and only the prefix case needs a bound.\n const bounded = above !== undefined && above.startsWith(key)\n const first = randomJitterChar(bounded ? above[key.length] : undefined)\n if (first === \"\") return key as IndexKey\n let out = key + first\n for (let i = 1; i < JITTER_LENGTH; i++) out += randomJitterChar()\n return out as IndexKey\n}\n\n/**\n * Generate a key strictly between `below` and `above`; either may be omitted.\n * Throws when `below >= above`.\n *\n * Jittered — see the note above {@link JITTER_DIGITS}. Two calls with the same\n * arguments return *different* keys, both in the same gap, which is what lets\n * two clients insert at one position without one of them being merged away.\n */\nexport function getIndexBetween(below?: IndexKey | undefined, above?: IndexKey | undefined): IndexKey {\n assertOrdered(below, above)\n return withJitter(generateKeyBetween(below ?? null, above ?? null), above)\n}\n\n/** Generate a key strictly above `below` (or a first key when omitted). Jittered. */\nexport function getIndexAbove(below?: IndexKey | undefined): IndexKey {\n return withJitter(generateKeyBetween(below ?? null, null), undefined)\n}\n\n/** Generate a key strictly below `above` (or a first key when omitted). Jittered. */\nexport function getIndexBelow(above?: IndexKey | undefined): IndexKey {\n return withJitter(generateKeyBetween(null, above ?? null), above)\n}\n\n/**\n * Jitter a run of keys without disturbing their order.\n *\n * Each key is bounded by the *next* one rather than by the outer `above`: two\n * keys in a run are often prefixes of one another, and jittering one past its\n * successor would reorder the run it belongs to.\n */\nfunction withJitterEach(keys: string[], above: string | undefined): IndexKey[] {\n const out: IndexKey[] = []\n for (let i = 0; i < keys.length; i++) {\n out.push(withJitter(keys[i]!, i + 1 < keys.length ? keys[i + 1] : above))\n }\n return out\n}\n\n/** Generate `n` sorted keys strictly between `below` and `above`. Jittered. */\nexport function getIndicesBetween(\n below: IndexKey | undefined,\n above: IndexKey | undefined,\n n: number,\n): IndexKey[] {\n assertOrdered(below, above)\n return withJitterEach(generateNKeysBetween(below ?? null, above ?? null, n), above)\n}\n\n/** Generate `n` sorted keys strictly above `below`. Jittered. */\nexport function getIndicesAbove(below: IndexKey | undefined, n: number): IndexKey[] {\n return withJitterEach(generateNKeysBetween(below ?? null, null, n), undefined)\n}\n\n/** Generate `n` sorted keys strictly below `above`. Jittered. */\nexport function getIndicesBelow(above: IndexKey | undefined, n: number): IndexKey[] {\n return withJitterEach(generateNKeysBetween(null, above ?? null, n), above)\n}\n\n/**\n * Generate `n` sorted keys, the first of which is `start` (default `a0`).\n * Useful when creating `n` items at once.\n */\nexport function getIndices(n: number, start: IndexKey = ZERO_INDEX_KEY): IndexKey[] {\n if (n <= 0) return []\n validateIndexKey(start)\n return [start, ...getIndicesAbove(start, n - 1)]\n}\n\n/** Return a sorted copy of `items` ordered by their `index` (stable). */\nexport function sortByIndex<T extends { index: IndexKey }>(items: readonly T[]): T[] {\n return items\n .map((item, i) => [item, i] as const)\n .sort(([a, ai], [b, bi]) => {\n if (a.index < b.index) return -1\n if (a.index > b.index) return 1\n return ai - bi\n })\n .map(([item]) => item)\n}\n\n/** Compare two keys: negative, zero, or positive. */\nexport function compareIndexKeys(a: IndexKey, b: IndexKey): number {\n return a < b ? -1 : a > b ? 1 : 0\n}\n\nconst BASE_62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\nconst IS_DIGIT = new Uint8Array(128)\nfor (let i = 0; i < BASE_62.length; i++) IS_DIGIT[BASE_62.charCodeAt(i)] = 1\n\n/**\n * Length of the integer part (head marker included) encoded by a head\n * character, or -1 when the character is not a head marker.\n * `a`..`z` mark positive integer parts of length 2..27, `Z`..`A` negative ones.\n */\nfunction integerPartLength(head: number): number {\n if (head >= 97 && head <= 122) return head - 97 + 2 // a..z\n if (head >= 65 && head <= 90) return 90 - head + 2 // A..Z\n return -1\n}\n\n/**\n * Throws if `key` is not a well-formed fractional index key: a head marker,\n * enough base-62 integer digits for that head, then an optional fraction of\n * base-62 digits that does not end in `0`.\n * Narrows the type on success.\n */\nexport function validateIndexKey(key: string): asserts key is IndexKey {\n const fail = (why: string): never => {\n throw new Error(`Invalid index key ${JSON.stringify(key)}: ${why}`)\n }\n if (typeof key !== \"string\" || key.length === 0) fail(\"empty\")\n const intLen = integerPartLength(key.charCodeAt(0))\n if (intLen < 0) fail(\"bad head marker\")\n if (key.length < intLen) fail(`integer part needs ${intLen - 1} digits`)\n for (let i = 1; i < key.length; i++) {\n const c = key.charCodeAt(i)\n if (c > 127 || IS_DIGIT[c] !== 1) fail(`bad digit at ${i}`)\n }\n if (key.length > intLen && key.endsWith(\"0\")) fail(\"fraction ends in 0\")\n}\n\n/** Non-throwing variant of `validateIndexKey`. */\nexport function isIndexKey(key: unknown): key is IndexKey {\n if (typeof key !== \"string\") return false\n try {\n validateIndexKey(key)\n return true\n } catch {\n return false\n }\n}\n","import type { IndexKey } from \"./indexKey\"\n\n/**\n * Convert a fractional index key into a 64-bit unsigned sortable integer,\n * returned as two uint32 words `[lo, hi]` for transport into WASM memory.\n *\n * Key anatomy (fractional-indexing spec): the first character is a *head*\n * marker drawn from `A..Z` (negative integer parts, `Z` shortest) and `a..z`\n * (positive integer parts, `a` shortest). It encodes the length of the\n * integer part; the remaining characters are base-62 digits (integer digits\n * followed by fractional digits, no trailing `0` in the fraction).\n *\n * Because the head already sorts integer parts by length and sign, the\n * lexicographic order of two keys is: head rank first, then the digit string\n * compared as a zero-padded fixed-point fraction. We encode exactly that:\n *\n * zkey = headRank * 62^10 + Σ digit[i] * 62^(9 - i) for i in 0..9\n *\n * with headRank in 0..51 (`A`=0 … `Z`=25, `a`=26 … `z`=51). The maximum value\n * is 52 * 62^10 - 1 ≈ 4.36e18 < 2^64, so it fits in 64 bits. Ten base-62\n * digits after the head are significant; keys that agree on those ten digits\n * tie, which only happens for keys sharing a long common prefix.\n */\n\nconst BASE_62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\nconst HEADS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\n/** Number of base-62 digits (after the head marker) that affect the zkey. */\nexport const ZKEY_SIGNIFICANT_DIGITS = 10\n\nconst DIGIT_VALUE = new Int8Array(128).fill(-1)\nfor (let i = 0; i < BASE_62.length; i++) DIGIT_VALUE[BASE_62.charCodeAt(i)] = i\n\nconst HEAD_RANK = new Int8Array(128).fill(-1)\nfor (let i = 0; i < HEADS.length; i++) HEAD_RANK[HEADS.charCodeAt(i)] = i\n\nconst B = 62n\nconst B10 = B ** BigInt(ZKEY_SIGNIFICANT_DIGITS)\nconst MASK_32 = 0xffff_ffffn\n\nexport type ZKey = readonly [lo: number, hi: number]\n\nexport function indexKeyToZKey(key: IndexKey): [lo: number, hi: number] {\n if (key.length === 0) throw new Error(\"Cannot convert an empty index key\")\n const headRank = HEAD_RANK[key.charCodeAt(0)] ?? -1\n if (headRank < 0) throw new Error(`Invalid index key head in ${JSON.stringify(key)}`)\n\n let fraction = 0n\n const n = Math.min(key.length - 1, ZKEY_SIGNIFICANT_DIGITS)\n for (let i = 0; i < n; i++) {\n const d = DIGIT_VALUE[key.charCodeAt(i + 1)] ?? -1\n if (d < 0) throw new Error(`Invalid index key digit in ${JSON.stringify(key)}`)\n fraction = fraction * B + BigInt(d)\n }\n // Pad remaining digit positions with zero so shorter keys sort first.\n for (let i = n; i < ZKEY_SIGNIFICANT_DIGITS; i++) fraction *= B\n\n const value = BigInt(headRank) * B10 + fraction\n const lo = Number(value & MASK_32)\n const hi = Number((value >> 32n) & MASK_32)\n return [lo, hi]\n}\n\n/** Recombine a zkey into a BigInt (mostly for tests and debugging). */\nexport function zKeyToBigInt([lo, hi]: ZKey): bigint {\n return (BigInt(hi) << 32n) | BigInt(lo)\n}\n\n/** Compare two zkeys as unsigned 64-bit integers. */\nexport function compareZKeys(a: ZKey, b: ZKey): number {\n if (a[1] !== b[1]) return a[1] < b[1] ? -1 : 1\n if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1\n return 0\n}\n","import type { IdOf, UnknownRecord } from \"./ids\"\n\n/** A set of changes to a store's records. */\nexport interface RecordsDiff<R extends UnknownRecord> {\n added: Record<IdOf<R>, R>\n updated: Record<IdOf<R>, [from: R, to: R]>\n removed: Record<IdOf<R>, R>\n}\n\nexport function createEmptyRecordsDiff<R extends UnknownRecord>(): RecordsDiff<R> {\n return { added: {}, updated: {}, removed: {} } as RecordsDiff<R>\n}\n\nexport function isRecordsDiffEmpty<R extends UnknownRecord>(diff: RecordsDiff<R>): boolean {\n for (const _ in diff.added) return false\n for (const _ in diff.updated) return false\n for (const _ in diff.removed) return false\n return true\n}\n\n/** Produce the diff that undoes `diff`. */\nexport function reverseRecordsDiff<R extends UnknownRecord>(diff: RecordsDiff<R>): RecordsDiff<R> {\n const result = createEmptyRecordsDiff<R>()\n for (const id in diff.added) {\n result.removed[id as IdOf<R>] = diff.added[id as IdOf<R>]!\n }\n for (const id in diff.removed) {\n result.added[id as IdOf<R>] = diff.removed[id as IdOf<R>]!\n }\n for (const id in diff.updated) {\n const [from, to] = diff.updated[id as IdOf<R>]!\n result.updated[id as IdOf<R>] = [to, from]\n }\n return result\n}\n\n/**\n * Record that `id` went from `before` to `after` in `target`, collapsing with\n * any change already recorded for the same id:\n *\n * added + updated -> added (latest)\n * added + removed -> (nothing)\n * updated + updated -> updated [original from, latest to]\n * updated + removed -> removed (original from)\n * removed + added -> updated [removed, added] (or nothing if identical)\n */\nexport function applyChangeToDiff<R extends UnknownRecord>(\n target: RecordsDiff<R>,\n id: IdOf<R>,\n before: R | undefined,\n after: R | undefined,\n): void {\n if (before === undefined && after === undefined) return\n\n if (id in target.added) {\n if (after === undefined) {\n delete target.added[id]\n } else {\n target.added[id] = after\n }\n return\n }\n\n if (id in target.updated) {\n const [from] = target.updated[id]!\n if (after === undefined) {\n delete target.updated[id]\n target.removed[id] = from\n } else if (from === after) {\n delete target.updated[id]\n } else {\n target.updated[id] = [from, after]\n }\n return\n }\n\n if (id in target.removed) {\n const original = target.removed[id]!\n if (after === undefined) return // removed twice: keep original\n delete target.removed[id]\n if (original !== after) target.updated[id] = [original, after]\n return\n }\n\n // No prior entry for this id.\n if (before === undefined) {\n if (after !== undefined) target.added[id] = after\n } else if (after === undefined) {\n target.removed[id] = before\n } else if (before !== after) {\n target.updated[id] = [before, after]\n }\n}\n\n/** Merge `diff` into `target` in place (see `applyChangeToDiff` for the rules). */\nexport function squashRecordDiffsMutable<R extends UnknownRecord>(\n target: RecordsDiff<R>,\n diff: RecordsDiff<R>,\n): void {\n for (const id in diff.added) {\n applyChangeToDiff(target, id as IdOf<R>, undefined, diff.added[id as IdOf<R>]!)\n }\n for (const id in diff.updated) {\n const [from, to] = diff.updated[id as IdOf<R>]!\n applyChangeToDiff(target, id as IdOf<R>, from, to)\n }\n for (const id in diff.removed) {\n applyChangeToDiff(target, id as IdOf<R>, diff.removed[id as IdOf<R>]!, undefined)\n }\n}\n\n/** Squash a sequence of diffs into one equivalent diff (does not mutate inputs). */\nexport function squashRecordDiffs<R extends UnknownRecord>(diffs: readonly RecordsDiff<R>[]): RecordsDiff<R> {\n const result = createEmptyRecordsDiff<R>()\n for (const diff of diffs) squashRecordDiffsMutable(result, diff)\n return result\n}\n\n/** Shallow-copy a diff (entries are shared). */\nexport function cloneRecordsDiff<R extends UnknownRecord>(diff: RecordsDiff<R>): RecordsDiff<R> {\n return {\n added: { ...diff.added },\n updated: { ...diff.updated },\n removed: { ...diff.removed },\n } as RecordsDiff<R>\n}\n","import type { IdOf, UnknownRecord } from \"./ids\"\nimport type { SerializedSchemaV1 } from \"./legacy\"\n\n/** Serialized records keyed by id. */\nexport type SerializedStore<R extends UnknownRecord> = Record<IdOf<R>, R>\n\n/**\n * Persisted description of a schema: for each migration sequence, how many\n * migrations had been applied when the data was saved.\n */\nexport interface SerializedSchemaV2 {\n schemaVersion: 2\n sequences: { [sequenceId: string]: number }\n}\n\n/**\n * A persisted schema, in either format mocanvas can read.\n *\n * Only {@link SerializedSchemaV2} is ever *written* — see\n * `StoreSchema.serialize`. The v1 arm is here so a document saved by an older,\n * pre-sequence writer is still loadable rather than being rejected as\n * \"unsupported schema version\".\n */\nexport type SerializedSchema = SerializedSchemaV1 | SerializedSchemaV2\n\nexport type MigrationId = `${string}/${number}`\n\nexport interface RecordMigration {\n readonly id: MigrationId\n readonly scope: \"record\"\n /** Only records for which this returns true are migrated. Defaults to all records. */\n readonly filter?: ((record: UnknownRecord) => boolean) | undefined\n /** Mutate the record in place, or return a replacement. */\n readonly up: (record: UnknownRecord) => void | UnknownRecord\n readonly down?: ((record: UnknownRecord) => void | UnknownRecord) | undefined\n}\n\nexport interface StoreMigration {\n readonly id: MigrationId\n readonly scope: \"store\"\n /** Mutate the store in place, or return a replacement. */\n readonly up: (store: SerializedStore<UnknownRecord>) => void | SerializedStore<UnknownRecord>\n readonly down?:\n | ((store: SerializedStore<UnknownRecord>) => void | SerializedStore<UnknownRecord>)\n | undefined\n}\n\nexport type Migration = RecordMigration | StoreMigration\n\nexport interface MigrationSequence {\n readonly sequenceId: string\n /**\n * When data is loaded that has never seen this sequence, should every\n * migration be applied (`true`, the default) or should the data be assumed\n * already up to date (`false`)? Use `false` for sequences added to a type\n * that already existed before the sequence did.\n */\n readonly retroactive: boolean\n readonly sequence: readonly Migration[]\n}\n\nexport type MigrationResult<T> = { type: \"success\"; value: T } | { type: \"error\"; reason: string }\n\n/**\n * Build the ids of a sequence's migrations from friendly names:\n *\n * ```ts\n * const Versions = createMigrationIds('com.example.shape.box', { AddColor: 1, AddSize: 2 })\n * // Versions.AddColor === 'com.example.shape.box/1'\n * ```\n */\nexport function createMigrationIds<const ID extends string, const Versions extends Record<string, number>>(\n sequenceId: ID,\n versions: Versions,\n): { readonly [K in keyof Versions]: `${ID}/${Versions[K]}` } {\n const result: Record<string, string> = {}\n for (const [name, version] of Object.entries(versions)) {\n result[name] = `${sequenceId}/${version}`\n }\n return result as { readonly [K in keyof Versions]: `${ID}/${Versions[K]}` }\n}\n\nexport function parseMigrationId(id: string): { sequenceId: string; version: number } {\n const slash = id.lastIndexOf(\"/\")\n if (slash <= 0) throw new Error(`Malformed migration id ${JSON.stringify(id)}`)\n const version = Number(id.slice(slash + 1))\n if (!Number.isInteger(version) || version < 1) {\n throw new Error(`Malformed migration id ${JSON.stringify(id)}: version must be a positive integer`)\n }\n return { sequenceId: id.slice(0, slash), version }\n}\n\n/**\n * Create a validated migration sequence. Migration ids must be\n * `${sequenceId}/1`, `${sequenceId}/2`, ... in order.\n */\nexport function createMigrationSequence(options: {\n sequenceId: string\n retroactive?: boolean | undefined\n sequence: readonly Migration[]\n}): MigrationSequence {\n const { sequenceId, retroactive = true, sequence } = options\n if (!sequenceId || sequenceId.includes(\"/\")) {\n throw new Error(`Invalid sequenceId ${JSON.stringify(sequenceId)}: must be non-empty and not contain \"/\"`)\n }\n sequence.forEach((migration, i) => {\n const id = migration.id\n const parsed = parseMigrationId(id)\n if (parsed.sequenceId !== sequenceId) {\n throw new Error(`Migration ${id} does not belong to sequence ${sequenceId}`)\n }\n if (parsed.version !== i + 1) {\n throw new Error(`Migration ${id} is out of order: expected version ${i + 1}`)\n }\n const scope: string = migration.scope\n if (scope !== \"record\" && scope !== \"store\") {\n throw new Error(`Migration ${id} has invalid scope ${JSON.stringify(scope)}`)\n }\n })\n return { sequenceId, retroactive, sequence: [...sequence] }\n}\n\n/**\n * Convenience for the common case: a sequence of record-scoped migrations\n * that all apply to one record type (optionally narrowed further by `filter`).\n */\nexport function createRecordMigrationSequence(options: {\n sequenceId: string\n recordType: string\n retroactive?: boolean | undefined\n filter?: ((record: UnknownRecord) => boolean) | undefined\n sequence: readonly Omit<RecordMigration, \"scope\" | \"filter\">[]\n}): MigrationSequence {\n const { recordType, filter } = options\n const combinedFilter = (record: UnknownRecord) =>\n record.typeName === recordType && (filter ? filter(record) : true)\n return createMigrationSequence({\n sequenceId: options.sequenceId,\n retroactive: options.retroactive,\n sequence: options.sequence.map(\n (m): RecordMigration => ({ id: m.id, scope: \"record\", filter: combinedFilter, up: m.up, down: m.down }),\n ),\n })\n}\n\n/** Apply one record migration to a single record, honoring its filter. */\nexport function applyRecordMigration(\n migration: RecordMigration,\n record: UnknownRecord,\n direction: \"up\" | \"down\",\n): UnknownRecord {\n if (migration.filter && !migration.filter(record)) return record\n const fn = direction === \"up\" ? migration.up : migration.down\n if (!fn) throw new Error(`Migration ${migration.id} has no ${direction} function`)\n const result = fn(record)\n return result === undefined ? record : result\n}\n\n/** Apply one migration (record- or store-scoped) to a whole store in place. */\nexport function applyMigrationToStore(\n migration: Migration,\n store: SerializedStore<UnknownRecord>,\n direction: \"up\" | \"down\",\n): SerializedStore<UnknownRecord> {\n if (migration.scope === \"store\") {\n const fn = direction === \"up\" ? migration.up : migration.down\n if (!fn) throw new Error(`Migration ${migration.id} has no ${direction} function`)\n const result = fn(store)\n return result === undefined ? store : result\n }\n for (const id in store) {\n const record = store[id as IdOf<UnknownRecord>]!\n const next = applyRecordMigration(migration, record, direction)\n if (next !== record) store[id as IdOf<UnknownRecord>] = next\n }\n return store\n}\n","/**\n * The pre-sequence migration format, and the reasons a migration can fail.\n *\n * Before migrations were named sequences, a schema declared one integer version\n * per record type plus one for the store, and a table of numbered up/down\n * functions between them. mocanvas never *writes* that format — {@link\n * SerializedSchemaV1} exists so a document saved by something that did can\n * still be recognised and loaded, and so a schema written against the old shape\n * can still be described.\n *\n * Nothing here changes what mocanvas persists. See `StoreSchema.serialize`,\n * which always produces the v2 shape.\n */\n\nimport type { UnknownRecord } from \"./ids\"\n\n/**\n * The persisted schema shape used before migration sequences: a version number\n * per record type, and one for the store as a whole.\n *\n * Read-only as far as mocanvas is concerned. A snapshot carrying one is treated\n * as knowing none of today's sequences, so every retroactive sequence runs from\n * the beginning — which is right, because none of them existed when the file\n * was written.\n */\nexport interface SerializedSchemaV1 {\n schemaVersion: 1\n storeVersion: number\n recordVersions: Record<\n string,\n { version: number } | { version: number; subTypeVersions: Record<string, number>; subTypeKey: string }\n >\n}\n\n/** Whether a persisted schema is in the pre-sequence format. */\nexport function isSerializedSchemaV1(schema: { schemaVersion: number }): schema is SerializedSchemaV1 {\n return schema.schemaVersion === 1\n}\n\n/** One numbered step of a {@link LegacyMigrations} table. */\nexport interface LegacyMigration<Before = any, After = any> {\n up: (oldState: Before) => After\n down: (newState: After) => Before\n}\n\n/** The version bounds every legacy migration table declares. */\nexport interface LegacyBaseMigrationsInfo {\n firstVersion: number\n currentVersion: number\n migrators: { [version: number]: LegacyMigration }\n}\n\n/**\n * A legacy migration table: the version range it covers, the numbered steps,\n * and optionally the sub-type split a record type used (a shape's `type`, say,\n * each with its own version line).\n */\nexport interface LegacyMigrations extends LegacyBaseMigrationsInfo {\n subTypeKey?: string\n subTypeMigrations?: Record<string, LegacyBaseMigrationsInfo>\n}\n\n/**\n * A dependency declared by a standalone migration sequence: it must run after\n * (or before) another sequence's numbered migration, even though neither owns\n * the other.\n *\n * Ordering between sequences is otherwise registration order, which is fine\n * until one sequence's `up` reads a field another sequence is still about to\n * add.\n */\nexport interface StandaloneDependsOn {\n dependsOn: readonly string[]\n}\n\n/**\n * Why loading a persisted snapshot failed.\n *\n * These are the cases worth telling apart in a UI: \"this file is from a newer\n * version of the app\" is a message a user can act on, and\n * \"migrationError\" is not.\n */\nexport const MigrationFailureReason = {\n /** The persisted schema names a sequence version higher than this schema knows. */\n TargetVersionTooNew: \"target-version-too-new\",\n /** The persisted data is older than the oldest migration that survives. */\n TargetVersionTooOld: \"target-version-too-old\",\n /** A record's type is not registered in this schema and cannot be migrated. */\n UnrecognizedType: \"unrecognized-type\",\n /** A migration function threw. */\n MigrationError: \"migration-error\",\n /** The persisted schema itself is malformed. */\n IncompatibleSubtype: \"incompatible-subtype\",\n /** The persisted schema version is not one this store understands. */\n UnknownSchemaVersion: \"unknown-schema-version\",\n} as const\n\n/** One of the {@link MigrationFailureReason} values. */\nexport type MigrationFailureReason = (typeof MigrationFailureReason)[keyof typeof MigrationFailureReason]\n","import { isRecordLike, type IdOf, type RecordScope, type RecordType, type UnknownRecord } from \"./ids\"\nimport {\n applyMigrationToStore,\n applyRecordMigration,\n type Migration,\n type MigrationResult,\n type MigrationSequence,\n type SerializedSchema,\n type SerializedSchemaV2,\n type SerializedStore,\n} from \"./migrate\"\nimport { isSerializedSchemaV1 } from \"./legacy\"\nimport type { Store } from \"./Store\"\n\nexport type StoreValidationPhase = \"initialize\" | \"createRecord\" | \"updateRecord\" | \"tests\"\n\nexport type RecordTypeMap<R extends UnknownRecord> = {\n readonly [TypeName in R[\"typeName\"]]: RecordType<Extract<R, { typeName: TypeName }>, any>\n}\n\nexport interface StoreValidationFailure<R extends UnknownRecord> {\n error: unknown\n store: Store<R, any>\n record: R\n phase: StoreValidationPhase\n recordBefore: R | null\n}\n\nexport interface StoreSchemaOptions<R extends UnknownRecord, Props> {\n readonly migrations?: readonly MigrationSequence[] | undefined\n /**\n * Called when a record fails validation. Return a repaired record to keep\n * going, or throw to abort the operation. When omitted the error is thrown.\n */\n readonly onValidationFailure?: ((data: StoreValidationFailure<R>) => R) | undefined\n /** Reserved for store-level integrity checks; unused by the schema itself. */\n readonly createIntegrityChecker?: ((store: Store<R, Props>) => void) | undefined\n}\n\nexport interface StoreSnapshot<R extends UnknownRecord> {\n store: SerializedStore<R>\n schema: SerializedSchema\n}\n\n/**\n * The set of record types a store holds plus the migrations that bring\n * persisted data up to date.\n */\nexport class StoreSchema<R extends UnknownRecord, Props = unknown> {\n static create<R extends UnknownRecord, Props = unknown>(\n types: RecordTypeMap<R>,\n options?: StoreSchemaOptions<R, Props>,\n ): StoreSchema<R, Props> {\n return new StoreSchema<R, Props>(types, options ?? {})\n }\n\n readonly migrations: Readonly<Record<string, MigrationSequence>>\n /** All migrations in application order (sequence registration order, then version). */\n readonly sortedMigrations: readonly Migration[]\n private readonly typeByName: ReadonlyMap<string, RecordType<R, any>>\n\n private constructor(\n readonly types: RecordTypeMap<R>,\n private readonly options: StoreSchemaOptions<R, Props>,\n ) {\n const byName = new Map<string, RecordType<R, any>>()\n for (const [name, type] of Object.entries(types) as [string, RecordType<R, any>][]) {\n if (type.typeName !== name) {\n throw new Error(`Record type registered under \"${name}\" has typeName \"${type.typeName}\"`)\n }\n byName.set(name, type)\n }\n this.typeByName = byName\n\n const migrations: Record<string, MigrationSequence> = {}\n const sorted: Migration[] = []\n const seenIds = new Set<string>()\n for (const sequence of options.migrations ?? []) {\n if (migrations[sequence.sequenceId]) {\n throw new Error(`Duplicate migration sequence \"${sequence.sequenceId}\"`)\n }\n migrations[sequence.sequenceId] = sequence\n for (const migration of sequence.sequence) {\n if (seenIds.has(migration.id)) throw new Error(`Duplicate migration id \"${migration.id}\"`)\n seenIds.add(migration.id)\n sorted.push(migration)\n }\n }\n this.migrations = migrations\n this.sortedMigrations = sorted\n }\n\n getType(typeName: string): RecordType<R, any> | undefined {\n return this.typeByName.get(typeName)\n }\n\n /** Scope of a record type; unknown types are treated as `document`. */\n getScope(typeName: string): RecordScope {\n return this.typeByName.get(typeName)?.scope ?? \"document\"\n }\n\n /**\n * Validate a record, delegating to its record type's validator.\n *\n * Two things are checked before the delegation. First, the value has to be a\n * record at all: an object with a string `id` and a string `typeName`.\n * Without that check a value carrying no `typeName` looks up `undefined` in\n * the type map, misses, and takes the unknown-type path below — which is how\n * `store.put([{ id: \"shape:bogus\", x: 0, y: 0 }])` used to be accepted.\n *\n * Second, a record whose `typeName` this schema does not know is passed\n * through untouched, so foreign data survives a load/save round-trip. That\n * is the escape hatch; it is not meant to cover malformed input, hence the\n * first check.\n */\n validateRecord(\n store: Store<R, any>,\n record: R,\n phase: StoreValidationPhase,\n recordBefore: R | undefined,\n ): R {\n if (!isRecordLike(record)) {\n return this.onFailure(\n new Error(\n `Expected a record with a string \\`id\\` and \\`typeName\\`, got ${describeRecord(record)}`,\n ),\n store,\n record,\n phase,\n recordBefore,\n )\n }\n const type = this.typeByName.get(record.typeName)\n if (!type) return record\n try {\n return type.validate(record, recordBefore)\n } catch (error) {\n return this.onFailure(error, store, record, phase, recordBefore)\n }\n }\n\n private onFailure(\n error: unknown,\n store: Store<R, any>,\n record: R,\n phase: StoreValidationPhase,\n recordBefore: R | undefined,\n ): R {\n if (this.options.onValidationFailure) {\n return this.options.onValidationFailure({\n error,\n store,\n record,\n phase,\n recordBefore: recordBefore ?? null,\n })\n }\n throw error\n }\n\n /** The current version of every sequence. Always the v2 shape — mocanvas never writes v1. */\n serialize(): SerializedSchemaV2 {\n const sequences: Record<string, number> = {}\n for (const sequence of Object.values(this.migrations)) {\n sequences[sequence.sequenceId] = sequence.sequence.length\n }\n return { schemaVersion: 2, sequences }\n }\n\n /** A schema at version 0 of every sequence (all migrations still pending). */\n serializeEarliestVersion(): SerializedSchemaV2 {\n const sequences: Record<string, number> = {}\n for (const sequence of Object.values(this.migrations)) sequences[sequence.sequenceId] = 0\n return { schemaVersion: 2, sequences }\n }\n\n /**\n * The migrations that must run to bring data saved under `persistedSchema`\n * up to this schema, in order. Sequences the persisted schema knows but we\n * do not are ignored with a warning.\n */\n getMigrationsSince(persistedSchema: SerializedSchema): MigrationResult<Migration[]> {\n // A pre-sequence schema records one version number per record type and\n // says nothing about which of today's sequences have run. There is no\n // sound mapping from that to sequence versions, and guessing would\n // re-apply migrations that had already been applied — so this is refused\n // rather than migrated. `SerializedSchemaV1` exists so such a file can be\n // *recognised* and reported, not silently corrupted.\n if (isSerializedSchemaV1(persistedSchema)) {\n return {\n type: \"error\",\n reason:\n \"Schema version 1 (per-record-type versions) predates migration sequences and cannot be migrated automatically\",\n }\n }\n if (persistedSchema.schemaVersion !== 2) {\n return {\n type: \"error\",\n reason: `Unsupported schema version ${String((persistedSchema as { schemaVersion: unknown }).schemaVersion)}`,\n }\n }\n return this.migrationsSince(persistedSchema.sequences ?? {})\n }\n\n private migrationsSince(persisted: { [sequenceId: string]: number }): MigrationResult<Migration[]> {\n for (const sequenceId of Object.keys(persisted)) {\n if (!this.migrations[sequenceId]) {\n console.warn(`[store] ignoring unknown migration sequence \"${sequenceId}\" in persisted schema`)\n }\n }\n\n const result: Migration[] = []\n for (const sequence of Object.values(this.migrations)) {\n const persistedVersion = persisted[sequence.sequenceId]\n let startAt: number\n if (persistedVersion === undefined) {\n if (!sequence.retroactive) continue\n startAt = 0\n } else {\n if (!Number.isInteger(persistedVersion) || persistedVersion < 0) {\n return { type: \"error\", reason: `Invalid version ${String(persistedVersion)} for sequence \"${sequence.sequenceId}\"` }\n }\n if (persistedVersion > sequence.sequence.length) {\n return {\n type: \"error\",\n reason: `Sequence \"${sequence.sequenceId}\" is at version ${persistedVersion} but this schema only knows ${sequence.sequence.length}: data comes from a newer version`,\n }\n }\n startAt = persistedVersion\n }\n for (let i = startAt; i < sequence.sequence.length; i++) result.push(sequence.sequence[i]!)\n }\n return { type: \"success\", value: result }\n }\n\n /**\n * Migrate a single record. Only record-scoped migrations can be applied;\n * encountering a store-scoped one is an error. `down` runs the migrations\n * in reverse (from this schema to `persistedSchema`).\n */\n migratePersistedRecord(\n record: UnknownRecord,\n persistedSchema: SerializedSchema,\n direction: \"up\" | \"down\" = \"up\",\n ): MigrationResult<UnknownRecord> {\n const migrations = this.getMigrationsSince(persistedSchema)\n if (migrations.type === \"error\") return migrations\n const ordered = direction === \"up\" ? migrations.value : [...migrations.value].reverse()\n let current: UnknownRecord = structuredClone(record)\n try {\n for (const migration of ordered) {\n if (migration.scope !== \"record\") {\n return { type: \"error\", reason: `Migration ${migration.id} is store-scoped and cannot be applied to a single record` }\n }\n if (direction === \"down\" && !migration.down) {\n return { type: \"error\", reason: `Migration ${migration.id} has no down migration` }\n }\n current = applyRecordMigration(migration, current, direction)\n }\n } catch (error) {\n return { type: \"error\", reason: `Migration failed: ${error instanceof Error ? error.message : String(error)}` }\n }\n return { type: \"success\", value: current }\n }\n\n /**\n * Bring a whole persisted store up to date. The input is not mutated.\n * Records of types this schema does not know are preserved as-is.\n */\n migrateStoreSnapshot(snapshot: StoreSnapshot<R>): MigrationResult<SerializedStore<R>> {\n const migrations = this.getMigrationsSince(snapshot.schema)\n if (migrations.type === \"error\") return migrations\n\n let store: SerializedStore<UnknownRecord> = structuredClone(snapshot.store)\n if (migrations.value.length === 0) return { type: \"success\", value: store as SerializedStore<R> }\n\n try {\n for (const migration of migrations.value) {\n store = applyMigrationToStore(migration, store, \"up\")\n }\n } catch (error) {\n return { type: \"error\", reason: `Migration failed: ${error instanceof Error ? error.message : String(error)}` }\n }\n\n // Migrations must not change a record's id or lose it.\n for (const id in store) {\n const record = store[id as IdOf<UnknownRecord>]\n if (!record || record.id !== id) {\n return { type: \"error\", reason: `Migration produced a record whose id does not match its key (${id})` }\n }\n }\n return { type: \"success\", value: store as SerializedStore<R> }\n }\n}\n\n/** How a non-record reads back in the failure message. */\nfunction describeRecord(value: unknown): string {\n if (value === null) return \"null\"\n if (typeof value !== \"object\") return typeof value\n if (Array.isArray(value)) return \"an array\"\n const { id, typeName } = value as { id?: unknown; typeName?: unknown }\n const parts: string[] = []\n parts.push(typeof id === \"string\" ? `id ${JSON.stringify(id)}` : `id ${id === undefined ? \"missing\" : typeof id}`)\n parts.push(\n typeof typeName === \"string\"\n ? `typeName ${JSON.stringify(typeName)}`\n : `typeName ${typeName === undefined ? \"missing\" : typeof typeName}`,\n )\n return `an object with ${parts.join(\" and \")}`\n}\n","/**\n * Declarative queries over the store, and the incremental indexes they run on.\n *\n * A query is a plain object — `{ type: { eq: \"geo\" }, parentId: { eq: pageId } }`\n * — rather than a predicate function, and that is the point: an object can be\n * inspected. The store picks one of the query's properties, maintains an index\n * from that property's value to the ids that hold it, and answers the query by\n * intersecting index buckets instead of scanning every record. A predicate can\n * only be run over everything.\n *\n * The index is itself a signal, and it carries diffs: a dependent that already\n * built a result can patch it from {@link RSIndexDiff} rather than rebuilding.\n */\n\nimport type { IdOf, UnknownRecord } from \"./ids\"\n\n/**\n * What changed in a set: the members added and the members removed.\n *\n * Either side may be absent, which means \"nothing on that side\" — a diff with\n * neither is a diff that says nothing happened.\n */\nexport interface CollectionDiff<T> {\n added?: Set<T>\n removed?: Set<T>\n}\n\n/**\n * How one property of a record is matched.\n *\n * SEMANTICS-ASSUMED: three comparisons — equality, inequality and a numeric\n * greater-than — are what an index can answer without scanning, which is the\n * whole reason queries are data rather than functions. `gt` is deliberately\n * numeric: the only ordered property records carry is a number.\n */\nexport type QueryValueMatcher<T> = { eq: T } | { neq: T } | { gt: number }\n\n/**\n * A query over the records of one type: property name to matcher, every entry\n * of which must hold (they are ANDed).\n *\n * ```ts\n * store.query.records(\"shape\", () => ({ type: { eq: \"geo\" }, isLocked: { eq: false } }))\n * ```\n */\nexport type QueryExpression<R extends object> = {\n [K in keyof R]?: QueryValueMatcher<R[K]>\n}\n\n/**\n * An index over one property of one record type: for each value that property\n * takes, the ids of the records that hold it.\n */\nexport type RSIndexMap<R extends UnknownRecord, Property extends keyof R & string = keyof R & string> = Map<\n R[Property],\n Set<IdOf<R>>\n>\n\n/** How an {@link RSIndexMap} changed: per property value, which ids joined and left. */\nexport type RSIndexDiff<R extends UnknownRecord, Property extends keyof R & string = keyof R & string> = Map<\n R[Property],\n CollectionDiff<IdOf<R>>\n>\n\n/**\n * A live index over one property, as a diff-carrying signal.\n *\n * Reading it gives the current {@link RSIndexMap}; asking it for the diffs\n * since a past epoch gives {@link RSIndexDiff}s that describe how to get from\n * the old map to the new one.\n */\nexport type RSIndex<R extends UnknownRecord, Property extends keyof R & string = keyof R & string> = import(\"./_signals\").Computed<\n RSIndexMap<R, Property>,\n RSIndexDiff<R, Property>\n>\n\n/** Whether `value` satisfies `matcher`. */\nexport function matchesQueryValue<T>(matcher: QueryValueMatcher<T>, value: T): boolean {\n if (\"eq\" in matcher) return Object.is(matcher.eq, value)\n if (\"neq\" in matcher) return !Object.is(matcher.neq, value)\n return typeof value === \"number\" && value > matcher.gt\n}\n\n/** Whether `record` satisfies every entry of `query`. An empty query matches everything. */\nexport function matchesQuery<R extends object>(query: QueryExpression<R>, record: R): boolean {\n for (const key of Object.keys(query) as (keyof R)[]) {\n const matcher = query[key]\n if (matcher === undefined) continue\n if (!matchesQueryValue(matcher, record[key])) return false\n }\n return true\n}\n\n/**\n * The property this query can be answered from an index on, or `undefined`\n * when none of it is indexable.\n *\n * Only an `eq` clause narrows to a single index bucket; `neq` and `gt` still\n * need every bucket looked at, so they are no better than a scan. The first\n * `eq` wins — the remaining clauses are checked against the records it yields.\n */\nexport function getIndexablePropertyOf<R extends object>(query: QueryExpression<R>): (keyof R & string) | undefined {\n for (const key of Object.keys(query) as (keyof R & string)[]) {\n const matcher = query[key]\n if (matcher && \"eq\" in matcher) return key\n }\n return undefined\n}\n\n/** Apply a {@link CollectionDiff} to a set, in place. */\nexport function applyCollectionDiff<T>(set: Set<T>, diff: CollectionDiff<T>): Set<T> {\n if (diff.removed) for (const value of diff.removed) set.delete(value)\n if (diff.added) for (const value of diff.added) set.add(value)\n return set\n}\n\n/** Whether a {@link CollectionDiff} describes no change at all. */\nexport function isCollectionDiffEmpty<T>(diff: CollectionDiff<T>): boolean {\n return (diff.added?.size ?? 0) === 0 && (diff.removed?.size ?? 0) === 0\n}\n","import {\n atom,\n computed,\n isUninitialized,\n RESET_VALUE,\n transact,\n unsafe__withoutCapture,\n withDiff,\n type Atom,\n type Computed,\n} from \"./_signals\"\nimport type { IdOf, RecordFromId, RecordScope, RecordType, StoreValidator, UnknownRecord } from \"./ids\"\nimport { parseRecordId, uniqueId } from \"./ids\"\nimport {\n getIndexablePropertyOf,\n matchesQuery,\n type CollectionDiff,\n type QueryExpression,\n type RSIndex,\n type RSIndexDiff,\n type RSIndexMap,\n} from \"./query\"\nimport type { SerializedSchema, SerializedStore } from \"./migrate\"\nimport {\n applyChangeToDiff,\n createEmptyRecordsDiff,\n isRecordsDiffEmpty,\n squashRecordDiffs,\n type RecordsDiff,\n} from \"./RecordsDiff\"\nimport type { StoreSchema, StoreSnapshot, StoreValidationPhase } from \"./StoreSchema\"\n\nexport type ChangeSource = \"user\" | \"remote\"\n\nexport interface HistoryEntry<R extends UnknownRecord> {\n changes: RecordsDiff<R>\n source: ChangeSource\n}\n\nexport type StoreListener<R extends UnknownRecord> = (entry: HistoryEntry<R>) => void\n\nexport interface StoreListenerFilters {\n source: ChangeSource | \"all\"\n scope: RecordScope | \"all\"\n}\n\nexport type RecordFromTypeName<R extends UnknownRecord, T extends string> = Extract<R, { typeName: T }>\n\nexport type StoreRecord<S extends Store<any, any>> = S extends Store<infer R, any> ? R : never\n\n/**\n * Anything that owns a store: a `Store` itself, or an object holding one (an\n * `Editor`). Written for the helpers that want to accept either without their\n * callers having to reach for `.store`.\n */\nexport type StoreObject<R extends UnknownRecord = UnknownRecord> = Store<R, any> | { store: Store<R, any> }\n\n/** The record union of whatever store a {@link StoreObject} carries. */\nexport type StoreObjectRecordType<Context extends StoreObject<any>> = Context extends Store<infer R, any>\n ? R\n : Context extends { store: Store<infer R, any> }\n ? R\n : never\n\n/** A validator per record type, as `StoreSchema` collects them from the record types. */\nexport type StoreValidators<R extends UnknownRecord> = {\n [TypeName in R[\"typeName\"]]: StoreValidator<Extract<R, { typeName: TypeName }>>\n}\n\n/**\n * A record that failed validation, with enough context to say what was being\n * done to it at the time.\n *\n * Thrown rather than returned: a store that keeps going after writing an\n * invalid record is a store whose next save produces a file nothing can load.\n */\nexport interface StoreError {\n error: Error\n phase: \"initialize\" | \"createRecord\" | \"updateRecord\" | \"tests\"\n recordBefore?: unknown\n recordAfter: unknown\n isExistingValidationIssue: boolean\n}\n\nexport interface StoreOptions<R extends UnknownRecord, Props> {\n schema: StoreSchema<R, Props>\n initialData?: SerializedStore<R> | undefined\n props: Props\n id?: string | undefined\n}\n\n/* ------------------------------------------------------------------------ */\n/* side effects */\n/* ------------------------------------------------------------------------ */\n\nexport type StoreBeforeCreateHandler<R extends UnknownRecord> = (record: R, source: ChangeSource) => R\nexport type StoreAfterCreateHandler<R extends UnknownRecord> = (record: R, source: ChangeSource) => void\nexport type StoreBeforeChangeHandler<R extends UnknownRecord> = (prev: R, next: R, source: ChangeSource) => R\nexport type StoreAfterChangeHandler<R extends UnknownRecord> = (prev: R, next: R, source: ChangeSource) => void\n/** Return `false` to veto the deletion. */\nexport type StoreBeforeDeleteHandler<R extends UnknownRecord> = (record: R, source: ChangeSource) => void | false\nexport type StoreAfterDeleteHandler<R extends UnknownRecord> = (record: R, source: ChangeSource) => void\nexport type StoreOperationCompleteHandler = (source: ChangeSource) => void\n\nexport interface StoreSideEffectHandlers<R extends UnknownRecord> {\n beforeCreate?: StoreBeforeCreateHandler<R> | undefined\n afterCreate?: StoreAfterCreateHandler<R> | undefined\n beforeChange?: StoreBeforeChangeHandler<R> | undefined\n afterChange?: StoreAfterChangeHandler<R> | undefined\n beforeDelete?: StoreBeforeDeleteHandler<R> | undefined\n afterDelete?: StoreAfterDeleteHandler<R> | undefined\n}\n\ninterface HandlerSets<R extends UnknownRecord> {\n beforeCreate: Set<StoreBeforeCreateHandler<R>>\n afterCreate: Set<StoreAfterCreateHandler<R>>\n beforeChange: Set<StoreBeforeChangeHandler<R>>\n afterChange: Set<StoreAfterChangeHandler<R>>\n beforeDelete: Set<StoreBeforeDeleteHandler<R>>\n afterDelete: Set<StoreAfterDeleteHandler<R>>\n}\n\n/**\n * Hooks that run around record writes. `before*` handlers may replace the\n * record being written (or veto a delete); `after*` handlers observe.\n * `operationComplete` handlers run once when the outermost operation ends,\n * before history listeners are notified.\n */\nexport class StoreSideEffects<R extends UnknownRecord> {\n private readonly byType = new Map<string, HandlerSets<R>>()\n private readonly operationComplete = new Set<StoreOperationCompleteHandler>()\n private enabled = true\n\n isEnabled(): boolean {\n return this.enabled\n }\n\n setIsEnabled(enabled: boolean): void {\n this.enabled = enabled\n }\n\n private sets(typeName: string): HandlerSets<R> {\n let sets = this.byType.get(typeName)\n if (!sets) {\n sets = {\n beforeCreate: new Set(),\n afterCreate: new Set(),\n beforeChange: new Set(),\n afterChange: new Set(),\n beforeDelete: new Set(),\n afterDelete: new Set(),\n }\n this.byType.set(typeName, sets)\n }\n return sets\n }\n\n private add<K extends keyof HandlerSets<R>>(\n typeName: string,\n kind: K,\n handler: HandlerSets<R>[K] extends Set<infer H> ? H : never,\n ): () => void {\n const set = this.sets(typeName)[kind] as Set<unknown>\n set.add(handler)\n return () => {\n set.delete(handler)\n }\n }\n\n /** Register several handlers for several types at once. Returns a disposer for all of them. */\n register(handlers: {\n [T in R[\"typeName\"]]?: StoreSideEffectHandlers<RecordFromTypeName<R, T>>\n }): () => void {\n const disposers: (() => void)[] = []\n for (const [typeName, h] of Object.entries(handlers) as [string, StoreSideEffectHandlers<any> | undefined][]) {\n if (!h) continue\n if (h.beforeCreate) disposers.push(this.add(typeName, \"beforeCreate\", h.beforeCreate))\n if (h.afterCreate) disposers.push(this.add(typeName, \"afterCreate\", h.afterCreate))\n if (h.beforeChange) disposers.push(this.add(typeName, \"beforeChange\", h.beforeChange))\n if (h.afterChange) disposers.push(this.add(typeName, \"afterChange\", h.afterChange))\n if (h.beforeDelete) disposers.push(this.add(typeName, \"beforeDelete\", h.beforeDelete))\n if (h.afterDelete) disposers.push(this.add(typeName, \"afterDelete\", h.afterDelete))\n }\n return () => disposers.forEach((d) => d())\n }\n\n registerBeforeCreateHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreBeforeCreateHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"beforeCreate\", handler as unknown as StoreBeforeCreateHandler<R>)\n }\n\n registerAfterCreateHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreAfterCreateHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"afterCreate\", handler as unknown as StoreAfterCreateHandler<R>)\n }\n\n registerBeforeChangeHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreBeforeChangeHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"beforeChange\", handler as unknown as StoreBeforeChangeHandler<R>)\n }\n\n registerAfterChangeHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreAfterChangeHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"afterChange\", handler as unknown as StoreAfterChangeHandler<R>)\n }\n\n registerBeforeDeleteHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreBeforeDeleteHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"beforeDelete\", handler as unknown as StoreBeforeDeleteHandler<R>)\n }\n\n registerAfterDeleteHandler<T extends R[\"typeName\"]>(\n typeName: T,\n handler: StoreAfterDeleteHandler<RecordFromTypeName<R, T>>,\n ): () => void {\n return this.add(typeName, \"afterDelete\", handler as unknown as StoreAfterDeleteHandler<R>)\n }\n\n registerOperationCompleteHandler(handler: StoreOperationCompleteHandler): () => void {\n this.operationComplete.add(handler)\n return () => {\n this.operationComplete.delete(handler)\n }\n }\n\n /** @internal */\n handleBeforeCreate(record: R, source: ChangeSource): R {\n const sets = this.byType.get(record.typeName)\n if (!sets) return record\n let result = record\n for (const handler of sets.beforeCreate) result = handler(result, source)\n return result\n }\n\n /** @internal */\n handleAfterCreate(record: R, source: ChangeSource): void {\n const sets = this.byType.get(record.typeName)\n if (!sets) return\n for (const handler of sets.afterCreate) handler(record, source)\n }\n\n /** @internal */\n handleBeforeChange(prev: R, next: R, source: ChangeSource): R {\n const sets = this.byType.get(next.typeName)\n if (!sets) return next\n let result = next\n for (const handler of sets.beforeChange) result = handler(prev, result, source)\n return result\n }\n\n /** @internal */\n handleAfterChange(prev: R, next: R, source: ChangeSource): void {\n const sets = this.byType.get(next.typeName)\n if (!sets) return\n for (const handler of sets.afterChange) handler(prev, next, source)\n }\n\n /** @internal Returns false when a handler vetoed the delete. */\n handleBeforeDelete(record: R, source: ChangeSource): boolean {\n const sets = this.byType.get(record.typeName)\n if (!sets) return true\n for (const handler of sets.beforeDelete) {\n if (handler(record, source) === false) return false\n }\n return true\n }\n\n /** @internal */\n handleAfterDelete(record: R, source: ChangeSource): void {\n const sets = this.byType.get(record.typeName)\n if (!sets) return\n for (const handler of sets.afterDelete) handler(record, source)\n }\n\n /** @internal */\n handleOperationComplete(source: ChangeSource): void {\n for (const handler of this.operationComplete) handler(source)\n }\n}\n\n/* ------------------------------------------------------------------------ */\n/* helpers */\n/* ------------------------------------------------------------------------ */\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\nfunction shallowEqualObjects(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n if (a === b) return true\n const aKeys = Object.keys(a)\n const bKeys = Object.keys(b)\n if (aKeys.length !== bKeys.length) return false\n for (const key of aKeys) {\n if (!(key in b) || a[key] !== b[key]) return false\n }\n return true\n}\n\n/**\n * Records are considered unchanged when every top-level value is identical,\n * with `props` and `meta` compared one level deeper. Cheap enough to run on\n * every `put`, and avoids no-op history entries.\n */\nexport function isRecordShallowEqual(a: UnknownRecord, b: UnknownRecord): boolean {\n if (a === b) return true\n const ao = a as unknown as Record<string, unknown>\n const bo = b as unknown as Record<string, unknown>\n const aKeys = Object.keys(ao)\n const bKeys = Object.keys(bo)\n if (aKeys.length !== bKeys.length) return false\n for (const key of aKeys) {\n if (!(key in bo)) return false\n const av = ao[key]\n const bv = bo[key]\n if (av === bv) continue\n if ((key === \"props\" || key === \"meta\") && isPlainObject(av) && isPlainObject(bv)) {\n if (!shallowEqualObjects(av, bv)) return false\n continue\n }\n return false\n }\n return true\n}\n\n/** Freeze a record and its `props` / `meta` bags (one level). */\nexport function freezeRecord<R extends UnknownRecord>(record: R): R {\n const r = record as unknown as Record<string, unknown>\n if (isPlainObject(r[\"props\"]) && !Object.isFrozen(r[\"props\"])) Object.freeze(r[\"props\"])\n if (isPlainObject(r[\"meta\"]) && !Object.isFrozen(r[\"meta\"])) Object.freeze(r[\"meta\"])\n return Object.freeze(record)\n}\n\ninterface TypeIndex<R extends UnknownRecord> {\n /** Mutated in place on every add/remove: O(1) per record. */\n readonly live: Set<IdOf<R>>\n /** Bumped whenever `live` changes; the reactive handle on membership. */\n readonly epoch: Atom<number>\n}\n\ninterface Listener<R extends UnknownRecord> {\n onHistory: StoreListener<R>\n filters: StoreListenerFilters\n}\n\n/* ------------------------------------------------------------------------ */\n/* queries */\n/* ------------------------------------------------------------------------ */\n\n/** Reactive views over the store's records, cached per type name. */\n/**\n * How the records of one type are narrowed: a predicate, or a declarative\n * {@link QueryExpression} the store can answer from an index.\n *\n * Prefer the query object. A predicate has to be run against every record of\n * the type; a query with an `eq` clause is answered from an index bucket.\n */\nexport type StoreQueryFilter<Rec extends UnknownRecord> =\n | ((record: Rec) => boolean)\n | QueryExpression<Rec>\n\nfunction toPredicate<Rec extends UnknownRecord>(filter: StoreQueryFilter<Rec>): (record: Rec) => boolean {\n return typeof filter === \"function\" ? filter : (record) => matchesQuery(filter, record)\n}\n\nexport class StoreQueries<R extends UnknownRecord> {\n private readonly idsCache = new Map<string, Computed<ReadonlySet<IdOf<R>>>>()\n private readonly recordsCache = new Map<string, Computed<R[]>>()\n private readonly indexCache = new Map<string, RSIndex<any, any>>()\n private readonly historyCache = new Map<string, Computed<number, RecordsDiff<R>>>()\n\n constructor(private readonly store: Store<R, any>) {}\n\n /**\n * The set of ids of every record of `typeName`, optionally narrowed by a\n * filter. Maintained incrementally.\n */\n ids<T extends R[\"typeName\"]>(\n typeName: T,\n filter?: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): Computed<ReadonlySet<IdOf<RecordFromTypeName<R, T>>>> {\n if (filter) {\n const records = this.records(typeName, filter)\n return computed(`store:${this.store.id}:ids:${typeName}:filtered`, () => {\n const set = new Set<IdOf<RecordFromTypeName<R, T>>>()\n for (const record of records.get()) set.add(record.id as IdOf<RecordFromTypeName<R, T>>)\n return set as ReadonlySet<IdOf<RecordFromTypeName<R, T>>>\n })\n }\n let c = this.idsCache.get(typeName)\n if (!c) {\n const index = this.store.getTypeIndex(typeName)\n c = computed(`store:${this.store.id}:ids:${typeName}`, () => {\n index.epoch.get()\n return new Set(index.live) as ReadonlySet<IdOf<R>>\n })\n this.idsCache.set(typeName, c)\n }\n return c as unknown as Computed<ReadonlySet<IdOf<RecordFromTypeName<R, T>>>>\n }\n\n /**\n * Every record of `typeName`, in insertion order, optionally narrowed by a\n * filter.\n *\n * A {@link QueryExpression} with an `eq` clause is answered from the index on\n * that property, so a page with ten thousand shapes does not have to be\n * walked to find the twelve on one frame.\n */\n records<T extends R[\"typeName\"]>(\n typeName: T,\n filter?: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): Computed<RecordFromTypeName<R, T>[]> {\n if (filter) return this.filteredRecords(typeName, filter)\n let c = this.recordsCache.get(typeName)\n if (!c) {\n const ids = this.ids(typeName)\n c = computed(`store:${this.store.id}:records:${typeName}`, () => {\n const result: R[] = []\n for (const id of ids.get()) {\n const record = this.store.get(id as IdOf<R>) as R | undefined\n if (record !== undefined) result.push(record)\n }\n return result\n })\n this.recordsCache.set(typeName, c)\n }\n return c as unknown as Computed<RecordFromTypeName<R, T>[]>\n }\n\n private filteredRecords<T extends R[\"typeName\"]>(\n typeName: T,\n filter: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): Computed<RecordFromTypeName<R, T>[]> {\n type Rec = RecordFromTypeName<R, T>\n const predicate = toPredicate<Rec>(filter)\n const indexedProperty = typeof filter === \"function\" ? undefined : getIndexablePropertyOf(filter)\n\n if (indexedProperty !== undefined) {\n const clause = (filter as QueryExpression<Rec>)[indexedProperty as keyof Rec]\n const wanted = clause && \"eq\" in clause ? clause.eq : undefined\n const index = this.index(typeName, indexedProperty as keyof Rec & string)\n return computed(`store:${this.store.id}:records:${typeName}:${String(indexedProperty)}`, () => {\n const bucket = index.get().get(wanted as Rec[keyof Rec & string])\n if (!bucket) return []\n const result: Rec[] = []\n for (const id of bucket) {\n const record = this.store.get(id as IdOf<R>) as Rec | undefined\n if (record !== undefined && predicate(record)) result.push(record)\n }\n return result\n })\n }\n\n const all = this.records(typeName)\n return computed(`store:${this.store.id}:records:${typeName}:filtered`, () => all.get().filter(predicate))\n }\n\n /** The first record of `typeName` matching `filter` (or the first record, when omitted). */\n record<T extends R[\"typeName\"]>(\n typeName: T,\n filter?: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): Computed<RecordFromTypeName<R, T> | undefined> {\n const records = filter ? this.filteredRecords(typeName, filter) : this.records(typeName)\n return computed(`store:${this.store.id}:record:${typeName}`, () => records.get()[0])\n }\n\n /** Non-reactive filter over the records of `typeName`. */\n exec<T extends R[\"typeName\"]>(\n typeName: T,\n filter: StoreQueryFilter<RecordFromTypeName<R, T>>,\n ): RecordFromTypeName<R, T>[] {\n return unsafe__withoutCapture(() => this.filteredRecords(typeName, filter).get())\n }\n\n /**\n * A live index from the values of one property to the ids of the records\n * holding them.\n *\n * The index is cached per type and property, and it carries diffs: a\n * dependent that already built something from it can ask\n * `index.getDiffSince(epoch)` and patch, instead of walking the whole map\n * again. That is what makes \"every shape whose parentId is this frame\" cheap\n * enough to recompute on every pointer move.\n */\n index<T extends R[\"typeName\"], Property extends keyof RecordFromTypeName<R, T> & string>(\n typeName: T,\n property: Property,\n ): RSIndex<RecordFromTypeName<R, T>, Property> {\n type Rec = RecordFromTypeName<R, T>\n const key = `${typeName}:${property}`\n const cached = this.indexCache.get(key)\n if (cached) return cached as RSIndex<Rec, Property>\n\n const history = this.filterHistory(typeName)\n\n const index = computed<RSIndexMap<Rec, Property>, RSIndexDiff<Rec, Property>>(\n `store:${this.store.id}:index:${key}`,\n (previous, lastComputedEpoch) => {\n if (isUninitialized(previous)) {\n history.get()\n return this.buildIndex<T, Property>(typeName, property)\n }\n\n const diffs = history.getDiffSince(lastComputedEpoch)\n if (diffs === RESET_VALUE) return this.buildIndex<T, Property>(typeName, property)\n\n const nextMap: RSIndexMap<Rec, Property> = new Map(previous)\n const indexDiff: RSIndexDiff<Rec, Property> = new Map()\n let changed = false\n\n const remove = (value: Rec[Property], id: IdOf<Rec>) => {\n const bucket = nextMap.get(value)\n if (!bucket?.has(id)) return\n const next = new Set(bucket)\n next.delete(id)\n if (next.size === 0) nextMap.delete(value)\n else nextMap.set(value, next)\n const entry = indexDiff.get(value) ?? {}\n ;(entry.removed ??= new Set()).add(id)\n indexDiff.set(value, entry)\n changed = true\n }\n const add = (value: Rec[Property], id: IdOf<Rec>) => {\n const bucket = nextMap.get(value)\n if (bucket?.has(id)) return\n nextMap.set(value, new Set(bucket).add(id))\n const entry = indexDiff.get(value) ?? {}\n ;(entry.added ??= new Set()).add(id)\n indexDiff.set(value, entry)\n changed = true\n }\n\n for (const diff of diffs) {\n for (const id in diff.added) {\n const record = diff.added[id as IdOf<R>] as Rec | undefined\n if (record?.typeName === typeName) add(record[property], record.id as IdOf<Rec>)\n }\n for (const id in diff.updated) {\n const [before, after] = diff.updated[id as IdOf<R>] as [Rec, Rec]\n if (after.typeName !== typeName) continue\n if (Object.is(before[property], after[property])) continue\n remove(before[property], before.id as IdOf<Rec>)\n add(after[property], after.id as IdOf<Rec>)\n }\n for (const id in diff.removed) {\n const record = diff.removed[id as IdOf<R>] as Rec | undefined\n if (record?.typeName === typeName) remove(record[property], record.id as IdOf<Rec>)\n }\n }\n\n if (!changed) return previous\n return withDiff(nextMap, indexDiff)\n },\n { historyLength: 128 },\n )\n\n this.indexCache.set(key, index as RSIndex<any, any>)\n return index as RSIndex<Rec, Property>\n }\n\n private buildIndex<T extends R[\"typeName\"], Property extends keyof RecordFromTypeName<R, T> & string>(\n typeName: T,\n property: Property,\n ): RSIndexMap<RecordFromTypeName<R, T>, Property> {\n type Rec = RecordFromTypeName<R, T>\n const map: RSIndexMap<Rec, Property> = new Map()\n for (const record of this.records(typeName).get()) {\n const value = record[property]\n const bucket = map.get(value)\n if (bucket) bucket.add(record.id as IdOf<Rec>)\n else map.set(value, new Set([record.id as IdOf<Rec>]))\n }\n return map\n }\n\n /**\n * The store's history, narrowed to one record type.\n *\n * Its *value* is only a counter — what it is for is the diffs it carries.\n * `filterHistory(\"shape\").getDiffSince(epoch)` is every change to shapes\n * since `epoch`, with changes to other record types dropped, which is how a\n * derived collection stays incremental without re-reading the store.\n */\n filterHistory<T extends R[\"typeName\"]>(typeName: T): Computed<number, RecordsDiff<RecordFromTypeName<R, T>>> {\n const cached = this.historyCache.get(typeName)\n if (cached) return cached as unknown as Computed<number, RecordsDiff<RecordFromTypeName<R, T>>>\n\n const filtered = computed<number, RecordsDiff<R>>(\n `store:${this.store.id}:history:${typeName}`,\n (previous, lastComputedEpoch) => {\n const epoch = this.store.history.get()\n if (isUninitialized(previous)) return epoch\n\n const diffs = this.store.history.getDiffSince(lastComputedEpoch)\n if (diffs === RESET_VALUE) return epoch\n\n const merged = createEmptyRecordsDiff<R>()\n let any = false\n for (const diff of diffs) {\n for (const id in diff.added) {\n const record = diff.added[id as IdOf<R>]!\n if (record.typeName !== typeName) continue\n merged.added[id as IdOf<R>] = record\n any = true\n }\n for (const id in diff.updated) {\n const pair = diff.updated[id as IdOf<R>]!\n if (pair[1].typeName !== typeName) continue\n merged.updated[id as IdOf<R>] = pair\n any = true\n }\n for (const id in diff.removed) {\n const record = diff.removed[id as IdOf<R>]!\n if (record.typeName !== typeName) continue\n merged.removed[id as IdOf<R>] = record\n any = true\n }\n }\n // Nothing of this type changed: keep the old value so dependents are\n // not woken at all.\n if (!any) return previous\n return withDiff(epoch, merged)\n },\n { historyLength: 128 },\n )\n\n this.historyCache.set(typeName, filtered)\n return filtered as unknown as Computed<number, RecordsDiff<RecordFromTypeName<R, T>>>\n }\n}\n\n/* ------------------------------------------------------------------------ */\n/* store */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A reactive, transactional collection of records.\n *\n * - one atom per record, so consumers subscribe to exactly what they read\n * - per-type id sets maintained incrementally\n * - writes are batched; listeners receive one squashed diff per outermost operation\n * - records are frozen on write\n */\nexport class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {\n readonly id: string\n readonly schema: StoreSchema<R, Props>\n readonly props: Props\n readonly scopedTypes: { readonly [S in RecordScope]: ReadonlySet<string> }\n readonly sideEffects = new StoreSideEffects<R>()\n readonly query: StoreQueries<R>\n /**\n * Bumped once per completed operation that changed something.\n *\n * The counter itself carries no information; the diffs do. The atom keeps a\n * bounded history of the squashed {@link RecordsDiff} of each operation, so a\n * derived collection can ask `history.getDiffSince(epoch)` and patch itself\n * instead of rebuilding. `store.query.filterHistory(typeName)` is the same\n * thing narrowed to one record type.\n */\n readonly history: Atom<number, RecordsDiff<R>>\n\n private readonly records = new Map<IdOf<R>, Atom<R | undefined>>()\n private readonly typeIndexes = new Map<string, TypeIndex<R>>()\n private readonly listeners = new Set<Listener<R>>()\n private pendingEntries: HistoryEntry<R>[] = []\n private readonly extractStack: RecordsDiff<R>[] = []\n private depth = 0\n private source: ChangeSource = \"user\"\n private runCallbacks = true\n private inOperationComplete = false\n private disposed = false\n /**\n * The diff of the operation currently being committed, handed to the history\n * atom's `computeDiff` as it is written. The atom only sees two counter\n * values, so the diff has to be staged here for the one write that follows.\n */\n private pendingHistoryDiff: RecordsDiff<R> | null = null\n\n constructor(options: StoreOptions<R, Props>) {\n this.id = options.id ?? uniqueId()\n this.schema = options.schema\n this.props = options.props\n this.history = atom<number, RecordsDiff<R>>(`store:${this.id}:history`, 0, {\n // 128 operations is deep enough that a dependent which rendered a frame\n // ago can still patch, and shallow enough that the buffer costs nothing.\n historyLength: 128,\n computeDiff: () => this.pendingHistoryDiff ?? RESET_VALUE,\n })\n this.query = new StoreQueries(this)\n\n const scoped = { document: new Set<string>(), session: new Set<string>(), presence: new Set<string>() }\n for (const type of Object.values(this.schema.types) as RecordType<R, any>[]) {\n scoped[type.scope].add(type.typeName)\n }\n this.scopedTypes = scoped\n\n if (options.initialData) {\n const records = Object.values(options.initialData) as R[]\n this.atomic(() => this.put(records, \"initialize\"), { runCallbacks: false })\n }\n }\n\n /* ---- reading ---------------------------------------------------------- */\n\n /** @internal */\n getTypeIndex(typeName: string): TypeIndex<R> {\n let index = this.typeIndexes.get(typeName)\n if (!index) {\n index = { live: new Set(), epoch: atom(`store:${this.id}:index:${typeName}`, 0) }\n this.typeIndexes.set(typeName, index)\n }\n return index\n }\n\n /** Get a record (reactive: subscribes to the record, or to its type's membership when absent). */\n get<K extends IdOf<R>>(id: K): RecordFromId<K> | undefined {\n const a = this.records.get(id)\n if (a) return a.get() as RecordFromId<K> | undefined\n // Not present: depend on membership of this id's type so creation is observed.\n this.getTypeIndex(typeNameOfId(id)).epoch.get()\n return undefined\n }\n\n /** Get a record without registering a reactive dependency. */\n unsafeGetWithoutCapture<K extends IdOf<R>>(id: K): RecordFromId<K> | undefined {\n const a = this.records.get(id)\n return a ? (unsafe__withoutCapture(() => a.get()) as RecordFromId<K> | undefined) : undefined\n }\n\n has<K extends IdOf<R>>(id: K): boolean {\n return this.get(id) !== undefined\n }\n\n /** All records (reactive over every record and every type's membership). */\n allRecords(): R[] {\n for (const index of this.typeIndexes.values()) index.epoch.get()\n const result: R[] = []\n for (const a of this.records.values()) {\n const record = a.get()\n if (record !== undefined) result.push(record)\n }\n return result\n }\n\n /** Scope of a record type; unknown types are `document`. */\n getScope(typeName: string): RecordScope {\n return this.schema.getScope(typeName)\n }\n\n /* ---- writing ---------------------------------------------------------- */\n\n /**\n * Insert or update records. Records are validated, passed through `before*`\n * side effects, frozen, and written. `after*` side effects run once every\n * record in the call has been written.\n */\n put(records: readonly R[], phaseOverride?: StoreValidationPhase): void {\n this.atomic(() => {\n const source = this.source\n const callbacks = this.runCallbacks && this.sideEffects.isEnabled()\n const created: R[] = []\n const changed: [R, R][] = []\n\n for (const record of records) {\n const id = record.id\n const existing = this.records.get(id)\n const before = existing?.get()\n\n if (before !== undefined) {\n if (before === record) continue\n let next = this.schema.validateRecord(this, record, phaseOverride ?? \"updateRecord\", before)\n if (callbacks) next = this.sideEffects.handleBeforeChange(before, next, source)\n if (next === before || isRecordShallowEqual(before, next)) continue\n if (next.id !== id) {\n throw new Error(`Cannot change the id of a record (${id} -> ${next.id})`)\n }\n freezeRecord(next)\n if (before.typeName !== next.typeName) {\n this.removeFromIndex(before.typeName, id)\n this.addToIndex(next.typeName, id)\n }\n existing!.set(next)\n this.recordChange(id, before, next)\n changed.push([before, next])\n } else {\n let next = this.schema.validateRecord(this, record, phaseOverride ?? \"createRecord\", undefined)\n if (callbacks) next = this.sideEffects.handleBeforeCreate(next, source)\n if (next.id !== id) {\n throw new Error(`Cannot change the id of a record (${id} -> ${next.id})`)\n }\n freezeRecord(next)\n const a = existing ?? atom<R | undefined>(`store:${this.id}:record:${id}`, undefined)\n a.set(next)\n this.records.set(id, a)\n this.addToIndex(next.typeName, id)\n this.recordChange(id, undefined, next)\n created.push(next)\n }\n }\n\n if (callbacks) {\n for (const record of created) this.sideEffects.handleAfterCreate(record, source)\n for (const [prev, next] of changed) this.sideEffects.handleAfterChange(prev, next, source)\n }\n })\n }\n\n /** Remove records by id. Missing ids are ignored. `beforeDelete` handlers may veto. */\n remove(ids: readonly IdOf<R>[]): void {\n this.atomic(() => {\n const source = this.source\n const callbacks = this.runCallbacks && this.sideEffects.isEnabled()\n const toRemove: R[] = []\n\n for (const id of ids) {\n const a = this.records.get(id)\n if (!a) continue\n const record = a.get()\n if (record === undefined) continue\n if (callbacks && !this.sideEffects.handleBeforeDelete(record, source)) continue\n toRemove.push(record)\n }\n\n const removed: R[] = []\n for (const record of toRemove) {\n const a = this.records.get(record.id)\n if (!a) continue // a handler already removed it\n const current = a.get()\n if (current === undefined) continue\n a.set(undefined)\n this.records.delete(record.id)\n this.removeFromIndex(current.typeName, record.id)\n this.recordChange(record.id, current, undefined)\n removed.push(current)\n }\n\n if (callbacks) {\n for (const record of removed) this.sideEffects.handleAfterDelete(record, source)\n }\n })\n }\n\n /** Remove every record. */\n clear(): void {\n this.remove(Array.from(this.records.keys()))\n }\n\n /**\n * Update one record with a function. No-op when the record does not exist.\n */\n update<K extends IdOf<R>>(id: K, updater: (record: RecordFromId<K>) => RecordFromId<K>): void {\n const current = this.unsafeGetWithoutCapture(id)\n if (current === undefined) return\n this.put([updater(current) as unknown as R])\n }\n\n /* ---- transactions ----------------------------------------------------- */\n\n /**\n * Run `fn` as one operation: side effects' `operationComplete` handlers run\n * once at the end, and listeners get a single squashed history entry.\n */\n atomic<T>(fn: () => T, options?: { source?: ChangeSource | undefined; runCallbacks?: boolean | undefined }): T {\n const prevSource = this.source\n const prevRunCallbacks = this.runCallbacks\n if (options?.source !== undefined) this.source = options.source\n if (options?.runCallbacks !== undefined) this.runCallbacks = options.runCallbacks\n const source = this.source\n const runCallbacks = this.runCallbacks\n this.depth++\n try {\n return transact(() => unsafe__withoutCapture(fn))\n } finally {\n this.depth--\n if (this.depth === 0) {\n try {\n this.completeOperation(source, runCallbacks)\n } finally {\n this.source = prevSource\n this.runCallbacks = prevRunCallbacks\n }\n } else {\n this.source = prevSource\n this.runCallbacks = prevRunCallbacks\n }\n }\n }\n\n /** Changes made inside `fn` are reported to listeners with source `remote`. */\n mergeRemoteChanges(fn: () => void): void {\n this.atomic(fn, { source: \"remote\" })\n }\n\n /** Run `fn` and return the squashed diff of everything it changed. Listeners are still notified. */\n extractingChanges(fn: () => void): RecordsDiff<R> {\n const diff = createEmptyRecordsDiff<R>()\n this.extractStack.push(diff)\n try {\n this.atomic(fn)\n } finally {\n this.extractStack.pop()\n }\n return diff\n }\n\n /**\n * Apply a diff (e.g. from `extractingChanges` or `reverseRecordsDiff`).\n * With `ignoreEphemeralKeys`, ephemeral keys of updated records keep their\n * current store values instead of the diff's.\n */\n applyDiff(\n diff: RecordsDiff<R>,\n options?: { runCallbacks?: boolean | undefined; ignoreEphemeralKeys?: boolean | undefined },\n ): void {\n const runCallbacks = options?.runCallbacks ?? true\n const ignoreEphemeralKeys = options?.ignoreEphemeralKeys ?? false\n this.atomic(\n () => {\n const toPut: R[] = []\n for (const id in diff.added) toPut.push(diff.added[id as IdOf<R>]!)\n for (const id in diff.updated) {\n let [, to] = diff.updated[id as IdOf<R>]!\n if (ignoreEphemeralKeys) {\n const current = this.unsafeGetWithoutCapture(id as IdOf<R>)\n const type = this.schema.getType(to.typeName)\n if (current !== undefined && type && type.ephemeralKeySet.size > 0) {\n const merged: Record<string, unknown> = { ...(to as unknown as Record<string, unknown>) }\n const cur = current as unknown as Record<string, unknown>\n for (const key of type.ephemeralKeySet) {\n if (key in cur) merged[key] = cur[key]\n else delete merged[key]\n }\n to = merged as unknown as R\n }\n }\n toPut.push(to)\n }\n this.put(toPut)\n const toRemove = Object.keys(diff.removed) as IdOf<R>[]\n if (toRemove.length > 0) this.remove(toRemove)\n },\n { runCallbacks },\n )\n }\n\n /* ---- listening -------------------------------------------------------- */\n\n /**\n * Subscribe to history entries. Called after each outermost operation with\n * the squashed changes, filtered by source and record scope.\n */\n listen(onHistory: StoreListener<R>, filters?: Partial<StoreListenerFilters>): () => void {\n const listener: Listener<R> = {\n onHistory,\n filters: { source: filters?.source ?? \"all\", scope: filters?.scope ?? \"all\" },\n }\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n /* ---- persistence ------------------------------------------------------ */\n\n /** Plain-object snapshot of the records in `scope` (default `document`). */\n serialize(scope: RecordScope | \"all\" = \"document\"): SerializedStore<R> {\n const result = {} as SerializedStore<R>\n unsafe__withoutCapture(() => {\n for (const [id, a] of this.records) {\n const record = a.get()\n if (record === undefined) continue\n if (scope === \"all\" || this.getScope(record.typeName) === scope) result[id] = record\n }\n })\n return result\n }\n\n getStoreSnapshot(scope: RecordScope | \"all\" = \"document\"): StoreSnapshot<R> {\n return { store: this.serialize(scope), schema: this.schema.serialize() }\n }\n\n /**\n * Bring a snapshot saved by an older document up to this store's schema,\n * without loading it.\n *\n * Every migration sequence the schema knows is run — including the ones\n * `createStore` derives from the shape and binding utils, so a board saved\n * before a prop existed is backfilled here rather than failing validation on\n * load. The input is not mutated: the result is a new snapshot carrying this\n * schema's serialized version, ready for {@link Store.loadStoreSnapshot} (or\n * for a caller that wants to inspect the migrated records first).\n *\n * A snapshot that cannot be migrated — an unknown schema version, a sequence\n * from a NEWER build than this one, a migration that throws — raises rather\n * than returning half-migrated data, so a caller can fail closed on it.\n */\n migrateSnapshot(snapshot: StoreSnapshot<R>): StoreSnapshot<R> {\n const migrated = this.schema.migrateStoreSnapshot(snapshot)\n if (migrated.type === \"error\") {\n throw new Error(`Failed to migrate snapshot: ${migrated.reason}`)\n }\n return { store: migrated.value, schema: this.schema.serialize() }\n }\n\n /**\n * Replace the store's contents with a snapshot (migrating it first).\n * Existing records in `document` scope and in every scope present in the\n * snapshot are removed unless the snapshot contains them; other scopes are\n * left alone. Side effects do not run; listeners are notified.\n */\n loadStoreSnapshot(snapshot: StoreSnapshot<R>): void {\n const migrated = this.schema.migrateStoreSnapshot(snapshot)\n if (migrated.type === \"error\") {\n throw new Error(`Failed to migrate snapshot: ${migrated.reason}`)\n }\n const incoming = migrated.value\n const records = Object.values(incoming) as R[]\n this.atomic(\n () => {\n const scopes = new Set<RecordScope>([\"document\"])\n for (const record of records) scopes.add(this.getScope(record.typeName))\n const toRemove: IdOf<R>[] = []\n for (const [id, a] of this.records) {\n const record = a.get()\n if (record === undefined) continue\n if (scopes.has(this.getScope(record.typeName)) && !(id in incoming)) toRemove.push(id)\n }\n this.remove(toRemove)\n this.put(records, \"initialize\")\n },\n { runCallbacks: false },\n )\n }\n\n /* ---- derived caches --------------------------------------------------- */\n\n /**\n * A per-record derived value, recomputed only when that record changes.\n * Entries are dropped automatically when records are removed.\n */\n createComputedCache<T, K extends IdOf<R> = IdOf<R>>(\n name: string,\n derive: (record: RecordFromId<K>) => T,\n options?: { isEqual?: ((a: T, b: T) => boolean) | undefined },\n ): { get(id: K): T | undefined } {\n const cache = new WeakMap<Atom<R | undefined>, Computed<T | undefined>>()\n return {\n get: (id: K) => {\n const a = this.records.get(id)\n if (!a) {\n this.getTypeIndex(typeNameOfId(id)).epoch.get()\n return undefined\n }\n let c = cache.get(a)\n if (!c) {\n c = computed(\n `${name}:${id}`,\n () => {\n const record = a.get()\n return record === undefined ? undefined : derive(record as unknown as RecordFromId<K>)\n },\n options?.isEqual\n ? { isEqual: (x, y) => (x === undefined || y === undefined ? x === y : options.isEqual!(x, y)) }\n : undefined,\n )\n cache.set(a, c)\n }\n return c.get()\n },\n }\n }\n\n /* ---- lifecycle -------------------------------------------------------- */\n\n isDisposed(): boolean {\n return this.disposed\n }\n\n dispose(): void {\n this.disposed = true\n this.listeners.clear()\n }\n\n /* ---- internals -------------------------------------------------------- */\n\n private addToIndex(typeName: string, id: IdOf<R>) {\n const index = this.getTypeIndex(typeName)\n if (index.live.has(id)) return\n index.live.add(id)\n index.epoch.update((n) => n + 1)\n }\n\n private removeFromIndex(typeName: string, id: IdOf<R>) {\n const index = this.typeIndexes.get(typeName)\n if (!index || !index.live.delete(id)) return\n index.epoch.update((n) => n + 1)\n }\n\n private recordChange(id: IdOf<R>, before: R | undefined, after: R | undefined) {\n const last = this.pendingEntries[this.pendingEntries.length - 1]\n let entry: HistoryEntry<R>\n if (last && last.source === this.source) {\n entry = last\n } else {\n entry = { changes: createEmptyRecordsDiff<R>(), source: this.source }\n this.pendingEntries.push(entry)\n }\n applyChangeToDiff(entry.changes, id, before, after)\n for (const diff of this.extractStack) applyChangeToDiff(diff, id, before, after)\n }\n\n private completeOperation(source: ChangeSource, runCallbacks: boolean) {\n if (!this.pendingEntries.some((e) => !isRecordsDiffEmpty(e.changes))) {\n this.pendingEntries = []\n return\n }\n if (runCallbacks && this.sideEffects.isEnabled() && !this.inOperationComplete) {\n this.inOperationComplete = true\n const prevSource = this.source\n this.source = source\n this.depth++\n try {\n transact(() => unsafe__withoutCapture(() => this.sideEffects.handleOperationComplete(source)))\n } finally {\n this.depth--\n this.source = prevSource\n this.inOperationComplete = false\n }\n }\n this.pendingHistoryDiff = this.squashPendingEntries()\n try {\n this.history.update((n) => n + 1)\n } finally {\n this.pendingHistoryDiff = null\n }\n this.flushHistory()\n }\n\n /** One diff describing everything the operation just committed changed. */\n private squashPendingEntries(): RecordsDiff<R> {\n const diffs = this.pendingEntries.map((entry) => entry.changes).filter((diff) => !isRecordsDiffEmpty(diff))\n if (diffs.length === 1) return diffs[0]!\n return squashRecordDiffs(diffs)\n }\n\n private flushHistory() {\n const entries = this.pendingEntries\n this.pendingEntries = []\n if (this.listeners.size === 0) return\n for (const entry of entries) {\n if (isRecordsDiffEmpty(entry.changes)) continue\n for (const listener of Array.from(this.listeners)) {\n if (listener.filters.source !== \"all\" && listener.filters.source !== entry.source) continue\n const changes =\n listener.filters.scope === \"all\" ? entry.changes : this.filterDiffByScope(entry.changes, listener.filters.scope)\n if (isRecordsDiffEmpty(changes)) continue\n listener.onHistory({ changes, source: entry.source })\n }\n }\n }\n\n private filterDiffByScope(diff: RecordsDiff<R>, scope: RecordScope): RecordsDiff<R> {\n const result = createEmptyRecordsDiff<R>()\n for (const id in diff.added) {\n const record = diff.added[id as IdOf<R>]!\n if (this.getScope(record.typeName) === scope) result.added[id as IdOf<R>] = record\n }\n for (const id in diff.updated) {\n const pair = diff.updated[id as IdOf<R>]!\n if (this.getScope(pair[1].typeName) === scope) result.updated[id as IdOf<R>] = pair\n }\n for (const id in diff.removed) {\n const record = diff.removed[id as IdOf<R>]!\n if (this.getScope(record.typeName) === scope) result.removed[id as IdOf<R>] = record\n }\n return result\n }\n}\n\nfunction typeNameOfId(id: string): string {\n const colon = id.indexOf(\":\")\n return colon > 0 ? id.slice(0, colon) : parseRecordId(id).typeName\n}\n","import { isRecordLike, type IdOf, type UnknownRecord } from \"./ids\"\nimport type { SerializedSchema, SerializedStore } from \"./migrate\"\n\n/**\n * `.tldr` file envelope. Schema-agnostic: this module does not know or care\n * what record types the file holds.\n */\nexport const TLDR_FILE_FORMAT_VERSION = 1\n\nexport interface TldrFile {\n tldrawFileFormatVersion: number\n schema: SerializedSchema\n records: UnknownRecord[]\n}\n\nexport type TldrFileParseError = \"notATldrFile\" | \"v1File\" | \"invalidRecords\" | \"futureVersion\"\n\nexport type ParseTldrFileResult =\n | { ok: true; schema: SerializedSchema; records: UnknownRecord[] }\n | { ok: false; error: TldrFileParseError; cause?: unknown }\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nfunction isSerializedSchema(value: unknown): value is SerializedSchema {\n return isPlainObject(value) && typeof value[\"schemaVersion\"] === \"number\"\n}\n\n/**\n * Parse a `.tldr` file. Accepts either the JSON text or the already-parsed\n * value. Never throws.\n */\nexport function parseTldrFile(json: unknown): ParseTldrFileResult {\n let data: unknown = json\n if (typeof json === \"string\") {\n try {\n data = JSON.parse(json)\n } catch (cause) {\n return { ok: false, error: \"notATldrFile\", cause }\n }\n }\n\n if (!isPlainObject(data)) return { ok: false, error: \"notATldrFile\" }\n\n if (!(\"tldrawFileFormatVersion\" in data)) {\n // The legacy (pre-envelope) format stored a whole document object.\n const legacyDocument = data[\"document\"]\n if (isPlainObject(legacyDocument) && (\"pages\" in legacyDocument || \"version\" in legacyDocument)) {\n return { ok: false, error: \"v1File\" }\n }\n return { ok: false, error: \"notATldrFile\" }\n }\n\n const version = data[\"tldrawFileFormatVersion\"]\n if (typeof version !== \"number\" || !Number.isInteger(version) || version < 1) {\n return { ok: false, error: \"notATldrFile\" }\n }\n if (version > TLDR_FILE_FORMAT_VERSION) return { ok: false, error: \"futureVersion\" }\n\n if (!isSerializedSchema(data[\"schema\"])) return { ok: false, error: \"notATldrFile\" }\n\n const records = data[\"records\"]\n if (!Array.isArray(records)) return { ok: false, error: \"invalidRecords\" }\n const seen = new Set<string>()\n for (const record of records) {\n if (!isRecordLike(record)) return { ok: false, error: \"invalidRecords\" }\n if (seen.has(record.id)) return { ok: false, error: \"invalidRecords\" }\n seen.add(record.id)\n }\n\n return { ok: true, schema: data[\"schema\"], records: records as UnknownRecord[] }\n}\n\n/**\n * JSON.stringify with object keys sorted recursively so that identical data\n * always produces identical text. Arrays keep their order.\n */\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeysDeep)\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(value).sort()) {\n const v = value[key]\n if (v !== undefined) out[key] = sortKeysDeep(v)\n }\n return out\n }\n return value\n}\n\n/**\n * Serialize records and their schema into the `.tldr` envelope\n * (pretty-printed, stable key order). Records are written in the given order.\n */\nexport function serializeTldrFile(schema: SerializedSchema, records: readonly UnknownRecord[]): string {\n const envelope = {\n tldrawFileFormatVersion: TLDR_FILE_FORMAT_VERSION,\n schema: sortKeysDeep(schema),\n records: records.map(sortKeysDeep),\n }\n return JSON.stringify(envelope, null, 2)\n}\n\n/** Convert a parsed file into a `{ store, schema }` snapshot. */\nexport function tldrFileToStoreSnapshot(file: { schema: SerializedSchema; records: readonly UnknownRecord[] }): {\n store: SerializedStore<UnknownRecord>\n schema: SerializedSchema\n} {\n const store = {} as SerializedStore<UnknownRecord>\n for (const record of file.records) store[record.id as IdOf<UnknownRecord>] = record\n return { store, schema: file.schema }\n}\n\n/** Convert a `{ store, schema }` snapshot into `.tldr` text. Records are ordered by id. */\nexport function storeSnapshotToTldrFile(snapshot: {\n store: SerializedStore<UnknownRecord>\n schema: SerializedSchema\n}): string {\n const records = Object.values(snapshot.store).sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n return serializeTldrFile(snapshot.schema, records)\n}\n","/**\n * Standalone per-record memos.\n *\n * `Store.createComputedCache` already memoizes a value per record, but it is a\n * method: the cache belongs to one store instance, and the derivation cannot see\n * anything else. A shape util or binding util usually needs the opposite shape —\n * one cache declared once at module scope, derived from a record *and* the editor\n * that owns it, and shared by every store that editor drives.\n *\n * `createComputedCache` is that form. The context is passed in at `get` time and\n * the underlying per-record cache is created lazily, once per context.\n */\nimport type { IdOf, RecordId, UnknownRecord } from \"./ids\"\nimport { Store } from \"./Store\"\n\n/**\n * A context a computed cache can read a store from: a store itself, or anything\n * holding one (an `Editor`).\n */\nexport type ComputedCacheContext = Store<any, any> | { readonly store: Store<any, any> }\n\n/** The handle returned by {@link createComputedCache}. */\nexport interface ComputedCache<Context, R extends UnknownRecord, Result> {\n /** The derived value for `id`, or `undefined` if no such record exists. */\n get(context: Context, id: IdOf<R>): Result | undefined\n}\n\n/** Options for {@link createComputedCache}. */\nexport interface CreateComputedCacheOptions<Result> {\n /**\n * Treat two derived values as the same, so dependents are not woken when the\n * derivation recomputes to an equivalent result.\n */\n isEqual?: ((a: Result, b: Result) => boolean) | undefined\n}\n\nfunction storeOf(context: unknown): Store<any, any> {\n if (context instanceof Store) return context\n const store = (context as { store?: unknown } | null | undefined)?.store\n if (store instanceof Store) return store\n throw new Error(\"createComputedCache: context is neither a Store nor an object holding one\")\n}\n\n/**\n * Declare a per-record memo, keyed by record id, recomputed only when that\n * record changes.\n *\n * ```ts\n * const bindingsCache = createComputedCache(\"connection bindings\", (editor: Editor, shape: TLShape) =>\n * editor.getBindingsFromShape(shape.id, \"connection\"),\n * )\n * bindingsCache.get(editor, shapeId)\n * ```\n *\n * SEMANTICS-ASSUMED: `Context` is unconstrained rather than bound to\n * {@link ComputedCacheContext}. The consumer annotates the derivation's own\n * parameter (`(editor: Editor, shape: TLShape) => …`) and that is what `get`\n * must accept; constraining the type parameter as well would force every caller\n * to prove `Editor` is structurally a store holder at each call site for no\n * added safety. The store is resolved at `get` time instead, and a context that\n * carries none throws immediately rather than silently returning `undefined`.\n */\nexport function createComputedCache<Context, R extends UnknownRecord, Result>(\n name: string,\n derive: (context: Context, record: R) => Result,\n options?: CreateComputedCacheOpts<Result, R>,\n): ComputedCache<Context, R, Result> {\n // Keyed on the context object, so an editor that is torn down takes its\n // caches with it and a second editor does not read the first one's values.\n const perContext = new WeakMap<object, { get(id: RecordId<UnknownRecord>): Result | undefined }>()\n\n return {\n get(context: Context, id: IdOf<R>): Result | undefined {\n const key = context as unknown as object\n if (key === null || (typeof key !== \"object\" && typeof key !== \"function\")) {\n throw new Error(\"createComputedCache: context must be an object\")\n }\n let cache = perContext.get(key)\n if (!cache) {\n // `areRecordsEqual` gates the derivation itself: when the incoming\n // record is equivalent to the one the last result came from, the\n // previous result is handed back untouched.\n const areRecordsEqual = options?.areRecordsEqual\n // Memoized per record id, not per cache: one shared \"last record\" would\n // compare a shape against whichever unrelated shape was derived before it.\n const previous = new Map<string, { record: R; result: Result }>()\n const derivation = areRecordsEqual\n ? (record: UnknownRecord): Result => {\n const next = record as R\n const last = previous.get(record.id)\n if (last && areRecordsEqual(last.record, next)) return last.result\n const result = derive(context, next)\n previous.set(record.id, { record: next, result })\n return result\n }\n : (record: UnknownRecord): Result => derive(context, record as R)\n\n cache = storeOf(context).createComputedCache<Result>(\n name,\n derivation,\n options?.isEqual ? { isEqual: options.isEqual } : undefined,\n )\n perContext.set(key, cache)\n }\n return cache.get(id as unknown as RecordId<UnknownRecord>)\n },\n }\n}\n\n/**\n * Options for {@link createComputedCache}, including the record-level equality\n * that decides when a derivation is worth re-running at all.\n */\nexport type CreateComputedCacheOpts<Result, R extends UnknownRecord = UnknownRecord> =\n CreateComputedCacheOptions<Result> & {\n /**\n * Treat two versions of the *record* as the same, so the derivation is not\n * re-run when only parts it does not read have changed.\n *\n * `isEqual` compares results and can only save the dependents work;\n * `areRecordsEqual` compares inputs and saves the derivation itself. Use it\n * when the derivation is expensive and reads only a couple of fields —\n * geometry from `props`, say, which should not be rebuilt because the shape\n * moved.\n */\n areRecordsEqual?: ((a: R, b: R) => boolean) | undefined\n }\n","/**\n * Two small guards the store leans on: a development-only deep freeze, and an\n * id assertion that narrows.\n */\n\nimport type { IdOf, RecordType, UnknownRecord } from \"./ids\"\n\n/** Whether the bundle is a development build. Frozen at module load. */\nconst IS_DEV =\n typeof process !== \"undefined\" && typeof process.env === \"object\" && process.env[\"NODE_ENV\"] !== \"production\"\n\n/**\n * Deep-freeze `object` in development builds, and hand it straight back in\n * production.\n *\n * Records in the store are shared by reference with every consumer that read\n * them, so mutating one in place skips the whole change pipeline: no diff, no\n * side effects, no listeners, and an undo that silently does nothing. Freezing\n * turns that from a bug someone finds a week later into a `TypeError` on the\n * line that did it. The check is skipped in production because freezing every\n * record on every write is not free.\n *\n * Already-frozen objects are left alone, so re-freezing a record that came out\n * of the store costs one property read.\n */\nexport function devFreeze<T>(object: T): T {\n if (!IS_DEV) return object\n return deepFreeze(object)\n}\n\nfunction deepFreeze<T>(object: T): T {\n if (object === null || typeof object !== \"object\") return object\n if (Object.isFrozen(object)) return object\n Object.freeze(object)\n // `Object.freeze` is shallow; a record's `props` and `meta` are the parts\n // most likely to be mutated in place, and they are one level down.\n for (const value of Object.values(object as Record<string, unknown>)) deepFreeze(value)\n if (Array.isArray(object)) for (const value of object) deepFreeze(value)\n return object\n}\n\n/**\n * Assert that `id` belongs to `type`, narrowing it to that type's id.\n *\n * Record ids are branded strings, so the compiler already stops most mix-ups —\n * but ids that arrive from outside the program (a URL, a saved file, a sync\n * message) are plain strings that someone has to vouch for. This is the place\n * to do that vouching: it throws with the offending id rather than letting a\n * `page:` id be looked up as a shape and quietly returning `undefined`.\n *\n * ```ts\n * assertIdType(idFromUrl, PageRecordType)\n * editor.setCurrentPage(idFromUrl) // now typed as TLPageId\n * ```\n */\nexport function assertIdType<R extends UnknownRecord>(\n id: string | undefined,\n type: RecordType<R, any>,\n): asserts id is IdOf<R> {\n if (!type.isId(id)) {\n throw new Error(`Expected ${type.typeName} id, got ${JSON.stringify(id)}`)\n }\n}\n","/**\n * The synchronous storage contract a store can be backed by.\n *\n * Deliberately synchronous and deliberately tiny: it is the shape an embedded\n * key-value store (a SQLite table, a `Map`, an in-process test double) already\n * has, so a host can hand one over without writing an adapter. Anything\n * asynchronous — a network, IndexedDB — belongs behind a snapshot load and save\n * rather than behind this.\n */\n\nimport type { IdOf, UnknownRecord } from \"./ids\"\nimport type { SerializedSchema } from \"./migrate\"\n\n/**\n * Somewhere records can be read from and written to, one at a time, without\n * awaiting.\n *\n * Implementations must be consistent within a call: `getAll` reflects every\n * `set` and `delete` that has already returned.\n */\nexport interface SynchronousRecordStorage<R extends UnknownRecord = UnknownRecord> {\n /** The record stored under `id`, or `undefined`. */\n get(id: IdOf<R>): R | undefined\n /** Every stored record. Order is not significant. */\n getAll(): R[]\n /** Store `record` under its own id, replacing anything already there. */\n set(record: R): void\n /** Remove the record stored under `id`. Removing an absent id is not an error. */\n delete(id: IdOf<R>): void\n /** Remove every record. */\n clear(): void\n}\n\n/**\n * Record storage that also remembers the schema its records were written\n * against, so they can be migrated when they are read back.\n *\n * Storing records without their schema is the one mistake that cannot be\n * recovered from later: there is no way to tell which migrations have already\n * run, and re-running them corrupts the data.\n */\nexport interface SynchronousStorage<R extends UnknownRecord = UnknownRecord> extends SynchronousRecordStorage<R> {\n /** The schema the stored records were written against, or `undefined` when empty. */\n getSchema(): SerializedSchema | undefined\n /** Record the schema the stored records are written against. */\n setSchema(schema: SerializedSchema): void\n}\n\n/**\n * A {@link SynchronousStorage} backed by a plain `Map`.\n *\n * Useful in tests and as the reference implementation of the contract — the\n * shortest correct answer to \"what does a storage have to do?\".\n */\nexport function createInMemoryStorage<R extends UnknownRecord = UnknownRecord>(): SynchronousStorage<R> {\n const records = new Map<IdOf<R>, R>()\n let schema: SerializedSchema | undefined\n\n return {\n get: (id) => records.get(id),\n getAll: () => [...records.values()],\n set: (record) => {\n records.set(record.id as IdOf<R>, record)\n },\n delete: (id) => {\n records.delete(id)\n },\n clear: () => records.clear(),\n getSchema: () => schema,\n setSchema: (next) => {\n schema = next\n },\n }\n}\n","/**\n * Grapheme cluster iteration.\n *\n * \"One character\" as a person sees it is a grapheme cluster, not a UTF-16 code\n * unit and not a code point: `👩‍👩‍👧` is one, `é` written as `e` + a combining\n * accent is one, and a flag emoji is one. Anything that measures, truncates or\n * steps through text a character at a time has to walk clusters or it will cut a\n * family emoji in half.\n */\n\n/** Lazily created, because constructing a `Segmenter` is not free. */\nlet segmenter: Intl.Segmenter | undefined\nlet segmenterChecked = false\n\nfunction getSegmenter(): Intl.Segmenter | undefined {\n if (!segmenterChecked) {\n segmenterChecked = true\n try {\n // `Intl.Segmenter` is missing on older Safari and on some minimal Node builds.\n if (typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\") {\n segmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" })\n }\n } catch {\n segmenter = undefined\n }\n }\n return segmenter\n}\n\n/**\n * Iterate the grapheme clusters of `str`.\n *\n * Uses `Intl.Segmenter` where it exists and falls back to code-point iteration\n * otherwise — which keeps surrogate pairs intact (so a plain emoji survives) but\n * cannot join a ZWJ sequence or a combining mark to its base.\n *\n * ```ts\n * [...iterateGraphemes(\"a👍🏽b\")] // [\"a\", \"👍🏽\", \"b\"]\n * ```\n */\nexport function* iterateGraphemes(str: string): Generator<string, void, undefined> {\n const seg = getSegmenter()\n if (seg) {\n for (const { segment } of seg.segment(str)) yield segment\n return\n }\n // SEMANTICS-ASSUMED: the fallback splits on code points. It is the closest\n // approximation available without shipping a Unicode break table, and it is\n // never worse than the `for (const c of str)` a caller would otherwise write.\n for (const codePoint of str) yield codePoint\n}\n\n/** The grapheme clusters of `str`, as an array. */\nexport function getGraphemes(str: string): string[] {\n return [...iterateGraphemes(str)]\n}\n\n/** How many grapheme clusters `str` has — its length as a reader would count it. */\nexport function getGraphemeLength(str: string): number {\n let n = 0\n for (const _ of iterateGraphemes(str)) n++\n return n\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mocanvas/store",
3
- "version": "4.1.1",
3
+ "version": "4.2.0",
4
4
  "description": "The mocanvas document model: reactive records, schema, migrations and .tldr file IO.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Symbio Digital",
@@ -45,7 +45,7 @@
45
45
  "dependencies": {
46
46
  "fractional-indexing": "^3.2.0",
47
47
  "nanoid": "^5.1.0",
48
- "@mocanvas/state": "4.1.1"
48
+ "@mocanvas/state": "4.2.0"
49
49
  },
50
50
  "scripts": {
51
51
  "build": "tsup",