@tldraw/store 5.5.0 → 5.6.0-canary.669b4c97f643

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.
@@ -2,6 +2,7 @@ import { react } from '@tldraw/state'
2
2
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3
3
  import { BaseRecord, RecordId } from './BaseRecord'
4
4
  import { createMigrationSequence } from './migrate'
5
+ import { RecordsDiff } from './RecordsDiff'
5
6
  import { createRecordType } from './RecordType'
6
7
  import { createComputedCache, Store } from './Store'
7
8
  import { StoreSchema } from './StoreSchema'
@@ -228,6 +229,34 @@ describe('Store: reading and writing (S)', () => {
228
229
  expect(unsafeOnly).toEqual(['Jimmy Tolks'])
229
230
  stop2()
230
231
  })
232
+
233
+ it('[S11] a reaction that puts records does not re-run for unrelated store changes', () => {
234
+ const a = Author.create({ name: 'A' })
235
+ const b = Author.create({ name: 'B' })
236
+ store.put([a, b])
237
+ let runs = 0
238
+ const stop = react('writer', () => {
239
+ runs++
240
+ store.put([{ ...a, name: 'A' + runs }])
241
+ })
242
+ store.put([{ ...b, name: 'B2' }])
243
+ expect(runs).toBe(1)
244
+ stop()
245
+ })
246
+
247
+ it('[S11] a reaction that removes records does not re-run for unrelated store changes', () => {
248
+ const a = Author.create({ name: 'A' })
249
+ const b = Author.create({ name: 'B' })
250
+ store.put([a, b])
251
+ let runs = 0
252
+ const stop = react('remover', () => {
253
+ runs++
254
+ store.remove([a.id])
255
+ })
256
+ store.put([{ ...b, name: 'B2' }])
257
+ expect(runs).toBe(1)
258
+ stop()
259
+ })
231
260
  })
232
261
 
233
262
  describe('Store: serialization and snapshots (S)', () => {
@@ -765,3 +794,61 @@ describe('integrity (IC)', () => {
765
794
  store.dispose()
766
795
  })
767
796
  })
797
+
798
+ describe('Store: repeated ids in one put (S)', () => {
799
+ let store: Store<LibraryType>
800
+ beforeEach(() => {
801
+ store = new Store({ props: {}, schema: schema() })
802
+ })
803
+ afterEach(() => {
804
+ store.dispose()
805
+ })
806
+
807
+ it('[S12] repeated ids in one put record one update whose from is the pre-put record', () => {
808
+ const author = Author.create({ name: 'Start' })
809
+ store.put([author])
810
+ const entries: RecordsDiff<LibraryType>[] = []
811
+ store.addHistoryInterceptor((entry) => entries.push(entry.changes))
812
+
813
+ store.put([
814
+ { ...author, name: 'Middle' },
815
+ { ...author, name: 'End' },
816
+ ])
817
+
818
+ expect(entries).toHaveLength(1)
819
+ expect(entries[0].updated).toEqual({
820
+ [author.id]: [author, { ...author, name: 'End' }],
821
+ })
822
+ })
823
+
824
+ it('[S12] a record created then updated in one put is recorded as a single addition', () => {
825
+ const author = Author.create({ name: 'Start' })
826
+ const entries: RecordsDiff<LibraryType>[] = []
827
+ store.addHistoryInterceptor((entry) => entries.push(entry.changes))
828
+
829
+ store.put([author, { ...author, name: 'End' }])
830
+
831
+ expect(entries).toHaveLength(1)
832
+ expect(entries[0]).toEqual({
833
+ added: { [author.id]: { ...author, name: 'End' } },
834
+ updated: {},
835
+ removed: {},
836
+ })
837
+ })
838
+
839
+ it('[S12] a record changed and changed back within one put records nothing', () => {
840
+ const author = Author.create({ name: 'Start' })
841
+ store.put([author])
842
+ const stored = store.get(author.id)!
843
+ const entries: RecordsDiff<LibraryType>[] = []
844
+ store.addHistoryInterceptor((entry) => entries.push(entry.changes))
845
+ const afterChange = vi.fn()
846
+ store.sideEffects.registerAfterChangeHandler('author', afterChange)
847
+
848
+ store.put([{ ...stored, name: 'Middle' }, stored])
849
+
850
+ expect(entries).toEqual([])
851
+ expect(afterChange).not.toHaveBeenCalled()
852
+ expect(store.get(author.id)).toBe(stored)
853
+ })
854
+ })
package/src/lib/Store.ts CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  import { AtomMap } from './AtomMap'
15
15
  import { IdOf, RecordId, UnknownRecord } from './BaseRecord'
