@tldraw/state 5.7.0-next.fa882a2e4018 → 5.8.0-canary.15ae3e10cc28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-cjs/index.d.ts +6 -0
- package/dist-cjs/index.js +4 -1
- package/dist-cjs/index.js.map +2 -2
- package/dist-cjs/lib/transactions.js +102 -5
- package/dist-cjs/lib/transactions.js.map +2 -2
- package/dist-esm/index.d.mts +6 -0
- package/dist-esm/index.mjs +12 -2
- package/dist-esm/index.mjs.map +2 -2
- package/dist-esm/lib/transactions.mjs +102 -5
- package/dist-esm/lib/transactions.mjs.map +2 -2
- package/package.json +2 -2
- package/src/index.ts +8 -1
- package/src/lib/__tests__/deferAsyncEffects.test.ts +21 -1
- package/src/lib/__tests__/transactions.test.ts +132 -1
- package/src/lib/transactions.ts +142 -6
package/dist-cjs/index.d.ts
CHANGED
|
@@ -92,6 +92,8 @@ export declare interface AtomOptions<Value, Diff> {
|
|
|
92
92
|
isEqual?(a: any, b: any): boolean;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
/* Excluded from this release type: beforeTransactionCommit */
|
|
96
|
+
|
|
95
97
|
/* Excluded from this release type: Child */
|
|
96
98
|
|
|
97
99
|
/**
|
|
@@ -450,6 +452,8 @@ export declare const EMPTY_ARRAY: [];
|
|
|
450
452
|
*/
|
|
451
453
|
export declare function getComputedInstance<Obj extends object, Prop extends keyof Obj>(obj: Obj, propertyName: Prop): Computed<Obj[Prop] extends () => infer Value ? Value : Obj[Prop]>;
|
|
452
454
|
|
|
455
|
+
/* Excluded from this release type: getValueBeforeTransaction */
|
|
456
|
+
|
|
453
457
|
/**
|
|
454
458
|
* Returns true if the given value is an {@link Atom}.
|
|
455
459
|
*
|
|
@@ -546,6 +550,8 @@ export declare function isUninitialized(value: any): value is UNINITIALIZED;
|
|
|
546
550
|
*/
|
|
547
551
|
export declare function localStorageAtom<Value, Diff = unknown>(name: string, initialValue: Value, options?: AtomOptions<Value, Diff>): [Atom<Value, Diff>, () => void];
|
|
548
552
|
|
|
553
|
+
/* Excluded from this release type: onTransactionAbort */
|
|
554
|
+
|
|
549
555
|
/**
|
|
550
556
|
* Starts a new effect scheduler, scheduling the effect immediately.
|
|
551
557
|
*
|
package/dist-cjs/index.js
CHANGED
|
@@ -24,13 +24,16 @@ __export(index_exports, {
|
|
|
24
24
|
RESET_VALUE: () => import_types.RESET_VALUE,
|
|
25
25
|
UNINITIALIZED: () => import_Computed.UNINITIALIZED,
|
|
26
26
|
atom: () => import_Atom.atom,
|
|
27
|
+
beforeTransactionCommit: () => import_transactions.beforeTransactionCommit,
|
|
27
28
|
computed: () => import_Computed.computed,
|
|
28
29
|
deferAsyncEffects: () => import_transactions.deferAsyncEffects,
|
|
29
30
|
getComputedInstance: () => import_Computed.getComputedInstance,
|
|
31
|
+
getValueBeforeTransaction: () => import_transactions.getValueBeforeTransaction,
|
|
30
32
|
isAtom: () => import_Atom.isAtom,
|
|
31
33
|
isSignal: () => import_isSignal.isSignal,
|
|
32
34
|
isUninitialized: () => import_Computed.isUninitialized,
|
|
33
35
|
localStorageAtom: () => import_localStorageAtom.localStorageAtom,
|
|
36
|
+
onTransactionAbort: () => import_transactions.onTransactionAbort,
|
|
34
37
|
react: () => import_EffectScheduler.react,
|
|
35
38
|
reactor: () => import_EffectScheduler.reactor,
|
|
36
39
|
transact: () => import_transactions.transact,
|
|
@@ -61,7 +64,7 @@ if (actualApiVersion !== currentApiVersion) {
|
|
|
61
64
|
}
|
|
62
65
|
(0, import_utils.registerTldrawLibraryVersion)(
|
|
63
66
|
"@tldraw/state",
|
|
64
|
-
"5.
|
|
67
|
+
"5.8.0-canary.15ae3e10cc28",
|
|
65
68
|
"cjs"
|
|
66
69
|
);
|
|
67
70
|
//# sourceMappingURL=index.js.map
|
package/dist-cjs/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { registerTldrawLibraryVersion } from '@tldraw/utils'\nimport { singleton } from './lib/helpers'\n\nexport { ArraySet } from './lib/ArraySet'\nexport { atom, isAtom } from './lib/Atom'\nexport type { Atom, AtomOptions } from './lib/Atom'\nexport { unsafe__withoutCapture, whyAmIRunning } from './lib/capture'\nexport {\n\tcomputed,\n\tgetComputedInstance,\n\tisUninitialized,\n\tUNINITIALIZED,\n\twithDiff,\n} from './lib/Computed'\nexport type { Computed, ComputedOptions, WithDiff } from './lib/Computed'\nexport { EffectScheduler, react, reactor } from './lib/EffectScheduler'\nexport type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'\nexport { EMPTY_ARRAY } from './lib/helpers'\nexport { isSignal } from './lib/isSignal'\nexport { localStorageAtom } from './lib/localStorageAtom'\nexport {
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA6C;AAC7C,qBAA0B;AAE1B,sBAAyB;AACzB,kBAA6B;AAE7B,qBAAsD;AACtD,sBAMO;AAEP,6BAAgD;AAEhD,IAAAA,kBAA4B;AAC5B,sBAAyB;AACzB,8BAAiC;AACjC,
|
|
4
|
+
"sourcesContent": ["import { registerTldrawLibraryVersion } from '@tldraw/utils'\nimport { singleton } from './lib/helpers'\n\nexport { ArraySet } from './lib/ArraySet'\nexport { atom, isAtom } from './lib/Atom'\nexport type { Atom, AtomOptions } from './lib/Atom'\nexport { unsafe__withoutCapture, whyAmIRunning } from './lib/capture'\nexport {\n\tcomputed,\n\tgetComputedInstance,\n\tisUninitialized,\n\tUNINITIALIZED,\n\twithDiff,\n} from './lib/Computed'\nexport type { Computed, ComputedOptions, WithDiff } from './lib/Computed'\nexport { EffectScheduler, react, reactor } from './lib/EffectScheduler'\nexport type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'\nexport { EMPTY_ARRAY } from './lib/helpers'\nexport { isSignal } from './lib/isSignal'\nexport { localStorageAtom } from './lib/localStorageAtom'\nexport {\n\tbeforeTransactionCommit,\n\tdeferAsyncEffects,\n\tgetValueBeforeTransaction,\n\tonTransactionAbort,\n\ttransact,\n\ttransaction,\n} from './lib/transactions'\nexport { RESET_VALUE } from './lib/types'\nexport type { Child, ComputeDiff, Signal } from './lib/types'\n\n// This should be incremented any time an API change is made. i.e. for additions or removals.\n// Bugfixes need not increment this.\nconst currentApiVersion = 1\n\nconst actualApiVersion = singleton('apiVersion', () => currentApiVersion)\n\nif (actualApiVersion !== currentApiVersion) {\n\tthrow new Error(\n\t\t`You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.`\n\t)\n}\n\nregisterTldrawLibraryVersion(\n\t(globalThis as any).TLDRAW_LIBRARY_NAME,\n\t(globalThis as any).TLDRAW_LIBRARY_VERSION,\n\t(globalThis as any).TLDRAW_LIBRARY_MODULES\n)\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA6C;AAC7C,qBAA0B;AAE1B,sBAAyB;AACzB,kBAA6B;AAE7B,qBAAsD;AACtD,sBAMO;AAEP,6BAAgD;AAEhD,IAAAA,kBAA4B;AAC5B,sBAAyB;AACzB,8BAAiC;AACjC,0BAOO;AACP,mBAA4B;AAK5B,MAAM,oBAAoB;AAE1B,MAAM,uBAAmB,0BAAU,cAAc,MAAM,iBAAiB;AAExE,IAAI,qBAAqB,mBAAmB;AAC3C,QAAM,IAAI;AAAA,IACT;AAAA,EACD;AACD;AAAA,IAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AACF;",
|
|
6
6
|
"names": ["import_helpers"]
|
|
7
7
|
}
|
|
@@ -20,9 +20,12 @@ var transactions_exports = {};
|
|
|
20
20
|
__export(transactions_exports, {
|
|
21
21
|
advanceGlobalEpoch: () => advanceGlobalEpoch,
|
|
22
22
|
atomDidChange: () => atomDidChange,
|
|
23
|
+
beforeTransactionCommit: () => beforeTransactionCommit,
|
|
23
24
|
deferAsyncEffects: () => deferAsyncEffects,
|
|
24
25
|
getGlobalEpoch: () => getGlobalEpoch,
|
|
25
26
|
getIsInTransaction: () => getIsInTransaction,
|
|
27
|
+
getValueBeforeTransaction: () => getValueBeforeTransaction,
|
|
28
|
+
onTransactionAbort: () => onTransactionAbort,
|
|
26
29
|
transact: () => transact,
|
|
27
30
|
transaction: () => transaction
|
|
28
31
|
});
|
|
@@ -38,11 +41,18 @@ class Transaction {
|
|
|
38
41
|
isSync;
|
|
39
42
|
asyncProcessCount = 0;
|
|
40
43
|
initialAtomValues = /* @__PURE__ */ new Map();
|
|
44
|
+
// See `onTransactionAbort`. Oldest first.
|
|
45
|
+
abortCallbacks = null;
|
|
46
|
+
// See `beforeTransactionCommit`. Oldest first.
|
|
47
|
+
commitCallbacks = null;
|
|
41
48
|
commit() {
|
|
42
49
|
if (this.parent === null) {
|
|
43
50
|
flushChanges(this.initialAtomValues.keys());
|
|
44
51
|
return;
|
|
45
52
|
}
|
|
53
|
+
const parent = this.parent;
|
|
54
|
+
parent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks);
|
|
55
|
+
parent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks);
|
|
46
56
|
const parentValues = this.parent.initialAtomValues;
|
|
47
57
|
if (parentValues.size === 0) {
|
|
48
58
|
this.parent.initialAtomValues = this.initialAtomValues;
|
|
@@ -54,6 +64,31 @@ class Transaction {
|
|
|
54
64
|
}
|
|
55
65
|
});
|
|
56
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* Run the callbacks registered with `beforeTransactionCommit`, including any that they
|
|
69
|
+
* register. Only a root transaction has a commit of its own to prepare for: a nested one hands
|
|
70
|
+
* its callbacks to its parent. Returns true if a callback asked for a rollback.
|
|
71
|
+
*/
|
|
72
|
+
prepare() {
|
|
73
|
+
if (this.parent !== null) return false;
|
|
74
|
+
let rollback = false;
|
|
75
|
+
const requestRollback = () => {
|
|
76
|
+
rollback = true;
|
|
77
|
+
};
|
|
78
|
+
let passes = 0;
|
|
79
|
+
while (this.commitCallbacks) {
|
|
80
|
+
if (passes++ > 100) {
|
|
81
|
+
throw new Error("Commit callback depth limit exceeded");
|
|
82
|
+
}
|
|
83
|
+
const callbacks = this.commitCallbacks;
|
|
84
|
+
this.commitCallbacks = null;
|
|
85
|
+
for (let i = 0; i < callbacks.length; i++) {
|
|
86
|
+
callbacks[i](requestRollback);
|
|
87
|
+
if (rollback) return true;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
57
92
|
/**
|
|
58
93
|
* Abort the transaction. Restores every atom changed in this transaction to its initial
|
|
59
94
|
* value, then commits. Must be called while this is still `inst.currentTransaction`, so that
|
|
@@ -67,9 +102,35 @@ class Transaction {
|
|
|
67
102
|
atom.set(value);
|
|
68
103
|
atom.historyBuffer?.clear();
|
|
69
104
|
});
|
|
105
|
+
const callbacks = this.abortCallbacks;
|
|
106
|
+
this.abortCallbacks = null;
|
|
107
|
+
this.commitCallbacks = null;
|
|
108
|
+
let failure = null;
|
|
109
|
+
if (callbacks) {
|
|
110
|
+
for (let i = callbacks.length - 1; i >= 0; i--) {
|
|
111
|
+
try {
|
|
112
|
+
callbacks[i]();
|
|
113
|
+
} catch (error) {
|
|
114
|
+
failure ??= { error };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
70
118
|
this.commit();
|
|
119
|
+
if (failure) throw failure.error;
|
|
71
120
|
}
|
|
72
121
|
}
|
|
122
|
+
function abortAfterError(txn) {
|
|
123
|
+
try {
|
|
124
|
+
txn.abort();
|
|
125
|
+
} catch {
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function concatCallbacks(parent, child) {
|
|
129
|
+
if (!child) return parent;
|
|
130
|
+
if (!parent) return child;
|
|
131
|
+
for (let i = 0; i < child.length; i++) parent.push(child[i]);
|
|
132
|
+
return parent;
|
|
133
|
+
}
|
|
73
134
|
const inst = (0, import_helpers.singleton)("transactions", () => ({
|
|
74
135
|
// The current epoch (global to all atoms).
|
|
75
136
|
globalEpoch: import_constants.GLOBAL_START_EPOCH + 1,
|
|
@@ -134,6 +195,26 @@ function flushChanges(atoms) {
|
|
|
134
195
|
traverseReactors = void 0;
|
|
135
196
|
}
|
|
136
197
|
}
|
|
198
|
+
function onTransactionAbort(undo) {
|
|
199
|
+
const txn = inst.currentTransaction;
|
|
200
|
+
if (!txn) return;
|
|
201
|
+
if (txn.abortCallbacks) txn.abortCallbacks.push(undo);
|
|
202
|
+
else txn.abortCallbacks = [undo];
|
|
203
|
+
}
|
|
204
|
+
function beforeTransactionCommit(fn) {
|
|
205
|
+
const txn = inst.currentTransaction;
|
|
206
|
+
if (!txn) return;
|
|
207
|
+
if (txn.commitCallbacks) txn.commitCallbacks.push(fn);
|
|
208
|
+
else txn.commitCallbacks = [fn];
|
|
209
|
+
}
|
|
210
|
+
function getValueBeforeTransaction(atom) {
|
|
211
|
+
let value = atom.__unsafe__getWithoutCapture();
|
|
212
|
+
for (let txn = inst.currentTransaction; txn; txn = txn.parent) {
|
|
213
|
+
const initialValues = txn.initialAtomValues;
|
|
214
|
+
if (initialValues.has(atom)) value = initialValues.get(atom);
|
|
215
|
+
}
|
|
216
|
+
return value;
|
|
217
|
+
}
|
|
137
218
|
function atomDidChange(atom, previousValue) {
|
|
138
219
|
if (inst.currentTransaction) {
|
|
139
220
|
if (!inst.currentTransaction.initialAtomValues.has(atom)) {
|
|
@@ -159,12 +240,20 @@ function transaction(fn) {
|
|
|
159
240
|
try {
|
|
160
241
|
result = fn(() => rollback = true);
|
|
161
242
|
} catch (e) {
|
|
162
|
-
txn
|
|
243
|
+
abortAfterError(txn);
|
|
163
244
|
throw e;
|
|
164
245
|
}
|
|
165
246
|
if (inst.currentTransaction !== txn) {
|
|
166
247
|
throw new Error("Transaction boundaries overlap");
|
|
167
248
|
}
|
|
249
|
+
if (!rollback) {
|
|
250
|
+
try {
|
|
251
|
+
if (txn.prepare()) rollback = true;
|
|
252
|
+
} catch (e) {
|
|
253
|
+
abortAfterError(txn);
|
|
254
|
+
throw e;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
168
257
|
if (rollback) {
|
|
169
258
|
txn.abort();
|
|
170
259
|
} else {
|
|
@@ -207,13 +296,21 @@ async function deferAsyncEffects(fn) {
|
|
|
207
296
|
}
|
|
208
297
|
}
|
|
209
298
|
try {
|
|
299
|
+
let rollback = false;
|
|
300
|
+
if (typeof error === "undefined") {
|
|
301
|
+
try {
|
|
302
|
+
rollback = txn.prepare();
|
|
303
|
+
} catch (e) {
|
|
304
|
+
error = e ?? null;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
210
307
|
if (typeof error !== "undefined") {
|
|
211
|
-
txn
|
|
308
|
+
abortAfterError(txn);
|
|
212
309
|
throw error;
|
|
213
|
-
} else {
|
|
214
|
-
txn.commit();
|
|
215
|
-
return result;
|
|
216
310
|
}
|
|
311
|
+
if (rollback) txn.abort();
|
|
312
|
+
else txn.commit();
|
|
313
|
+
return result;
|
|
217
314
|
} finally {
|
|
218
315
|
inst.currentTransaction = null;
|
|
219
316
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/transactions.ts"],
|
|
4
|
-
"sourcesContent": ["import { _Atom } from './Atom'\nimport { GLOBAL_START_EPOCH } from './constants'\nimport { singleton } from './helpers'\nimport { Child, Signal } from './types'\n\ninterface Reactor {\n\tmaybeScheduleEffect(): void\n\tlastTraversedEpoch: number\n}\n\nclass Transaction {\n\tasyncProcessCount = 0\n\tconstructor(\n\t\tpublic readonly parent: Transaction | null,\n\t\tpublic readonly isSync: boolean\n\t) {}\n\n\tinitialAtomValues = new Map<_Atom, any>()\n\n\tcommit() {\n\t\tif (this.parent === null) {\n\t\t\t// For root transactions, flush changed atoms\n\t\t\tflushChanges(this.initialAtomValues.keys())\n\t\t\treturn\n\t\t}\n\t\t// For transactions with parents, add the transaction's initial values to the parent's, so\n\t\t// an outer rollback can still undo them (T7). This must come before any \"are we reacting?\" special case: a nested\n\t\t// transaction committed by an effect during the reaction phase used to skip this fold and\n\t\t// its changes survived the outer rollback.\n\t\t// A parent that has recorded nothing yet adopts the map outright: this transaction is\n\t\t// finished with it, and the common nested case is a single inner transaction doing all\n\t\t// the writes.\n\t\tconst parentValues = this.parent!.initialAtomValues\n\t\tif (parentValues.size === 0) {\n\t\t\tthis.parent!.initialAtomValues = this.initialAtomValues\n\t\t\treturn\n\t\t}\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tif (!parentValues.has(atom)) {\n\t\t\t\tparentValues.set(atom, value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Abort the transaction. Restores every atom changed in this transaction to its initial\n\t * value, then commits. Must be called while this is still `inst.currentTransaction`, so that\n\t * the restoring sets are recorded against it instead of each flushing effects on their own.\n\t *\n\t * @public\n\t */\n\tabort() {\n\t\tinst.globalEpoch++\n\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tatom.set(value)\n\t\t\tatom.historyBuffer?.clear()\n\t\t})\n\n\t\tthis.commit()\n\t}\n}\n\nconst inst = singleton('transactions', () => ({\n\t// The current epoch (global to all atoms).\n\tglobalEpoch: GLOBAL_START_EPOCH + 1,\n\t// Whether any transaction is reacting.\n\tglobalIsReacting: false,\n\tcurrentTransaction: null as Transaction | null,\n\n\tcleanupReactors: null as null | Set<Reactor>,\n}))\n\n/**\n * Gets the current global epoch, which is incremented every time any atom changes.\n * This is used to track changes across the entire reactive system.\n *\n * @returns The current global epoch number\n * @public\n */\nexport function getGlobalEpoch() {\n\treturn inst.globalEpoch\n}\n\n/**\n * Whether a transaction (sync or async) is currently open. While one is, atom changes are\n * recorded but their children are not traversed until it commits.\n *\n * @internal\n */\nexport function getIsInTransaction() {\n\treturn inst.currentTransaction !== null\n}\n\n// The set `traverseChild` collects reactors into. Module-level rather than a closure so that a\n// flush over thousands of atoms doesn't allocate a visitor per atom; traversal never runs user\n// code, so nothing can re-enter and swap it mid-walk.\nlet traverseReactors: Set<Reactor>\n\nfunction traverseChild(child: Child) {\n\tif (child.lastTraversedEpoch === inst.globalEpoch) {\n\t\treturn\n\t}\n\n\tchild.lastTraversedEpoch = inst.globalEpoch\n\n\tif ('__isEffectScheduler' in child) {\n\t\ttraverseReactors.add(child as unknown as Reactor)\n\t} else {\n\t\t;(child as any as Signal<any>).children.visit(traverseChild)\n\t}\n}\n\n/**\n * Collect all of the reactors that need to run for an atom and run them. During the reaction\n * phase the affected effects are instead queued for the cleanup pass, so a change made by an\n * effect never interrupts the pass that is running (P4).\n *\n * @param atoms - The atoms to flush changes for.\n */\nfunction flushChanges(atoms: Iterable<_Atom>) {\n\tif (inst.globalIsReacting) {\n\t\tfor (const atom of atoms) {\n\t\t\ttraverseAtomForCleanup(atom)\n\t\t}\n\t\treturn\n\t}\n\n\tconst outerTxn = inst.currentTransaction\n\ttry {\n\t\t// clear the transaction stack. Transactions started by effects must be roots: the committing\n\t\t// transaction (if any) has already handed its changes to this flush.\n\t\tinst.currentTransaction = null\n\t\tinst.globalIsReacting = true\n\n\t\tconst reactors = new Set<Reactor>()\n\t\ttraverseReactors = reactors\n\t\tfor (const atom of atoms) {\n\t\t\tatom.children.visit(traverseChild)\n\t\t}\n\n\t\t// Run each reactor.\n\t\tfor (const r of reactors) {\n\t\t\tr.maybeScheduleEffect()\n\t\t}\n\n\t\tlet updateDepth = 0\n\t\twhile (inst.cleanupReactors?.size) {\n\t\t\tif (updateDepth++ > 1000) {\n\t\t\t\tthrow new Error('Reaction update depth limit exceeded')\n\t\t\t}\n\t\t\tconst reactors = inst.cleanupReactors\n\t\t\tinst.cleanupReactors = null\n\t\t\tfor (const r of reactors) {\n\t\t\t\tr.maybeScheduleEffect()\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tinst.cleanupReactors = null\n\t\tinst.globalIsReacting = false\n\t\tinst.currentTransaction = outerTxn\n\t\ttraverseReactors = undefined! // free memory\n\t}\n}\n\n/** @internal */\nexport function atomDidChange(atom: _Atom, previousValue: any) {\n\tif (inst.currentTransaction) {\n\t\t// If we are in a transaction, then all we have to do is preserve\n\t\t// the value of the atom at the start of the transaction in case\n\t\t// we need to roll back. Children are not traversed until the\n\t\t// transaction commits, which is why `Computed` must not trust its\n\t\t// traversal-based cache shortcut while a transaction is open.\n\t\tif (!inst.currentTransaction.initialAtomValues.has(atom)) {\n\t\t\tinst.currentTransaction.initialAtomValues.set(atom, previousValue)\n\t\t}\n\t} else {\n\t\t// If there is no transaction, flush the changes immediately.\n\t\tflushChanges([atom])\n\t}\n}\n\nfunction traverseAtomForCleanup(atom: _Atom) {\n\ttraverseReactors = inst.cleanupReactors ??= new Set()\n\tatom.children.visit(traverseChild)\n}\n\n/** @internal */\nexport function advanceGlobalEpoch() {\n\tinst.globalEpoch++\n}\n\n/**\n * Batches state updates, deferring side effects until after the transaction completes.\n * Unlike {@link transact}, this function always creates a new transaction, allowing for nested transactions.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * })\n *\n * // Logs \"Hello, Jane Smith!\"\n * ```\n *\n * If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * throw new Error('oops')\n * })\n *\n * // firstName.get() === 'John'\n * // Logs \"Hello, John Doe!\" again: effects whose parents were changed and restored still run,\n * // and observe the restored values.\n * ```\n *\n * A `rollback` callback is passed into the function.\n * Calling this will prevent the transaction from committing and will revert any signals that were updated during the transaction to their state before the transaction began.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction((rollback) => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * rollback()\n * })\n *\n * // firstName.get() === 'John'\n * // lastName.get() === 'Doe'\n * // Logs \"Hello, John Doe!\" again, as above.\n * ```\n *\n * @param fn - The function to run in a transaction, called with a function to roll back the change.\n * @returns The return value of the function\n * @public\n */\nexport function transaction<T>(fn: (rollback: () => void) => T) {\n\tconst txn = new Transaction(inst.currentTransaction, true)\n\n\tinst.currentTransaction = txn\n\n\ttry {\n\t\tlet result = undefined as T | undefined\n\t\tlet rollback = false\n\n\t\ttry {\n\t\t\tresult = fn(() => (rollback = true))\n\t\t} catch (e) {\n\t\t\ttxn.abort()\n\t\t\tthrow e\n\t\t}\n\n\t\tif (inst.currentTransaction !== txn) {\n\t\t\tthrow new Error('Transaction boundaries overlap')\n\t\t}\n\n\t\tif (rollback) {\n\t\t\ttxn.abort()\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t}\n\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = txn.parent\n\t}\n}\n\n/**\n * Like {@link transaction}, but does not create a new transaction if there is already one in progress.\n * This is the preferred way to batch state updates when you don't need the rollback functionality.\n *\n * @example\n * ```ts\n * const count = atom('count', 0)\n * const doubled = atom('doubled', 0)\n *\n * react('update doubled', () => {\n * console.log(`Count: ${count.get()}, Doubled: ${doubled.get()}`)\n * })\n *\n * // This batches both updates into a single reaction\n * transact(() => {\n * count.set(5)\n * doubled.set(count.get() * 2)\n * })\n * // Logs: \"Count: 5, Doubled: 10\"\n * ```\n *\n * @param fn - The function to run in a transaction\n * @returns The return value of the function\n * @public\n */\nexport function transact<T>(fn: () => T): T {\n\tif (inst.currentTransaction) {\n\t\treturn fn()\n\t}\n\treturn transaction(fn)\n}\n\n/**\n * Defers the execution of asynchronous effects until they can be properly handled.\n * This function creates an asynchronous transaction context that batches state updates\n * across async operations while preventing conflicts with synchronous transactions.\n *\n * @example\n * ```ts\n * const data = atom('data', null)\n * const loading = atom('loading', false)\n *\n * await deferAsyncEffects(async () => {\n * loading.set(true)\n * const result = await fetch('/api/data')\n * const json = await result.json()\n * data.set(json)\n * loading.set(false)\n * })\n * ```\n *\n * @param fn - The async function to execute within the deferred context\n * @returns A promise that resolves to the return value of the function\n * @throws Will throw if called during a synchronous transaction\n * @internal\n */\nexport async function deferAsyncEffects<T>(fn: () => Promise<T>) {\n\t// Can't kick off async transactions during a sync transaction because\n\t// the async transaction won't finish until after the sync transaction\n\t// is done.\n\tif (inst.currentTransaction?.isSync) {\n\t\tthrow new Error('deferAsyncEffects cannot be called during a sync transaction')\n\t}\n\n\t// Can't kick off async transactions during a reaction phase at the moment,\n\t// because the transaction stack is cleared after the reaction phase.\n\t// So wait until the path ahead is clear\n\twhile (inst.globalIsReacting) {\n\t\tawait new Promise((r) => queueMicrotask(() => r(null)))\n\t}\n\n\tconst txn = inst.currentTransaction ?? new Transaction(null, false)\n\n\t// don't think this can happen, but just in case\n\tif (txn.isSync) throw new Error('deferAsyncEffects cannot be called during a sync transaction')\n\n\tinst.currentTransaction = txn\n\ttxn.asyncProcessCount++\n\n\tlet result = undefined as T | undefined\n\n\t// `undefined` means \"did not throw\"; a thrown `undefined` is stored as `null` so it still counts.\n\tlet error = undefined as any\n\ttry {\n\t\t// Run the function.\n\t\tresult = await fn()\n\t} catch (e) {\n\t\t// Abort the transaction if the function throws.\n\t\terror = e ?? null\n\t}\n\n\tif (--txn.asyncProcessCount > 0) {\n\t\t// Other processes still share this transaction; it settles when the last one finishes.\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tthrow error\n\t\t} else {\n\t\t\treturn result\n\t\t}\n\t}\n\n\t// Settle while this is still the current transaction (see `Transaction.abort`): clearing it\n\t// first made every restoring set inside `abort()` flush effects on its own, so effects\n\t// observed half-restored state.\n\ttry {\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\ttxn.abort()\n\t\t\tthrow error\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t\treturn result\n\t\t}\n\t} finally {\n\t\tinst.currentTransaction = null\n\t}\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAAmC;AACnC,qBAA0B;AAQ1B,MAAM,YAAY;AAAA,EAEjB,YACiB,QACA,QACf;AAFe;AACA;AAAA,EACd;AAAA,EAFc;AAAA,EACA;AAAA,EAHjB,oBAAoB;AAAA,EAMpB,oBAAoB,oBAAI,IAAgB;AAAA,
|
|
4
|
+
"sourcesContent": ["import { _Atom, Atom } from './Atom'\nimport { GLOBAL_START_EPOCH } from './constants'\nimport { singleton } from './helpers'\nimport { Child, Signal } from './types'\n\ninterface Reactor {\n\tmaybeScheduleEffect(): void\n\tlastTraversedEpoch: number\n}\n\nclass Transaction {\n\tasyncProcessCount = 0\n\tconstructor(\n\t\tpublic readonly parent: Transaction | null,\n\t\tpublic readonly isSync: boolean\n\t) {}\n\n\tinitialAtomValues = new Map<_Atom, any>()\n\n\t// See `onTransactionAbort`. Oldest first.\n\tabortCallbacks: (() => void)[] | null = null\n\n\t// See `beforeTransactionCommit`. Oldest first.\n\tcommitCallbacks: CommitCallback[] | null = null\n\n\tcommit() {\n\t\tif (this.parent === null) {\n\t\t\t// For root transactions, flush changed atoms\n\t\t\tflushChanges(this.initialAtomValues.keys())\n\t\t\treturn\n\t\t}\n\t\t// For transactions with parents, add the transaction's initial values to the parent's, so\n\t\t// an outer rollback can still undo them (T7). This must come before any \"are we reacting?\" special case: a nested\n\t\t// transaction committed by an effect during the reaction phase used to skip this fold and\n\t\t// its changes survived the outer rollback.\n\t\t// A parent that has recorded nothing yet adopts the map outright: this transaction is\n\t\t// finished with it, and the common nested case is a single inner transaction doing all\n\t\t// the writes.\n\t\tconst parent = this.parent!\n\t\tparent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks)\n\t\tparent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks)\n\t\tconst parentValues = this.parent!.initialAtomValues\n\t\tif (parentValues.size === 0) {\n\t\t\tthis.parent!.initialAtomValues = this.initialAtomValues\n\t\t\treturn\n\t\t}\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tif (!parentValues.has(atom)) {\n\t\t\t\tparentValues.set(atom, value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Run the callbacks registered with `beforeTransactionCommit`, including any that they\n\t * register. Only a root transaction has a commit of its own to prepare for: a nested one hands\n\t * its callbacks to its parent. Returns true if a callback asked for a rollback.\n\t */\n\tprepare(): boolean {\n\t\tif (this.parent !== null) return false\n\t\tlet rollback = false\n\t\tconst requestRollback = () => {\n\t\t\trollback = true\n\t\t}\n\t\tlet passes = 0\n\t\twhile (this.commitCallbacks) {\n\t\t\tif (passes++ > 100) {\n\t\t\t\tthrow new Error('Commit callback depth limit exceeded')\n\t\t\t}\n\t\t\tconst callbacks = this.commitCallbacks\n\t\t\tthis.commitCallbacks = null\n\t\t\tfor (let i = 0; i < callbacks.length; i++) {\n\t\t\t\tcallbacks[i](requestRollback)\n\t\t\t\tif (rollback) return true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t/**\n\t * Abort the transaction. Restores every atom changed in this transaction to its initial\n\t * value, then commits. Must be called while this is still `inst.currentTransaction`, so that\n\t * the restoring sets are recorded against it instead of each flushing effects on their own.\n\t *\n\t * @public\n\t */\n\tabort() {\n\t\tinst.globalEpoch++\n\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tatom.set(value)\n\t\t\tatom.historyBuffer?.clear()\n\t\t})\n\n\t\t// Taken off before `commit`, which would otherwise hand them to the parent.\n\t\tconst callbacks = this.abortCallbacks\n\t\tthis.abortCallbacks = null\n\t\tthis.commitCallbacks = null\n\t\tlet failure: { error: unknown } | null = null\n\t\tif (callbacks) {\n\t\t\tfor (let i = callbacks.length - 1; i >= 0; i--) {\n\t\t\t\t// A throw must not skip the older callbacks: each one left out keeps its state wrong for good.\n\t\t\t\ttry {\n\t\t\t\t\tcallbacks[i]()\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailure ??= { error }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.commit()\n\t\tif (failure) throw failure.error\n\t}\n}\n\ntype CommitCallback = (rollback: () => void) => void\n\n// For an abort caused by `error`: a throw from an abort callback must not replace it.\nfunction abortAfterError(txn: Transaction) {\n\ttry {\n\t\ttxn.abort()\n\t} catch {\n\t\t// `error` is the one to report\n\t}\n}\n\nfunction concatCallbacks<T>(parent: T[] | null, child: T[] | null): T[] | null {\n\tif (!child) return parent\n\tif (!parent) return child\n\tfor (let i = 0; i < child.length; i++) parent.push(child[i])\n\treturn parent\n}\n\nconst inst = singleton('transactions', () => ({\n\t// The current epoch (global to all atoms).\n\tglobalEpoch: GLOBAL_START_EPOCH + 1,\n\t// Whether any transaction is reacting.\n\tglobalIsReacting: false,\n\tcurrentTransaction: null as Transaction | null,\n\n\tcleanupReactors: null as null | Set<Reactor>,\n}))\n\n/**\n * Gets the current global epoch, which is incremented every time any atom changes.\n * This is used to track changes across the entire reactive system.\n *\n * @returns The current global epoch number\n * @public\n */\nexport function getGlobalEpoch() {\n\treturn inst.globalEpoch\n}\n\n/**\n * Whether a transaction (sync or async) is currently open. While one is, atom changes are\n * recorded but their children are not traversed until it commits.\n *\n * @internal\n */\nexport function getIsInTransaction() {\n\treturn inst.currentTransaction !== null\n}\n\n// The set `traverseChild` collects reactors into. Module-level rather than a closure so that a\n// flush over thousands of atoms doesn't allocate a visitor per atom; traversal never runs user\n// code, so nothing can re-enter and swap it mid-walk.\nlet traverseReactors: Set<Reactor>\n\nfunction traverseChild(child: Child) {\n\tif (child.lastTraversedEpoch === inst.globalEpoch) {\n\t\treturn\n\t}\n\n\tchild.lastTraversedEpoch = inst.globalEpoch\n\n\tif ('__isEffectScheduler' in child) {\n\t\ttraverseReactors.add(child as unknown as Reactor)\n\t} else {\n\t\t;(child as any as Signal<any>).children.visit(traverseChild)\n\t}\n}\n\n/**\n * Collect all of the reactors that need to run for an atom and run them. During the reaction\n * phase the affected effects are instead queued for the cleanup pass, so a change made by an\n * effect never interrupts the pass that is running (P4).\n *\n * @param atoms - The atoms to flush changes for.\n */\nfunction flushChanges(atoms: Iterable<_Atom>) {\n\tif (inst.globalIsReacting) {\n\t\tfor (const atom of atoms) {\n\t\t\ttraverseAtomForCleanup(atom)\n\t\t}\n\t\treturn\n\t}\n\n\tconst outerTxn = inst.currentTransaction\n\ttry {\n\t\t// clear the transaction stack. Transactions started by effects must be roots: the committing\n\t\t// transaction (if any) has already handed its changes to this flush.\n\t\tinst.currentTransaction = null\n\t\tinst.globalIsReacting = true\n\n\t\tconst reactors = new Set<Reactor>()\n\t\ttraverseReactors = reactors\n\t\tfor (const atom of atoms) {\n\t\t\tatom.children.visit(traverseChild)\n\t\t}\n\n\t\t// Run each reactor.\n\t\tfor (const r of reactors) {\n\t\t\tr.maybeScheduleEffect()\n\t\t}\n\n\t\tlet updateDepth = 0\n\t\twhile (inst.cleanupReactors?.size) {\n\t\t\tif (updateDepth++ > 1000) {\n\t\t\t\tthrow new Error('Reaction update depth limit exceeded')\n\t\t\t}\n\t\t\tconst reactors = inst.cleanupReactors\n\t\t\tinst.cleanupReactors = null\n\t\t\tfor (const r of reactors) {\n\t\t\t\tr.maybeScheduleEffect()\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tinst.cleanupReactors = null\n\t\tinst.globalIsReacting = false\n\t\tinst.currentTransaction = outerTxn\n\t\ttraverseReactors = undefined! // free memory\n\t}\n}\n\n/**\n * Registers `undo` to run if the current transaction, or a transaction around it, rolls back. For\n * state kept outside atoms, which a rollback would otherwise leave as it is. Callbacks run newest\n * first, after the atoms are restored and before effects are flushed. They must not throw, and\n * must not change atoms or register callbacks: the transaction is already ending. Outside\n * a transaction nothing can roll back, so this does nothing.\n *\n * @internal\n */\nexport function onTransactionAbort(undo: () => void) {\n\tconst txn = inst.currentTransaction\n\tif (!txn) return\n\tif (txn.abortCallbacks) txn.abortCallbacks.push(undo)\n\telse txn.abortCallbacks = [undo]\n}\n\n/**\n * Registers `fn` to run when the outermost transaction is about to commit: every change is made,\n * no effect has run, and nothing outside the transaction has seen it. For checks on a transaction\n * as a whole. `fn` may change atoms and register further callbacks, which run before the same\n * commit. Calling `rollback` aborts the transaction and skips the callbacks that are left, and a\n * throw aborts it and propagates. Callbacks from a transaction that aborts never run. Outside a\n * transaction this does nothing.\n *\n * @internal\n */\nexport function beforeTransactionCommit(fn: (rollback: () => void) => void) {\n\tconst txn = inst.currentTransaction\n\tif (!txn) return\n\tif (txn.commitCallbacks) txn.commitCallbacks.push(fn)\n\telse txn.commitCallbacks = [fn]\n}\n\n/**\n * The value `atom` had before the outermost open transaction changed it, which is the value it\n * goes back to if that transaction rolls back. The atom's current value when no open transaction\n * has changed it.\n *\n * @internal\n */\nexport function getValueBeforeTransaction<T>(atom: Atom<T>): T {\n\tlet value = atom.__unsafe__getWithoutCapture()\n\tfor (let txn = inst.currentTransaction; txn; txn = txn.parent) {\n\t\tconst initialValues = txn.initialAtomValues\n\t\tif (initialValues.has(atom as any)) value = initialValues.get(atom as any)\n\t}\n\treturn value\n}\n\n/** @internal */\nexport function atomDidChange(atom: _Atom, previousValue: any) {\n\tif (inst.currentTransaction) {\n\t\t// If we are in a transaction, then all we have to do is preserve\n\t\t// the value of the atom at the start of the transaction in case\n\t\t// we need to roll back. Children are not traversed until the\n\t\t// transaction commits, which is why `Computed` must not trust its\n\t\t// traversal-based cache shortcut while a transaction is open.\n\t\tif (!inst.currentTransaction.initialAtomValues.has(atom)) {\n\t\t\tinst.currentTransaction.initialAtomValues.set(atom, previousValue)\n\t\t}\n\t} else {\n\t\t// If there is no transaction, flush the changes immediately.\n\t\tflushChanges([atom])\n\t}\n}\n\nfunction traverseAtomForCleanup(atom: _Atom) {\n\ttraverseReactors = inst.cleanupReactors ??= new Set()\n\tatom.children.visit(traverseChild)\n}\n\n/** @internal */\nexport function advanceGlobalEpoch() {\n\tinst.globalEpoch++\n}\n\n/**\n * Batches state updates, deferring side effects until after the transaction completes.\n * Unlike {@link transact}, this function always creates a new transaction, allowing for nested transactions.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * })\n *\n * // Logs \"Hello, Jane Smith!\"\n * ```\n *\n * If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * throw new Error('oops')\n * })\n *\n * // firstName.get() === 'John'\n * // Logs \"Hello, John Doe!\" again: effects whose parents were changed and restored still run,\n * // and observe the restored values.\n * ```\n *\n * A `rollback` callback is passed into the function.\n * Calling this will prevent the transaction from committing and will revert any signals that were updated during the transaction to their state before the transaction began.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction((rollback) => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * rollback()\n * })\n *\n * // firstName.get() === 'John'\n * // lastName.get() === 'Doe'\n * // Logs \"Hello, John Doe!\" again, as above.\n * ```\n *\n * @param fn - The function to run in a transaction, called with a function to roll back the change.\n * @returns The return value of the function\n * @public\n */\nexport function transaction<T>(fn: (rollback: () => void) => T) {\n\tconst txn = new Transaction(inst.currentTransaction, true)\n\n\tinst.currentTransaction = txn\n\n\ttry {\n\t\tlet result = undefined as T | undefined\n\t\tlet rollback = false\n\n\t\ttry {\n\t\t\tresult = fn(() => (rollback = true))\n\t\t} catch (e) {\n\t\t\tabortAfterError(txn)\n\t\t\tthrow e\n\t\t}\n\n\t\tif (inst.currentTransaction !== txn) {\n\t\t\tthrow new Error('Transaction boundaries overlap')\n\t\t}\n\n\t\tif (!rollback) {\n\t\t\ttry {\n\t\t\t\t// Never assign: a callback can call `fn`'s own `rollback`, which `prepare` can't see.\n\t\t\t\tif (txn.prepare()) rollback = true\n\t\t\t} catch (e) {\n\t\t\t\tabortAfterError(txn)\n\t\t\t\tthrow e\n\t\t\t}\n\t\t}\n\n\t\tif (rollback) {\n\t\t\ttxn.abort()\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t}\n\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = txn.parent\n\t}\n}\n\n/**\n * Like {@link transaction}, but does not create a new transaction if there is already one in progress.\n * This is the preferred way to batch state updates when you don't need the rollback functionality.\n *\n * @example\n * ```ts\n * const count = atom('count', 0)\n * const doubled = atom('doubled', 0)\n *\n * react('update doubled', () => {\n * console.log(`Count: ${count.get()}, Doubled: ${doubled.get()}`)\n * })\n *\n * // This batches both updates into a single reaction\n * transact(() => {\n * count.set(5)\n * doubled.set(count.get() * 2)\n * })\n * // Logs: \"Count: 5, Doubled: 10\"\n * ```\n *\n * @param fn - The function to run in a transaction\n * @returns The return value of the function\n * @public\n */\nexport function transact<T>(fn: () => T): T {\n\tif (inst.currentTransaction) {\n\t\treturn fn()\n\t}\n\treturn transaction(fn)\n}\n\n/**\n * Defers the execution of asynchronous effects until they can be properly handled.\n * This function creates an asynchronous transaction context that batches state updates\n * across async operations while preventing conflicts with synchronous transactions.\n *\n * @example\n * ```ts\n * const data = atom('data', null)\n * const loading = atom('loading', false)\n *\n * await deferAsyncEffects(async () => {\n * loading.set(true)\n * const result = await fetch('/api/data')\n * const json = await result.json()\n * data.set(json)\n * loading.set(false)\n * })\n * ```\n *\n * @param fn - The async function to execute within the deferred context\n * @returns A promise that resolves to the return value of the function\n * @throws Will throw if called during a synchronous transaction\n * @internal\n */\nexport async function deferAsyncEffects<T>(fn: () => Promise<T>) {\n\t// Can't kick off async transactions during a sync transaction because\n\t// the async transaction won't finish until after the sync transaction\n\t// is done.\n\tif (inst.currentTransaction?.isSync) {\n\t\tthrow new Error('deferAsyncEffects cannot be called during a sync transaction')\n\t}\n\n\t// Can't kick off async transactions during a reaction phase at the moment,\n\t// because the transaction stack is cleared after the reaction phase.\n\t// So wait until the path ahead is clear\n\twhile (inst.globalIsReacting) {\n\t\tawait new Promise((r) => queueMicrotask(() => r(null)))\n\t}\n\n\tconst txn = inst.currentTransaction ?? new Transaction(null, false)\n\n\t// don't think this can happen, but just in case\n\tif (txn.isSync) throw new Error('deferAsyncEffects cannot be called during a sync transaction')\n\n\tinst.currentTransaction = txn\n\ttxn.asyncProcessCount++\n\n\tlet result = undefined as T | undefined\n\n\t// `undefined` means \"did not throw\"; a thrown `undefined` is stored as `null` so it still counts.\n\tlet error = undefined as any\n\ttry {\n\t\t// Run the function.\n\t\tresult = await fn()\n\t} catch (e) {\n\t\t// Abort the transaction if the function throws.\n\t\terror = e ?? null\n\t}\n\n\tif (--txn.asyncProcessCount > 0) {\n\t\t// Other processes still share this transaction; it settles when the last one finishes.\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tthrow error\n\t\t} else {\n\t\t\treturn result\n\t\t}\n\t}\n\n\t// Settle while this is still the current transaction (see `Transaction.abort`): clearing it\n\t// first made every restoring set inside `abort()` flush effects on its own, so effects\n\t// observed half-restored state.\n\ttry {\n\t\tlet rollback = false\n\t\tif (typeof error === 'undefined') {\n\t\t\ttry {\n\t\t\t\trollback = txn.prepare()\n\t\t\t} catch (e) {\n\t\t\t\terror = e ?? null\n\t\t\t}\n\t\t}\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tabortAfterError(txn)\n\t\t\tthrow error\n\t\t}\n\t\tif (rollback) txn.abort()\n\t\telse txn.commit()\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = null\n\t}\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAAmC;AACnC,qBAA0B;AAQ1B,MAAM,YAAY;AAAA,EAEjB,YACiB,QACA,QACf;AAFe;AACA;AAAA,EACd;AAAA,EAFc;AAAA,EACA;AAAA,EAHjB,oBAAoB;AAAA,EAMpB,oBAAoB,oBAAI,IAAgB;AAAA;AAAA,EAGxC,iBAAwC;AAAA;AAAA,EAGxC,kBAA2C;AAAA,EAE3C,SAAS;AACR,QAAI,KAAK,WAAW,MAAM;AAEzB,mBA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sB,IAAI,YAAY,MAAM,KAAK;AAGlE,MAAI,IAAI,OAAQ,OAAM,IAAI,MAAM,8DAA8D;AAE9F,OAAK,qBAAqB;AAC1B,MAAI;AAEJ,MAAI,SAAS;AAGb,MAAI,QAAQ;AACZ,MAAI;AAEH,aAAS,MAAM,GAAG;AAAA,EACnB,SAAS,GAAG;AAEX,YAAQ,KAAK;AAAA,EACd;AAEA,MAAI,EAAE,IAAI,oBAAoB,GAAG;AAEhC,QAAI,OAAO,UAAU,aAAa;AAEjC,YAAM;AAAA,IACP,OAAO;AACN,aAAO;AAAA,IACR;AAAA,EACD;AAKA,MAAI;AACH,QAAI,WAAW;AACf,QAAI,OAAO,UAAU,aAAa;AACjC,UAAI;AACH,mBAAW,IAAI,QAAQ;AAAA,MACxB,SAAS,GAAG;AACX,gBAAQ,KAAK;AAAA,MACd;AAAA,IACD;AACA,QAAI,OAAO,UAAU,aAAa;AAEjC,sBAAgB,GAAG;AACnB,YAAM;AAAA,IACP;AACA,QAAI,SAAU,KAAI,MAAM;AAAA,QACnB,KAAI,OAAO;AAChB,WAAO;AAAA,EACR,UAAE;AACD,SAAK,qBAAqB;AAAA,EAC3B;AACD;",
|
|
6
6
|
"names": ["reactors"]
|
|
7
7
|
}
|
package/dist-esm/index.d.mts
CHANGED
|
@@ -92,6 +92,8 @@ export declare interface AtomOptions<Value, Diff> {
|
|
|
92
92
|
isEqual?(a: any, b: any): boolean;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
/* Excluded from this release type: beforeTransactionCommit */
|
|
96
|
+
|
|
95
97
|
/* Excluded from this release type: Child */
|
|
96
98
|
|
|
97
99
|
/**
|
|
@@ -450,6 +452,8 @@ export declare const EMPTY_ARRAY: [];
|
|
|
450
452
|
*/
|
|
451
453
|
export declare function getComputedInstance<Obj extends object, Prop extends keyof Obj>(obj: Obj, propertyName: Prop): Computed<Obj[Prop] extends () => infer Value ? Value : Obj[Prop]>;
|
|
452
454
|
|
|
455
|
+
/* Excluded from this release type: getValueBeforeTransaction */
|
|
456
|
+
|
|
453
457
|
/**
|
|
454
458
|
* Returns true if the given value is an {@link Atom}.
|
|
455
459
|
*
|
|
@@ -546,6 +550,8 @@ export declare function isUninitialized(value: any): value is UNINITIALIZED;
|
|
|
546
550
|
*/
|
|
547
551
|
export declare function localStorageAtom<Value, Diff = unknown>(name: string, initialValue: Value, options?: AtomOptions<Value, Diff>): [Atom<Value, Diff>, () => void];
|
|
548
552
|
|
|
553
|
+
/* Excluded from this release type: onTransactionAbort */
|
|
554
|
+
|
|
549
555
|
/**
|
|
550
556
|
* Starts a new effect scheduler, scheduling the effect immediately.
|
|
551
557
|
*
|
package/dist-esm/index.mjs
CHANGED
|
@@ -14,7 +14,14 @@ import { EffectScheduler, react, reactor } from "./lib/EffectScheduler.mjs";
|
|
|
14
14
|
import { EMPTY_ARRAY } from "./lib/helpers.mjs";
|
|
15
15
|
import { isSignal } from "./lib/isSignal.mjs";
|
|
16
16
|
import { localStorageAtom } from "./lib/localStorageAtom.mjs";
|
|
17
|
-
import {
|
|
17
|
+
import {
|
|
18
|
+
beforeTransactionCommit,
|
|
19
|
+
deferAsyncEffects,
|
|
20
|
+
getValueBeforeTransaction,
|
|
21
|
+
onTransactionAbort,
|
|
22
|
+
transact,
|
|
23
|
+
transaction
|
|
24
|
+
} from "./lib/transactions.mjs";
|
|
18
25
|
import { RESET_VALUE } from "./lib/types.mjs";
|
|
19
26
|
const currentApiVersion = 1;
|
|
20
27
|
const actualApiVersion = singleton("apiVersion", () => currentApiVersion);
|
|
@@ -25,7 +32,7 @@ if (actualApiVersion !== currentApiVersion) {
|
|
|
25
32
|
}
|
|
26
33
|
registerTldrawLibraryVersion(
|
|
27
34
|
"@tldraw/state",
|
|
28
|
-
"5.
|
|
35
|
+
"5.8.0-canary.15ae3e10cc28",
|
|
29
36
|
"esm"
|
|
30
37
|
);
|
|
31
38
|
export {
|
|
@@ -35,13 +42,16 @@ export {
|
|
|
35
42
|
RESET_VALUE,
|
|
36
43
|
UNINITIALIZED,
|
|
37
44
|
atom,
|
|
45
|
+
beforeTransactionCommit,
|
|
38
46
|
computed,
|
|
39
47
|
deferAsyncEffects,
|
|
40
48
|
getComputedInstance,
|
|
49
|
+
getValueBeforeTransaction,
|
|
41
50
|
isAtom,
|
|
42
51
|
isSignal,
|
|
43
52
|
isUninitialized,
|
|
44
53
|
localStorageAtom,
|
|
54
|
+
onTransactionAbort,
|
|
45
55
|
react,
|
|
46
56
|
reactor,
|
|
47
57
|
transact,
|
package/dist-esm/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { registerTldrawLibraryVersion } from '@tldraw/utils'\nimport { singleton } from './lib/helpers'\n\nexport { ArraySet } from './lib/ArraySet'\nexport { atom, isAtom } from './lib/Atom'\nexport type { Atom, AtomOptions } from './lib/Atom'\nexport { unsafe__withoutCapture, whyAmIRunning } from './lib/capture'\nexport {\n\tcomputed,\n\tgetComputedInstance,\n\tisUninitialized,\n\tUNINITIALIZED,\n\twithDiff,\n} from './lib/Computed'\nexport type { Computed, ComputedOptions, WithDiff } from './lib/Computed'\nexport { EffectScheduler, react, reactor } from './lib/EffectScheduler'\nexport type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'\nexport { EMPTY_ARRAY } from './lib/helpers'\nexport { isSignal } from './lib/isSignal'\nexport { localStorageAtom } from './lib/localStorageAtom'\nexport {
|
|
5
|
-
"mappings": "AAAA,SAAS,oCAAoC;AAC7C,SAAS,iBAAiB;AAE1B,SAAS,gBAAgB;AACzB,SAAS,MAAM,cAAc;AAE7B,SAAS,wBAAwB,qBAAqB;AACtD;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAEP,SAAS,iBAAiB,OAAO,eAAe;AAEhD,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,wBAAwB;AACjC,
|
|
4
|
+
"sourcesContent": ["import { registerTldrawLibraryVersion } from '@tldraw/utils'\nimport { singleton } from './lib/helpers'\n\nexport { ArraySet } from './lib/ArraySet'\nexport { atom, isAtom } from './lib/Atom'\nexport type { Atom, AtomOptions } from './lib/Atom'\nexport { unsafe__withoutCapture, whyAmIRunning } from './lib/capture'\nexport {\n\tcomputed,\n\tgetComputedInstance,\n\tisUninitialized,\n\tUNINITIALIZED,\n\twithDiff,\n} from './lib/Computed'\nexport type { Computed, ComputedOptions, WithDiff } from './lib/Computed'\nexport { EffectScheduler, react, reactor } from './lib/EffectScheduler'\nexport type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'\nexport { EMPTY_ARRAY } from './lib/helpers'\nexport { isSignal } from './lib/isSignal'\nexport { localStorageAtom } from './lib/localStorageAtom'\nexport {\n\tbeforeTransactionCommit,\n\tdeferAsyncEffects,\n\tgetValueBeforeTransaction,\n\tonTransactionAbort,\n\ttransact,\n\ttransaction,\n} from './lib/transactions'\nexport { RESET_VALUE } from './lib/types'\nexport type { Child, ComputeDiff, Signal } from './lib/types'\n\n// This should be incremented any time an API change is made. i.e. for additions or removals.\n// Bugfixes need not increment this.\nconst currentApiVersion = 1\n\nconst actualApiVersion = singleton('apiVersion', () => currentApiVersion)\n\nif (actualApiVersion !== currentApiVersion) {\n\tthrow new Error(\n\t\t`You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.`\n\t)\n}\n\nregisterTldrawLibraryVersion(\n\t(globalThis as any).TLDRAW_LIBRARY_NAME,\n\t(globalThis as any).TLDRAW_LIBRARY_VERSION,\n\t(globalThis as any).TLDRAW_LIBRARY_MODULES\n)\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oCAAoC;AAC7C,SAAS,iBAAiB;AAE1B,SAAS,gBAAgB;AACzB,SAAS,MAAM,cAAc;AAE7B,SAAS,wBAAwB,qBAAqB;AACtD;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AAEP,SAAS,iBAAiB,OAAO,eAAe;AAEhD,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAS,wBAAwB;AACjC;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACM;AACP,SAAS,mBAAmB;AAK5B,MAAM,oBAAoB;AAE1B,MAAM,mBAAmB,UAAU,cAAc,MAAM,iBAAiB;AAExE,IAAI,qBAAqB,mBAAmB;AAC3C,QAAM,IAAI;AAAA,IACT;AAAA,EACD;AACD;AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -9,11 +9,18 @@ class Transaction {
|
|
|
9
9
|
isSync;
|
|
10
10
|
asyncProcessCount = 0;
|
|
11
11
|
initialAtomValues = /* @__PURE__ */ new Map();
|
|
12
|
+
// See `onTransactionAbort`. Oldest first.
|
|
13
|
+
abortCallbacks = null;
|
|
14
|
+
// See `beforeTransactionCommit`. Oldest first.
|
|
15
|
+
commitCallbacks = null;
|
|
12
16
|
commit() {
|
|
13
17
|
if (this.parent === null) {
|
|
14
18
|
flushChanges(this.initialAtomValues.keys());
|
|
15
19
|
return;
|
|
16
20
|
}
|
|
21
|
+
const parent = this.parent;
|
|
22
|
+
parent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks);
|
|
23
|
+
parent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks);
|
|
17
24
|
const parentValues = this.parent.initialAtomValues;
|
|
18
25
|
if (parentValues.size === 0) {
|
|
19
26
|
this.parent.initialAtomValues = this.initialAtomValues;
|
|
@@ -25,6 +32,31 @@ class Transaction {
|
|
|
25
32
|
}
|
|
26
33
|
});
|
|
27
34
|
}
|
|
35
|
+
/**
|
|
36
|
+
* Run the callbacks registered with `beforeTransactionCommit`, including any that they
|
|
37
|
+
* register. Only a root transaction has a commit of its own to prepare for: a nested one hands
|
|
38
|
+
* its callbacks to its parent. Returns true if a callback asked for a rollback.
|
|
39
|
+
*/
|
|
40
|
+
prepare() {
|
|
41
|
+
if (this.parent !== null) return false;
|
|
42
|
+
let rollback = false;
|
|
43
|
+
const requestRollback = () => {
|
|
44
|
+
rollback = true;
|
|
45
|
+
};
|
|
46
|
+
let passes = 0;
|
|
47
|
+
while (this.commitCallbacks) {
|
|
48
|
+
if (passes++ > 100) {
|
|
49
|
+
throw new Error("Commit callback depth limit exceeded");
|
|
50
|
+
}
|
|
51
|
+
const callbacks = this.commitCallbacks;
|
|
52
|
+
this.commitCallbacks = null;
|
|
53
|
+
for (let i = 0; i < callbacks.length; i++) {
|
|
54
|
+
callbacks[i](requestRollback);
|
|
55
|
+
if (rollback) return true;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
28
60
|
/**
|
|
29
61
|
* Abort the transaction. Restores every atom changed in this transaction to its initial
|
|
30
62
|
* value, then commits. Must be called while this is still `inst.currentTransaction`, so that
|
|
@@ -38,9 +70,35 @@ class Transaction {
|
|
|
38
70
|
atom.set(value);
|
|
39
71
|
atom.historyBuffer?.clear();
|
|
40
72
|
});
|
|
73
|
+
const callbacks = this.abortCallbacks;
|
|
74
|
+
this.abortCallbacks = null;
|
|
75
|
+
this.commitCallbacks = null;
|
|
76
|
+
let failure = null;
|
|
77
|
+
if (callbacks) {
|
|
78
|
+
for (let i = callbacks.length - 1; i >= 0; i--) {
|
|
79
|
+
try {
|
|
80
|
+
callbacks[i]();
|
|
81
|
+
} catch (error) {
|
|
82
|
+
failure ??= { error };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
41
86
|
this.commit();
|
|
87
|
+
if (failure) throw failure.error;
|
|
42
88
|
}
|
|
43
89
|
}
|
|
90
|
+
function abortAfterError(txn) {
|
|
91
|
+
try {
|
|
92
|
+
txn.abort();
|
|
93
|
+
} catch {
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function concatCallbacks(parent, child) {
|
|
97
|
+
if (!child) return parent;
|
|
98
|
+
if (!parent) return child;
|
|
99
|
+
for (let i = 0; i < child.length; i++) parent.push(child[i]);
|
|
100
|
+
return parent;
|
|
101
|
+
}
|
|
44
102
|
const inst = singleton("transactions", () => ({
|
|
45
103
|
// The current epoch (global to all atoms).
|
|
46
104
|
globalEpoch: GLOBAL_START_EPOCH + 1,
|
|
@@ -105,6 +163,26 @@ function flushChanges(atoms) {
|
|
|
105
163
|
traverseReactors = void 0;
|
|
106
164
|
}
|
|
107
165
|
}
|
|
166
|
+
function onTransactionAbort(undo) {
|
|
167
|
+
const txn = inst.currentTransaction;
|
|
168
|
+
if (!txn) return;
|
|
169
|
+
if (txn.abortCallbacks) txn.abortCallbacks.push(undo);
|
|
170
|
+
else txn.abortCallbacks = [undo];
|
|
171
|
+
}
|
|
172
|
+
function beforeTransactionCommit(fn) {
|
|
173
|
+
const txn = inst.currentTransaction;
|
|
174
|
+
if (!txn) return;
|
|
175
|
+
if (txn.commitCallbacks) txn.commitCallbacks.push(fn);
|
|
176
|
+
else txn.commitCallbacks = [fn];
|
|
177
|
+
}
|
|
178
|
+
function getValueBeforeTransaction(atom) {
|
|
179
|
+
let value = atom.__unsafe__getWithoutCapture();
|
|
180
|
+
for (let txn = inst.currentTransaction; txn; txn = txn.parent) {
|
|
181
|
+
const initialValues = txn.initialAtomValues;
|
|
182
|
+
if (initialValues.has(atom)) value = initialValues.get(atom);
|
|
183
|
+
}
|
|
184
|
+
return value;
|
|
185
|
+
}
|
|
108
186
|
function atomDidChange(atom, previousValue) {
|
|
109
187
|
if (inst.currentTransaction) {
|
|
110
188
|
if (!inst.currentTransaction.initialAtomValues.has(atom)) {
|
|
@@ -130,12 +208,20 @@ function transaction(fn) {
|
|
|
130
208
|
try {
|
|
131
209
|
result = fn(() => rollback = true);
|
|
132
210
|
} catch (e) {
|
|
133
|
-
txn
|
|
211
|
+
abortAfterError(txn);
|
|
134
212
|
throw e;
|
|
135
213
|
}
|
|
136
214
|
if (inst.currentTransaction !== txn) {
|
|
137
215
|
throw new Error("Transaction boundaries overlap");
|
|
138
216
|
}
|
|
217
|
+
if (!rollback) {
|
|
218
|
+
try {
|
|
219
|
+
if (txn.prepare()) rollback = true;
|
|
220
|
+
} catch (e) {
|
|
221
|
+
abortAfterError(txn);
|
|
222
|
+
throw e;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
139
225
|
if (rollback) {
|
|
140
226
|
txn.abort();
|
|
141
227
|
} else {
|
|
@@ -178,13 +264,21 @@ async function deferAsyncEffects(fn) {
|
|
|
178
264
|
}
|
|
179
265
|
}
|
|
180
266
|
try {
|
|
267
|
+
let rollback = false;
|
|
268
|
+
if (typeof error === "undefined") {
|
|
269
|
+
try {
|
|
270
|
+
rollback = txn.prepare();
|
|
271
|
+
} catch (e) {
|
|
272
|
+
error = e ?? null;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
181
275
|
if (typeof error !== "undefined") {
|
|
182
|
-
txn
|
|
276
|
+
abortAfterError(txn);
|
|
183
277
|
throw error;
|
|
184
|
-
} else {
|
|
185
|
-
txn.commit();
|
|
186
|
-
return result;
|
|
187
278
|
}
|
|
279
|
+
if (rollback) txn.abort();
|
|
280
|
+
else txn.commit();
|
|
281
|
+
return result;
|
|
188
282
|
} finally {
|
|
189
283
|
inst.currentTransaction = null;
|
|
190
284
|
}
|
|
@@ -192,9 +286,12 @@ async function deferAsyncEffects(fn) {
|
|
|
192
286
|
export {
|
|
193
287
|
advanceGlobalEpoch,
|
|
194
288
|
atomDidChange,
|
|
289
|
+
beforeTransactionCommit,
|
|
195
290
|
deferAsyncEffects,
|
|
196
291
|
getGlobalEpoch,
|
|
197
292
|
getIsInTransaction,
|
|
293
|
+
getValueBeforeTransaction,
|
|
294
|
+
onTransactionAbort,
|
|
198
295
|
transact,
|
|
199
296
|
transaction
|
|
200
297
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/transactions.ts"],
|
|
4
|
-
"sourcesContent": ["import { _Atom } from './Atom'\nimport { GLOBAL_START_EPOCH } from './constants'\nimport { singleton } from './helpers'\nimport { Child, Signal } from './types'\n\ninterface Reactor {\n\tmaybeScheduleEffect(): void\n\tlastTraversedEpoch: number\n}\n\nclass Transaction {\n\tasyncProcessCount = 0\n\tconstructor(\n\t\tpublic readonly parent: Transaction | null,\n\t\tpublic readonly isSync: boolean\n\t) {}\n\n\tinitialAtomValues = new Map<_Atom, any>()\n\n\tcommit() {\n\t\tif (this.parent === null) {\n\t\t\t// For root transactions, flush changed atoms\n\t\t\tflushChanges(this.initialAtomValues.keys())\n\t\t\treturn\n\t\t}\n\t\t// For transactions with parents, add the transaction's initial values to the parent's, so\n\t\t// an outer rollback can still undo them (T7). This must come before any \"are we reacting?\" special case: a nested\n\t\t// transaction committed by an effect during the reaction phase used to skip this fold and\n\t\t// its changes survived the outer rollback.\n\t\t// A parent that has recorded nothing yet adopts the map outright: this transaction is\n\t\t// finished with it, and the common nested case is a single inner transaction doing all\n\t\t// the writes.\n\t\tconst parentValues = this.parent!.initialAtomValues\n\t\tif (parentValues.size === 0) {\n\t\t\tthis.parent!.initialAtomValues = this.initialAtomValues\n\t\t\treturn\n\t\t}\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tif (!parentValues.has(atom)) {\n\t\t\t\tparentValues.set(atom, value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Abort the transaction. Restores every atom changed in this transaction to its initial\n\t * value, then commits. Must be called while this is still `inst.currentTransaction`, so that\n\t * the restoring sets are recorded against it instead of each flushing effects on their own.\n\t *\n\t * @public\n\t */\n\tabort() {\n\t\tinst.globalEpoch++\n\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tatom.set(value)\n\t\t\tatom.historyBuffer?.clear()\n\t\t})\n\n\t\tthis.commit()\n\t}\n}\n\nconst inst = singleton('transactions', () => ({\n\t// The current epoch (global to all atoms).\n\tglobalEpoch: GLOBAL_START_EPOCH + 1,\n\t// Whether any transaction is reacting.\n\tglobalIsReacting: false,\n\tcurrentTransaction: null as Transaction | null,\n\n\tcleanupReactors: null as null | Set<Reactor>,\n}))\n\n/**\n * Gets the current global epoch, which is incremented every time any atom changes.\n * This is used to track changes across the entire reactive system.\n *\n * @returns The current global epoch number\n * @public\n */\nexport function getGlobalEpoch() {\n\treturn inst.globalEpoch\n}\n\n/**\n * Whether a transaction (sync or async) is currently open. While one is, atom changes are\n * recorded but their children are not traversed until it commits.\n *\n * @internal\n */\nexport function getIsInTransaction() {\n\treturn inst.currentTransaction !== null\n}\n\n// The set `traverseChild` collects reactors into. Module-level rather than a closure so that a\n// flush over thousands of atoms doesn't allocate a visitor per atom; traversal never runs user\n// code, so nothing can re-enter and swap it mid-walk.\nlet traverseReactors: Set<Reactor>\n\nfunction traverseChild(child: Child) {\n\tif (child.lastTraversedEpoch === inst.globalEpoch) {\n\t\treturn\n\t}\n\n\tchild.lastTraversedEpoch = inst.globalEpoch\n\n\tif ('__isEffectScheduler' in child) {\n\t\ttraverseReactors.add(child as unknown as Reactor)\n\t} else {\n\t\t;(child as any as Signal<any>).children.visit(traverseChild)\n\t}\n}\n\n/**\n * Collect all of the reactors that need to run for an atom and run them. During the reaction\n * phase the affected effects are instead queued for the cleanup pass, so a change made by an\n * effect never interrupts the pass that is running (P4).\n *\n * @param atoms - The atoms to flush changes for.\n */\nfunction flushChanges(atoms: Iterable<_Atom>) {\n\tif (inst.globalIsReacting) {\n\t\tfor (const atom of atoms) {\n\t\t\ttraverseAtomForCleanup(atom)\n\t\t}\n\t\treturn\n\t}\n\n\tconst outerTxn = inst.currentTransaction\n\ttry {\n\t\t// clear the transaction stack. Transactions started by effects must be roots: the committing\n\t\t// transaction (if any) has already handed its changes to this flush.\n\t\tinst.currentTransaction = null\n\t\tinst.globalIsReacting = true\n\n\t\tconst reactors = new Set<Reactor>()\n\t\ttraverseReactors = reactors\n\t\tfor (const atom of atoms) {\n\t\t\tatom.children.visit(traverseChild)\n\t\t}\n\n\t\t// Run each reactor.\n\t\tfor (const r of reactors) {\n\t\t\tr.maybeScheduleEffect()\n\t\t}\n\n\t\tlet updateDepth = 0\n\t\twhile (inst.cleanupReactors?.size) {\n\t\t\tif (updateDepth++ > 1000) {\n\t\t\t\tthrow new Error('Reaction update depth limit exceeded')\n\t\t\t}\n\t\t\tconst reactors = inst.cleanupReactors\n\t\t\tinst.cleanupReactors = null\n\t\t\tfor (const r of reactors) {\n\t\t\t\tr.maybeScheduleEffect()\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tinst.cleanupReactors = null\n\t\tinst.globalIsReacting = false\n\t\tinst.currentTransaction = outerTxn\n\t\ttraverseReactors = undefined! // free memory\n\t}\n}\n\n/** @internal */\nexport function atomDidChange(atom: _Atom, previousValue: any) {\n\tif (inst.currentTransaction) {\n\t\t// If we are in a transaction, then all we have to do is preserve\n\t\t// the value of the atom at the start of the transaction in case\n\t\t// we need to roll back. Children are not traversed until the\n\t\t// transaction commits, which is why `Computed` must not trust its\n\t\t// traversal-based cache shortcut while a transaction is open.\n\t\tif (!inst.currentTransaction.initialAtomValues.has(atom)) {\n\t\t\tinst.currentTransaction.initialAtomValues.set(atom, previousValue)\n\t\t}\n\t} else {\n\t\t// If there is no transaction, flush the changes immediately.\n\t\tflushChanges([atom])\n\t}\n}\n\nfunction traverseAtomForCleanup(atom: _Atom) {\n\ttraverseReactors = inst.cleanupReactors ??= new Set()\n\tatom.children.visit(traverseChild)\n}\n\n/** @internal */\nexport function advanceGlobalEpoch() {\n\tinst.globalEpoch++\n}\n\n/**\n * Batches state updates, deferring side effects until after the transaction completes.\n * Unlike {@link transact}, this function always creates a new transaction, allowing for nested transactions.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * })\n *\n * // Logs \"Hello, Jane Smith!\"\n * ```\n *\n * If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * throw new Error('oops')\n * })\n *\n * // firstName.get() === 'John'\n * // Logs \"Hello, John Doe!\" again: effects whose parents were changed and restored still run,\n * // and observe the restored values.\n * ```\n *\n * A `rollback` callback is passed into the function.\n * Calling this will prevent the transaction from committing and will revert any signals that were updated during the transaction to their state before the transaction began.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction((rollback) => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * rollback()\n * })\n *\n * // firstName.get() === 'John'\n * // lastName.get() === 'Doe'\n * // Logs \"Hello, John Doe!\" again, as above.\n * ```\n *\n * @param fn - The function to run in a transaction, called with a function to roll back the change.\n * @returns The return value of the function\n * @public\n */\nexport function transaction<T>(fn: (rollback: () => void) => T) {\n\tconst txn = new Transaction(inst.currentTransaction, true)\n\n\tinst.currentTransaction = txn\n\n\ttry {\n\t\tlet result = undefined as T | undefined\n\t\tlet rollback = false\n\n\t\ttry {\n\t\t\tresult = fn(() => (rollback = true))\n\t\t} catch (e) {\n\t\t\ttxn.abort()\n\t\t\tthrow e\n\t\t}\n\n\t\tif (inst.currentTransaction !== txn) {\n\t\t\tthrow new Error('Transaction boundaries overlap')\n\t\t}\n\n\t\tif (rollback) {\n\t\t\ttxn.abort()\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t}\n\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = txn.parent\n\t}\n}\n\n/**\n * Like {@link transaction}, but does not create a new transaction if there is already one in progress.\n * This is the preferred way to batch state updates when you don't need the rollback functionality.\n *\n * @example\n * ```ts\n * const count = atom('count', 0)\n * const doubled = atom('doubled', 0)\n *\n * react('update doubled', () => {\n * console.log(`Count: ${count.get()}, Doubled: ${doubled.get()}`)\n * })\n *\n * // This batches both updates into a single reaction\n * transact(() => {\n * count.set(5)\n * doubled.set(count.get() * 2)\n * })\n * // Logs: \"Count: 5, Doubled: 10\"\n * ```\n *\n * @param fn - The function to run in a transaction\n * @returns The return value of the function\n * @public\n */\nexport function transact<T>(fn: () => T): T {\n\tif (inst.currentTransaction) {\n\t\treturn fn()\n\t}\n\treturn transaction(fn)\n}\n\n/**\n * Defers the execution of asynchronous effects until they can be properly handled.\n * This function creates an asynchronous transaction context that batches state updates\n * across async operations while preventing conflicts with synchronous transactions.\n *\n * @example\n * ```ts\n * const data = atom('data', null)\n * const loading = atom('loading', false)\n *\n * await deferAsyncEffects(async () => {\n * loading.set(true)\n * const result = await fetch('/api/data')\n * const json = await result.json()\n * data.set(json)\n * loading.set(false)\n * })\n * ```\n *\n * @param fn - The async function to execute within the deferred context\n * @returns A promise that resolves to the return value of the function\n * @throws Will throw if called during a synchronous transaction\n * @internal\n */\nexport async function deferAsyncEffects<T>(fn: () => Promise<T>) {\n\t// Can't kick off async transactions during a sync transaction because\n\t// the async transaction won't finish until after the sync transaction\n\t// is done.\n\tif (inst.currentTransaction?.isSync) {\n\t\tthrow new Error('deferAsyncEffects cannot be called during a sync transaction')\n\t}\n\n\t// Can't kick off async transactions during a reaction phase at the moment,\n\t// because the transaction stack is cleared after the reaction phase.\n\t// So wait until the path ahead is clear\n\twhile (inst.globalIsReacting) {\n\t\tawait new Promise((r) => queueMicrotask(() => r(null)))\n\t}\n\n\tconst txn = inst.currentTransaction ?? new Transaction(null, false)\n\n\t// don't think this can happen, but just in case\n\tif (txn.isSync) throw new Error('deferAsyncEffects cannot be called during a sync transaction')\n\n\tinst.currentTransaction = txn\n\ttxn.asyncProcessCount++\n\n\tlet result = undefined as T | undefined\n\n\t// `undefined` means \"did not throw\"; a thrown `undefined` is stored as `null` so it still counts.\n\tlet error = undefined as any\n\ttry {\n\t\t// Run the function.\n\t\tresult = await fn()\n\t} catch (e) {\n\t\t// Abort the transaction if the function throws.\n\t\terror = e ?? null\n\t}\n\n\tif (--txn.asyncProcessCount > 0) {\n\t\t// Other processes still share this transaction; it settles when the last one finishes.\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tthrow error\n\t\t} else {\n\t\t\treturn result\n\t\t}\n\t}\n\n\t// Settle while this is still the current transaction (see `Transaction.abort`): clearing it\n\t// first made every restoring set inside `abort()` flush effects on its own, so effects\n\t// observed half-restored state.\n\ttry {\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\ttxn.abort()\n\t\t\tthrow error\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t\treturn result\n\t\t}\n\t} finally {\n\t\tinst.currentTransaction = null\n\t}\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,0BAA0B;AACnC,SAAS,iBAAiB;AAQ1B,MAAM,YAAY;AAAA,EAEjB,YACiB,QACA,QACf;AAFe;AACA;AAAA,EACd;AAAA,EAFc;AAAA,EACA;AAAA,EAHjB,oBAAoB;AAAA,EAMpB,oBAAoB,oBAAI,IAAgB;AAAA,
|
|
4
|
+
"sourcesContent": ["import { _Atom, Atom } from './Atom'\nimport { GLOBAL_START_EPOCH } from './constants'\nimport { singleton } from './helpers'\nimport { Child, Signal } from './types'\n\ninterface Reactor {\n\tmaybeScheduleEffect(): void\n\tlastTraversedEpoch: number\n}\n\nclass Transaction {\n\tasyncProcessCount = 0\n\tconstructor(\n\t\tpublic readonly parent: Transaction | null,\n\t\tpublic readonly isSync: boolean\n\t) {}\n\n\tinitialAtomValues = new Map<_Atom, any>()\n\n\t// See `onTransactionAbort`. Oldest first.\n\tabortCallbacks: (() => void)[] | null = null\n\n\t// See `beforeTransactionCommit`. Oldest first.\n\tcommitCallbacks: CommitCallback[] | null = null\n\n\tcommit() {\n\t\tif (this.parent === null) {\n\t\t\t// For root transactions, flush changed atoms\n\t\t\tflushChanges(this.initialAtomValues.keys())\n\t\t\treturn\n\t\t}\n\t\t// For transactions with parents, add the transaction's initial values to the parent's, so\n\t\t// an outer rollback can still undo them (T7). This must come before any \"are we reacting?\" special case: a nested\n\t\t// transaction committed by an effect during the reaction phase used to skip this fold and\n\t\t// its changes survived the outer rollback.\n\t\t// A parent that has recorded nothing yet adopts the map outright: this transaction is\n\t\t// finished with it, and the common nested case is a single inner transaction doing all\n\t\t// the writes.\n\t\tconst parent = this.parent!\n\t\tparent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks)\n\t\tparent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks)\n\t\tconst parentValues = this.parent!.initialAtomValues\n\t\tif (parentValues.size === 0) {\n\t\t\tthis.parent!.initialAtomValues = this.initialAtomValues\n\t\t\treturn\n\t\t}\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tif (!parentValues.has(atom)) {\n\t\t\t\tparentValues.set(atom, value)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Run the callbacks registered with `beforeTransactionCommit`, including any that they\n\t * register. Only a root transaction has a commit of its own to prepare for: a nested one hands\n\t * its callbacks to its parent. Returns true if a callback asked for a rollback.\n\t */\n\tprepare(): boolean {\n\t\tif (this.parent !== null) return false\n\t\tlet rollback = false\n\t\tconst requestRollback = () => {\n\t\t\trollback = true\n\t\t}\n\t\tlet passes = 0\n\t\twhile (this.commitCallbacks) {\n\t\t\tif (passes++ > 100) {\n\t\t\t\tthrow new Error('Commit callback depth limit exceeded')\n\t\t\t}\n\t\t\tconst callbacks = this.commitCallbacks\n\t\t\tthis.commitCallbacks = null\n\t\t\tfor (let i = 0; i < callbacks.length; i++) {\n\t\t\t\tcallbacks[i](requestRollback)\n\t\t\t\tif (rollback) return true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t/**\n\t * Abort the transaction. Restores every atom changed in this transaction to its initial\n\t * value, then commits. Must be called while this is still `inst.currentTransaction`, so that\n\t * the restoring sets are recorded against it instead of each flushing effects on their own.\n\t *\n\t * @public\n\t */\n\tabort() {\n\t\tinst.globalEpoch++\n\n\t\tthis.initialAtomValues.forEach((value, atom) => {\n\t\t\tatom.set(value)\n\t\t\tatom.historyBuffer?.clear()\n\t\t})\n\n\t\t// Taken off before `commit`, which would otherwise hand them to the parent.\n\t\tconst callbacks = this.abortCallbacks\n\t\tthis.abortCallbacks = null\n\t\tthis.commitCallbacks = null\n\t\tlet failure: { error: unknown } | null = null\n\t\tif (callbacks) {\n\t\t\tfor (let i = callbacks.length - 1; i >= 0; i--) {\n\t\t\t\t// A throw must not skip the older callbacks: each one left out keeps its state wrong for good.\n\t\t\t\ttry {\n\t\t\t\t\tcallbacks[i]()\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailure ??= { error }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.commit()\n\t\tif (failure) throw failure.error\n\t}\n}\n\ntype CommitCallback = (rollback: () => void) => void\n\n// For an abort caused by `error`: a throw from an abort callback must not replace it.\nfunction abortAfterError(txn: Transaction) {\n\ttry {\n\t\ttxn.abort()\n\t} catch {\n\t\t// `error` is the one to report\n\t}\n}\n\nfunction concatCallbacks<T>(parent: T[] | null, child: T[] | null): T[] | null {\n\tif (!child) return parent\n\tif (!parent) return child\n\tfor (let i = 0; i < child.length; i++) parent.push(child[i])\n\treturn parent\n}\n\nconst inst = singleton('transactions', () => ({\n\t// The current epoch (global to all atoms).\n\tglobalEpoch: GLOBAL_START_EPOCH + 1,\n\t// Whether any transaction is reacting.\n\tglobalIsReacting: false,\n\tcurrentTransaction: null as Transaction | null,\n\n\tcleanupReactors: null as null | Set<Reactor>,\n}))\n\n/**\n * Gets the current global epoch, which is incremented every time any atom changes.\n * This is used to track changes across the entire reactive system.\n *\n * @returns The current global epoch number\n * @public\n */\nexport function getGlobalEpoch() {\n\treturn inst.globalEpoch\n}\n\n/**\n * Whether a transaction (sync or async) is currently open. While one is, atom changes are\n * recorded but their children are not traversed until it commits.\n *\n * @internal\n */\nexport function getIsInTransaction() {\n\treturn inst.currentTransaction !== null\n}\n\n// The set `traverseChild` collects reactors into. Module-level rather than a closure so that a\n// flush over thousands of atoms doesn't allocate a visitor per atom; traversal never runs user\n// code, so nothing can re-enter and swap it mid-walk.\nlet traverseReactors: Set<Reactor>\n\nfunction traverseChild(child: Child) {\n\tif (child.lastTraversedEpoch === inst.globalEpoch) {\n\t\treturn\n\t}\n\n\tchild.lastTraversedEpoch = inst.globalEpoch\n\n\tif ('__isEffectScheduler' in child) {\n\t\ttraverseReactors.add(child as unknown as Reactor)\n\t} else {\n\t\t;(child as any as Signal<any>).children.visit(traverseChild)\n\t}\n}\n\n/**\n * Collect all of the reactors that need to run for an atom and run them. During the reaction\n * phase the affected effects are instead queued for the cleanup pass, so a change made by an\n * effect never interrupts the pass that is running (P4).\n *\n * @param atoms - The atoms to flush changes for.\n */\nfunction flushChanges(atoms: Iterable<_Atom>) {\n\tif (inst.globalIsReacting) {\n\t\tfor (const atom of atoms) {\n\t\t\ttraverseAtomForCleanup(atom)\n\t\t}\n\t\treturn\n\t}\n\n\tconst outerTxn = inst.currentTransaction\n\ttry {\n\t\t// clear the transaction stack. Transactions started by effects must be roots: the committing\n\t\t// transaction (if any) has already handed its changes to this flush.\n\t\tinst.currentTransaction = null\n\t\tinst.globalIsReacting = true\n\n\t\tconst reactors = new Set<Reactor>()\n\t\ttraverseReactors = reactors\n\t\tfor (const atom of atoms) {\n\t\t\tatom.children.visit(traverseChild)\n\t\t}\n\n\t\t// Run each reactor.\n\t\tfor (const r of reactors) {\n\t\t\tr.maybeScheduleEffect()\n\t\t}\n\n\t\tlet updateDepth = 0\n\t\twhile (inst.cleanupReactors?.size) {\n\t\t\tif (updateDepth++ > 1000) {\n\t\t\t\tthrow new Error('Reaction update depth limit exceeded')\n\t\t\t}\n\t\t\tconst reactors = inst.cleanupReactors\n\t\t\tinst.cleanupReactors = null\n\t\t\tfor (const r of reactors) {\n\t\t\t\tr.maybeScheduleEffect()\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tinst.cleanupReactors = null\n\t\tinst.globalIsReacting = false\n\t\tinst.currentTransaction = outerTxn\n\t\ttraverseReactors = undefined! // free memory\n\t}\n}\n\n/**\n * Registers `undo` to run if the current transaction, or a transaction around it, rolls back. For\n * state kept outside atoms, which a rollback would otherwise leave as it is. Callbacks run newest\n * first, after the atoms are restored and before effects are flushed. They must not throw, and\n * must not change atoms or register callbacks: the transaction is already ending. Outside\n * a transaction nothing can roll back, so this does nothing.\n *\n * @internal\n */\nexport function onTransactionAbort(undo: () => void) {\n\tconst txn = inst.currentTransaction\n\tif (!txn) return\n\tif (txn.abortCallbacks) txn.abortCallbacks.push(undo)\n\telse txn.abortCallbacks = [undo]\n}\n\n/**\n * Registers `fn` to run when the outermost transaction is about to commit: every change is made,\n * no effect has run, and nothing outside the transaction has seen it. For checks on a transaction\n * as a whole. `fn` may change atoms and register further callbacks, which run before the same\n * commit. Calling `rollback` aborts the transaction and skips the callbacks that are left, and a\n * throw aborts it and propagates. Callbacks from a transaction that aborts never run. Outside a\n * transaction this does nothing.\n *\n * @internal\n */\nexport function beforeTransactionCommit(fn: (rollback: () => void) => void) {\n\tconst txn = inst.currentTransaction\n\tif (!txn) return\n\tif (txn.commitCallbacks) txn.commitCallbacks.push(fn)\n\telse txn.commitCallbacks = [fn]\n}\n\n/**\n * The value `atom` had before the outermost open transaction changed it, which is the value it\n * goes back to if that transaction rolls back. The atom's current value when no open transaction\n * has changed it.\n *\n * @internal\n */\nexport function getValueBeforeTransaction<T>(atom: Atom<T>): T {\n\tlet value = atom.__unsafe__getWithoutCapture()\n\tfor (let txn = inst.currentTransaction; txn; txn = txn.parent) {\n\t\tconst initialValues = txn.initialAtomValues\n\t\tif (initialValues.has(atom as any)) value = initialValues.get(atom as any)\n\t}\n\treturn value\n}\n\n/** @internal */\nexport function atomDidChange(atom: _Atom, previousValue: any) {\n\tif (inst.currentTransaction) {\n\t\t// If we are in a transaction, then all we have to do is preserve\n\t\t// the value of the atom at the start of the transaction in case\n\t\t// we need to roll back. Children are not traversed until the\n\t\t// transaction commits, which is why `Computed` must not trust its\n\t\t// traversal-based cache shortcut while a transaction is open.\n\t\tif (!inst.currentTransaction.initialAtomValues.has(atom)) {\n\t\t\tinst.currentTransaction.initialAtomValues.set(atom, previousValue)\n\t\t}\n\t} else {\n\t\t// If there is no transaction, flush the changes immediately.\n\t\tflushChanges([atom])\n\t}\n}\n\nfunction traverseAtomForCleanup(atom: _Atom) {\n\ttraverseReactors = inst.cleanupReactors ??= new Set()\n\tatom.children.visit(traverseChild)\n}\n\n/** @internal */\nexport function advanceGlobalEpoch() {\n\tinst.globalEpoch++\n}\n\n/**\n * Batches state updates, deferring side effects until after the transaction completes.\n * Unlike {@link transact}, this function always creates a new transaction, allowing for nested transactions.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * })\n *\n * // Logs \"Hello, Jane Smith!\"\n * ```\n *\n * If the function throws, the transaction is aborted and any signals that were updated during the transaction revert to their state before the transaction began. An aborted transaction still flushes effects: effects whose parents went through a change-and-restore round trip are checked again and, if a parent's value differs from what they last saw (an atom they read directly always will), run once more with the restored values.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction(() => {\n * firstName.set('Jane')\n * throw new Error('oops')\n * })\n *\n * // firstName.get() === 'John'\n * // Logs \"Hello, John Doe!\" again: effects whose parents were changed and restored still run,\n * // and observe the restored values.\n * ```\n *\n * A `rollback` callback is passed into the function.\n * Calling this will prevent the transaction from committing and will revert any signals that were updated during the transaction to their state before the transaction began.\n *\n * @example\n * ```ts\n * const firstName = atom('firstName', 'John')\n * const lastName = atom('lastName', 'Doe')\n *\n * react('greet', () => {\n * console.log(`Hello, ${firstName.get()} ${lastName.get()}!`)\n * })\n *\n * // Logs \"Hello, John Doe!\"\n *\n * transaction((rollback) => {\n * firstName.set('Jane')\n * lastName.set('Smith')\n * rollback()\n * })\n *\n * // firstName.get() === 'John'\n * // lastName.get() === 'Doe'\n * // Logs \"Hello, John Doe!\" again, as above.\n * ```\n *\n * @param fn - The function to run in a transaction, called with a function to roll back the change.\n * @returns The return value of the function\n * @public\n */\nexport function transaction<T>(fn: (rollback: () => void) => T) {\n\tconst txn = new Transaction(inst.currentTransaction, true)\n\n\tinst.currentTransaction = txn\n\n\ttry {\n\t\tlet result = undefined as T | undefined\n\t\tlet rollback = false\n\n\t\ttry {\n\t\t\tresult = fn(() => (rollback = true))\n\t\t} catch (e) {\n\t\t\tabortAfterError(txn)\n\t\t\tthrow e\n\t\t}\n\n\t\tif (inst.currentTransaction !== txn) {\n\t\t\tthrow new Error('Transaction boundaries overlap')\n\t\t}\n\n\t\tif (!rollback) {\n\t\t\ttry {\n\t\t\t\t// Never assign: a callback can call `fn`'s own `rollback`, which `prepare` can't see.\n\t\t\t\tif (txn.prepare()) rollback = true\n\t\t\t} catch (e) {\n\t\t\t\tabortAfterError(txn)\n\t\t\t\tthrow e\n\t\t\t}\n\t\t}\n\n\t\tif (rollback) {\n\t\t\ttxn.abort()\n\t\t} else {\n\t\t\ttxn.commit()\n\t\t}\n\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = txn.parent\n\t}\n}\n\n/**\n * Like {@link transaction}, but does not create a new transaction if there is already one in progress.\n * This is the preferred way to batch state updates when you don't need the rollback functionality.\n *\n * @example\n * ```ts\n * const count = atom('count', 0)\n * const doubled = atom('doubled', 0)\n *\n * react('update doubled', () => {\n * console.log(`Count: ${count.get()}, Doubled: ${doubled.get()}`)\n * })\n *\n * // This batches both updates into a single reaction\n * transact(() => {\n * count.set(5)\n * doubled.set(count.get() * 2)\n * })\n * // Logs: \"Count: 5, Doubled: 10\"\n * ```\n *\n * @param fn - The function to run in a transaction\n * @returns The return value of the function\n * @public\n */\nexport function transact<T>(fn: () => T): T {\n\tif (inst.currentTransaction) {\n\t\treturn fn()\n\t}\n\treturn transaction(fn)\n}\n\n/**\n * Defers the execution of asynchronous effects until they can be properly handled.\n * This function creates an asynchronous transaction context that batches state updates\n * across async operations while preventing conflicts with synchronous transactions.\n *\n * @example\n * ```ts\n * const data = atom('data', null)\n * const loading = atom('loading', false)\n *\n * await deferAsyncEffects(async () => {\n * loading.set(true)\n * const result = await fetch('/api/data')\n * const json = await result.json()\n * data.set(json)\n * loading.set(false)\n * })\n * ```\n *\n * @param fn - The async function to execute within the deferred context\n * @returns A promise that resolves to the return value of the function\n * @throws Will throw if called during a synchronous transaction\n * @internal\n */\nexport async function deferAsyncEffects<T>(fn: () => Promise<T>) {\n\t// Can't kick off async transactions during a sync transaction because\n\t// the async transaction won't finish until after the sync transaction\n\t// is done.\n\tif (inst.currentTransaction?.isSync) {\n\t\tthrow new Error('deferAsyncEffects cannot be called during a sync transaction')\n\t}\n\n\t// Can't kick off async transactions during a reaction phase at the moment,\n\t// because the transaction stack is cleared after the reaction phase.\n\t// So wait until the path ahead is clear\n\twhile (inst.globalIsReacting) {\n\t\tawait new Promise((r) => queueMicrotask(() => r(null)))\n\t}\n\n\tconst txn = inst.currentTransaction ?? new Transaction(null, false)\n\n\t// don't think this can happen, but just in case\n\tif (txn.isSync) throw new Error('deferAsyncEffects cannot be called during a sync transaction')\n\n\tinst.currentTransaction = txn\n\ttxn.asyncProcessCount++\n\n\tlet result = undefined as T | undefined\n\n\t// `undefined` means \"did not throw\"; a thrown `undefined` is stored as `null` so it still counts.\n\tlet error = undefined as any\n\ttry {\n\t\t// Run the function.\n\t\tresult = await fn()\n\t} catch (e) {\n\t\t// Abort the transaction if the function throws.\n\t\terror = e ?? null\n\t}\n\n\tif (--txn.asyncProcessCount > 0) {\n\t\t// Other processes still share this transaction; it settles when the last one finishes.\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tthrow error\n\t\t} else {\n\t\t\treturn result\n\t\t}\n\t}\n\n\t// Settle while this is still the current transaction (see `Transaction.abort`): clearing it\n\t// first made every restoring set inside `abort()` flush effects on its own, so effects\n\t// observed half-restored state.\n\ttry {\n\t\tlet rollback = false\n\t\tif (typeof error === 'undefined') {\n\t\t\ttry {\n\t\t\t\trollback = txn.prepare()\n\t\t\t} catch (e) {\n\t\t\t\terror = e ?? null\n\t\t\t}\n\t\t}\n\t\tif (typeof error !== 'undefined') {\n\t\t\t// If the rollback was triggered, abort the transaction.\n\t\t\tabortAfterError(txn)\n\t\t\tthrow error\n\t\t}\n\t\tif (rollback) txn.abort()\n\t\telse txn.commit()\n\t\treturn result\n\t} finally {\n\t\tinst.currentTransaction = null\n\t}\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,0BAA0B;AACnC,SAAS,iBAAiB;AAQ1B,MAAM,YAAY;AAAA,EAEjB,YACiB,QACA,QACf;AAFe;AACA;AAAA,EACd;AAAA,EAFc;AAAA,EACA;AAAA,EAHjB,oBAAoB;AAAA,EAMpB,oBAAoB,oBAAI,IAAgB;AAAA;AAAA,EAGxC,iBAAwC;AAAA;AAAA,EAGxC,kBAA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E,IAAI,CAAC,CAAC;AAAA,EACvD;AAEA,QAAM,MAAM,KAAK,sBAAsB,IAAI,YAAY,MAAM,KAAK;AAGlE,MAAI,IAAI,OAAQ,OAAM,IAAI,MAAM,8DAA8D;AAE9F,OAAK,qBAAqB;AAC1B,MAAI;AAEJ,MAAI,SAAS;AAGb,MAAI,QAAQ;AACZ,MAAI;AAEH,aAAS,MAAM,GAAG;AAAA,EACnB,SAAS,GAAG;AAEX,YAAQ,KAAK;AAAA,EACd;AAEA,MAAI,EAAE,IAAI,oBAAoB,GAAG;AAEhC,QAAI,OAAO,UAAU,aAAa;AAEjC,YAAM;AAAA,IACP,OAAO;AACN,aAAO;AAAA,IACR;AAAA,EACD;AAKA,MAAI;AACH,QAAI,WAAW;AACf,QAAI,OAAO,UAAU,aAAa;AACjC,UAAI;AACH,mBAAW,IAAI,QAAQ;AAAA,MACxB,SAAS,GAAG;AACX,gBAAQ,KAAK;AAAA,MACd;AAAA,IACD;AACA,QAAI,OAAO,UAAU,aAAa;AAEjC,sBAAgB,GAAG;AACnB,YAAM;AAAA,IACP;AACA,QAAI,SAAU,KAAI,MAAM;AAAA,QACnB,KAAI,OAAO;AAChB,WAAO;AAAA,EACR,UAAE;AACD,SAAK,qBAAqB;AAAA,EAC3B;AACD;",
|
|
6
6
|
"names": ["reactors"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tldraw/state",
|
|
3
3
|
"description": "tldraw infinite canvas SDK (state).",
|
|
4
|
-
"version": "5.
|
|
4
|
+
"version": "5.8.0-canary.15ae3e10cc28",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "tldraw Inc.",
|
|
7
7
|
"email": "hello@tldraw.com"
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"vitest": "^5.0.0"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@tldraw/utils": "5.
|
|
47
|
+
"@tldraw/utils": "5.8.0-canary.15ae3e10cc28"
|
|
48
48
|
},
|
|
49
49
|
"typedoc": {
|
|
50
50
|
"readmeFile": "none",
|
package/src/index.ts
CHANGED
|
@@ -18,7 +18,14 @@ export type { EffectSchedulerOptions, Reactor } from './lib/EffectScheduler'
|
|
|
18
18
|
export { EMPTY_ARRAY } from './lib/helpers'
|
|
19
19
|
export { isSignal } from './lib/isSignal'
|
|
20
20
|
export { localStorageAtom } from './lib/localStorageAtom'
|
|
21
|
-
export {
|
|
21
|
+
export {
|
|
22
|
+
beforeTransactionCommit,
|
|
23
|
+
deferAsyncEffects,
|
|
24
|
+
getValueBeforeTransaction,
|
|
25
|
+
onTransactionAbort,
|
|
26
|
+
transact,
|
|
27
|
+
transaction,
|
|
28
|
+
} from './lib/transactions'
|
|
22
29
|
export { RESET_VALUE } from './lib/types'
|
|
23
30
|
export type { Child, ComputeDiff, Signal } from './lib/types'
|
|
24
31
|
|
|
@@ -3,7 +3,7 @@ import { vi } from 'vitest'
|
|
|
3
3
|
import { atom } from '../Atom'
|
|
4
4
|
import { computed } from '../Computed'
|
|
5
5
|
import { react } from '../EffectScheduler'
|
|
6
|
-
import { deferAsyncEffects, transact, transaction } from '../transactions'
|
|
6
|
+
import { beforeTransactionCommit, deferAsyncEffects, transact, transaction } from '../transactions'
|
|
7
7
|
|
|
8
8
|
// Tests for SPEC.md §12 (async transactions: deferAsyncEffects).
|
|
9
9
|
// Rule IDs like [AT3] in test names refer to that document.
|
|
@@ -253,3 +253,23 @@ describe('deferAsyncEffects (AT)', () => {
|
|
|
253
253
|
await expect(deferAsyncEffects(async () => 'value')).resolves.toBe('value')
|
|
254
254
|
})
|
|
255
255
|
})
|
|
256
|
+
|
|
257
|
+
describe('beforeTransactionCommit in an async transaction (T12)', () => {
|
|
258
|
+
it('runs when the async transaction settles, and can roll it back', async () => {
|
|
259
|
+
const a = atom('', 0)
|
|
260
|
+
const seen: number[] = []
|
|
261
|
+
|
|
262
|
+
await deferAsyncEffects(async () => {
|
|
263
|
+
a.set(1)
|
|
264
|
+
beforeTransactionCommit((rollback) => {
|
|
265
|
+
seen.push(a.get())
|
|
266
|
+
rollback()
|
|
267
|
+
})
|
|
268
|
+
await sleep(1)
|
|
269
|
+
a.set(2)
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
expect(seen).toEqual([2])
|
|
273
|
+
expect(a.get()).toBe(0)
|
|
274
|
+
})
|
|
275
|
+
})
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import { atom } from '../Atom'
|
|
2
2
|
import { computed } from '../Computed'
|
|
3
3
|
import { react } from '../EffectScheduler'
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
beforeTransactionCommit,
|
|
6
|
+
getGlobalEpoch,
|
|
7
|
+
onTransactionAbort,
|
|
8
|
+
transact,
|
|
9
|
+
transaction,
|
|
10
|
+
} from '../transactions'
|
|
5
11
|
|
|
6
12
|
// Tests for SPEC.md §11 (transactions), plus rule EP6.
|
|
7
13
|
// Rule IDs like [T4] in test names refer to that document.
|
|
@@ -263,3 +269,128 @@ describe('transact (T)', () => {
|
|
|
263
269
|
expect.assertions(3)
|
|
264
270
|
})
|
|
265
271
|
})
|
|
272
|
+
|
|
273
|
+
describe('beforeTransactionCommit (T12)', () => {
|
|
274
|
+
it('runs once when the outermost transaction is about to commit, before effects', () => {
|
|
275
|
+
const a = atom('', 0)
|
|
276
|
+
const seenByEffect: number[] = []
|
|
277
|
+
react('', () => void seenByEffect.push(a.get()))
|
|
278
|
+
const log: string[] = []
|
|
279
|
+
|
|
280
|
+
transaction(() => {
|
|
281
|
+
transaction(() => {
|
|
282
|
+
a.set(1)
|
|
283
|
+
beforeTransactionCommit(() => log.push(`commit ${a.get()}, effect saw ${seenByEffect}`))
|
|
284
|
+
})
|
|
285
|
+
log.push('inner committed')
|
|
286
|
+
a.set(2)
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
expect(log).toEqual(['inner committed', 'commit 2, effect saw 0'])
|
|
290
|
+
expect(seenByEffect).toEqual([0, 2])
|
|
291
|
+
})
|
|
292
|
+
|
|
293
|
+
it('does not run callbacks from a transaction that aborts', () => {
|
|
294
|
+
const ran = vi.fn()
|
|
295
|
+
transaction(() => {
|
|
296
|
+
transaction((rollback) => {
|
|
297
|
+
beforeTransactionCommit(ran)
|
|
298
|
+
rollback()
|
|
299
|
+
})
|
|
300
|
+
})
|
|
301
|
+
expect(() =>
|
|
302
|
+
transaction(() => {
|
|
303
|
+
beforeTransactionCommit(ran)
|
|
304
|
+
throw new Error('boom')
|
|
305
|
+
})
|
|
306
|
+
).toThrow('boom')
|
|
307
|
+
expect(ran).not.toHaveBeenCalled()
|
|
308
|
+
})
|
|
309
|
+
|
|
310
|
+
it('runs callbacks registered by a callback, and commits what callbacks change', () => {
|
|
311
|
+
const a = atom('', 0)
|
|
312
|
+
transaction(() => {
|
|
313
|
+
beforeTransactionCommit(() => {
|
|
314
|
+
a.set(1)
|
|
315
|
+
beforeTransactionCommit(() => a.set(a.get() + 1))
|
|
316
|
+
})
|
|
317
|
+
})
|
|
318
|
+
expect(a.get()).toBe(2)
|
|
319
|
+
})
|
|
320
|
+
|
|
321
|
+
it.each([
|
|
322
|
+
['rollback', (rollback: () => void) => rollback(), undefined],
|
|
323
|
+
[
|
|
324
|
+
'a throw',
|
|
325
|
+
() => {
|
|
326
|
+
throw new Error('boom')
|
|
327
|
+
},
|
|
328
|
+
'boom',
|
|
329
|
+
],
|
|
330
|
+
])('aborts the whole transaction on %s', (_name, refuse, error) => {
|
|
331
|
+
const a = atom('', 0)
|
|
332
|
+
const aborted = vi.fn()
|
|
333
|
+
const later = vi.fn()
|
|
334
|
+
const run = () =>
|
|
335
|
+
transaction(() => {
|
|
336
|
+
a.set(1)
|
|
337
|
+
onTransactionAbort(aborted)
|
|
338
|
+
beforeTransactionCommit(refuse)
|
|
339
|
+
beforeTransactionCommit(later)
|
|
340
|
+
return 'result'
|
|
341
|
+
})
|
|
342
|
+
|
|
343
|
+
if (error) expect(run).toThrow(error)
|
|
344
|
+
else expect(run()).toBe('result')
|
|
345
|
+
|
|
346
|
+
expect(a.get()).toBe(0)
|
|
347
|
+
expect(aborted).toHaveBeenCalledTimes(1)
|
|
348
|
+
expect(later).not.toHaveBeenCalled()
|
|
349
|
+
})
|
|
350
|
+
|
|
351
|
+
it("aborts when a callback calls the transaction's own rollback", () => {
|
|
352
|
+
const a = atom('', 0)
|
|
353
|
+
const later = vi.fn()
|
|
354
|
+
transaction((rollback) => {
|
|
355
|
+
a.set(1)
|
|
356
|
+
beforeTransactionCommit(() => rollback())
|
|
357
|
+
beforeTransactionCommit(later)
|
|
358
|
+
})
|
|
359
|
+
expect(a.get()).toBe(0)
|
|
360
|
+
expect(later).toHaveBeenCalledTimes(1)
|
|
361
|
+
})
|
|
362
|
+
|
|
363
|
+
it('runs every abort callback when one throws, then rethrows the first error', () => {
|
|
364
|
+
const a = atom('', 0)
|
|
365
|
+
const older = vi.fn()
|
|
366
|
+
expect(() =>
|
|
367
|
+
transaction((rollback) => {
|
|
368
|
+
a.set(1)
|
|
369
|
+
onTransactionAbort(older)
|
|
370
|
+
onTransactionAbort(() => {
|
|
371
|
+
throw new Error('second')
|
|
372
|
+
})
|
|
373
|
+
onTransactionAbort(() => {
|
|
374
|
+
throw new Error('first')
|
|
375
|
+
})
|
|
376
|
+
rollback()
|
|
377
|
+
})
|
|
378
|
+
).toThrow('first')
|
|
379
|
+
expect(a.get()).toBe(0)
|
|
380
|
+
expect(older).toHaveBeenCalledTimes(1)
|
|
381
|
+
})
|
|
382
|
+
|
|
383
|
+
it('keeps the original error when an abort callback also throws', () => {
|
|
384
|
+
const older = vi.fn()
|
|
385
|
+
expect(() =>
|
|
386
|
+
transaction(() => {
|
|
387
|
+
onTransactionAbort(older)
|
|
388
|
+
onTransactionAbort(() => {
|
|
389
|
+
throw new Error('callback')
|
|
390
|
+
})
|
|
391
|
+
throw new Error('original')
|
|
392
|
+
})
|
|
393
|
+
).toThrow('original')
|
|
394
|
+
expect(older).toHaveBeenCalledTimes(1)
|
|
395
|
+
})
|
|
396
|
+
})
|
package/src/lib/transactions.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _Atom } from './Atom'
|
|
1
|
+
import { _Atom, Atom } from './Atom'
|
|
2
2
|
import { GLOBAL_START_EPOCH } from './constants'
|
|
3
3
|
import { singleton } from './helpers'
|
|
4
4
|
import { Child, Signal } from './types'
|
|
@@ -17,6 +17,12 @@ class Transaction {
|
|
|
17
17
|
|
|
18
18
|
initialAtomValues = new Map<_Atom, any>()
|
|
19
19
|
|
|
20
|
+
// See `onTransactionAbort`. Oldest first.
|
|
21
|
+
abortCallbacks: (() => void)[] | null = null
|
|
22
|
+
|
|
23
|
+
// See `beforeTransactionCommit`. Oldest first.
|
|
24
|
+
commitCallbacks: CommitCallback[] | null = null
|
|
25
|
+
|
|
20
26
|
commit() {
|
|
21
27
|
if (this.parent === null) {
|
|
22
28
|
// For root transactions, flush changed atoms
|
|
@@ -30,6 +36,9 @@ class Transaction {
|
|
|
30
36
|
// A parent that has recorded nothing yet adopts the map outright: this transaction is
|
|
31
37
|
// finished with it, and the common nested case is a single inner transaction doing all
|
|
32
38
|
// the writes.
|
|
39
|
+
const parent = this.parent!
|
|
40
|
+
parent.abortCallbacks = concatCallbacks(parent.abortCallbacks, this.abortCallbacks)
|
|
41
|
+
parent.commitCallbacks = concatCallbacks(parent.commitCallbacks, this.commitCallbacks)
|
|
33
42
|
const parentValues = this.parent!.initialAtomValues
|
|
34
43
|
if (parentValues.size === 0) {
|
|
35
44
|
this.parent!.initialAtomValues = this.initialAtomValues
|
|
@@ -42,6 +51,32 @@ class Transaction {
|
|
|
42
51
|
})
|
|
43
52
|
}
|
|
44
53
|
|
|
54
|
+
/**
|
|
55
|
+
* Run the callbacks registered with `beforeTransactionCommit`, including any that they
|
|
56
|
+
* register. Only a root transaction has a commit of its own to prepare for: a nested one hands
|
|
57
|
+
* its callbacks to its parent. Returns true if a callback asked for a rollback.
|
|
58
|
+
*/
|
|
59
|
+
prepare(): boolean {
|
|
60
|
+
if (this.parent !== null) return false
|
|
61
|
+
let rollback = false
|
|
62
|
+
const requestRollback = () => {
|
|
63
|
+
rollback = true
|
|
64
|
+
}
|
|
65
|
+
let passes = 0
|
|
66
|
+
while (this.commitCallbacks) {
|
|
67
|
+
if (passes++ > 100) {
|
|
68
|
+
throw new Error('Commit callback depth limit exceeded')
|
|
69
|
+
}
|
|
70
|
+
const callbacks = this.commitCallbacks
|
|
71
|
+
this.commitCallbacks = null
|
|
72
|
+
for (let i = 0; i < callbacks.length; i++) {
|
|
73
|
+
callbacks[i](requestRollback)
|
|
74
|
+
if (rollback) return true
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
|
|
45
80
|
/**
|
|
46
81
|
* Abort the transaction. Restores every atom changed in this transaction to its initial
|
|
47
82
|
* value, then commits. Must be called while this is still `inst.currentTransaction`, so that
|
|
@@ -57,10 +92,44 @@ class Transaction {
|
|
|
57
92
|
atom.historyBuffer?.clear()
|
|
58
93
|
})
|
|
59
94
|
|
|
95
|
+
// Taken off before `commit`, which would otherwise hand them to the parent.
|
|
96
|
+
const callbacks = this.abortCallbacks
|
|
97
|
+
this.abortCallbacks = null
|
|
98
|
+
this.commitCallbacks = null
|
|
99
|
+
let failure: { error: unknown } | null = null
|
|
100
|
+
if (callbacks) {
|
|
101
|
+
for (let i = callbacks.length - 1; i >= 0; i--) {
|
|
102
|
+
// A throw must not skip the older callbacks: each one left out keeps its state wrong for good.
|
|
103
|
+
try {
|
|
104
|
+
callbacks[i]()
|
|
105
|
+
} catch (error) {
|
|
106
|
+
failure ??= { error }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
60
110
|
this.commit()
|
|
111
|
+
if (failure) throw failure.error
|
|
61
112
|
}
|
|
62
113
|
}
|
|
63
114
|
|
|
115
|
+
type CommitCallback = (rollback: () => void) => void
|
|
116
|
+
|
|
117
|
+
// For an abort caused by `error`: a throw from an abort callback must not replace it.
|
|
118
|
+
function abortAfterError(txn: Transaction) {
|
|
119
|
+
try {
|
|
120
|
+
txn.abort()
|
|
121
|
+
} catch {
|
|
122
|
+
// `error` is the one to report
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function concatCallbacks<T>(parent: T[] | null, child: T[] | null): T[] | null {
|
|
127
|
+
if (!child) return parent
|
|
128
|
+
if (!parent) return child
|
|
129
|
+
for (let i = 0; i < child.length; i++) parent.push(child[i])
|
|
130
|
+
return parent
|
|
131
|
+
}
|
|
132
|
+
|
|
64
133
|
const inst = singleton('transactions', () => ({
|
|
65
134
|
// The current epoch (global to all atoms).
|
|
66
135
|
globalEpoch: GLOBAL_START_EPOCH + 1,
|
|
@@ -163,6 +232,55 @@ function flushChanges(atoms: Iterable<_Atom>) {
|
|
|
163
232
|
}
|
|
164
233
|
}
|
|
165
234
|
|
|
235
|
+
/**
|
|
236
|
+
* Registers `undo` to run if the current transaction, or a transaction around it, rolls back. For
|
|
237
|
+
* state kept outside atoms, which a rollback would otherwise leave as it is. Callbacks run newest
|
|
238
|
+
* first, after the atoms are restored and before effects are flushed. They must not throw, and
|
|
239
|
+
* must not change atoms or register callbacks: the transaction is already ending. Outside
|
|
240
|
+
* a transaction nothing can roll back, so this does nothing.
|
|
241
|
+
*
|
|
242
|
+
* @internal
|
|
243
|
+
*/
|
|
244
|
+
export function onTransactionAbort(undo: () => void) {
|
|
245
|
+
const txn = inst.currentTransaction
|
|
246
|
+
if (!txn) return
|
|
247
|
+
if (txn.abortCallbacks) txn.abortCallbacks.push(undo)
|
|
248
|
+
else txn.abortCallbacks = [undo]
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Registers `fn` to run when the outermost transaction is about to commit: every change is made,
|
|
253
|
+
* no effect has run, and nothing outside the transaction has seen it. For checks on a transaction
|
|
254
|
+
* as a whole. `fn` may change atoms and register further callbacks, which run before the same
|
|
255
|
+
* commit. Calling `rollback` aborts the transaction and skips the callbacks that are left, and a
|
|
256
|
+
* throw aborts it and propagates. Callbacks from a transaction that aborts never run. Outside a
|
|
257
|
+
* transaction this does nothing.
|
|
258
|
+
*
|
|
259
|
+
* @internal
|
|
260
|
+
*/
|
|
261
|
+
export function beforeTransactionCommit(fn: (rollback: () => void) => void) {
|
|
262
|
+
const txn = inst.currentTransaction
|
|
263
|
+
if (!txn) return
|
|
264
|
+
if (txn.commitCallbacks) txn.commitCallbacks.push(fn)
|
|
265
|
+
else txn.commitCallbacks = [fn]
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The value `atom` had before the outermost open transaction changed it, which is the value it
|
|
270
|
+
* goes back to if that transaction rolls back. The atom's current value when no open transaction
|
|
271
|
+
* has changed it.
|
|
272
|
+
*
|
|
273
|
+
* @internal
|
|
274
|
+
*/
|
|
275
|
+
export function getValueBeforeTransaction<T>(atom: Atom<T>): T {
|
|
276
|
+
let value = atom.__unsafe__getWithoutCapture()
|
|
277
|
+
for (let txn = inst.currentTransaction; txn; txn = txn.parent) {
|
|
278
|
+
const initialValues = txn.initialAtomValues
|
|
279
|
+
if (initialValues.has(atom as any)) value = initialValues.get(atom as any)
|
|
280
|
+
}
|
|
281
|
+
return value
|
|
282
|
+
}
|
|
283
|
+
|
|
166
284
|
/** @internal */
|
|
167
285
|
export function atomDidChange(atom: _Atom, previousValue: any) {
|
|
168
286
|
if (inst.currentTransaction) {
|
|
@@ -277,7 +395,7 @@ export function transaction<T>(fn: (rollback: () => void) => T) {
|
|
|
277
395
|
try {
|
|
278
396
|
result = fn(() => (rollback = true))
|
|
279
397
|
} catch (e) {
|
|
280
|
-
txn
|
|
398
|
+
abortAfterError(txn)
|
|
281
399
|
throw e
|
|
282
400
|
}
|
|
283
401
|
|
|
@@ -285,6 +403,16 @@ export function transaction<T>(fn: (rollback: () => void) => T) {
|
|
|
285
403
|
throw new Error('Transaction boundaries overlap')
|
|
286
404
|
}
|
|
287
405
|
|
|
406
|
+
if (!rollback) {
|
|
407
|
+
try {
|
|
408
|
+
// Never assign: a callback can call `fn`'s own `rollback`, which `prepare` can't see.
|
|
409
|
+
if (txn.prepare()) rollback = true
|
|
410
|
+
} catch (e) {
|
|
411
|
+
abortAfterError(txn)
|
|
412
|
+
throw e
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
288
416
|
if (rollback) {
|
|
289
417
|
txn.abort()
|
|
290
418
|
} else {
|
|
@@ -402,14 +530,22 @@ export async function deferAsyncEffects<T>(fn: () => Promise<T>) {
|
|
|
402
530
|
// first made every restoring set inside `abort()` flush effects on its own, so effects
|
|
403
531
|
// observed half-restored state.
|
|
404
532
|
try {
|
|
533
|
+
let rollback = false
|
|
534
|
+
if (typeof error === 'undefined') {
|
|
535
|
+
try {
|
|
536
|
+
rollback = txn.prepare()
|
|
537
|
+
} catch (e) {
|
|
538
|
+
error = e ?? null
|
|
539
|
+
}
|
|
540
|
+
}
|
|
405
541
|
if (typeof error !== 'undefined') {
|
|
406
542
|
// If the rollback was triggered, abort the transaction.
|
|
407
|
-
txn
|
|
543
|
+
abortAfterError(txn)
|
|
408
544
|
throw error
|
|
409
|
-
} else {
|
|
410
|
-
txn.commit()
|
|
411
|
-
return result
|
|
412
545
|
}
|
|
546
|
+
if (rollback) txn.abort()
|
|
547
|
+
else txn.commit()
|
|
548
|
+
return result
|
|
413
549
|
} finally {
|
|
414
550
|
inst.currentTransaction = null
|
|
415
551
|
}
|