@tldraw/store 5.7.0-internal.5fe8922939ec → 5.7.0-internal.d83eaf8e2d50

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/src/lib/Store.ts CHANGED
@@ -7,8 +7,6 @@ import {
7
7
  isUninitialized,
8
8
  reactor,
9
9
  transact,
10
- transaction,
11
- unsafe__withoutCapture,
12
10
  } from '@tldraw/state'
13
11
  import {
14
12
  WeakCache,
@@ -25,15 +23,7 @@ import {
25
23
  import { AtomMap } from './AtomMap'
26
24
  import { IdOf, RecordId, UnknownRecord } from './BaseRecord'
27
25
  import { devFreeze } from './devFreeze'
28
- import {
29
- createEmptyRecordsDiff,
30
- hasAnyKey,
31
- isRecordsDiffEmpty,
32
- RecordsDiff,
33
- reverseRecordsDiff,
34
- squashRecordDiffs,
35
- squashRecordDiffsMutable,
36
- } from './RecordsDiff'
26
+ import { hasAnyKey, isRecordsDiffEmpty, RecordsDiff, squashRecordDiffs } from './RecordsDiff'
37
27
  import { RecordScope } from './RecordType'
38
28
  import { StoreQueries } from './StoreQueries'
39
29
  import { SerializedSchema, StoreSchema } from './StoreSchema'
@@ -539,12 +529,6 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
539
529
  private isFlushingHistory = false
540
530
 
541
531
  public _flushHistory() {
542
- // listeners must never see changes a pending commit check may still revert
543
- if (this.checkedChanges) {
544
- this.didDeferFlush = true
545
- return
546
- }
547
- this.didDeferFlush = false
548
532
  // If we have accumulated history, flush it and update listeners
549
533
  const version = this.history.__unsafe__getWithoutCapture()
550
534
  const entries = this.historyAccumulator.flush(version)
@@ -623,9 +607,6 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
623
607
  // Set the atom before recording the entry: interceptors run inside `add`, and a flush they
624
608
  // trigger (e.g. via `listen`) would otherwise discard the entry as not yet committed.
625
609
  this.history.set(version, changes)
626
- if (this.checkedChanges && !this.isMergingRemoteChanges && !this.isUnchecked) {
627
- squashRecordDiffsMutable(this.checkedChanges, [changes])
628
- }
629
610
  this.historyAccumulator.add(
630
611
  {
631
612
  changes,
@@ -1258,33 +1239,12 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
1258
1239
 
1259
1240
  private _integrityChecker?: () => void | undefined
1260
1241
 
1261
- private isUnchecked = false
1262
-
1263
- /**
1264
- * Run housekeeping writes the store or editor makes for itself (repairs, the current user's
1265
- * record) without commit checks. Refusing one would bring back the state it fixes, and the
1266
- * next fix would loop. Inside a checked operation they're judged as part of it.
1267
- *
1268
- * @internal
1269
- */
1270
- runUnchecked<T>(fn: () => T): T {
1271
- const wasUnchecked = this.isUnchecked
1272
- this.isUnchecked = true
1273
- try {
1274
- return fn()
1275
- } finally {
1276
- this.isUnchecked = wasUnchecked
1277
- }
1278
- }
1279
-
1280
1242
  /** @internal */
1281
1243
  ensureStoreIsUsable() {
1282
- this.runUnchecked(() =>
1283
- this.atomic(() => {
1284
- this._integrityChecker ??= this.schema.createIntegrityChecker(this)
1285
- this._integrityChecker?.()
1286
- })
1287
- )
1244
+ this.atomic(() => {
1245
+ this._integrityChecker ??= this.schema.createIntegrityChecker(this)
1246
+ this._integrityChecker?.()
1247
+ })
1288
1248
  }
1289
1249
 
1290
1250
  private _isPossiblyCorrupted = false
@@ -1346,16 +1306,6 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
1346
1306
  private _isInAtomicOp = false
1347
1307
  /** @internal */
1348
1308
  atomic<T>(fn: () => T, runCallbacks = true, isMergingRemoteChanges = false): T {
1349
- // a user operation outside any check scope is its own checked unit
1350
- if (
1351
- !this._isInAtomicOp &&
1352
- this.checkScopeDepth === 0 &&
1353
- this.commitChecks.size > 0 &&
1354
- !isMergingRemoteChanges &&
1355
- !this.isUnchecked
1356
- ) {
1357
- return this.checkAsOneOperation(() => this.atomic(fn, runCallbacks, isMergingRemoteChanges))
1358
- }
1359
1309
  return transact(() => {
1360
1310
  if (this._isInAtomicOp) {
1361
1311
  if (!this.pendingAfterEvents) this.pendingAfterEvents = new Map()
@@ -1399,121 +1349,6 @@ export class Store<R extends UnknownRecord = UnknownRecord, Props = unknown> {
1399
1349
  })
1400
1350
  }
1401
1351
 
1402
- private readonly commitChecks = new Set<
1403
- (changes: RecordsDiff<R>) => TLStoreCommitRefusal | null
1404
- >()
1405
- private checkedChanges: RecordsDiff<R> | null = null
1406
- private didDeferFlush = false
1407
- private readonly settledListeners = new Set<(outcome: TLStoreOperationOutcome) => void>()
1408
-
1409
- /**
1410
- * Called at the end of every checked operation, once its outcome is final: after a refused one
1411
- * was reverted (and before its check is told), after an aborted one (it threw) was rolled back.
1412
- * Lets state kept outside the store's atoms (history) follow the operation's fate.
1413
- *
1414
- * @internal
1415
- */
1416
- onCheckedOperationSettled(listener: (outcome: TLStoreOperationOutcome) => void): () => void {
1417
- this.settledListeners.add(listener)
1418
- return () => {
1419
- this.settledListeners.delete(listener)
1420
- }
1421
- }
1422
-
1423
- /** Whether a commit check will judge what's being written now. @internal */
1424
- isInCheckedOperation() {
1425
- return this.checkedChanges !== null
1426
- }
1427
-
1428
- /**
1429
- * Check every user operation once it has fully settled: after all side effects, including
1430
- * operation-complete handlers and anything they wrote, and before history or listeners see it.
1431
- * Returning a refusal reverts the whole operation in place, so it nets out of history. Remote
1432
- * changes are never checked.
1433
- *
1434
- * @internal
1435
- */
1436
- addCommitCheck(check: (changes: RecordsDiff<R>) => TLStoreCommitRefusal | null): () => void {
1437
- this.commitChecks.add(check)
1438
- return () => {
1439
- this.commitChecks.delete(check)
1440
- }
1441
- }
1442
-
1443
- private checkScopeDepth = 0
1444
-
1445
- /**
1446
- * Check everything `fn` writes as one operation: the store operations inside collect their
1447
- * changes instead of being checked one by one, and the checks run once `fn` returns. For
1448
- * callers whose single user action spans several store operations (an editor `run`).
1449
- *
1450
- * @internal
1451
- */
1452
- checkAsOneOperation<T>(fn: () => T): T {
1453
- if (this.checkScopeDepth > 0 || this.commitChecks.size === 0) {
1454
- this.checkScopeDepth++
1455
- try {
1456
- return fn()
1457
- } finally {
1458
- this.checkScopeDepth--
1459
- }
1460
- }
1461
- // The unit owns its transaction, so a throw has rolled its writes back by the time it's
1462
- // settled, even inside someone else's transaction. A thrown unit is never judged: there's
1463
- // nothing left of it to allow or refuse.
1464
- this.checkScopeDepth = 1
1465
- this.checkedChanges = createEmptyRecordsDiff()
1466
- let refusal: TLStoreCommitRefusal | null = null
1467
- let result: T
1468
- try {
1469
- result = transaction(() => {
1470
- const value = fn()
1471
- this.checkScopeDepth = 0
1472
- refusal = this.judgeAndRevert()
1473
- return value
1474
- })
1475
- } catch (error) {
1476
- this.endCheckedOperation('aborted')
1477
- throw error
1478
- }
1479
- this.endCheckedOperation(refusal ? 'refused' : 'accepted')
1480
- // hosts hear about it once the outcome is final; a throwing listener can't change it
1481
- ;(refusal as TLStoreCommitRefusal | null)?.afterRevert?.()
1482
- return result
1483
- }
1484
-
1485
- private endCheckedOperation(outcome: TLStoreOperationOutcome) {
1486
- this.checkScopeDepth = 0
1487
- this.checkedChanges = null
1488
- for (const listener of this.settledListeners) listener(outcome)
1489
- if (this.didDeferFlush) {
1490
- this.didDeferFlush = false
1491
- this._flushHistory()
1492
- }
1493
- }
1494
-
1495
- private judgeAndRevert(): TLStoreCommitRefusal | null {
1496
- const changes = this.checkedChanges
1497
- this.checkedChanges = null
1498
- if (!changes || isRecordsDiffEmpty(changes)) return null
1499
- let refusal: TLStoreCommitRefusal | null = null
1500
- for (const check of this.commitChecks) {
1501
- // a check reads the store; inside a reaction that read must not become its dependency
1502
- refusal = unsafe__withoutCapture(() => check(changes))
1503
- if (refusal) break
1504
- }
1505
- if (refusal) {
1506
- // the revert itself is never checked: refusing it would leave the refused changes in place
1507
- this.runUnchecked(() =>
1508
- this.atomic(
1509
- () => this.applyDiff(reverseRecordsDiff(changes), { runCallbacks: false }),
1510
- false
1511
- )
1512
- )
1513
- }
1514
- return refusal
1515
- }
1516
-
1517
1352
  /** @internal */
1518
1353
  addHistoryInterceptor(fn: (entry: HistoryEntry<R>, source: ChangeSource) => void) {
1519
1354
  return this.historyAccumulator.addInterceptor((entry) =>
@@ -1574,24 +1409,6 @@ function squashHistoryEntries<T extends UnknownRecord>(
1574
1409
  )
1575
1410
  }
1576
1411
 
1577
- /**
1578
- * How a checked operation ended: allowed, refused by a commit check (and reverted), or aborted
1579
- * because it threw (and rolled back).
1580
- *
1581
- * @internal
1582
- */
1583
- export type TLStoreOperationOutcome = 'accepted' | 'refused' | 'aborted'
1584
-
1585
- /**
1586
- * What a commit check returns to revert the operation it was shown.
1587
- *
1588
- * @internal
1589
- */
1590
- export interface TLStoreCommitRefusal {
1591
- /** Called once the operation has been reverted. */
1592
- afterRevert?(): void
1593
- }
1594
-
1595
1412
  /**
1596
1413
  * Internal class that accumulates history entries before they are flushed to listeners.
1597
1414
  * Handles batching and squashing of adjacent entries from the same source.
@@ -1,213 +0,0 @@
1
- import { transact } from '@tldraw/state'
2
- import { beforeEach, describe, expect, it, vi } from 'vitest'
3
- import { BaseRecord, RecordId } from './BaseRecord'
4
- import { RecordsDiff } from './RecordsDiff'
5
- import { createRecordType } from './RecordType'
6
- import { Store } from './Store'
7
- import { StoreSchema } from './StoreSchema'
8
-
9
- interface Book extends BaseRecord<'book', RecordId<Book>> {
10
- title: string
11
- }
12
- interface Author extends BaseRecord<'author', RecordId<Author>> {
13
- name: string
14
- }
15
- const Book = createRecordType<Book>('book', {
16
- validator: { validate: (book) => book as Book },
17
- scope: 'document',
18
- })
19
- const Author = createRecordType<Author>('author', {
20
- validator: { validate: (author) => author as Author },
21
- scope: 'document',
22
- })
23
- type Library = Book | Author
24
-
25
- const book = Book.create({ id: Book.createId('a'), title: 'a' })
26
- const author = Author.create({ id: Author.createId('b'), name: 'b' })
27
-
28
- let store: Store<Library>
29
- beforeEach(() => {
30
- store = new Store({
31
- props: {},
32
- schema: StoreSchema.create<Library>({ book: Book, author: Author }),
33
- })
34
- })
35
-
36
- const ids = (diff: RecordsDiff<Library>) => ({
37
- added: Object.keys(diff.added).sort(),
38
- updated: Object.keys(diff.updated).sort(),
39
- removed: Object.keys(diff.removed).sort(),
40
- })
41
-
42
- describe('commit checks', () => {
43
- it('see the whole operation once side effects have settled, including late handlers', () => {
44
- const seen: RecordsDiff<Library>[] = []
45
- store.addCommitCheck((changes) => (seen.push(changes), null))
46
- // registered after the check, and writes more records from operation-complete
47
- let wrote = false
48
- store.sideEffects.registerOperationCompleteHandler(() => {
49
- if (wrote) return
50
- wrote = true
51
- store.put([author])
52
- })
53
- store.put([book])
54
- expect(seen.map(ids)).toEqual([{ added: [author.id, book.id], updated: [], removed: [] }])
55
- })
56
-
57
- it('runs once per outermost operation, not per nested write', () => {
58
- const check = vi.fn(() => null)
59
- store.addCommitCheck(check)
60
- store.atomic(() => {
61
- store.put([book])
62
- store.put([author])
63
- })
64
- expect(check).toHaveBeenCalledTimes(1)
65
- })
66
-
67
- it('revert a refused operation whole, then tell the check', () => {
68
- store.put([book])
69
- const afterRevert = vi.fn(() => {
70
- expect(store.get(author.id)).toBeUndefined()
71
- })
72
- store.addCommitCheck(() => ({ afterRevert }))
73
- store.atomic(() => {
74
- store.put([author])
75
- store.update(book.id, (b) => ({ ...b, title: 'changed' }))
76
- store.remove([book.id])
77
- })
78
- expect(store.get(book.id)).toEqual(book)
79
- expect(store.get(author.id)).toBeUndefined()
80
- expect(afterRevert).toHaveBeenCalledTimes(1)
81
- })
82
-
83
- it('leave nothing for listeners or history interceptors to apply after a refusal', () => {
84
- store.put([book])
85
- const listener = vi.fn()
86
- store.listen(listener, { scope: 'document' })
87
- const squashed: RecordsDiff<Library>[] = []
88
- store.addHistoryInterceptor((entry) => squashed.push(entry.changes))
89
- store.addCommitCheck(() => ({}))
90
- store.update(book.id, (b) => ({ ...b, title: 'changed' }))
91
- store.put([author])
92
- store._flushHistory()
93
- // whatever reached them must net out to the store as it was
94
- const applied = new Store({
95
- props: {},
96
- schema: StoreSchema.create<Library>({ book: Book, author: Author }),
97
- })
98
- applied.put([book])
99
- for (const diff of squashed) applied.applyDiff(diff)
100
- expect(applied.serialize('document')).toEqual(store.serialize('document'))
101
- })
102
-
103
- it('never check remote changes', () => {
104
- const check = vi.fn(() => ({}))
105
- store.addCommitCheck(check)
106
- store.mergeRemoteChanges(() => store.put([book]))
107
- expect(check).not.toHaveBeenCalled()
108
- expect(store.get(book.id)).toEqual(book)
109
- })
110
-
111
- it('stop checking once removed', () => {
112
- const remove = store.addCommitCheck(() => ({}))
113
- remove()
114
- store.put([book])
115
- expect(store.get(book.id)).toEqual(book)
116
- })
117
-
118
- it('check a scope as one operation, once, with every store operation inside it', () => {
119
- const seen: RecordsDiff<Library>[] = []
120
- store.addCommitCheck((changes) => (seen.push(changes), null))
121
- store.checkAsOneOperation(() => {
122
- store.put([book])
123
- store.put([author])
124
- })
125
- expect(seen.map(ids)).toEqual([{ added: [author.id, book.id], updated: [], removed: [] }])
126
- })
127
-
128
- it('revert every store operation of a refused scope', () => {
129
- store.put([book])
130
- store.addCommitCheck((changes) => (author.id in changes.added ? {} : null))
131
- store.checkAsOneOperation(() => {
132
- store.update(book.id, (b) => ({ ...b, title: 'changed' }))
133
- store.put([author])
134
- })
135
- expect(store.get(book.id)).toEqual(book)
136
- expect(store.get(author.id)).toBeUndefined()
137
- })
138
-
139
- it("keep a scope's changes from listeners until its check has run", () => {
140
- const heard: string[] = []
141
- store.listen(({ changes }) => heard.push(...Object.keys(changes.added)), { scope: 'document' })
142
- store.addCommitCheck((changes) => (author.id in changes.added ? {} : null))
143
- store.checkAsOneOperation(() => {
144
- // an editor `run` is a transaction, so the history reactor fires when it ends
145
- transact(() => store.put([author]))
146
- // and anything may flush history by hand
147
- store._flushHistory()
148
- })
149
- store._flushHistory()
150
- expect(heard).toEqual([])
151
-
152
- store.checkAsOneOperation(() => store.put([book]))
153
- store._flushHistory()
154
- expect(heard).toEqual([book.id])
155
- })
156
-
157
- it('report how each checked operation settled, before the check hears of a refusal', () => {
158
- const order: string[] = []
159
- store.onCheckedOperationSettled((outcome) => order.push(outcome))
160
- store.addCommitCheck((changes) =>
161
- author.id in changes.added ? { afterRevert: () => order.push('afterRevert') } : null
162
- )
163
- store.put([book])
164
- store.put([author])
165
- // remote and unchecked writes aren't checked operations
166
- store.mergeRemoteChanges(() => store.update(book.id, (b) => ({ ...b, title: 'remote' })))
167
- store.runUnchecked(() => store.update(book.id, (b) => ({ ...b, title: 'unchecked' })))
168
- expect(order).toEqual(['accepted', 'refused', 'afterRevert'])
169
- })
170
-
171
- it('settle an operation that throws as aborted, after it rolled back, without checking it', () => {
172
- const order: string[] = []
173
- const check = vi.fn(() => null)
174
- store.addCommitCheck(check)
175
- store.onCheckedOperationSettled((outcome) => order.push(`${outcome}:${store.has(book.id)}`))
176
- expect(() =>
177
- store.atomic(() => {
178
- store.put([book])
179
- throw new Error('boom')
180
- })
181
- ).toThrow('boom')
182
- expect(() =>
183
- store.checkAsOneOperation(() => {
184
- store.put([book])
185
- throw new Error('boom')
186
- })
187
- ).toThrow('boom')
188
- expect(order).toEqual(['aborted:false', 'aborted:false'])
189
- expect(check).not.toHaveBeenCalled()
190
- // the store keeps working, and checks the next operation
191
- store.put([book])
192
- expect(check).toHaveBeenCalledTimes(1)
193
- })
194
-
195
- it('roll back a unit that throws inside an outer transaction, and only that unit', () => {
196
- const outcomes: string[] = []
197
- store.addCommitCheck(() => null)
198
- store.onCheckedOperationSettled((outcome) => outcomes.push(outcome))
199
- transact(() => {
200
- store.put([author])
201
- try {
202
- store.checkAsOneOperation(() => {
203
- store.put([book])
204
- throw new Error('boom')
205
- })
206
- } catch {
207
- // the caller recovers and the outer transaction carries on
208
- }
209
- })
210
- expect([store.has(author.id), store.has(book.id)]).toEqual([true, false])
211
- expect(outcomes).toEqual(['accepted', 'aborted'])
212
- })
213
- })