16
16
  import { devFreeze } from './devFreeze'
17
- import { isRecordsDiffEmpty, RecordsDiff, squashRecordDiffs } from './RecordsDiff'
17
+ import { hasAnyKey, isRecordsDiffEmpty, RecordsDiff, squashRecordDiffs } from './RecordsDiff'
18
18
  import { RecordScope } from './RecordType'
19
19
  import { StoreQueries } from './StoreQueries'
20
20
  import { SerializedSchema, StoreSchema } from './StoreSchema'
@@ -513,11 +513,15 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
513
513
  this.scopedTypes = scopedTypes
514
514
  }
515
515
 
516
+ private isFlushingHistory = false
517
+
516
518
  public _flushHistory() {
517
519
  // If we have accumulated history, flush it and update listeners
518
520
  if (this.historyAccumulator.hasChanges()) {
519
521
  const entries = this.historyAccumulator.flush()
520
522
  const errors: unknown[] = []
523
+ const wasFlushingHistory = this.isFlushingHistory
524
+ this.isFlushingHistory = true
521
525
  for (const { changes, source } of entries) {
522
526
  // Filtered diffs are computed at most once per scope per entry, and shared by every
523
527
  // listener watching that scope.
@@ -544,6 +548,7 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
544
548
  }
545
549
  }
546
550
  }
551
+ this.isFlushingHistory = wasFlushingHistory
547
552
  if (errors.length > 0) throw errors[0]
548
553
  }
549
554
  }
@@ -589,7 +594,8 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
589
594
  if (this.listeners.size === 0) {
590
595
  this.historyAccumulator.clear()
591
596
  }
592
- this.history.set(this.history.get() + 1, changes)
597
+ // Don't capture: a reaction that writes would otherwise re-run on every store change (S11).
598
+ this.history.set(this.history.__unsafe__getWithoutCapture() + 1, changes)
593
599
  }
594
600
 
595
601
  validate(phase: 'initialize' | 'createRecord' | 'updateRecord' | 'tests') {
@@ -622,12 +628,6 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
622
628
  // Iterate through all records, creating, updating or removing as needed
623
629
  let record: R
624
630
 
625
- // There's a chance that, despite having records, all of the values are
626
- // identical to what they were before; and so we'd end up with an "empty"
627
- // history entry. Let's keep track of whether we've actually made any
628
- // changes (e.g. additions, deletions, or updates that produce a new value).
629
- let didChange = false
630
-
631
631
  const source = this.isMergingRemoteChanges ? 'remote' : 'user'
632
632
 
633
633
  for (let i = 0, n = records.length; i < n; i++) {
@@ -652,14 +652,23 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
652
652
  record = devFreeze(validated)
653
653
  this.records.set(record.id, record)
654
654
 
655
- didChange = true
656
- updates[record.id] = [initialValue, record]
655
+ if (additions[record.id]) {
656
+ // the same record was created earlier in this call: fold the update into it
657
+ additions[record.id] = record
658
+ } else {
659
+ // an earlier update to the same record in this call owns the `from`
660
+ const from = updates[record.id]?.[0] ?? initialValue
661
+ if (from === record) {
662
+ // back to where it started within this call: nothing to record
663
+ delete updates[record.id]
664
+ } else {
665
+ updates[record.id] = [from, record]
666
+ }
667
+ }
657
668
  this.addDiffForAfterEvent(initialValue, record)
658
669
  } else {
659
670
  record = this.sideEffects.handleBeforeCreate(record, source)
660
671
 
661
- didChange = true
662
-
663
672
  // If we don't have an atom, create one.
664
673
 
665
674
  // Validate the record
@@ -681,8 +690,9 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
681
690
  }
682
691
  }
683
692
 
684
- // If we did change, update the history
685
- if (!didChange) return
693
+ // Validation may have left every record identical to before, in which case there is no
694
+ // change-set to record.
695
+ if (!hasAnyKey(additions) && !hasAnyKey(updates)) return
686
696
  this.updateHistory({
687
697
  added: additions,
688
698
  updated: updates,
@@ -1008,6 +1018,18 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
1008
1018
  this.listeners.add(listener)
1009
1019
 
1010
1020
  return () => {
1021
+ // Flush so this listener's history ends at exactly now, but not from inside a flush:
1022
+ // the other listeners would then receive changes made during that flush before the
1023
+ // entry they are still being handed.
1024
+ if (!this.isFlushingHistory) {
1025
+ try {
1026
+ this._flushHistory()
1027
+ } catch (error) {
1028
+ // Removers run in teardown loops (Editor.dispose, TLSyncClient.close); throwing here
1029
+ // would skip the cleanups that follow.
1030
+ console.error(error)
1031
+ }
1032
+ }
1011
1033
  this.listeners.delete(listener)
1012
1034
 
1013
1035
  if (this.listeners.size === 0) {
@@ -1077,7 +1099,7 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
1077
1099
  for (const [_from, to] of objectMapValues(diff.updated)) {
1078
1100
  const type = this.schema.getType(to.typeName)
1079
1101
  if (ignoreEphemeralKeys && type.ephemeralKeySet.size) {
1080
- const existing = this.get(to.id)
1102
+ const existing = this.unsafeGetWithoutCapture(to.id)
1081
1103
  if (!existing) {
1082
1104
  toPut.push(to)
1083
1105
  continue
@@ -514,3 +514,67 @@ describe('listeners: dispose (H)', () => {
514
514
  }
515
515
  })
516
516
  })
517
+
518
+ describe('listeners: removing a listener (H)', () => {
519
+ const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve))
520
+
521
+ beforeEach(() => {
522
+ // @ts-expect-error - test-only escape hatch
523
+ globalThis.__FORCE_RAF_IN_TESTS__ = true
524
+ return () => {
525
+ // @ts-expect-error - test-only escape hatch
526
+ globalThis.__FORCE_RAF_IN_TESTS__ = false
527
+ }
528
+ })
529
+
530
+ it('[H14] the remover delivers pending change-sets before removing the listener', async () => {
531
+ const listener = vi.fn()
532
+ const removeListener = store.listen(listener)
533
+ store.put([tolkein()])
534
+ expect(listener).not.toHaveBeenCalled()
535
+
536
+ removeListener()
537
+ expect(listener).toHaveBeenCalledTimes(1)
538
+
539
+ store.put([hobbit()])
540
+ await nextFrame()
541
+ expect(listener).toHaveBeenCalledTimes(1)
542
+ })
543
+
544
+ it('[H14] the remover logs a listener error from its flush instead of throwing it', async () => {
545
+ const error = new Error('listener failed')
546
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
547
+ const listener = vi.fn(() => {
548
+ throw error
549
+ })
550
+ try {
551
+ const removeListener = store.listen(listener)
552
+ store.put([tolkein()])
553
+
554
+ expect(removeListener).not.toThrow()
555
+ expect(consoleError).toHaveBeenCalledWith(error)
556
+
557
+ store.put([hobbit()])
558
+ await nextFrame()
559
+ expect(listener).toHaveBeenCalledTimes(1)
560
+ } finally {
561
+ consoleError.mockRestore()
562
+ }
563
+ })
564
+
565
+ it('[H14] a listener that writes and then removes itself mid-flush does not reorder the others', async () => {
566
+ const received: string[][] = []
567
+ const removeWriter = store.listen(() => {
568
+ store.put([hobbit()])
569
+ removeWriter()
570
+ })
571
+ store.listen(({ changes }) => received.push(Object.keys(changes.added)))
572
+
573
+ const author = tolkein()
574
+ store.put([author])
575
+ await nextFrame()
576
+ await nextFrame()
577
+
578
+ expect(received).toEqual([[author.id], [hobbit().id]])
579
+ })
580
+ })
@@ -7,7 +7,7 @@ import {
7
7
  RESET_VALUE,
8
8
  withDiff,
9
9
  } from '@tldraw/state'
10
- import { areArraysShallowEqual, isEqual, objectMapValues } from '@tldraw/utils'
10
+ import { areArraysShallowEqual, isEqual } from '@tldraw/utils'
11
11
  import { AtomMap } from './AtomMap'
12
12
  import { IdOf, UnknownRecord } from './BaseRecord'
13
13
  import { executeQuery, objectMatchesQuery, QueryExpression } from './executeQuery'
@@ -324,25 +324,24 @@ export class StoreQueries<R extends UnknownRecord> {
324
324
 
325
325
  const setConstructors = new Map<any, IncrementalSetConstructor<IdOf<S>>>()
326
326
 
327
- const add = (value: any, id: IdOf<S>) => {
327
+ const setConstructorFor = (value: any) => {
328
328
  let setConstructor = setConstructors.get(value)
329
- if (!setConstructor)
329
+ if (!setConstructor) {
330
330
  setConstructor = new IncrementalSetConstructor<IdOf<S>>(
331
331
  prevValue.get(value) ?? new Set()
332
332
  )
333
- setConstructor.add(id)
334
- setConstructors.set(value, setConstructor)
335
- }
336
-
337
- const remove = (value: any, id: IdOf<S>) => {
338
- let set = setConstructors.get(value)
339
- if (!set) set = new IncrementalSetConstructor<IdOf<S>>(prevValue.get(value) ?? new Set())
340
- set.remove(id)
341
- setConstructors.set(value, set)
333
+ setConstructors.set(value, setConstructor)
334
+ }
335
+ return setConstructor
342
336
  }
337
+ const add = (value: any, id: IdOf<S>) => setConstructorFor(value).add(id)
338
+ const remove = (value: any, id: IdOf<S>) => setConstructorFor(value).remove(id)
343
339
 
340
+ // for-in rather than objectMapValues: this runs per frame while dragging, and an
341
+ // allocation per diff per index adds up (see the note in RecordsDiff.ts)
344
342
  for (const changes of history) {
345
- for (const record of objectMapValues(changes.added)) {
343
+ for (const id in changes.added) {
344
+ const record = changes.added[id as IdOf<R>]
346
345
  if (record.typeName === typeName) {
347
346
  const value = getPropertyValue(record as S)
348
347
  if (value !== undefined) {
@@ -350,7 +349,8 @@ export class StoreQueries<R extends UnknownRecord> {
350
349
  }
351
350
  }
352
351
  }
353
- for (const [from, to] of objectMapValues(changes.updated)) {
352
+ for (const id in changes.updated) {
353
+ const [from, to] = changes.updated[id as IdOf<R>]
354
354
  if (to.typeName === typeName) {
355
355
  const prev = getPropertyValue(from as S)
356
356
  const next = getPropertyValue(to as S)
@@ -364,7 +364,8 @@ export class StoreQueries<R extends UnknownRecord> {
364
364
  }
365
365
  }
366
366
  }
367
- for (const record of objectMapValues(changes.removed)) {
367
+ for (const id in changes.removed) {
368
+ const record = changes.removed[id as IdOf<R>]
368
369
  if (record.typeName === typeName) {
369
370
  const value = getPropertyValue(record as S)
370
371
  if (value !== undefined) {
@@ -564,17 +565,18 @@ export class StoreQueries<R extends UnknownRecord> {
564
565
  return fromScratchWithDiff(prevValue)
565
566
  }
566
567
 
567
- const setConstructor = new IncrementalSetConstructor<IdOf<S>>(
568
- prevValue
569
- ) as IncrementalSetConstructor<IdOf<S>>
568
+ const setConstructor = new IncrementalSetConstructor<IdOf<S>>(prevValue)
570
569
 
570
+ // for-in rather than objectMapValues: see the index derive above
571
571
  for (const changes of history) {
572
- for (const added of objectMapValues(changes.added)) {
572
+ for (const id in changes.added) {
573
+ const added = changes.added[id as IdOf<R>]
573
574
  if (added.typeName === typeName && objectMatchesQuery(query, added)) {
574
575
  setConstructor.add(added.id)
575
576
  }
576
577
  }
577
- for (const [_, updated] of objectMapValues(changes.updated)) {
578
+ for (const id in changes.updated) {
579
+ const updated = changes.updated[id as IdOf<R>][1]
578
580
  if (updated.typeName === typeName) {
579
581
  if (objectMatchesQuery(query, updated)) {
580
582
  setConstructor.add(updated.id)
@@ -583,7 +585,8 @@ export class StoreQueries<R extends UnknownRecord> {
583
585
  }
584
586
  }
585
587
  }
586
- for (const removed of objectMapValues(changes.removed)) {
588
+ for (const id in changes.removed) {
589
+ const removed = changes.removed[id as IdOf<R>]
587
590
  if (removed.typeName === typeName) {
588
591
  setConstructor.remove(removed.id)
589
592
  }
@@ -444,6 +444,22 @@ describe('getMigrationsSince (MG)', () => {
444
444
  expect(result.error).toBe('Incompatible schema?')
445
445
  })
446
446
 
447
+ it('[MG5] a persisted version that is present but not a number is an error', () => {
448
+ for (const retroactive of [true, false]) {
449
+ const foo = mockSequence({ id: 'foo', retroactive, versions: 2 })
450
+ const schema = StoreSchema.create({}, { migrations: [foo] })
451
+
452
+ for (const version of [null, '2', '0']) {
453
+ const result = schema.getMigrationsSince({
454
+ schemaVersion: 2,
455
+ sequences: { foo: version as any },
456
+ })
457
+ assert(!result.ok)
458
+ expect(result.error).toBe('Incompatible schema?')
459
+ }
460
+ }
461
+ })
462
+
447
463
  it('[MG6] results are cached per persisted-schema object identity', () => {
448
464
  const schema = makeSchema([mockSequence({ id: 'foo', retroactive: true, versions: 2 })])
449
465
  const oldSchema = schema.serializeEarliestVersion()
@@ -1107,3 +1123,65 @@ describe('migrateStorage (MA)', () => {
1107
1123
  expect(result.value[newRecord.id as keyof typeof result.value]).toMatchObject({ name: 'new' })
1108
1124
  })
1109
1125
  })
1126
+
1127
+ describe('malformed persisted schemas (SC, MA)', () => {
1128
+ const schema = StoreSchema.create<Book>(
1129
+ { book: Book },
1130
+ {
1131
+ migrations: [
1132
+ createMigrationSequence({
1133
+ sequenceId: 'com.tldraw.book',
1134
+ sequence: [{ id: 'com.tldraw.book/1', scope: 'record', up: () => {} }],
1135
+ }),
1136
+ ],
1137
+ }
1138
+ )
1139
+
1140
+ it('[SC5] schemas with a missing version or collections produce an error result, not a throw', () => {
1141
+ expect(upgradeSchema({} as any).ok).toBe(false)
1142
+ expect(upgradeSchema({ schemaVersion: 2 } as any).ok).toBe(false)
1143
+ expect(upgradeSchema({ schemaVersion: 1 } as any).ok).toBe(false)
1144
+ expect(upgradeSchema(null as any).ok).toBe(false)
1145
+ })
1146
+
1147
+ it('[MA6] migrateStoreSnapshot reports malformed schemas as a migration error', () => {
1148
+ for (const bad of [{}, { schemaVersion: 2 }, { schemaVersion: 1, recordVersions: null }]) {
1149
+ expect(schema.migrateStoreSnapshot({ store: {}, schema: bad as any })).toEqual({
1150
+ type: 'error',
1151
+ reason: 'migration-error',
1152
+ })
1153
+ }
1154
+ })
1155
+
1156
+ it('[MG3] a persisted sequence named after an Object.prototype member is just unknown', () => {
1157
+ const persisted = { schemaVersion: 2, sequences: { constructor: 1, 'com.tldraw.book': 1 } }
1158
+ expect(schema.getMigrationsSince(persisted as any)).toEqual({ ok: true, value: [] })
1159
+ })
1160
+ })
1161
+
1162
+ describe('malformed v1 schemas (SC)', () => {
1163
+ it('[SC5] a v1 schema with a malformed record entry produces an error result', () => {
1164
+ expect(
1165
+ upgradeSchema({ schemaVersion: 1, storeVersion: 1, recordVersions: { book: null } } as any).ok
1166
+ ).toBe(false)
1167
+ expect(
1168
+ upgradeSchema({
1169
+ schemaVersion: 1,
1170
+ storeVersion: 1,
1171
+ recordVersions: { book: { version: 1, subTypeKey: 'type', subTypeVersions: null } },
1172
+ } as any).ok
1173
+ ).toBe(false)
1174
+ })
1175
+ })
1176
+
1177
+ describe('non-object persisted schemas (MA)', () => {
1178
+ it('[MA6] a missing schema is a migration error, not a throw', () => {
1179
+ const schema = StoreSchema.create<Book>({ book: Book })
1180
+ for (const bad of [undefined, null, 'v2', 3]) {
1181
+ expect(schema.migrateStoreSnapshot({ store: {}, schema: bad as any })).toEqual({
1182
+ type: 'error',
1183
+ reason: 'migration-error',
1184
+ })
1185
+ }
1186
+ })
1187
+ })
@@ -123,6 +123,10 @@ export interface SerializedSchemaV2 {
123
123
  */
124
124
  export type SerializedSchema = SerializedSchemaV1 | SerializedSchemaV2
125
125
 
126
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
127
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
128
+ }
129
+
126
130
  /**
127
131
  * Upgrades a serialized schema from version 1 to version 2 format.
128
132
  *
@@ -153,8 +157,15 @@ export type SerializedSchema = SerializedSchemaV1 | SerializedSchemaV2
153
157
  * @public
154
158
  */
155
159
  export function upgradeSchema(schema: SerializedSchema): Result<SerializedSchemaV2, string> {
156
- if (schema.schemaVersion > 2 || schema.schemaVersion < 1) return Result.err('Bad schema version')
157
- if (schema.schemaVersion === 2) return Result.ok(schema as SerializedSchemaV2)
160
+ // Persisted schemas are untrusted input: check the shape rather than crash on a missing or
161
+ // malformed `sequences`/`recordVersions` further down.
162
+ if (!isPlainRecord(schema)) return Result.err('Bad schema')
163
+ if (schema.schemaVersion === 2) {
164
+ if (!isPlainRecord(schema.sequences)) return Result.err('Bad schema: missing sequences')
165
+ return Result.ok(schema)
166
+ }
167
+ if (schema.schemaVersion !== 1) return Result.err('Bad schema version')
168
+ if (!isPlainRecord(schema.recordVersions)) return Result.err('Bad schema: missing recordVersions')
158
169
  const result: SerializedSchemaV2 = {
159
170
  schemaVersion: 2,
160
171
  sequences: {
@@ -163,8 +174,12 @@ export function upgradeSchema(schema: SerializedSchema): Result<SerializedSchema
163
174
  }
164
175
 
165
176
  for (const [typeName, recordVersion] of Object.entries(schema.recordVersions)) {
177
+ if (!isPlainRecord(recordVersion)) return Result.err('Bad schema: malformed recordVersions')
166
178
  result.sequences[`com.tldraw.${typeName}`] = recordVersion.version
167
179
  if ('subTypeKey' in recordVersion) {
180
+ if (!isPlainRecord(recordVersion.subTypeVersions)) {
181
+ return Result.err('Bad schema: malformed subTypeVersions')
182
+ }
168
183
  for (const [subType, version] of Object.entries(recordVersion.subTypeVersions)) {
169
184
  result.sequences[`com.tldraw.${typeName}.${subType}`] = version
170
185
  }
@@ -425,6 +440,10 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
425
440
  public getMigrationsSince(persistedSchema: SerializedSchema): Result<Migration[], string> {
426
441
  // Every result — success, empty, or error — is cached, so cache once around the whole
427
442
  // computation rather than at each of its exit points.
443
+ // A non-object schema (see upgradeSchema) cannot be a WeakMap key; its error result is cheap
444
+ // to recompute.
445
+ if (!isPlainRecord(persistedSchema)) return this.computeMigrationsSince(persistedSchema)
446
+
428
447
  const cached = this.migrationCache.get(persistedSchema)
429
448
  if (cached) {
430
449
  return cached
@@ -442,8 +461,11 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
442
461
  }
443
462
  const schema = upgradeResult.value
444
463
  const sequenceIdsToInclude = new Set(
445
- // start with any shared sequences
446
- Object.keys(schema.sequences).filter((sequenceId) => this.migrations[sequenceId])
464
+ // start with any shared sequences. Own-property lookups: a persisted sequence id like
465
+ // 'constructor' must not resolve to an Object.prototype member.
466
+ Object.keys(schema.sequences).filter((sequenceId) =>
467
+ getOwnProperty(this.migrations, sequenceId)
468
+ )
447
469
  )
448
470
 
449
471
  // also include any sequences that are not in the persisted schema but are marked as postHoc
@@ -460,8 +482,13 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
460
482
  const allMigrationsToInclude = new Set<MigrationId>()
461
483
  for (const sequenceId of sequenceIdsToInclude) {
462
484
  const theirVersion = schema.sequences[sequenceId]
485
+ // Only a missing version means "never applied"; rerunning migrations on data that may
486
+ // already be migrated would corrupt it.
487
+ if (theirVersion !== undefined && typeof theirVersion !== 'number') {
488
+ return Result.err('Incompatible schema?')
489
+ }
463
490
  if (
464
- (typeof theirVersion !== 'number' && this.migrations[sequenceId].retroactive) ||
491
+ (theirVersion === undefined && this.migrations[sequenceId].retroactive) ||
465
492
  theirVersion === 0
466
493
  ) {
467
494
  for (const migration of this.migrations[sequenceId].sequence) {
@@ -548,8 +575,8 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
548
575
  migrationsToApply = migrationsToApply.slice().reverse()
549
576
  }
550
577
 
551
- record = structuredClone(record)
552
578
  try {
579
+ record = structuredClone(record)
553
580
  for (const migration of migrationsToApply) {
554
581
  if (migration.scope === 'store') throw new Error(/* won't happen, just for TS */)
555
582
  if (migration.scope === 'storage') throw new Error(/* won't happen, just for TS */)
@@ -683,14 +710,15 @@ export class StoreSchema<R extends UnknownRecord, P = unknown> {
683
710
  if (migrationsToApply.length === 0) {
684
711
  return { type: 'success', value: snapshot.store }
685
712
  }
686
- const store = Object.assign(
687
- new Map<string, R>(objectMapEntries(snapshot.store).map(devFreeze)),
688
- {
689
- getSchema: () => snapshot.schema,
690
- setSchema: (_: SerializedSchema) => {},
691
- }
692
- )
693
713
  try {
714
+ // devFreeze throws for non-plain values, which is a migration failure like any other
715
+ const store = Object.assign(
716
+ new Map<string, R>(objectMapEntries(snapshot.store).map(devFreeze)),
717
+ {
718
+ getSchema: () => snapshot.schema,
719
+ setSchema: (_: SerializedSchema) => {},
720
+ }
721
+ )
694
722
  this.migrateStorage(store)
695
723
  if (opts?.mutateInputStore) {
696
724
  for (const [id, record] of store.entries()) {